SessionData.cpp 187 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "SessionData.h"
  5. #include "Common.h"
  6. #include "Exceptions.h"
  7. #include "FileBuffer.h"
  8. #include "CoreMain.h"
  9. #include "TextsCore.h"
  10. #include "PuttyIntf.h"
  11. #include "RemoteFiles.h"
  12. #include "SFTPFileSystem.h"
  13. #include "S3FileSystem.h"
  14. #include "FileMasks.h"
  15. #include <Soap.EncdDecd.hpp>
  16. #include <StrUtils.hpp>
  17. #include <XMLDoc.hpp>
  18. #include <StrUtils.hpp>
  19. #include <algorithm>
  20. //---------------------------------------------------------------------------
  21. #pragma package(smart_init)
  22. //---------------------------------------------------------------------------
  23. #define SET_SESSION_PROPERTY_FROM(PROPERTY, FROM) \
  24. if (F##PROPERTY != FROM) { F##PROPERTY = FROM; Modify(); }
  25. //---------------------------------------------------------------------------
  26. #define SET_SESSION_PROPERTY(PROPERTY) \
  27. SET_SESSION_PROPERTY_FROM(PROPERTY, value)
  28. //---------------------------------------------------------------------------
  29. const wchar_t * PingTypeNames = L"Off;Null;Dummy";
  30. const wchar_t * ProxyMethodNames = L"None;SOCKS4;SOCKS5;HTTP;Telnet;Cmd";
  31. const wchar_t * DefaultName = L"Default Settings";
  32. const UnicodeString CipherNames[CIPHER_COUNT] = {L"WARN", L"3des", L"blowfish", L"aes", L"des", L"arcfour", L"chacha20"};
  33. const UnicodeString KexNames[KEX_COUNT] = {L"WARN", L"dh-group1-sha1", L"dh-group14-sha1", L"dh-gex-sha1", L"rsa", L"ecdh"};
  34. const UnicodeString HostKeyNames[HOSTKEY_COUNT] = {L"WARN", L"rsa", L"dsa", L"ecdsa", L"ed25519", L"ed448"};
  35. const UnicodeString GssLibNames[GSSLIB_COUNT] = {L"gssapi32", L"sspi", L"custom"};
  36. // Update also order in Ssh2CipherList()
  37. const TCipher DefaultCipherList[CIPHER_COUNT] =
  38. { cipAES, cipChaCha20, cipBlowfish, cip3DES, cipWarn, cipArcfour, cipDES };
  39. // Update also order in SshKexList()
  40. const TKex DefaultKexList[KEX_COUNT] =
  41. { kexECDH, kexDHGEx, kexDHGroup14, kexRSA, kexWarn, kexDHGroup1 };
  42. const THostKey DefaultHostKeyList[HOSTKEY_COUNT] =
  43. { hkED448, hkED25519, hkECDSA, hkRSA, hkDSA, hkWarn };
  44. const TGssLib DefaultGssLibList[GSSLIB_COUNT] =
  45. { gssGssApi32, gssSspi, gssCustom };
  46. const wchar_t FSProtocolNames[FSPROTOCOL_COUNT][16] = { L"SCP", L"SFTP (SCP)", L"SFTP", L"", L"", L"FTP", L"WebDAV", L"S3" };
  47. const int SshPortNumber = 22;
  48. const int FtpPortNumber = 21;
  49. const int FtpsImplicitPortNumber = 990;
  50. const int HTTPPortNumber = 80;
  51. const int HTTPSPortNumber = 443;
  52. const int TelnetPortNumber = 23;
  53. const int DefaultSendBuf = 262144;
  54. const int ProxyPortNumber = 80;
  55. const UnicodeString AnonymousUserName(L"anonymous");
  56. const UnicodeString AnonymousPassword(L"[email protected]");
  57. const UnicodeString PuttySshProtocol(L"ssh");
  58. const UnicodeString PuttyTelnetProtocol(L"telnet");
  59. const UnicodeString SftpProtocol(L"sftp");
  60. const UnicodeString ScpProtocol(L"scp");
  61. const UnicodeString FtpProtocol(L"ftp");
  62. const UnicodeString FtpsProtocol(L"ftps");
  63. const UnicodeString FtpesProtocol(L"ftpes");
  64. const UnicodeString WebDAVProtocol(L"dav");
  65. const UnicodeString WebDAVSProtocol(L"davs");
  66. const UnicodeString S3Protocol(L"s3");
  67. const UnicodeString SshProtocol(L"ssh");
  68. const UnicodeString WinSCPProtocolPrefix(L"winscp-");
  69. const wchar_t UrlParamSeparator = L';';
  70. const wchar_t UrlParamValueSeparator = L'=';
  71. const UnicodeString UrlHostKeyParamName(L"fingerprint");
  72. const UnicodeString UrlSaveParamName(L"save");
  73. const UnicodeString UrlRawSettingsParamNamePrefix(L"x-");
  74. const UnicodeString PassphraseOption(L"passphrase");
  75. const UnicodeString RawSettingsOption(L"rawsettings");
  76. const UnicodeString S3HostName(S3LibDefaultHostName());
  77. const UnicodeString OpensshHostDirective(L"Host");
  78. //---------------------------------------------------------------------
  79. TDateTime __fastcall SecToDateTime(int Sec)
  80. {
  81. return TDateTime(double(Sec) / SecsPerDay);
  82. }
  83. //---------------------------------------------------------------------
  84. static bool IsValidOpensshLine(const UnicodeString & Line)
  85. {
  86. return !Line.IsEmpty() && (Line[1] != L'#');
  87. }
  88. //---------------------------------------------------------------------
  89. static bool ParseOpensshDirective(const UnicodeString & ALine, UnicodeString & Directive, UnicodeString & Value)
  90. {
  91. bool Result = IsValidOpensshLine(ALine);
  92. if (Result)
  93. {
  94. int From = 1;
  95. wchar_t Equal = L'=';
  96. UnicodeString Delimiters(UnicodeString(L" \t") + Equal);
  97. wchar_t Delimiter;
  98. UnicodeString Line = Trim(ALine);
  99. Directive = CopyToChars(Line, From, Delimiters, false, &Delimiter, false);
  100. Result = !Directive.IsEmpty();
  101. if (Result)
  102. {
  103. Value = Line;
  104. Value.Delete(1, Directive.Length() + 1);
  105. Value = Trim(Value);
  106. if ((Delimiter != Equal) && !Value.IsEmpty() && (Value[1] == Equal))
  107. {
  108. Value.Delete(1, 1);
  109. Value = Trim(Value); // not sure about this, but for the directives we support it does not matter
  110. }
  111. Result = !Value.IsEmpty();
  112. }
  113. }
  114. return Result;
  115. }
  116. //--- TSessionData ----------------------------------------------------
  117. __fastcall TSessionData::TSessionData(UnicodeString aName):
  118. TNamedObject(aName)
  119. {
  120. Default();
  121. FModified = true;
  122. }
  123. //---------------------------------------------------------------------
  124. _fastcall TSessionData::~TSessionData()
  125. {
  126. }
  127. //---------------------------------------------------------------------
  128. int __fastcall TSessionData::Compare(TNamedObject * Other)
  129. {
  130. int Result;
  131. // To avoid using CompareLogicalText on hex names of sessions in workspace.
  132. // The session 000A would be sorted before 0001.
  133. if (IsWorkspace && DebugNotNull(dynamic_cast<TSessionData *>(Other))->IsWorkspace)
  134. {
  135. Result = CompareText(Name, Other->Name);
  136. }
  137. else
  138. {
  139. Result = TNamedObject::Compare(Other);
  140. }
  141. return Result;
  142. }
  143. //---------------------------------------------------------------------
  144. TSessionData * __fastcall TSessionData::Clone()
  145. {
  146. std::unique_ptr<TSessionData> Data(new TSessionData(L""));
  147. Data->Assign(this);
  148. return Data.release();
  149. }
  150. //---------------------------------------------------------------------
  151. void __fastcall TSessionData::DefaultSettings()
  152. {
  153. HostName = L"";
  154. PortNumber = SshPortNumber;
  155. UserName = L"";
  156. Password = L"";
  157. NewPassword = L"";
  158. ChangePassword = false;
  159. PingInterval = 30;
  160. PingType = ptOff;
  161. Timeout = 15;
  162. TryAgent = true;
  163. AgentFwd = false;
  164. AuthKI = true;
  165. AuthKIPassword = true;
  166. AuthGSSAPI = true;
  167. AuthGSSAPIKEX = false;
  168. GSSAPIFwdTGT = false;
  169. LogicalHostName = L"";
  170. ChangeUsername = false;
  171. Compression = false;
  172. Ssh2DES = false;
  173. SshNoUserAuth = false;
  174. for (int Index = 0; Index < CIPHER_COUNT; Index++)
  175. {
  176. Cipher[Index] = DefaultCipherList[Index];
  177. }
  178. for (int Index = 0; Index < KEX_COUNT; Index++)
  179. {
  180. Kex[Index] = DefaultKexList[Index];
  181. }
  182. for (int Index = 0; Index < HOSTKEY_COUNT; Index++)
  183. {
  184. HostKeys[Index] = DefaultHostKeyList[Index];
  185. }
  186. for (int Index = 0; Index < GSSLIB_COUNT; Index++)
  187. {
  188. GssLib[Index] = DefaultGssLibList[Index];
  189. }
  190. GssLibCustom = L"";
  191. PublicKeyFile = L"";
  192. Passphrase = L"";
  193. FPuttyProtocol = L"";
  194. TcpNoDelay = false;
  195. SendBuf = DefaultSendBuf;
  196. SourceAddress = L"";
  197. ProtocolFeatures = L"";
  198. SshSimple = true;
  199. HostKey = L"";
  200. FingerprintScan = false;
  201. FOverrideCachedHostKey = true;
  202. Note = L"";
  203. WinTitle = L"";
  204. InternalEditorEncoding = -1;
  205. EncryptKey = UnicodeString();
  206. WebDavLiberalEscaping = false;
  207. ProxyMethod = ::pmNone;
  208. ProxyHost = L"proxy";
  209. ProxyPort = ProxyPortNumber;
  210. ProxyUsername = L"";
  211. ProxyPassword = L"";
  212. ProxyTelnetCommand = L"connect %host %port\\n";
  213. ProxyLocalCommand = L"";
  214. ProxyDNS = asAuto;
  215. ProxyLocalhost = false;
  216. for (unsigned int Index = 0; Index < LENOF(FBugs); Index++)
  217. {
  218. Bug[(TSshBug)Index] = asAuto;
  219. }
  220. Special = false;
  221. FSProtocol = fsSFTP;
  222. AddressFamily = afAuto;
  223. RekeyData = L"1G";
  224. RekeyTime = MinsPerHour;
  225. // FS common
  226. LocalDirectory = L"";
  227. OtherLocalDirectory = L"";
  228. RemoteDirectory = L"";
  229. SynchronizeBrowsing = false;
  230. UpdateDirectories = true;
  231. CacheDirectories = true;
  232. CacheDirectoryChanges = true;
  233. PreserveDirectoryChanges = true;
  234. ResolveSymlinks = true;
  235. FollowDirectorySymlinks = false;
  236. DSTMode = dstmUnix;
  237. DeleteToRecycleBin = false;
  238. OverwrittenToRecycleBin = false;
  239. RecycleBinPath = L"";
  240. Color = 0;
  241. PostLoginCommands = L"";
  242. // SCP
  243. LookupUserGroups = asAuto;
  244. EOLType = eolLF;
  245. TrimVMSVersions = false;
  246. VMSAllRevisions = false;
  247. Shell = L""; //default shell
  248. ReturnVar = L"";
  249. ExitCode1IsError = false;
  250. ClearAliases = true;
  251. UnsetNationalVars = true;
  252. ListingCommand = L"ls -la";
  253. IgnoreLsWarnings = true;
  254. Scp1Compatibility = false;
  255. TimeDifference = 0;
  256. TimeDifferenceAuto = true;
  257. SCPLsFullTime = asAuto;
  258. NotUtf = asAuto;
  259. // S3
  260. S3DefaultRegion = L"";
  261. S3SessionToken = L"";
  262. S3UrlStyle = s3usVirtualHost;
  263. S3MaxKeys = asAuto;
  264. S3CredentialsEnv = false;
  265. // SFTP
  266. SftpServer = L"";
  267. SFTPDownloadQueue = 32;
  268. SFTPUploadQueue = 32;
  269. SFTPListingQueue = 2;
  270. SFTPMaxVersion = ::SFTPMaxVersion;
  271. SFTPMaxPacketSize = 0;
  272. SFTPRealPath = asAuto;
  273. for (unsigned int Index = 0; Index < LENOF(FSFTPBugs); Index++)
  274. {
  275. SFTPBug[(TSftpBug)Index] = asAuto;
  276. }
  277. Tunnel = false;
  278. TunnelHostName = L"";
  279. TunnelPortNumber = SshPortNumber;
  280. TunnelUserName = L"";
  281. TunnelPassword = L"";
  282. TunnelPublicKeyFile = L"";
  283. TunnelPassphrase = L"";
  284. TunnelLocalPortNumber = 0;
  285. TunnelPortFwd = L"";
  286. TunnelHostKey = L"";
  287. // FTP
  288. FtpPasvMode = true;
  289. FtpForcePasvIp = asAuto;
  290. FtpUseMlsd = asAuto;
  291. FtpAccount = L"";
  292. FtpPingInterval = 30;
  293. FtpPingType = ptDummyCommand;
  294. FtpTransferActiveImmediately = asAuto;
  295. Ftps = ftpsNone;
  296. MinTlsVersion = tls10;
  297. MaxTlsVersion = tls13;
  298. FtpListAll = asAuto;
  299. FtpHost = asAuto;
  300. FtpWorkFromCwd = asAuto;
  301. SslSessionReuse = true;
  302. TlsCertificateFile = L"";
  303. FtpProxyLogonType = 0; // none
  304. PuttySettings = UnicodeString();
  305. CustomParam1 = L"";
  306. CustomParam2 = L"";
  307. }
  308. //---------------------------------------------------------------------
  309. void __fastcall TSessionData::Default()
  310. {
  311. DefaultSettings();
  312. IsWorkspace = false;
  313. Link = L"";
  314. NameOverride = L"";
  315. Selected = false;
  316. FModified = false;
  317. FSource = ::ssNone;
  318. FSaveOnly = false;
  319. // add also to TSessionLog::AddStartupInfo()
  320. }
  321. //---------------------------------------------------------------------
  322. void __fastcall TSessionData::NonPersistant()
  323. {
  324. UpdateDirectories = false;
  325. PreserveDirectoryChanges = false;
  326. }
  327. //---------------------------------------------------------------------
  328. #define PROPERTY(P) PROPERTY_HANDLER(P, )
  329. #define BASE_PROPERTIES \
  330. PROPERTY(HostName); \
  331. PROPERTY(PortNumber); \
  332. PROPERTY(UserName); \
  333. PROPERTY_HANDLER(Password, F); \
  334. PROPERTY(PublicKeyFile); \
  335. PROPERTY_HANDLER(Passphrase, F); \
  336. PROPERTY(FSProtocol); \
  337. PROPERTY(Ftps); \
  338. PROPERTY(LocalDirectory); \
  339. PROPERTY(OtherLocalDirectory); \
  340. PROPERTY(RemoteDirectory); \
  341. PROPERTY(Color); \
  342. PROPERTY(SynchronizeBrowsing); \
  343. PROPERTY(Note);
  344. //---------------------------------------------------------------------
  345. #define ADVANCED_PROPERTIES \
  346. PROPERTY_HANDLER(NewPassword, F); \
  347. PROPERTY(ChangePassword); \
  348. PROPERTY(PingInterval); \
  349. PROPERTY(PingType); \
  350. PROPERTY(Timeout); \
  351. PROPERTY(TryAgent); \
  352. PROPERTY(AgentFwd); \
  353. PROPERTY(LogicalHostName); \
  354. PROPERTY(ChangeUsername); \
  355. PROPERTY(Compression); \
  356. PROPERTY(Ssh2DES); \
  357. PROPERTY(SshNoUserAuth); \
  358. PROPERTY(CipherList); \
  359. PROPERTY(KexList); \
  360. PROPERTY(HostKeyList); \
  361. PROPERTY(GssLibList); \
  362. PROPERTY(GssLibCustom); \
  363. PROPERTY(AddressFamily); \
  364. PROPERTY(RekeyData); \
  365. PROPERTY(RekeyTime); \
  366. PROPERTY(HostKey); \
  367. PROPERTY(FingerprintScan); \
  368. PROPERTY(InternalEditorEncoding); \
  369. \
  370. PROPERTY(UpdateDirectories); \
  371. PROPERTY(CacheDirectories); \
  372. PROPERTY(CacheDirectoryChanges); \
  373. PROPERTY(PreserveDirectoryChanges); \
  374. \
  375. PROPERTY(ResolveSymlinks); \
  376. PROPERTY(FollowDirectorySymlinks); \
  377. PROPERTY(DSTMode); \
  378. PROPERTY(Special); \
  379. PROPERTY(Selected); \
  380. PROPERTY(ReturnVar); \
  381. PROPERTY(ExitCode1IsError); \
  382. PROPERTY(LookupUserGroups); \
  383. PROPERTY(EOLType); \
  384. PROPERTY(TrimVMSVersions); \
  385. PROPERTY(VMSAllRevisions); \
  386. PROPERTY(Shell); \
  387. PROPERTY(ClearAliases); \
  388. PROPERTY(Scp1Compatibility); \
  389. PROPERTY(UnsetNationalVars); \
  390. PROPERTY(ListingCommand); \
  391. PROPERTY(IgnoreLsWarnings); \
  392. PROPERTY(SCPLsFullTime); \
  393. \
  394. PROPERTY(TimeDifference); \
  395. PROPERTY(TimeDifferenceAuto); \
  396. PROPERTY(TcpNoDelay); \
  397. PROPERTY(SendBuf); \
  398. PROPERTY(SourceAddress); \
  399. PROPERTY(ProtocolFeatures); \
  400. PROPERTY(SshSimple); \
  401. PROPERTY(AuthKI); \
  402. PROPERTY(AuthKIPassword); \
  403. PROPERTY(AuthGSSAPI); \
  404. PROPERTY(AuthGSSAPIKEX); \
  405. PROPERTY(GSSAPIFwdTGT); \
  406. PROPERTY(DeleteToRecycleBin); \
  407. PROPERTY(OverwrittenToRecycleBin); \
  408. PROPERTY(RecycleBinPath); \
  409. PROPERTY(NotUtf); \
  410. PROPERTY(PostLoginCommands); \
  411. \
  412. PROPERTY(S3DefaultRegion); \
  413. PROPERTY(S3SessionToken); \
  414. PROPERTY(S3UrlStyle); \
  415. PROPERTY(S3MaxKeys); \
  416. PROPERTY(S3CredentialsEnv); \
  417. \
  418. PROPERTY(ProxyMethod); \
  419. PROPERTY(ProxyHost); \
  420. PROPERTY(ProxyPort); \
  421. PROPERTY(ProxyUsername); \
  422. PROPERTY_HANDLER(ProxyPassword, F); \
  423. PROPERTY(ProxyTelnetCommand); \
  424. PROPERTY(ProxyLocalCommand); \
  425. PROPERTY(ProxyDNS); \
  426. PROPERTY(ProxyLocalhost); \
  427. \
  428. for (unsigned int Index = 0; Index < LENOF(FBugs); Index++) \
  429. { \
  430. PROPERTY(Bug[(TSshBug)Index]); \
  431. } \
  432. \
  433. PROPERTY(SftpServer); \
  434. PROPERTY(SFTPDownloadQueue); \
  435. PROPERTY(SFTPUploadQueue); \
  436. PROPERTY(SFTPListingQueue); \
  437. PROPERTY(SFTPMaxVersion); \
  438. PROPERTY(SFTPMaxPacketSize); \
  439. PROPERTY(SFTPRealPath); \
  440. \
  441. for (unsigned int Index = 0; Index < LENOF(FSFTPBugs); Index++) \
  442. { \
  443. PROPERTY(SFTPBug[(TSftpBug)Index]); \
  444. } \
  445. \
  446. PROPERTY(Tunnel); \
  447. PROPERTY(TunnelHostName); \
  448. PROPERTY(TunnelPortNumber); \
  449. PROPERTY(TunnelUserName); \
  450. PROPERTY_HANDLER(TunnelPassword, F); \
  451. PROPERTY(TunnelPublicKeyFile); \
  452. PROPERTY_HANDLER(TunnelPassphrase, F); \
  453. PROPERTY(TunnelLocalPortNumber); \
  454. PROPERTY(TunnelPortFwd); \
  455. PROPERTY(TunnelHostKey); \
  456. \
  457. PROPERTY(FtpPasvMode); \
  458. PROPERTY(FtpForcePasvIp); \
  459. PROPERTY(FtpUseMlsd); \
  460. PROPERTY(FtpAccount); \
  461. PROPERTY(FtpPingInterval); \
  462. PROPERTY(FtpPingType); \
  463. PROPERTY(FtpTransferActiveImmediately); \
  464. PROPERTY(FtpListAll); \
  465. PROPERTY(FtpHost); \
  466. PROPERTY(FtpWorkFromCwd); \
  467. PROPERTY(SslSessionReuse); \
  468. PROPERTY(TlsCertificateFile); \
  469. \
  470. PROPERTY(FtpProxyLogonType); \
  471. \
  472. PROPERTY(MinTlsVersion); \
  473. PROPERTY(MaxTlsVersion); \
  474. \
  475. PROPERTY(WinTitle); \
  476. \
  477. PROPERTY_HANDLER(EncryptKey, F); \
  478. \
  479. PROPERTY(WebDavLiberalEscaping); \
  480. \
  481. PROPERTY(PuttySettings); \
  482. \
  483. PROPERTY(CustomParam1); \
  484. PROPERTY(CustomParam2);
  485. #define META_PROPERTIES \
  486. PROPERTY(IsWorkspace); \
  487. PROPERTY(Link); \
  488. PROPERTY(NameOverride);
  489. //---------------------------------------------------------------------
  490. void __fastcall TSessionData::Assign(TPersistent * Source)
  491. {
  492. if (Source && Source->InheritsFrom(__classid(TSessionData)))
  493. {
  494. TSessionData * SourceData = (TSessionData *)Source;
  495. // Master password prompt shows implicitly here, when cloning the session data for a new terminal
  496. CopyData(SourceData);
  497. FSource = SourceData->FSource;
  498. }
  499. else
  500. {
  501. TNamedObject::Assign(Source);
  502. }
  503. }
  504. //---------------------------------------------------------------------
  505. void __fastcall TSessionData::DoCopyData(TSessionData * SourceData, bool NoRecrypt)
  506. {
  507. #define PROPERTY_HANDLER(P, F) \
  508. if (NoRecrypt) \
  509. { \
  510. F##P = SourceData->F##P; \
  511. } \
  512. else \
  513. { \
  514. P = SourceData->P; \
  515. }
  516. PROPERTY(Name);
  517. BASE_PROPERTIES;
  518. ADVANCED_PROPERTIES;
  519. META_PROPERTIES;
  520. #undef PROPERTY_HANDLER
  521. FOverrideCachedHostKey = SourceData->FOverrideCachedHostKey;
  522. FModified = SourceData->Modified;
  523. FSaveOnly = SourceData->FSaveOnly;
  524. }
  525. //---------------------------------------------------------------------
  526. void __fastcall TSessionData::CopyData(TSessionData * SourceData)
  527. {
  528. DoCopyData(SourceData, false);
  529. }
  530. //---------------------------------------------------------------------
  531. void __fastcall TSessionData::CopyDataNoRecrypt(TSessionData * SourceData)
  532. {
  533. DoCopyData(SourceData, true);
  534. }
  535. //---------------------------------------------------------------------
  536. void __fastcall TSessionData::CopyDirectoriesStateData(TSessionData * SourceData)
  537. {
  538. RemoteDirectory = SourceData->RemoteDirectory;
  539. LocalDirectory = SourceData->LocalDirectory;
  540. OtherLocalDirectory = SourceData->OtherLocalDirectory;
  541. SynchronizeBrowsing = SourceData->SynchronizeBrowsing;
  542. }
  543. //---------------------------------------------------------------------
  544. bool __fastcall TSessionData::HasStateData()
  545. {
  546. return
  547. !RemoteDirectory.IsEmpty() ||
  548. !LocalDirectory.IsEmpty() ||
  549. !OtherLocalDirectory.IsEmpty() ||
  550. (Color != 0);
  551. }
  552. //---------------------------------------------------------------------
  553. void __fastcall TSessionData::CopyStateData(TSessionData * SourceData)
  554. {
  555. // Keep in sync with TCustomScpExplorerForm::UpdateSessionData.
  556. CopyDirectoriesStateData(SourceData);
  557. Color = SourceData->Color;
  558. }
  559. //---------------------------------------------------------------------
  560. void __fastcall TSessionData::CopyNonCoreData(TSessionData * SourceData)
  561. {
  562. CopyStateData(SourceData);
  563. UpdateDirectories = SourceData->UpdateDirectories;
  564. Note = SourceData->Note;
  565. }
  566. //---------------------------------------------------------------------
  567. bool __fastcall TSessionData::IsSame(
  568. const TSessionData * Default, bool AdvancedOnly, TStrings * DifferentProperties, bool Decrypted)
  569. {
  570. bool Result = true;
  571. #define PROPERTY_HANDLER(P, F) \
  572. if ((Decrypted && (P != Default->P)) || \
  573. (!Decrypted && (F##P != Default->F##P))) \
  574. { \
  575. Result = false; \
  576. if (DifferentProperties != NULL) \
  577. { \
  578. DifferentProperties->Add(#P); \
  579. } \
  580. else \
  581. { \
  582. return Result; \
  583. } \
  584. }
  585. if (!AdvancedOnly)
  586. {
  587. BASE_PROPERTIES;
  588. META_PROPERTIES;
  589. }
  590. ADVANCED_PROPERTIES;
  591. #undef PROPERTY_HANDLER
  592. return Result;
  593. }
  594. //---------------------------------------------------------------------
  595. bool __fastcall TSessionData::IsSame(const TSessionData * Default, bool AdvancedOnly)
  596. {
  597. return IsSame(Default, AdvancedOnly, NULL, false);
  598. }
  599. //---------------------------------------------------------------------
  600. bool __fastcall TSessionData::IsSameDecrypted(const TSessionData * Default)
  601. {
  602. return IsSame(Default, false, NULL, true);
  603. }
  604. //---------------------------------------------------------------------
  605. TFSProtocol NormalizeFSProtocol(TFSProtocol FSProtocol)
  606. {
  607. if (FSProtocol == fsSFTPonly)
  608. {
  609. FSProtocol = fsSFTP;
  610. }
  611. return FSProtocol;
  612. }
  613. //---------------------------------------------------------------------
  614. bool __fastcall TSessionData::IsSameSite(const TSessionData * Other)
  615. {
  616. return
  617. // Particularly when handling /refresh,
  618. // fsSFTPonly sites when compared against sftp:// URLs (fsSFTP) have to match.
  619. // But similarly also falled back SCP sites.
  620. (NormalizeFSProtocol(FSProtocol) == NormalizeFSProtocol(Other->FSProtocol)) &&
  621. (HostName == Other->HostName) &&
  622. (PortNumber == Other->PortNumber) &&
  623. (UserName == Other->UserName);
  624. }
  625. //---------------------------------------------------------------------
  626. bool __fastcall TSessionData::IsInFolderOrWorkspace(UnicodeString AFolder)
  627. {
  628. return StartsText(UnixIncludeTrailingBackslash(AFolder), Name);
  629. }
  630. //---------------------------------------------------------------------
  631. void __fastcall TSessionData::DoLoad(THierarchicalStorage * Storage, bool PuttyImport, bool & RewritePassword, bool Unsafe)
  632. {
  633. // Make sure we only ever use methods supported by TOptionsStorage
  634. // (implemented by TOptionsIniFile)
  635. PortNumber = Storage->ReadInteger(L"PortNumber", PortNumber);
  636. UserName = Storage->ReadString(L"UserName", UserName);
  637. // must be loaded after UserName, because HostName may be in format user@host
  638. HostName = Storage->ReadString(L"HostName", HostName);
  639. #define LOAD_PASSWORD_EX(PROP, PLAIN_NAME, ENC_NAME, ONPLAIN) \
  640. if (Storage->ValueExists(PLAIN_NAME)) \
  641. { \
  642. PROP = Storage->ReadString(PLAIN_NAME, PROP); \
  643. ONPLAIN \
  644. } \
  645. else \
  646. { \
  647. RawByteString A##PROP = Storage->ReadStringAsBinaryData(ENC_NAME, F##PROP); \
  648. SET_SESSION_PROPERTY_FROM(PROP, A##PROP); \
  649. }
  650. #define LOAD_PASSWORD(PROP, PLAIN_NAME) LOAD_PASSWORD_EX(PROP, PLAIN_NAME, TEXT(#PROP), RewritePassword = true;)
  651. if (!Configuration->DisablePasswordStoring)
  652. {
  653. LOAD_PASSWORD(Password, L"PasswordPlain");
  654. }
  655. HostKey = Storage->ReadString(L"SshHostKey", HostKey); // probably never used
  656. Note = Storage->ReadString(L"Note", Note);
  657. // Putty uses PingIntervalSecs
  658. int PingIntervalSecs = Storage->ReadInteger(L"PingIntervalSecs", -1);
  659. if (PingIntervalSecs < 0)
  660. {
  661. PingIntervalSecs = Storage->ReadInteger(L"PingIntervalSec", PingInterval%SecsPerMin);
  662. }
  663. PingInterval =
  664. Storage->ReadInteger(L"PingInterval", PingInterval/SecsPerMin)*SecsPerMin +
  665. PingIntervalSecs;
  666. if (PingInterval == 0)
  667. {
  668. PingInterval = 30;
  669. }
  670. PingType = static_cast<TPingType>(Storage->ReadInteger(L"PingType", PingType));
  671. Timeout = Storage->ReadInteger(L"Timeout", Timeout);
  672. TryAgent = Storage->ReadBool(L"TryAgent", TryAgent);
  673. AgentFwd = Storage->ReadBool(L"AgentFwd", AgentFwd);
  674. AuthKI = Storage->ReadBool(L"AuthKI", AuthKI);
  675. AuthKIPassword = Storage->ReadBool(L"AuthKIPassword", AuthKIPassword);
  676. // Continue to use setting keys of previous kerberos implementation (vaclav tomec),
  677. // but fallback to keys of other implementations (official putty and vintela quest putty),
  678. // to allow imports from all putty versions.
  679. // Both vaclav tomec and official putty use AuthGSSAPI
  680. AuthGSSAPI = Storage->ReadBool(L"AuthGSSAPI", Storage->ReadBool(L"AuthSSPI", AuthGSSAPI));
  681. AuthGSSAPIKEX = Storage->ReadBool(L"AuthGSSAPIKEX", AuthGSSAPIKEX);
  682. GSSAPIFwdTGT = Storage->ReadBool(L"GSSAPIFwdTGT", Storage->ReadBool(L"GssapiFwd", Storage->ReadBool(L"SSPIFwdTGT", GSSAPIFwdTGT)));
  683. // KerbPrincipal was used by Quest PuTTY
  684. // GSSAPIServerRealm was used by Vaclav Tomec
  685. LogicalHostName = Storage->ReadString(L"LogicalHostName", Storage->ReadString(L"GSSAPIServerRealm", Storage->ReadString(L"KerbPrincipal", LogicalHostName)));
  686. ChangeUsername = Storage->ReadBool(L"ChangeUsername", ChangeUsername);
  687. Compression = Storage->ReadBool(L"Compression", Compression);
  688. Ssh2DES = Storage->ReadBool(L"Ssh2DES", Ssh2DES);
  689. SshNoUserAuth = Storage->ReadBool(L"SshNoUserAuth", SshNoUserAuth);
  690. CipherList = Storage->ReadString(L"Cipher", CipherList);
  691. KexList = Storage->ReadString(L"KEX", KexList);
  692. HostKeyList = Storage->ReadString(L"HostKey", HostKeyList);
  693. if (!Unsafe)
  694. {
  695. GssLibList = Storage->ReadString(L"GSSLibs", GssLibList);
  696. }
  697. GssLibCustom = Storage->ReadString(L"GSSCustom", GssLibCustom);
  698. PublicKeyFile = Storage->ReadString(L"PublicKeyFile", PublicKeyFile);
  699. AddressFamily = static_cast<TAddressFamily>
  700. (Storage->ReadInteger(L"AddressFamily", AddressFamily));
  701. RekeyData = Storage->ReadString(L"RekeyBytes", RekeyData);
  702. RekeyTime = Storage->ReadInteger(L"RekeyTime", RekeyTime);
  703. FSProtocol = (TFSProtocol)Storage->ReadInteger(L"FSProtocol", FSProtocol);
  704. LocalDirectory = Storage->ReadString(L"LocalDirectory", LocalDirectory);
  705. OtherLocalDirectory = Storage->ReadString(L"OtherLocalDirectory", OtherLocalDirectory);
  706. RemoteDirectory = Storage->ReadString(L"RemoteDirectory", RemoteDirectory);
  707. SynchronizeBrowsing = Storage->ReadBool(L"SynchronizeBrowsing", SynchronizeBrowsing);
  708. UpdateDirectories = Storage->ReadBool(L"UpdateDirectories", UpdateDirectories);
  709. CacheDirectories = Storage->ReadBool(L"CacheDirectories", CacheDirectories);
  710. CacheDirectoryChanges = Storage->ReadBool(L"CacheDirectoryChanges", CacheDirectoryChanges);
  711. PreserveDirectoryChanges = Storage->ReadBool(L"PreserveDirectoryChanges", PreserveDirectoryChanges);
  712. ResolveSymlinks = Storage->ReadBool(L"ResolveSymlinks", ResolveSymlinks);
  713. FollowDirectorySymlinks = Storage->ReadBool(L"FollowDirectorySymlinks", FollowDirectorySymlinks);
  714. DSTMode = (TDSTMode)Storage->ReadInteger(L"ConsiderDST", DSTMode);
  715. Special = Storage->ReadBool(L"Special", Special);
  716. if (!Unsafe)
  717. {
  718. Shell = Storage->ReadString(L"Shell", Shell);
  719. }
  720. ClearAliases = Storage->ReadBool(L"ClearAliases", ClearAliases);
  721. UnsetNationalVars = Storage->ReadBool(L"UnsetNationalVars", UnsetNationalVars);
  722. if (!Unsafe)
  723. {
  724. ListingCommand = Storage->ReadString(L"ListingCommand",
  725. Storage->ReadBool(L"AliasGroupList", false) ? UnicodeString(L"ls -gla") : ListingCommand);
  726. }
  727. IgnoreLsWarnings = Storage->ReadBool(L"IgnoreLsWarnings", IgnoreLsWarnings);
  728. SCPLsFullTime = Storage->ReadEnum(L"SCPLsFullTime", SCPLsFullTime, AutoSwitchMapping);
  729. Scp1Compatibility = Storage->ReadBool(L"Scp1Compatibility", Scp1Compatibility);
  730. TimeDifference = Storage->ReadFloat(L"TimeDifference", TimeDifference);
  731. TimeDifferenceAuto = Storage->ReadBool(L"TimeDifferenceAuto", (TimeDifference == TDateTime()));
  732. if (!Unsafe)
  733. {
  734. DeleteToRecycleBin = Storage->ReadBool(L"DeleteToRecycleBin", DeleteToRecycleBin);
  735. OverwrittenToRecycleBin = Storage->ReadBool(L"OverwrittenToRecycleBin", OverwrittenToRecycleBin);
  736. RecycleBinPath = Storage->ReadString(L"RecycleBinPath", RecycleBinPath);
  737. PostLoginCommands = Storage->ReadString(L"PostLoginCommands", PostLoginCommands);
  738. ReturnVar = Storage->ReadString(L"ReturnVar", ReturnVar);
  739. }
  740. ExitCode1IsError = Storage->ReadBool(L"ExitCode1IsError", ExitCode1IsError);
  741. LookupUserGroups = Storage->ReadEnum(L"LookupUserGroups2", LookupUserGroups, AutoSwitchMapping);
  742. EOLType = (TEOLType)Storage->ReadInteger(L"EOLType", EOLType);
  743. TrimVMSVersions = Storage->ReadBool(L"TrimVMSVersions", TrimVMSVersions);
  744. VMSAllRevisions = Storage->ReadBool(L"VMSAllRevisions", VMSAllRevisions);
  745. NotUtf = Storage->ReadEnum(L"Utf", Storage->ReadEnum(L"SFTPUtfBug", NotUtf), AutoSwitchReversedMapping);
  746. InternalEditorEncoding = Storage->ReadInteger(L"InternalEditorEncoding", InternalEditorEncoding);
  747. S3DefaultRegion = Storage->ReadString(L"S3DefaultRegion", S3DefaultRegion);
  748. S3SessionToken = Storage->ReadString(L"S3SessionToken", S3SessionToken);
  749. S3UrlStyle = (TS3UrlStyle)Storage->ReadInteger(L"S3UrlStyle", S3UrlStyle);
  750. S3MaxKeys = Storage->ReadEnum(L"S3MaxKeys", S3MaxKeys, AutoSwitchMapping);
  751. S3CredentialsEnv = Storage->ReadBool(L"S3CredentialsEnv", S3CredentialsEnv);
  752. // PuTTY defaults to TcpNoDelay, but the psftp/pscp ignores this preference, and always set this to off (what is our default too)
  753. if (!PuttyImport)
  754. {
  755. TcpNoDelay = Storage->ReadBool(L"TcpNoDelay", TcpNoDelay);
  756. }
  757. SendBuf = Storage->ReadInteger(L"SendBuf", Storage->ReadInteger("SshSendBuf", SendBuf));
  758. SourceAddress = Storage->ReadString(L"SourceAddress", SourceAddress);
  759. ProtocolFeatures = Storage->ReadString(L"ProtocolFeatures", ProtocolFeatures);
  760. SshSimple = Storage->ReadBool(L"SshSimple", SshSimple);
  761. ProxyMethod = (TProxyMethod)Storage->ReadInteger(L"ProxyMethod", ProxyMethod);
  762. ProxyHost = Storage->ReadString(L"ProxyHost", ProxyHost);
  763. ProxyPort = Storage->ReadInteger(L"ProxyPort", ProxyPort);
  764. ProxyUsername = Storage->ReadString(L"ProxyUsername", ProxyUsername);
  765. // proxy password is not rewritten
  766. LOAD_PASSWORD_EX(ProxyPassword, L"ProxyPassword", L"ProxyPasswordEnc", );
  767. if (!Unsafe)
  768. {
  769. if (ProxyMethod == pmCmd)
  770. {
  771. ProxyLocalCommand = Storage->ReadStringRaw(L"ProxyTelnetCommand", ProxyLocalCommand);
  772. }
  773. else
  774. {
  775. ProxyTelnetCommand = Storage->ReadStringRaw(L"ProxyTelnetCommand", ProxyTelnetCommand);
  776. }
  777. }
  778. ProxyDNS = TAutoSwitch((Storage->ReadInteger(L"ProxyDNS", (ProxyDNS + 2) % 3) + 1) % 3);
  779. ProxyLocalhost = Storage->ReadBool(L"ProxyLocalhost", ProxyLocalhost);
  780. #define READ_BUG(BUG) \
  781. Bug[sb##BUG] = TAutoSwitch(2 - Storage->ReadInteger(L"Bug"#BUG, \
  782. 2 - Bug[sb##BUG]));
  783. READ_BUG(HMAC2);
  784. READ_BUG(DeriveKey2);
  785. READ_BUG(RSAPad2);
  786. READ_BUG(PKSessID2);
  787. READ_BUG(Rekey2);
  788. READ_BUG(MaxPkt2);
  789. READ_BUG(Ignore2);
  790. READ_BUG(OldGex2);
  791. READ_BUG(WinAdj);
  792. READ_BUG(ChanReq);
  793. #undef READ_BUG
  794. if ((Bug[sbHMAC2] == asAuto) &&
  795. Storage->ReadBool(L"BuggyMAC", false))
  796. {
  797. Bug[sbHMAC2] = asOn;
  798. }
  799. if (!Unsafe)
  800. {
  801. SftpServer = Storage->ReadString(L"SftpServer", SftpServer);
  802. }
  803. #define READ_SFTP_BUG(BUG) \
  804. SFTPBug[sb##BUG] = Storage->ReadEnum(L"SFTP" #BUG "Bug", SFTPBug[sb##BUG], AutoSwitchMapping);
  805. READ_SFTP_BUG(Symlink);
  806. READ_SFTP_BUG(SignedTS);
  807. #undef READ_SFTP_BUG
  808. SFTPMaxVersion = Storage->ReadInteger(L"SFTPMaxVersion", SFTPMaxVersion);
  809. SFTPMaxPacketSize = Storage->ReadInteger(L"SFTPMaxPacketSize", SFTPMaxPacketSize);
  810. SFTPDownloadQueue = Storage->ReadInteger(L"SFTPDownloadQueue", SFTPDownloadQueue);
  811. SFTPUploadQueue = Storage->ReadInteger(L"SFTPUploadQueue", SFTPUploadQueue);
  812. SFTPListingQueue = Storage->ReadInteger(L"SFTPListingQueue", SFTPListingQueue);
  813. SFTPRealPath = Storage->ReadEnum(L"SFTPRealPath", SFTPRealPath, AutoSwitchMapping);
  814. Color = Storage->ReadInteger(L"Color", Color);
  815. PuttyProtocol = Storage->ReadString(L"Protocol", PuttyProtocol);
  816. Tunnel = Storage->ReadBool(L"Tunnel", Tunnel);
  817. TunnelPortNumber = Storage->ReadInteger(L"TunnelPortNumber", TunnelPortNumber);
  818. TunnelUserName = Storage->ReadString(L"TunnelUserName", TunnelUserName);
  819. // must be loaded after TunnelUserName,
  820. // because TunnelHostName may be in format user@host
  821. TunnelHostName = Storage->ReadString(L"TunnelHostName", TunnelHostName);
  822. if (!Configuration->DisablePasswordStoring)
  823. {
  824. LOAD_PASSWORD(TunnelPassword, L"TunnelPasswordPlain");
  825. }
  826. TunnelPublicKeyFile = Storage->ReadString(L"TunnelPublicKeyFile", TunnelPublicKeyFile);
  827. // Contrary to main session passphrase (which has -passphrase switch in scripting),
  828. // we are loading tunnel passphrase, as there's no other way to provide it in scripting
  829. if (!Configuration->DisablePasswordStoring)
  830. {
  831. LOAD_PASSWORD(TunnelPassphrase, L"TunnelPassphrasePlain");
  832. }
  833. TunnelLocalPortNumber = Storage->ReadInteger(L"TunnelLocalPortNumber", TunnelLocalPortNumber);
  834. TunnelHostKey = Storage->ReadString(L"TunnelHostKey", TunnelHostKey);
  835. // Ftp prefix
  836. FtpPasvMode = Storage->ReadBool(L"FtpPasvMode", FtpPasvMode);
  837. FtpForcePasvIp = Storage->ReadEnum(L"FtpForcePasvIp2", FtpForcePasvIp, AutoSwitchMapping);
  838. FtpUseMlsd = Storage->ReadEnum(L"FtpUseMlsd", FtpUseMlsd, AutoSwitchMapping);
  839. FtpAccount = Storage->ReadString(L"FtpAccount", FtpAccount);
  840. FtpPingInterval = Storage->ReadInteger(L"FtpPingInterval", FtpPingInterval);
  841. FtpPingType = static_cast<TPingType>(Storage->ReadInteger(L"FtpPingType", FtpPingType));
  842. FtpTransferActiveImmediately = Storage->ReadEnum(L"FtpTransferActiveImmediately2", FtpTransferActiveImmediately, AutoSwitchMapping);
  843. Ftps = static_cast<TFtps>(Storage->ReadInteger(L"Ftps", Ftps));
  844. FtpListAll = Storage->ReadEnum(L"FtpListAll", FtpListAll, AutoSwitchMapping);
  845. FtpHost = Storage->ReadEnum(L"FtpHost", FtpHost, AutoSwitchMapping);
  846. FtpWorkFromCwd = Storage->ReadEnum(L"FtpWorkFromCwd", Storage->ReadEnum(L"FtpDeleteFromCwd", FtpWorkFromCwd), AutoSwitchMapping);
  847. SslSessionReuse = Storage->ReadBool(L"SslSessionReuse", SslSessionReuse);
  848. TlsCertificateFile = Storage->ReadString(L"TlsCertificateFile", TlsCertificateFile);
  849. FtpProxyLogonType = Storage->ReadInteger(L"FtpProxyLogonType", FtpProxyLogonType);
  850. MinTlsVersion = static_cast<TTlsVersion>(Storage->ReadInteger(L"MinTlsVersion", MinTlsVersion));
  851. MaxTlsVersion = static_cast<TTlsVersion>(Storage->ReadInteger(L"MaxTlsVersion", MaxTlsVersion));
  852. LOAD_PASSWORD(EncryptKey, L"EncryptKeyPlain");
  853. WebDavLiberalEscaping = Storage->ReadBool(L"WebDavLiberalEscaping", WebDavLiberalEscaping);
  854. IsWorkspace = Storage->ReadBool(L"IsWorkspace", IsWorkspace);
  855. Link = Storage->ReadString(L"Link", Link);
  856. NameOverride = Storage->ReadString(L"NameOverride", NameOverride);
  857. PuttySettings = Storage->ReadString(L"PuttySettings", PuttySettings);
  858. CustomParam1 = Storage->ReadString(L"CustomParam1", CustomParam1);
  859. CustomParam2 = Storage->ReadString(L"CustomParam2", CustomParam2);
  860. #undef LOAD_PASSWORD
  861. #ifdef TEST
  862. #define KEX_TEST(VALUE, EXPECTED) KexList = VALUE; DebugAssert(KexList == EXPECTED);
  863. #define KEX_DEFAULT L"ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1"
  864. // Empty source should result in default list
  865. KEX_TEST(L"", KEX_DEFAULT);
  866. // Default of pre 5.8.1
  867. KEX_TEST(L"dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN", L"ecdh,dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN");
  868. // Missing first two priority algos, and last non-priority algo
  869. KEX_TEST(L"dh-group14-sha1,dh-group1-sha1,WARN", L"ecdh,dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN");
  870. // Missing first two priority algos, last non-priority algo and WARN
  871. KEX_TEST(L"dh-group14-sha1,dh-group1-sha1", L"ecdh,dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,rsa,WARN");
  872. // Old algos, with all but the first below WARN
  873. KEX_TEST(L"dh-gex-sha1,WARN,dh-group14-sha1,dh-group1-sha1,rsa", L"ecdh,dh-gex-sha1,WARN,dh-group14-sha1,dh-group1-sha1,rsa");
  874. // Unknown algo at front
  875. KEX_TEST(L"unknown,ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1", KEX_DEFAULT);
  876. // Unknown algo at back
  877. KEX_TEST(L"ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1,unknown", KEX_DEFAULT);
  878. // Unknown algo in the middle
  879. KEX_TEST(L"ecdh,dh-gex-sha1,dh-group14-sha1,unknown,rsa,WARN,dh-group1-sha1", KEX_DEFAULT);
  880. #undef KEX_DEFAULT
  881. #undef KEX_TEST
  882. #define CIPHER_TEST(VALUE, EXPECTED) CipherList = VALUE; DebugAssert(CipherList == EXPECTED);
  883. #define CIPHER_DEFAULT L"aes,chacha20,blowfish,3des,WARN,arcfour,des"
  884. // Empty source should result in default list
  885. CIPHER_TEST(L"", CIPHER_DEFAULT);
  886. // Default of pre 5.8.1
  887. CIPHER_TEST(L"aes,blowfish,3des,WARN,arcfour,des", L"aes,blowfish,3des,chacha20,WARN,arcfour,des");
  888. // Missing priority algo
  889. CIPHER_TEST(L"chacha20,blowfish,3des,WARN,arcfour,des", CIPHER_DEFAULT);
  890. // Missing non-priority algo
  891. CIPHER_TEST(L"aes,chacha20,3des,WARN,arcfour,des", L"aes,chacha20,3des,blowfish,WARN,arcfour,des");
  892. // Missing last warn algo
  893. CIPHER_TEST(L"aes,blowfish,chacha20,3des,WARN,arcfour", L"aes,blowfish,chacha20,3des,WARN,arcfour,des");
  894. // Missing first warn algo
  895. CIPHER_TEST(L"aes,blowfish,chacha20,3des,WARN,des", L"aes,blowfish,chacha20,3des,WARN,des,arcfour");
  896. #undef CIPHER_DEFAULT
  897. #undef CIPHER_TEST
  898. #define HOSTKEY_TEST(VALUE, EXPECTED) HostKeyList = VALUE; DebugAssert(HostKeyList == EXPECTED);
  899. #define HOSTKEY_DEFAULT L"ed25519,ecdsa,rsa,dsa,WARN"
  900. // Empty source should result in default list
  901. HOSTKEY_TEST(L"", HOSTKEY_DEFAULT);
  902. // Missing priority algo
  903. HOSTKEY_TEST(L"ecdsa,rsa,dsa,WARN", HOSTKEY_DEFAULT);
  904. // Missing non-priority algo
  905. HOSTKEY_TEST(L"ed25519,ecdsa,dsa,WARN", L"ed25519,ecdsa,dsa,rsa,WARN");
  906. #undef HOSTKEY_DEFAULT
  907. #undef HOSTKEY_TEST
  908. #endif
  909. }
  910. //---------------------------------------------------------------------
  911. void __fastcall TSessionData::Load(THierarchicalStorage * Storage, bool PuttyImport)
  912. {
  913. bool RewritePassword = false;
  914. if (Storage->OpenSubKey(InternalStorageKey, False))
  915. {
  916. // In case we are re-loading, reset passwords, to avoid pointless
  917. // re-cryption, while loading username/hostname. And moreover, when
  918. // the password is wrongly encrypted (using a different master password),
  919. // this breaks sites reload and consequently an overal operation,
  920. // such as opening Sites menu
  921. ClearSessionPasswords();
  922. FProxyPassword = L"";
  923. DoLoad(Storage, PuttyImport, RewritePassword, false);
  924. Storage->CloseSubKey();
  925. }
  926. if (RewritePassword)
  927. {
  928. TStorageAccessMode AccessMode = Storage->AccessMode;
  929. Storage->AccessMode = smReadWrite;
  930. try
  931. {
  932. if (Storage->OpenSubKey(InternalStorageKey, true))
  933. {
  934. #define REWRITE_PASSWORD(PROP, PLAIN_NAME) \
  935. Storage->DeleteValue(PLAIN_NAME); \
  936. if (!PROP.IsEmpty()) \
  937. { \
  938. Storage->WriteBinaryDataAsString(TEXT(#PROP), F##PROP); \
  939. }
  940. REWRITE_PASSWORD(Password, L"PasswordPlain");
  941. REWRITE_PASSWORD(TunnelPassword, L"TunnelPasswordPlain");
  942. REWRITE_PASSWORD(EncryptKey, L"EncryptKeyPlain");
  943. REWRITE_PASSWORD(TunnelPassphrase, L"TunnelPassphrasePlain");
  944. #undef REWRITE_PASSWORD
  945. Storage->CloseSubKey();
  946. }
  947. }
  948. catch(...)
  949. {
  950. // ignore errors (like read-only INI file)
  951. }
  952. Storage->AccessMode = AccessMode;
  953. }
  954. FModified = false;
  955. FSource = ssStored;
  956. }
  957. //---------------------------------------------------------------------
  958. void __fastcall TSessionData::DoSave(THierarchicalStorage * Storage,
  959. bool PuttyExport, const TSessionData * Default, bool DoNotEncryptPasswords)
  960. {
  961. // Same as in TCopyParamType::Save
  962. #define WRITE_DATA_EX(TYPE, NAME, PROPERTY, CONV) \
  963. if ((Default != NULL) && (CONV(Default->PROPERTY) == CONV(PROPERTY))) \
  964. { \
  965. Storage->DeleteValue(NAME); \
  966. } \
  967. else \
  968. { \
  969. Storage->Write ## TYPE(NAME, CONV(PROPERTY)); \
  970. }
  971. #define WRITE_DATA_CONV(TYPE, NAME, PROPERTY) WRITE_DATA_EX(TYPE, NAME, PROPERTY, WRITE_DATA_CONV_FUNC)
  972. #define WRITE_DATA(TYPE, PROPERTY) WRITE_DATA_EX(TYPE, TEXT(#PROPERTY), PROPERTY, )
  973. WRITE_DATA(String, HostName);
  974. WRITE_DATA(Integer, PortNumber);
  975. WRITE_DATA_EX(Integer, L"PingInterval", PingInterval / SecsPerMin, );
  976. WRITE_DATA_EX(Integer, L"PingIntervalSecs", PingInterval % SecsPerMin, );
  977. Storage->DeleteValue(L"PingIntervalSec"); // obsolete
  978. WRITE_DATA(Integer, PingType);
  979. WRITE_DATA(Integer, Timeout);
  980. WRITE_DATA(Bool, TryAgent);
  981. WRITE_DATA(Bool, AgentFwd);
  982. WRITE_DATA(Bool, AuthKI);
  983. WRITE_DATA(Bool, AuthKIPassword);
  984. WRITE_DATA_EX(String, L"SshHostKey", HostKey, );
  985. WRITE_DATA(String, Note);
  986. WRITE_DATA(Bool, AuthGSSAPI);
  987. WRITE_DATA(Bool, AuthGSSAPIKEX);
  988. WRITE_DATA(Bool, GSSAPIFwdTGT);
  989. Storage->DeleteValue(L"TryGSSKEX");
  990. Storage->DeleteValue(L"UserNameFromEnvironment");
  991. Storage->DeleteValue("GSSAPIServerChoosesUserName");
  992. Storage->DeleteValue(L"GSSAPITrustDNS");
  993. WRITE_DATA(String, LogicalHostName);
  994. if (PuttyExport)
  995. {
  996. // duplicate kerberos setting with keys of the vintela quest putty
  997. WRITE_DATA_EX(Bool, L"AuthSSPI", AuthGSSAPI, );
  998. WRITE_DATA_EX(Bool, L"SSPIFwdTGT", GSSAPIFwdTGT, );
  999. WRITE_DATA_EX(String, L"KerbPrincipal", LogicalHostName, );
  1000. // duplicate kerberos setting with keys of the official putty
  1001. WRITE_DATA_EX(Bool, L"GssapiFwd", GSSAPIFwdTGT, );
  1002. }
  1003. WRITE_DATA(Bool, ChangeUsername);
  1004. WRITE_DATA(Bool, Compression);
  1005. WRITE_DATA(Bool, Ssh2DES);
  1006. WRITE_DATA(Bool, SshNoUserAuth);
  1007. WRITE_DATA_EX(String, L"Cipher", CipherList, );
  1008. WRITE_DATA_EX(String, L"KEX", KexList, );
  1009. WRITE_DATA_EX(String, L"HostKey", HostKeyList, );
  1010. WRITE_DATA_EX(String, L"GSSLibs", GssLibList, );
  1011. WRITE_DATA_EX(String, L"GSSCustom", GssLibCustom, );
  1012. WRITE_DATA(Integer, AddressFamily);
  1013. WRITE_DATA_EX(String, L"RekeyBytes", RekeyData, );
  1014. WRITE_DATA(Integer, RekeyTime);
  1015. WRITE_DATA(Bool, TcpNoDelay);
  1016. if (PuttyExport)
  1017. {
  1018. WRITE_DATA(StringRaw, UserName);
  1019. // PuTTY is started in its binary directory to allow relative paths when opening PuTTY's own stored session.
  1020. // To allow relative paths in our sessions, we have to expand them for PuTTY.
  1021. WRITE_DATA_EX(StringRaw, L"PublicKeyFile", PublicKeyFile, ExpandFileName);
  1022. }
  1023. else
  1024. {
  1025. WRITE_DATA(String, UserName);
  1026. WRITE_DATA(String, PublicKeyFile);
  1027. WRITE_DATA(Integer, FSProtocol);
  1028. WRITE_DATA(String, LocalDirectory);
  1029. WRITE_DATA(String, OtherLocalDirectory);
  1030. WRITE_DATA(String, RemoteDirectory);
  1031. WRITE_DATA(Bool, SynchronizeBrowsing);
  1032. WRITE_DATA(Bool, UpdateDirectories);
  1033. WRITE_DATA(Bool, CacheDirectories);
  1034. WRITE_DATA(Bool, CacheDirectoryChanges);
  1035. WRITE_DATA(Bool, PreserveDirectoryChanges);
  1036. WRITE_DATA(Bool, ResolveSymlinks);
  1037. WRITE_DATA(Bool, FollowDirectorySymlinks);
  1038. WRITE_DATA_EX(Integer, L"ConsiderDST", DSTMode, );
  1039. // Special is never stored (if it would, login dialog must be modified not to
  1040. // duplicate Special parameter when Special session is loaded and then stored
  1041. // under different name)
  1042. // WRITE_DATA(Bool, Special);
  1043. WRITE_DATA(String, Shell);
  1044. WRITE_DATA(Bool, ClearAliases);
  1045. WRITE_DATA(Bool, UnsetNationalVars);
  1046. WRITE_DATA(String, ListingCommand);
  1047. WRITE_DATA(Bool, IgnoreLsWarnings);
  1048. WRITE_DATA(Integer, SCPLsFullTime);
  1049. WRITE_DATA(Bool, Scp1Compatibility);
  1050. // TimeDifferenceAuto is valid for FTP protocol only.
  1051. // For other protocols it's typically true (default value),
  1052. // but ignored so TimeDifference is still taken into account (SCP only actually)
  1053. if (TimeDifferenceAuto && (FSProtocol == fsFTP))
  1054. {
  1055. // Have to delete it as TimeDifferenceAuto is not saved when enabled,
  1056. // but the default is derived from value of TimeDifference.
  1057. Storage->DeleteValue(L"TimeDifference");
  1058. }
  1059. else
  1060. {
  1061. WRITE_DATA(Float, TimeDifference);
  1062. }
  1063. WRITE_DATA(Bool, TimeDifferenceAuto);
  1064. WRITE_DATA(Bool, DeleteToRecycleBin);
  1065. WRITE_DATA(Bool, OverwrittenToRecycleBin);
  1066. WRITE_DATA(String, RecycleBinPath);
  1067. WRITE_DATA(String, PostLoginCommands);
  1068. WRITE_DATA(String, ReturnVar);
  1069. WRITE_DATA(Bool, ExitCode1IsError);
  1070. WRITE_DATA_EX(Integer, L"LookupUserGroups2", LookupUserGroups, );
  1071. WRITE_DATA(Integer, EOLType);
  1072. WRITE_DATA(Bool, TrimVMSVersions);
  1073. WRITE_DATA(Bool, VMSAllRevisions);
  1074. Storage->DeleteValue(L"SFTPUtfBug");
  1075. WRITE_DATA_EX(Integer, L"Utf", NotUtf, );
  1076. WRITE_DATA(Integer, InternalEditorEncoding);
  1077. WRITE_DATA(String, S3DefaultRegion);
  1078. WRITE_DATA(String, S3SessionToken);
  1079. WRITE_DATA(Integer, S3UrlStyle);
  1080. WRITE_DATA(Integer, S3MaxKeys);
  1081. WRITE_DATA(Bool, S3CredentialsEnv);
  1082. WRITE_DATA(Integer, SendBuf);
  1083. WRITE_DATA(String, SourceAddress);
  1084. WRITE_DATA(String, ProtocolFeatures);
  1085. WRITE_DATA(Bool, SshSimple);
  1086. }
  1087. WRITE_DATA(Integer, ProxyMethod);
  1088. WRITE_DATA(String, ProxyHost);
  1089. WRITE_DATA(Integer, ProxyPort);
  1090. WRITE_DATA(String, ProxyUsername);
  1091. if (ProxyMethod == pmCmd)
  1092. {
  1093. WRITE_DATA_EX(StringRaw, L"ProxyTelnetCommand", ProxyLocalCommand, );
  1094. }
  1095. else
  1096. {
  1097. WRITE_DATA(StringRaw, ProxyTelnetCommand);
  1098. }
  1099. #define WRITE_DATA_CONV_FUNC(X) (((X) + 2) % 3)
  1100. WRITE_DATA_CONV(Integer, L"ProxyDNS", ProxyDNS);
  1101. #undef WRITE_DATA_CONV_FUNC
  1102. WRITE_DATA(Bool, ProxyLocalhost);
  1103. #define WRITE_DATA_CONV_FUNC(X) (2 - (X))
  1104. #define WRITE_BUG(BUG) WRITE_DATA_CONV(Integer, L"Bug" #BUG, Bug[sb##BUG]);
  1105. WRITE_BUG(HMAC2);
  1106. WRITE_BUG(DeriveKey2);
  1107. WRITE_BUG(RSAPad2);
  1108. WRITE_BUG(PKSessID2);
  1109. WRITE_BUG(Rekey2);
  1110. WRITE_BUG(MaxPkt2);
  1111. WRITE_BUG(Ignore2);
  1112. WRITE_BUG(OldGex2);
  1113. WRITE_BUG(WinAdj);
  1114. WRITE_BUG(ChanReq);
  1115. #undef WRITE_BUG
  1116. #undef WRITE_DATA_CONV_FUNC
  1117. Storage->DeleteValue(L"BuggyMAC");
  1118. Storage->DeleteValue(L"AliasGroupList");
  1119. if (PuttyExport)
  1120. {
  1121. WRITE_DATA_EX(String, L"Protocol", GetNormalizedPuttyProtocol(), );
  1122. WRITE_DATA(String, WinTitle);
  1123. }
  1124. if (!PuttyExport)
  1125. {
  1126. WRITE_DATA(String, SftpServer);
  1127. #define WRITE_SFTP_BUG(BUG) WRITE_DATA_EX(Integer, L"SFTP" #BUG "Bug", SFTPBug[sb##BUG], );
  1128. WRITE_SFTP_BUG(Symlink);
  1129. WRITE_SFTP_BUG(SignedTS);
  1130. #undef WRITE_SFTP_BUG
  1131. WRITE_DATA(Integer, SFTPMaxVersion);
  1132. WRITE_DATA(Integer, SFTPMaxPacketSize);
  1133. WRITE_DATA(Integer, SFTPDownloadQueue);
  1134. WRITE_DATA(Integer, SFTPUploadQueue);
  1135. WRITE_DATA(Integer, SFTPListingQueue);
  1136. WRITE_DATA(Integer, SFTPRealPath);
  1137. WRITE_DATA(Integer, Color);
  1138. WRITE_DATA(Bool, Tunnel);
  1139. WRITE_DATA(String, TunnelHostName);
  1140. WRITE_DATA(Integer, TunnelPortNumber);
  1141. WRITE_DATA(String, TunnelUserName);
  1142. WRITE_DATA(String, TunnelPublicKeyFile);
  1143. WRITE_DATA(Integer, TunnelLocalPortNumber);
  1144. WRITE_DATA(String, TunnelHostKey);
  1145. WRITE_DATA(Bool, FtpPasvMode);
  1146. WRITE_DATA_EX(Integer, L"FtpForcePasvIp2", FtpForcePasvIp, );
  1147. WRITE_DATA(Integer, FtpUseMlsd);
  1148. WRITE_DATA(String, FtpAccount);
  1149. WRITE_DATA(Integer, FtpPingInterval);
  1150. WRITE_DATA(Integer, FtpPingType);
  1151. WRITE_DATA_EX(Integer, L"FtpTransferActiveImmediately2", FtpTransferActiveImmediately, );
  1152. WRITE_DATA(Integer, Ftps);
  1153. WRITE_DATA(Integer, FtpListAll);
  1154. WRITE_DATA(Integer, FtpHost);
  1155. WRITE_DATA(Integer, FtpWorkFromCwd);
  1156. WRITE_DATA(Bool, SslSessionReuse);
  1157. WRITE_DATA(String, TlsCertificateFile);
  1158. WRITE_DATA(Integer, FtpProxyLogonType);
  1159. WRITE_DATA(Integer, MinTlsVersion);
  1160. WRITE_DATA(Integer, MaxTlsVersion);
  1161. WRITE_DATA(Bool, WebDavLiberalEscaping);
  1162. WRITE_DATA(Bool, IsWorkspace);
  1163. WRITE_DATA(String, Link);
  1164. WRITE_DATA(String, NameOverride);
  1165. WRITE_DATA(String, PuttySettings);
  1166. WRITE_DATA(String, CustomParam1);
  1167. WRITE_DATA(String, CustomParam2);
  1168. }
  1169. // This is for collecting all keys for TSiteRawDialog::AddButtonClick.
  1170. // It should be enough to test for (Default == NULL),
  1171. // the DoNotEncryptPasswords and PuttyExport were added to limit a possible unintended impact.
  1172. bool SaveAll = (Default == NULL) && DoNotEncryptPasswords && !PuttyExport;
  1173. SavePasswords(Storage, PuttyExport, DoNotEncryptPasswords, SaveAll);
  1174. if (PuttyExport)
  1175. {
  1176. WritePuttySettings(Storage, PuttySettings);
  1177. }
  1178. }
  1179. //---------------------------------------------------------------------
  1180. TStrings * __fastcall TSessionData::SaveToOptions(const TSessionData * Default, bool SaveName, bool PuttyExport)
  1181. {
  1182. std::unique_ptr<TStringList> Options(new TStringList());
  1183. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  1184. if (SaveName)
  1185. {
  1186. OptionsStorage->WriteString(L"Name", Name);
  1187. }
  1188. DoSave(OptionsStorage.get(), PuttyExport, Default, true);
  1189. return Options.release();
  1190. }
  1191. //---------------------------------------------------------------------
  1192. void __fastcall TSessionData::Save(THierarchicalStorage * Storage,
  1193. bool PuttyExport, const TSessionData * Default)
  1194. {
  1195. if (Storage->OpenSubKey(InternalStorageKey, true))
  1196. {
  1197. DoSave(Storage, PuttyExport, Default, false);
  1198. Storage->CloseSubKey();
  1199. }
  1200. }
  1201. //---------------------------------------------------------------------
  1202. UnicodeString __fastcall TSessionData::ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default)
  1203. {
  1204. _di_IXMLNode TheNode = Node->ChildNodes->FindNode(Name);
  1205. UnicodeString Result;
  1206. if (TheNode != NULL)
  1207. {
  1208. Result = TheNode->Text.Trim();
  1209. }
  1210. if (Result.IsEmpty())
  1211. {
  1212. Result = Default;
  1213. }
  1214. return Result;
  1215. }
  1216. //---------------------------------------------------------------------
  1217. int __fastcall TSessionData::ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, int Default)
  1218. {
  1219. _di_IXMLNode TheNode = Node->ChildNodes->FindNode(Name);
  1220. int Result;
  1221. if (TheNode != NULL)
  1222. {
  1223. Result = StrToIntDef(TheNode->Text.Trim(), Default);
  1224. }
  1225. else
  1226. {
  1227. Result = Default;
  1228. }
  1229. return Result;
  1230. }
  1231. //---------------------------------------------------------------------
  1232. _di_IXMLNode __fastcall TSessionData::FindSettingsNode(_di_IXMLNode Node, const UnicodeString & Name)
  1233. {
  1234. for (int Index = 0; Index < Node->ChildNodes->Count; Index++)
  1235. {
  1236. _di_IXMLNode ChildNode = Node->ChildNodes->Get(Index);
  1237. if (ChildNode->NodeName == L"Setting")
  1238. {
  1239. OleVariant SettingName = ChildNode->GetAttribute(L"name");
  1240. if (SettingName == Name)
  1241. {
  1242. return ChildNode;
  1243. }
  1244. }
  1245. }
  1246. return NULL;
  1247. }
  1248. //---------------------------------------------------------------------
  1249. UnicodeString __fastcall TSessionData::ReadSettingsNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default)
  1250. {
  1251. _di_IXMLNode TheNode = FindSettingsNode(Node, Name);
  1252. UnicodeString Result;
  1253. if (TheNode != NULL)
  1254. {
  1255. Result = TheNode->Text.Trim();
  1256. }
  1257. if (Result.IsEmpty())
  1258. {
  1259. Result = Default;
  1260. }
  1261. return Result;
  1262. }
  1263. //---------------------------------------------------------------------
  1264. int __fastcall TSessionData::ReadSettingsNode(_di_IXMLNode Node, const UnicodeString & Name, int Default)
  1265. {
  1266. _di_IXMLNode TheNode = FindSettingsNode(Node, Name);
  1267. int Result;
  1268. if (TheNode != NULL)
  1269. {
  1270. Result = StrToIntDef(TheNode->Text.Trim(), Default);
  1271. }
  1272. else
  1273. {
  1274. Result = Default;
  1275. }
  1276. return Result;
  1277. }
  1278. //---------------------------------------------------------------------
  1279. void __fastcall TSessionData::ImportFromFilezilla(
  1280. _di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode)
  1281. {
  1282. Name = UnixIncludeTrailingBackslash(Path) + MakeValidName(ReadXmlNode(Node, L"Name", Name));
  1283. HostName = ReadXmlNode(Node, L"Host", HostName);
  1284. PortNumber = ReadXmlNode(Node, L"Port", PortNumber);
  1285. int AProtocol = ReadXmlNode(Node, L"Protocol", 0);
  1286. // ServerProtocol enum
  1287. switch (AProtocol)
  1288. {
  1289. case 0: // FTP
  1290. default: // UNKNOWN, HTTP, HTTPS, INSECURE_FTP
  1291. FSProtocol = fsFTP;
  1292. break;
  1293. case 1: // SFTP
  1294. FSProtocol = fsSFTP;
  1295. break;
  1296. case 3: // FTPS
  1297. FSProtocol = fsFTP;
  1298. Ftps = ftpsImplicit;
  1299. break;
  1300. case 4: // FTPES
  1301. FSProtocol = fsFTP;
  1302. Ftps = ftpsExplicitTls;
  1303. break;
  1304. }
  1305. // LogonType enum
  1306. int LogonType = ReadXmlNode(Node, L"Logontype", 0);
  1307. if (LogonType == 0) // ANONYMOUS
  1308. {
  1309. UserName = AnonymousUserName;
  1310. Password = AnonymousPassword;
  1311. }
  1312. else
  1313. {
  1314. UserName = ReadXmlNode(Node, L"User", UserName);
  1315. FtpAccount = ReadXmlNode(Node, L"Account", FtpAccount);
  1316. _di_IXMLNode PassNode = Node->ChildNodes->FindNode(L"Pass");
  1317. if (PassNode != NULL)
  1318. {
  1319. UnicodeString APassword = PassNode->Text.Trim();
  1320. OleVariant EncodingValue = PassNode->GetAttribute(L"encoding");
  1321. if (!EncodingValue.IsNull())
  1322. {
  1323. UnicodeString EncodingValueStr = EncodingValue;
  1324. if (SameText(EncodingValueStr, L"base64"))
  1325. {
  1326. TBytes Bytes = DecodeBase64(APassword);
  1327. APassword = TEncoding::UTF8->GetString(Bytes);
  1328. }
  1329. }
  1330. Password = APassword;
  1331. }
  1332. }
  1333. PublicKeyFile = ReadXmlNode(Node, L"Keyfile", PublicKeyFile);
  1334. int DefaultTimeDifference = TimeToSeconds(TimeDifference);
  1335. TimeDifference =
  1336. (double(ReadXmlNode(Node, L"TimezoneOffset", DefaultTimeDifference) / SecsPerDay));
  1337. TimeDifferenceAuto = (TimeDifference == TDateTime());
  1338. UnicodeString PasvMode = ReadXmlNode(Node, L"PasvMode", L"");
  1339. if (SameText(PasvMode, L"MODE_PASSIVE"))
  1340. {
  1341. FtpPasvMode = true;
  1342. }
  1343. else if (SameText(PasvMode, L"MODE_ACTIVE"))
  1344. {
  1345. FtpPasvMode = false;
  1346. }
  1347. else if (SettingsNode != NULL)
  1348. {
  1349. int PasvMode = ReadSettingsNode(SettingsNode, L"Use Pasv mode", 1);
  1350. FtpPasvMode = (PasvMode != 0);
  1351. }
  1352. UnicodeString EncodingType = ReadXmlNode(Node, L"EncodingType", L"");
  1353. if (SameText(EncodingType, L"Auto"))
  1354. {
  1355. NotUtf = asAuto;
  1356. }
  1357. else if (SameText(EncodingType, L"UTF-8"))
  1358. {
  1359. NotUtf = asOff;
  1360. }
  1361. // todo PostLoginCommands
  1362. Note = ReadXmlNode(Node, L"Comments", Note);
  1363. LocalDirectory = ReadXmlNode(Node, L"LocalDir", LocalDirectory);
  1364. UnicodeString RemoteDir = ReadXmlNode(Node, L"RemoteDir", L"");
  1365. if (!RemoteDir.IsEmpty())
  1366. {
  1367. CutToChar(RemoteDir, L' ', false); // type
  1368. int PrefixSize = StrToIntDef(CutToChar(RemoteDir, L' ', false), 0); // prefix size
  1369. if (PrefixSize > 0)
  1370. {
  1371. RemoteDir.Delete(1, PrefixSize);
  1372. }
  1373. RemoteDirectory = L"/";
  1374. while (!RemoteDir.IsEmpty())
  1375. {
  1376. int SegmentSize = StrToIntDef(CutToChar(RemoteDir, L' ', false), 0);
  1377. UnicodeString Segment = RemoteDir.SubString(1, SegmentSize);
  1378. RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory) + Segment;
  1379. RemoteDir.Delete(1, SegmentSize + 1);
  1380. }
  1381. }
  1382. SynchronizeBrowsing = (ReadXmlNode(Node, L"SyncBrowsing", SynchronizeBrowsing ? 1 : 0) != 0);
  1383. if (SettingsNode != NULL)
  1384. {
  1385. if (UsesSsh && PublicKeyFile.IsEmpty())
  1386. {
  1387. UnicodeString KeyFiles = ReadSettingsNode(SettingsNode, L"SFTP keyfiles", UnicodeString());
  1388. UnicodeString KeyFile = CutToChar(KeyFiles, L'\n', true).Trim();
  1389. KeyFiles = KeyFiles.Trim();
  1390. // If there are more keys, ignore them, as we do not know which one to use
  1391. if (!KeyFile.IsEmpty() && KeyFiles.IsEmpty())
  1392. {
  1393. PublicKeyFile = KeyFile;
  1394. }
  1395. }
  1396. bool BypassProxy = (ReadXmlNode(Node, L"BypassProxy", 0) != 0);
  1397. if (!BypassProxy)
  1398. {
  1399. int FtpProxyType = ReadSettingsNode(SettingsNode, L"FTP Proxy type", -1);
  1400. if (FtpProxyType > 0)
  1401. {
  1402. switch (FtpProxyType)
  1403. {
  1404. case 1:
  1405. FtpProxyLogonType = 2;
  1406. break;
  1407. case 2:
  1408. FtpProxyLogonType = 1;
  1409. break;
  1410. case 3:
  1411. FtpProxyLogonType = 3;
  1412. break;
  1413. case 4:
  1414. // custom
  1415. // TODO: map known sequences to our enumeration
  1416. FtpProxyLogonType = 0;
  1417. break;
  1418. default:
  1419. DebugFail();
  1420. FtpProxyLogonType = 0;
  1421. break;
  1422. }
  1423. ProxyHost = ReadSettingsNode(SettingsNode, L"FTP Proxy host", ProxyHost);
  1424. ProxyUsername = ReadSettingsNode(SettingsNode, L"FTP Proxy user", ProxyUsername);
  1425. ProxyPassword = ReadSettingsNode(SettingsNode, L"FTP Proxy password", ProxyPassword);
  1426. // ProxyPort is not used with FtpProxyLogonType
  1427. }
  1428. else
  1429. {
  1430. int ProxyType = ReadSettingsNode(SettingsNode, L"Proxy type", -1);
  1431. if (ProxyType >= 0)
  1432. {
  1433. switch (ProxyType)
  1434. {
  1435. case 0:
  1436. ProxyMethod = ::pmNone;
  1437. break;
  1438. case 1:
  1439. ProxyMethod = pmHTTP;
  1440. break;
  1441. case 2:
  1442. ProxyMethod = pmSocks5;
  1443. break;
  1444. case 3:
  1445. ProxyMethod = pmSocks4;
  1446. break;
  1447. default:
  1448. DebugFail();
  1449. ProxyMethod = ::pmNone;
  1450. break;
  1451. }
  1452. ProxyHost = ReadSettingsNode(SettingsNode, L"Proxy host", ProxyHost);
  1453. ProxyPort = ReadSettingsNode(SettingsNode, L"Proxy port", ProxyPort);
  1454. ProxyUsername = ReadSettingsNode(SettingsNode, L"Proxy user", ProxyUsername);
  1455. ProxyPassword = ReadSettingsNode(SettingsNode, L"Proxy password", ProxyPassword);
  1456. }
  1457. }
  1458. }
  1459. }
  1460. }
  1461. //---------------------------------------------------------------------
  1462. bool OpensshBoolValue(const UnicodeString & Value)
  1463. {
  1464. return SameText(Value, L"yes");
  1465. }
  1466. //---------------------------------------------------------------------
  1467. UnicodeString CutOpensshToken(UnicodeString & S)
  1468. {
  1469. DebugAssert(!S.IsEmpty() && (S == Trim(S)));
  1470. int From = 1;
  1471. UnicodeString Result = CopyToChars(S, From, L" \t", false);
  1472. S.Delete(1, Result.Length());
  1473. S = Trim(S);
  1474. DebugAssert(!Result.IsEmpty() && (Result == Trim(Result)));
  1475. Result = Trim(Result);
  1476. return Result;
  1477. }
  1478. //---------------------------------------------------------------------
  1479. void TSessionData::ImportFromOpenssh(TStrings * Lines)
  1480. {
  1481. bool SkippingSection = false;
  1482. std::unique_ptr<TStrings> UsedDirectives(CreateSortedStringList());
  1483. for (int Index = 0; Index < Lines->Count; Index++)
  1484. {
  1485. UnicodeString Line = Lines->Strings[Index];
  1486. UnicodeString Directive, Value;
  1487. if (ParseOpensshDirective(Line, Directive, Value))
  1488. {
  1489. if (SameText(Directive, OpensshHostDirective))
  1490. {
  1491. DebugAssert(!Value.IsEmpty() && (Value == Trim(Value)));
  1492. SkippingSection = true;
  1493. while (!Value.IsEmpty())
  1494. {
  1495. UnicodeString M = CutOpensshToken(Value);
  1496. bool Negated = DebugAlwaysTrue(!M.IsEmpty()) && (M[1] == L'!');
  1497. if (Negated)
  1498. {
  1499. M.Delete(1, 1);
  1500. }
  1501. TFileMasks Mask;
  1502. Mask.SetMask(M);
  1503. // This does way more than OpenSSH, but on the other hand, the special characters of our file masks,
  1504. // should not be present in hostnames.
  1505. if (Mask.Matches(Name, false, UnicodeString(), NULL))
  1506. {
  1507. if (Negated)
  1508. {
  1509. // Skip even if matched by other possitive patterns
  1510. SkippingSection = true;
  1511. break;
  1512. }
  1513. else
  1514. {
  1515. // Keep looking, in case if negated
  1516. SkippingSection = false;
  1517. }
  1518. }
  1519. }
  1520. }
  1521. else if (SameText(Directive, L"Match"))
  1522. {
  1523. SkippingSection = true;
  1524. }
  1525. else if (!SkippingSection && (UsedDirectives->IndexOf(Directive) < 0))
  1526. {
  1527. if (SameText(Directive, L"AddressFamily"))
  1528. {
  1529. if (SameText(Value, L"inet"))
  1530. {
  1531. AddressFamily = afIPv4;
  1532. }
  1533. else if (SameText(Value, L"inet6"))
  1534. {
  1535. AddressFamily = afIPv6;
  1536. }
  1537. else
  1538. {
  1539. AddressFamily = afAuto;
  1540. }
  1541. }
  1542. else if (SameText(Directive, L"BindAddress"))
  1543. {
  1544. SourceAddress = Value;
  1545. }
  1546. else if (SameText(Directive, L"Compression"))
  1547. {
  1548. Compression = OpensshBoolValue(Value);
  1549. }
  1550. else if (SameText(Directive, L"ForwardAgent"))
  1551. {
  1552. AgentFwd = OpensshBoolValue(Value);
  1553. }
  1554. else if (SameText(Directive, L"GSSAPIAuthentication"))
  1555. {
  1556. AuthGSSAPI = OpensshBoolValue(Value);
  1557. }
  1558. else if (SameText(Directive, L"GSSAPIDelegateCredentials"))
  1559. {
  1560. AuthGSSAPIKEX = OpensshBoolValue(Value);
  1561. }
  1562. else if (SameText(Directive, L"Hostname"))
  1563. {
  1564. HostName = Value;
  1565. }
  1566. else if (SameText(Directive, L"IdentityFile"))
  1567. {
  1568. // It's likely there would be forward slashes in OpenSSH config file and our load/save dialogs
  1569. // (e.g. when converting keys) work suboptimally when working with forward slashes.
  1570. PublicKeyFile = GetNormalizedPath(Value);
  1571. }
  1572. else if (SameText(Directive, L"KbdInteractiveAuthentication"))
  1573. {
  1574. AuthKI = OpensshBoolValue(Value);
  1575. }
  1576. else if (SameText(Directive, L"Port"))
  1577. {
  1578. PortNumber = StrToInt(Value);
  1579. }
  1580. else if (SameText(Directive, L"User"))
  1581. {
  1582. UserName = Value;
  1583. }
  1584. else if (SameText(Directive, L"ProxyJump"))
  1585. {
  1586. UnicodeString Jump = Value;
  1587. // multiple jumps are not supported
  1588. if (Jump.Pos(L",") == 0)
  1589. {
  1590. std::unique_ptr<TSessionData> JumpData(new TSessionData(EmptyStr));
  1591. bool DefaultsOnly;
  1592. if ((JumpData->ParseUrl(Jump, NULL, NULL, DefaultsOnly, NULL, NULL, NULL, 0)) &&
  1593. !JumpData->HostName.IsEmpty())
  1594. {
  1595. JumpData->Name = JumpData->HostName;
  1596. JumpData->ImportFromOpenssh(Lines);
  1597. Tunnel = true;
  1598. TunnelHostName = JumpData->HostName;
  1599. TunnelPortNumber = JumpData->PortNumber;
  1600. TunnelUserName = JumpData->UserName;
  1601. TunnelPassword = JumpData->Password;
  1602. TunnelPublicKeyFile = JumpData->PublicKeyFile;
  1603. }
  1604. }
  1605. }
  1606. UsedDirectives->Add(Directive);
  1607. }
  1608. }
  1609. }
  1610. }
  1611. //---------------------------------------------------------------------
  1612. void __fastcall TSessionData::SavePasswords(THierarchicalStorage * Storage, bool PuttyExport, bool DoNotEncryptPasswords, bool SaveAll)
  1613. {
  1614. // It's probably safe to replace this with if (!PuttyExport) { SAVE_PASSWORD(...) }
  1615. if (!Configuration->DisablePasswordStoring && !PuttyExport && (!FPassword.IsEmpty() || SaveAll))
  1616. {
  1617. if (DoNotEncryptPasswords)
  1618. {
  1619. Storage->WriteString(L"PasswordPlain", Password);
  1620. Storage->DeleteValue(L"Password");
  1621. }
  1622. else
  1623. {
  1624. Storage->WriteBinaryDataAsString(L"Password", StronglyRecryptPassword(FPassword, UserName+HostName));
  1625. Storage->DeleteValue(L"PasswordPlain");
  1626. }
  1627. }
  1628. else
  1629. {
  1630. Storage->DeleteValue(L"Password");
  1631. Storage->DeleteValue(L"PasswordPlain");
  1632. }
  1633. if (PuttyExport)
  1634. {
  1635. // save password unencrypted
  1636. Storage->WriteString(L"ProxyPassword", ProxyPassword);
  1637. }
  1638. else
  1639. {
  1640. #define SAVE_PASSWORD_EX(PROP, PLAIN_NAME, ENC_NAME, ENC_KEY, COND) \
  1641. if (DoNotEncryptPasswords) \
  1642. { \
  1643. if (!F##PROP.IsEmpty() || SaveAll) \
  1644. { \
  1645. Storage->WriteString(PLAIN_NAME, PROP); \
  1646. } \
  1647. else \
  1648. { \
  1649. Storage->DeleteValue(PLAIN_NAME); \
  1650. } \
  1651. Storage->DeleteValue(ENC_NAME); \
  1652. } \
  1653. else \
  1654. { \
  1655. if (COND && (!F##PROP.IsEmpty() || SaveAll)) \
  1656. { \
  1657. Storage->WriteBinaryDataAsString(ENC_NAME, StronglyRecryptPassword(F##PROP, ENC_KEY)); \
  1658. } \
  1659. else \
  1660. { \
  1661. Storage->DeleteValue(ENC_NAME); \
  1662. } \
  1663. Storage->DeleteValue(PLAIN_NAME); \
  1664. }
  1665. #define SAVE_PASSWORD(PROP, PLAIN_NAME, ENC_KEY) SAVE_PASSWORD_EX(PROP, PLAIN_NAME, TEXT(#PROP), ENC_KEY, !Configuration->DisablePasswordStoring)
  1666. SAVE_PASSWORD_EX(ProxyPassword, L"ProxyPassword", L"ProxyPasswordEnc", ProxyUsername + ProxyHost, true);
  1667. SAVE_PASSWORD(TunnelPassword, L"TunnelPasswordPlain", TunnelUserName + TunnelHostName);
  1668. SAVE_PASSWORD_EX(EncryptKey, L"EncryptKeyPlain", L"EncryptKey", UserName + HostName, true);
  1669. }
  1670. }
  1671. //---------------------------------------------------------------------
  1672. void __fastcall TSessionData::RecryptPasswords()
  1673. {
  1674. Password = Password;
  1675. NewPassword = NewPassword;
  1676. ProxyPassword = ProxyPassword;
  1677. TunnelPassword = TunnelPassword;
  1678. TunnelPassphrase = TunnelPassphrase;
  1679. Passphrase = Passphrase;
  1680. EncryptKey = EncryptKey;
  1681. }
  1682. //---------------------------------------------------------------------
  1683. bool __fastcall TSessionData::HasPassword()
  1684. {
  1685. return !FPassword.IsEmpty();
  1686. }
  1687. //---------------------------------------------------------------------
  1688. bool __fastcall TSessionData::HasAnySessionPassword()
  1689. {
  1690. // Keep in sync with ClearSessionPasswords
  1691. return
  1692. HasPassword() ||
  1693. !FTunnelPassword.IsEmpty() ||
  1694. // will probably be never used
  1695. !FNewPassword.IsEmpty();
  1696. }
  1697. //---------------------------------------------------------------------
  1698. bool __fastcall TSessionData::HasAnyPassword()
  1699. {
  1700. // Keep in sync with MaskPasswords
  1701. return
  1702. HasAnySessionPassword() ||
  1703. !FProxyPassword.IsEmpty() ||
  1704. !FEncryptKey.IsEmpty() ||
  1705. !FPassphrase.IsEmpty() ||
  1706. !FTunnelPassphrase.IsEmpty();
  1707. }
  1708. //---------------------------------------------------------------------
  1709. void __fastcall TSessionData::ClearSessionPasswords()
  1710. {
  1711. // Keep in sync with HasAnySessionPassword
  1712. FPassword = L"";
  1713. FNewPassword = L"";
  1714. FTunnelPassword = L"";
  1715. }
  1716. //---------------------------------------------------------------------
  1717. void __fastcall TSessionData::Modify()
  1718. {
  1719. FModified = true;
  1720. if (FSource == ssStored)
  1721. {
  1722. FSource = ssStoredModified;
  1723. }
  1724. }
  1725. //---------------------------------------------------------------------
  1726. UnicodeString __fastcall TSessionData::GetSource()
  1727. {
  1728. switch (FSource)
  1729. {
  1730. case ::ssNone:
  1731. return L"Ad-Hoc site";
  1732. case ssStored:
  1733. return L"Site";
  1734. case ssStoredModified:
  1735. return L"Modified site";
  1736. default:
  1737. DebugFail();
  1738. return L"";
  1739. }
  1740. }
  1741. //---------------------------------------------------------------------
  1742. void __fastcall TSessionData::SaveRecryptedPasswords(THierarchicalStorage * Storage)
  1743. {
  1744. if (Storage->OpenSubKey(InternalStorageKey, true))
  1745. {
  1746. try
  1747. {
  1748. RecryptPasswords();
  1749. SavePasswords(Storage, false, false, false);
  1750. }
  1751. __finally
  1752. {
  1753. Storage->CloseSubKey();
  1754. }
  1755. }
  1756. }
  1757. //---------------------------------------------------------------------
  1758. void __fastcall TSessionData::Remove(THierarchicalStorage * Storage, const UnicodeString & Name)
  1759. {
  1760. Storage->RecursiveDeleteSubKey(Name);
  1761. }
  1762. //---------------------------------------------------------------------
  1763. void __fastcall TSessionData::Remove()
  1764. {
  1765. bool SessionList = true;
  1766. THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);
  1767. try
  1768. {
  1769. Storage->Explicit = true;
  1770. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, false))
  1771. {
  1772. Remove(Storage, InternalStorageKey);
  1773. }
  1774. }
  1775. __finally
  1776. {
  1777. delete Storage;
  1778. }
  1779. }
  1780. //---------------------------------------------------------------------
  1781. void __fastcall TSessionData::CacheHostKeyIfNotCached()
  1782. {
  1783. UnicodeString KeyType = KeyTypeFromFingerprint(HostKey);
  1784. // Should allow importing to INI file as ImportHostKeys
  1785. UnicodeString TargetKey = Configuration->RegistryStorageKey + L"\\" + Configuration->SshHostKeysSubKey;
  1786. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(TargetKey));
  1787. Storage->AccessMode = smReadWrite;
  1788. if (Storage->OpenRootKey(true))
  1789. {
  1790. UnicodeString HostKeyName = PuttyMungeStr(FORMAT(L"%s@%d:%s", (KeyType, PortNumber, HostName)));
  1791. if (!Storage->ValueExists(HostKeyName))
  1792. {
  1793. // fingerprint is a checksum of a host key, so it cannot be translated back to host key,
  1794. // so we store fingerprint and TSecureShell::VerifyHostKey was
  1795. // modified to accept also fingerprint
  1796. Storage->WriteString(HostKeyName, HostKey);
  1797. }
  1798. }
  1799. }
  1800. //---------------------------------------------------------------------
  1801. inline void __fastcall MoveStr(UnicodeString & Source, UnicodeString * Dest, int Count)
  1802. {
  1803. if (Dest != NULL)
  1804. {
  1805. (*Dest) += Source.SubString(1, Count);
  1806. }
  1807. Source.Delete(1, Count);
  1808. }
  1809. //---------------------------------------------------------------------
  1810. bool __fastcall TSessionData::DoIsProtocolUrl(
  1811. const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen)
  1812. {
  1813. bool Result = SameText(Url.SubString(1, Protocol.Length() + 1), Protocol + L":");
  1814. if (Result)
  1815. {
  1816. ProtocolLen = Protocol.Length() + 1;
  1817. }
  1818. return Result;
  1819. }
  1820. //---------------------------------------------------------------------
  1821. bool __fastcall TSessionData::IsProtocolUrl(
  1822. const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen)
  1823. {
  1824. return
  1825. DoIsProtocolUrl(Url, Protocol, ProtocolLen) ||
  1826. DoIsProtocolUrl(Url, WinSCPProtocolPrefix + Protocol, ProtocolLen);
  1827. }
  1828. //---------------------------------------------------------------------
  1829. bool __fastcall TSessionData::IsSensitiveOption(const UnicodeString & Option)
  1830. {
  1831. return
  1832. SameText(Option, PassphraseOption) ||
  1833. SameText(Option, PASSWORD_SWITCH) ||
  1834. SameText(Option, NEWPASSWORD_SWITCH);
  1835. }
  1836. //---------------------------------------------------------------------
  1837. bool __fastcall TSessionData::IsOptionWithParameters(const UnicodeString & Option)
  1838. {
  1839. return SameText(Option, RawSettingsOption);
  1840. }
  1841. //---------------------------------------------------------------------
  1842. bool __fastcall TSessionData::MaskPasswordInOptionParameter(const UnicodeString & Option, UnicodeString & Param)
  1843. {
  1844. bool Result = false;
  1845. if (SameText(Option, RawSettingsOption))
  1846. {
  1847. int P = Param.Pos(L"=");
  1848. if (P > 0)
  1849. {
  1850. // TStrings.IndexOfName does not trim
  1851. UnicodeString Key = Param.SubString(1, P - 1);
  1852. if (SameText(Key, L"ProxyPassword") ||
  1853. SameText(Key, L"ProxyPasswordEnc") ||
  1854. SameText(Key, L"TunnelPassword") ||
  1855. SameText(Key, L"TunnelPasswordPlain") ||
  1856. SameText(Key, L"TunnelPassphrase") ||
  1857. SameText(Key, L"TunnelPassphrasePlain") ||
  1858. SameText(Key, L"EncryptKey") ||
  1859. SameText(Key, L"EncryptKeyPlain"))
  1860. {
  1861. Param = Key + L"=" + PasswordMask;
  1862. Result = true;
  1863. }
  1864. }
  1865. }
  1866. return Result;
  1867. }
  1868. //---------------------------------------------------------------------
  1869. void __fastcall TSessionData::MaskPasswords()
  1870. {
  1871. // Keep in sync with HasAnyPassword
  1872. if (!Password.IsEmpty())
  1873. {
  1874. Password = PasswordMask;
  1875. }
  1876. if (!NewPassword.IsEmpty())
  1877. {
  1878. NewPassword = PasswordMask;
  1879. }
  1880. if (!ProxyPassword.IsEmpty())
  1881. {
  1882. ProxyPassword = PasswordMask;
  1883. }
  1884. if (!TunnelPassword.IsEmpty())
  1885. {
  1886. TunnelPassword = PasswordMask;
  1887. }
  1888. if (!TunnelPassphrase.IsEmpty())
  1889. {
  1890. TunnelPassphrase = PasswordMask;
  1891. }
  1892. if (!EncryptKey.IsEmpty())
  1893. {
  1894. EncryptKey = PasswordMask;
  1895. }
  1896. if (!Passphrase.IsEmpty())
  1897. {
  1898. Passphrase = PasswordMask;
  1899. }
  1900. }
  1901. //---------------------------------------------------------------------
  1902. static bool IsDomainOrSubdomain(const UnicodeString & FullDomain, const UnicodeString & Domain)
  1903. {
  1904. return
  1905. SameText(FullDomain, Domain) ||
  1906. EndsText(L"." + Domain, FullDomain);
  1907. }
  1908. //---------------------------------------------------------------------
  1909. bool __fastcall TSessionData::ParseUrl(UnicodeString Url, TOptions * Options,
  1910. TStoredSessionList * StoredSessions, bool & DefaultsOnly, UnicodeString * FileName,
  1911. bool * AProtocolDefined, UnicodeString * MaskedUrl, int Flags)
  1912. {
  1913. bool ProtocolDefined = false;
  1914. bool PortNumberDefined = false;
  1915. TFSProtocol AFSProtocol;
  1916. int DefaultProtocolPortNumber;
  1917. TFtps AFtps = ftpsNone;
  1918. int ProtocolLen = 0;
  1919. if (IsProtocolUrl(Url, ScpProtocol, ProtocolLen))
  1920. {
  1921. AFSProtocol = fsSCPonly;
  1922. DefaultProtocolPortNumber = SshPortNumber;
  1923. MoveStr(Url, MaskedUrl, ProtocolLen);
  1924. ProtocolDefined = true;
  1925. }
  1926. else if (IsProtocolUrl(Url, SftpProtocol, ProtocolLen))
  1927. {
  1928. AFSProtocol = fsSFTPonly;
  1929. DefaultProtocolPortNumber = SshPortNumber;
  1930. MoveStr(Url, MaskedUrl, ProtocolLen);
  1931. ProtocolDefined = true;
  1932. }
  1933. else if (IsProtocolUrl(Url, FtpProtocol, ProtocolLen))
  1934. {
  1935. AFSProtocol = fsFTP;
  1936. Ftps = ftpsNone;
  1937. DefaultProtocolPortNumber = FtpPortNumber;
  1938. MoveStr(Url, MaskedUrl, ProtocolLen);
  1939. ProtocolDefined = true;
  1940. }
  1941. else if (IsProtocolUrl(Url, FtpsProtocol, ProtocolLen))
  1942. {
  1943. AFSProtocol = fsFTP;
  1944. AFtps = ftpsImplicit;
  1945. DefaultProtocolPortNumber = FtpsImplicitPortNumber;
  1946. MoveStr(Url, MaskedUrl, ProtocolLen);
  1947. ProtocolDefined = true;
  1948. }
  1949. else if (IsProtocolUrl(Url, FtpesProtocol, ProtocolLen))
  1950. {
  1951. AFSProtocol = fsFTP;
  1952. AFtps = ftpsExplicitTls;
  1953. DefaultProtocolPortNumber = FtpPortNumber;
  1954. MoveStr(Url, MaskedUrl, ProtocolLen);
  1955. ProtocolDefined = true;
  1956. }
  1957. else if (IsProtocolUrl(Url, WebDAVProtocol, ProtocolLen) ||
  1958. IsProtocolUrl(Url, HttpProtocol, ProtocolLen))
  1959. {
  1960. AFSProtocol = fsWebDAV;
  1961. AFtps = ftpsNone;
  1962. DefaultProtocolPortNumber = HTTPPortNumber;
  1963. MoveStr(Url, MaskedUrl, ProtocolLen);
  1964. ProtocolDefined = true;
  1965. }
  1966. else if (IsProtocolUrl(Url, WebDAVSProtocol, ProtocolLen) ||
  1967. IsProtocolUrl(Url, HttpsProtocol, ProtocolLen))
  1968. {
  1969. AFSProtocol = fsWebDAV;
  1970. AFtps = ftpsImplicit;
  1971. DefaultProtocolPortNumber = HTTPSPortNumber;
  1972. MoveStr(Url, MaskedUrl, ProtocolLen);
  1973. ProtocolDefined = true;
  1974. }
  1975. else if (IsProtocolUrl(Url, S3Protocol, ProtocolLen))
  1976. {
  1977. AFSProtocol = fsS3;
  1978. AFtps = ftpsImplicit;
  1979. DefaultProtocolPortNumber = HTTPSPortNumber;
  1980. MoveStr(Url, MaskedUrl, ProtocolLen);
  1981. ProtocolDefined = true;
  1982. }
  1983. else if (IsProtocolUrl(Url, SshProtocol, ProtocolLen))
  1984. {
  1985. // For most uses, handling ssh:// the same way as sftp://
  1986. // The only place where a difference is made is GetLoginData() in WinMain.cpp
  1987. AFSProtocol = fsSFTPonly;
  1988. PuttyProtocol = PuttySshProtocol;
  1989. DefaultProtocolPortNumber = SshPortNumber;
  1990. MoveStr(Url, MaskedUrl, ProtocolLen);
  1991. ProtocolDefined = true;
  1992. }
  1993. if (ProtocolDefined && (Url.SubString(1, 2) == L"//"))
  1994. {
  1995. MoveStr(Url, MaskedUrl, 2);
  1996. }
  1997. if (AProtocolDefined != NULL)
  1998. {
  1999. *AProtocolDefined = ProtocolDefined;
  2000. }
  2001. bool Unsafe = FLAGSET(Flags, pufUnsafe);
  2002. if (!Url.IsEmpty())
  2003. {
  2004. UnicodeString DecodedUrl = DecodeUrlChars(Url);
  2005. // lookup stored session even if protocol was defined
  2006. // (this allows setting for example default username for host
  2007. // by creating stored session named by host)
  2008. TSessionData * Data = NULL;
  2009. // When using to paste URL on Login dialog, we do not want to lookup the stored sites
  2010. if ((StoredSessions != NULL) &&
  2011. (!ProtocolDefined || FLAGSET(Flags, pufAllowStoredSiteWithProtocol)))
  2012. {
  2013. // this can be optimized as the list is sorted
  2014. for (Integer Index = 0; Index < StoredSessions->CountIncludingHidden; Index++)
  2015. {
  2016. TSessionData * AData = (TSessionData *)StoredSessions->Items[Index];
  2017. if (!AData->IsWorkspace)
  2018. {
  2019. bool Match = false;
  2020. // Comparison optimizations as this is called many times
  2021. // e.g. when updating jumplist
  2022. if ((AData->Name.Length() == DecodedUrl.Length()) &&
  2023. SameText(AData->Name, DecodedUrl))
  2024. {
  2025. Match = true;
  2026. }
  2027. else if ((AData->Name.Length() < DecodedUrl.Length()) &&
  2028. (DecodedUrl[AData->Name.Length() + 1] == L'/') &&
  2029. // StrLIComp is an equivalent of SameText
  2030. (StrLIComp(AData->Name.c_str(), DecodedUrl.c_str(), AData->Name.Length()) == 0))
  2031. {
  2032. Match = true;
  2033. }
  2034. if (Match)
  2035. {
  2036. Data = AData;
  2037. break;
  2038. }
  2039. }
  2040. }
  2041. }
  2042. UnicodeString ARemoteDirectory;
  2043. if (Data != NULL)
  2044. {
  2045. Assign(Data);
  2046. int P = 1;
  2047. while (!AnsiSameText(DecodeUrlChars(Url.SubString(1, P)), Data->Name))
  2048. {
  2049. P++;
  2050. DebugAssert(P <= Url.Length());
  2051. }
  2052. ARemoteDirectory = Url.SubString(P + 1, Url.Length() - P);
  2053. if (Data->Hidden)
  2054. {
  2055. Data->Remove();
  2056. StoredSessions->Remove(Data);
  2057. // only modified, implicit
  2058. StoredSessions->Save(false, false);
  2059. }
  2060. if (MaskedUrl != NULL)
  2061. {
  2062. (*MaskedUrl) += Url;
  2063. }
  2064. }
  2065. else
  2066. {
  2067. // This happens when pasting URL on Login dialog
  2068. if (StoredSessions != NULL)
  2069. {
  2070. CopyData(StoredSessions->DefaultSettings);
  2071. }
  2072. Name = L"";
  2073. int PSlash = Url.Pos(L"/");
  2074. if (PSlash == 0)
  2075. {
  2076. PSlash = Url.Length() + 1;
  2077. }
  2078. UnicodeString ConnectInfo = Url.SubString(1, PSlash - 1);
  2079. int P = ConnectInfo.LastDelimiter(L"@");
  2080. UnicodeString UserInfo;
  2081. UnicodeString HostInfo;
  2082. if (P > 0)
  2083. {
  2084. UserInfo = ConnectInfo.SubString(1, P - 1);
  2085. HostInfo = ConnectInfo.SubString(P + 1, ConnectInfo.Length() - P);
  2086. }
  2087. else
  2088. {
  2089. HostInfo = ConnectInfo;
  2090. }
  2091. UnicodeString OrigHostInfo = HostInfo;
  2092. if ((HostInfo.Length() >= 2) && (HostInfo[1] == L'[') && ((P = HostInfo.Pos(L"]")) > 0))
  2093. {
  2094. HostName = HostInfo.SubString(2, P - 2);
  2095. HostInfo.Delete(1, P);
  2096. if (!HostInfo.IsEmpty() && (HostInfo[1] == L':'))
  2097. {
  2098. HostInfo.Delete(1, 1);
  2099. }
  2100. }
  2101. else
  2102. {
  2103. HostName = DecodeUrlChars(CutToChar(HostInfo, L':', true));
  2104. }
  2105. // expanded from ?: operator, as it caused strange "access violation" errors
  2106. if (!HostInfo.IsEmpty())
  2107. {
  2108. int APortNumber = StrToIntDef(DecodeUrlChars(HostInfo), -1);
  2109. if ((APortNumber > 0) && (APortNumber <= 65535))
  2110. {
  2111. PortNumber = APortNumber;
  2112. PortNumberDefined = true;
  2113. }
  2114. }
  2115. else if (ProtocolDefined)
  2116. {
  2117. if ((AFSProtocol == fsWebDAV) &&
  2118. (IsDomainOrSubdomain(HostName, S3LibDefaultHostName()) ||
  2119. IsDomainOrSubdomain(HostName, L"digitaloceanspaces.com") ||
  2120. IsDomainOrSubdomain(HostName, L"storage.googleapis.com")))
  2121. {
  2122. AFSProtocol = fsS3;
  2123. }
  2124. PortNumber = DefaultProtocolPortNumber;
  2125. }
  2126. if (ProtocolDefined)
  2127. {
  2128. Ftps = AFtps;
  2129. }
  2130. UnicodeString UserInfoWithoutConnectionParams = CutToChar(UserInfo, UrlParamSeparator, false);
  2131. UnicodeString ConnectionParams = UserInfo;
  2132. UserInfo = UserInfoWithoutConnectionParams;
  2133. std::unique_ptr<TStrings> RawSettings(new TStringList());
  2134. while (!ConnectionParams.IsEmpty())
  2135. {
  2136. UnicodeString ConnectionParam = CutToChar(ConnectionParams, UrlParamSeparator, false);
  2137. UnicodeString ConnectionParamName = CutToChar(ConnectionParam, UrlParamValueSeparator, false);
  2138. if (SameText(ConnectionParamName, UrlHostKeyParamName))
  2139. {
  2140. HostKey = DecodeUrlChars(ConnectionParam);
  2141. FOverrideCachedHostKey = false;
  2142. }
  2143. else if (StartsText(UrlRawSettingsParamNamePrefix, ConnectionParamName))
  2144. {
  2145. UnicodeString AName = RightStr(ConnectionParamName, ConnectionParamName.Length() - UrlRawSettingsParamNamePrefix.Length());
  2146. AName = DecodeUrlChars(AName);
  2147. UnicodeString Value = DecodeUrlChars(ConnectionParam);
  2148. if (SameText(AName, L"Name"))
  2149. {
  2150. Name = Value;
  2151. }
  2152. else
  2153. {
  2154. RawSettings->Values[AName] = Value;
  2155. }
  2156. }
  2157. }
  2158. if (RawSettings->Count > 0) // optimization
  2159. {
  2160. ApplyRawSettings(RawSettings.get(), FLAGSET(Flags, pufUnsafe));
  2161. }
  2162. bool HasPassword = (UserInfo.Pos(L':') > 0);
  2163. UnicodeString RawUserName = CutToChar(UserInfo, L':', false);
  2164. UserName = DecodeUrlChars(RawUserName);
  2165. Password = DecodeUrlChars(UserInfo);
  2166. if (HasPassword && Password.IsEmpty())
  2167. {
  2168. Password = EmptyString;
  2169. }
  2170. UnicodeString RemoteDirectoryWithSessionParams = Url.SubString(PSlash, Url.Length() - PSlash + 1);
  2171. ARemoteDirectory = CutToChar(RemoteDirectoryWithSessionParams, UrlParamSeparator, false);
  2172. UnicodeString SessionParams = RemoteDirectoryWithSessionParams;
  2173. // We should handle session params in "stored session" branch too.
  2174. // And particularly if there's a "save" param, we should actually not try to match the
  2175. // URL against site names
  2176. while (!SessionParams.IsEmpty())
  2177. {
  2178. UnicodeString SessionParam = CutToChar(SessionParams, UrlParamSeparator, false);
  2179. UnicodeString SessionParamName = CutToChar(SessionParam, UrlParamValueSeparator, false);
  2180. if (SameText(SessionParamName, UrlSaveParamName))
  2181. {
  2182. FSaveOnly = (StrToIntDef(SessionParam, 1) != 0);
  2183. }
  2184. }
  2185. if (MaskedUrl != NULL)
  2186. {
  2187. (*MaskedUrl) += RawUserName;
  2188. if (HasPassword)
  2189. {
  2190. (*MaskedUrl) += L":" + PasswordMask;
  2191. }
  2192. if (!RawUserName.IsEmpty() || HasPassword)
  2193. {
  2194. (*MaskedUrl) += L"@";
  2195. }
  2196. (*MaskedUrl) += OrigHostInfo + ARemoteDirectory;
  2197. }
  2198. }
  2199. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory != L"/"))
  2200. {
  2201. if ((ARemoteDirectory[ARemoteDirectory.Length()] != L'/') &&
  2202. (FileName != NULL))
  2203. {
  2204. *FileName = DecodeUrlChars(UnixExtractFileName(ARemoteDirectory));
  2205. ARemoteDirectory = UnixExtractFilePath(ARemoteDirectory);
  2206. }
  2207. RemoteDirectory = DecodeUrlChars(ARemoteDirectory);
  2208. }
  2209. DefaultsOnly = false;
  2210. }
  2211. else
  2212. {
  2213. // This happens when pasting URL on Login dialog
  2214. if (StoredSessions != NULL)
  2215. {
  2216. CopyData(StoredSessions->DefaultSettings);
  2217. }
  2218. DefaultsOnly = true;
  2219. }
  2220. if (ProtocolDefined)
  2221. {
  2222. FSProtocol = AFSProtocol;
  2223. }
  2224. if (Options != NULL)
  2225. {
  2226. // we deliberately do keep defaultonly to false, in presence of any option,
  2227. // as the option should not make session "connectable"
  2228. UnicodeString Value;
  2229. if (Options->FindSwitch(USERNAME_SWITCH, Value))
  2230. {
  2231. UserName = Value;
  2232. }
  2233. if (Options->FindSwitch(PASSWORD_SWITCH, Value))
  2234. {
  2235. Password = Value;
  2236. }
  2237. if (Options->FindSwitch(SESSIONNAME_SWICH, Value))
  2238. {
  2239. Name = Value;
  2240. }
  2241. if (Options->FindSwitch(NEWPASSWORD_SWITCH, Value))
  2242. {
  2243. ChangePassword = true;
  2244. NewPassword = Value;
  2245. }
  2246. if (Options->FindSwitch(L"privatekey", Value))
  2247. {
  2248. PublicKeyFile = Value;
  2249. }
  2250. if (Options->FindSwitch(L"clientcert", Value))
  2251. {
  2252. TlsCertificateFile = Value;
  2253. }
  2254. if (Options->FindSwitch(PassphraseOption, Value))
  2255. {
  2256. Passphrase = Value;
  2257. }
  2258. if (Options->FindSwitch(L"timeout", Value))
  2259. {
  2260. Timeout = StrToInt(Value);
  2261. }
  2262. if (Options->FindSwitch(L"hostkey", Value) ||
  2263. Options->FindSwitch(L"certificate", Value))
  2264. {
  2265. HostKey = Value;
  2266. FOverrideCachedHostKey = true;
  2267. }
  2268. FtpPasvMode = Options->SwitchValue(L"passive", FtpPasvMode);
  2269. if (Options->FindSwitch(L"implicit"))
  2270. {
  2271. bool Enabled = Options->SwitchValue(L"implicit", true);
  2272. Ftps = Enabled ? ftpsImplicit : ftpsNone;
  2273. if (!PortNumberDefined && Enabled)
  2274. {
  2275. PortNumber = FtpsImplicitPortNumber;
  2276. }
  2277. }
  2278. // BACKWARD COMPATIBILITY with 5.5.x
  2279. if (Options->FindSwitch(L"explicitssl"))
  2280. {
  2281. bool Enabled = Options->SwitchValue(L"explicitssl", true);
  2282. Ftps = Enabled ? ftpsExplicitSsl : ftpsNone;
  2283. if (!PortNumberDefined && Enabled)
  2284. {
  2285. PortNumber = FtpPortNumber;
  2286. }
  2287. }
  2288. if (Options->FindSwitch(L"explicit") ||
  2289. // BACKWARD COMPATIBILITY with 5.5.x
  2290. Options->FindSwitch(L"explicittls"))
  2291. {
  2292. UnicodeString SwitchName =
  2293. Options->FindSwitch(L"explicit") ? L"explicit" : L"explicittls";
  2294. bool Enabled = Options->SwitchValue(SwitchName, true);
  2295. Ftps = Enabled ? ftpsExplicitTls : ftpsNone;
  2296. if (!PortNumberDefined && Enabled)
  2297. {
  2298. PortNumber = FtpPortNumber;
  2299. }
  2300. }
  2301. if (Options->FindSwitch(RawSettingsOption))
  2302. {
  2303. std::unique_ptr<TStrings> RawSettings(new TStringList());
  2304. if (Options->FindSwitch(RawSettingsOption, RawSettings.get()))
  2305. {
  2306. ApplyRawSettings(RawSettings.get(), Unsafe);
  2307. }
  2308. }
  2309. }
  2310. return true;
  2311. }
  2312. //---------------------------------------------------------------------
  2313. void __fastcall TSessionData::ApplyRawSettings(TStrings * RawSettings, bool Unsafe)
  2314. {
  2315. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings, false));
  2316. ApplyRawSettings(OptionsStorage.get(), Unsafe);
  2317. }
  2318. //---------------------------------------------------------------------
  2319. void __fastcall TSessionData::ApplyRawSettings(THierarchicalStorage * Storage, bool Unsafe)
  2320. {
  2321. bool Dummy;
  2322. DoLoad(Storage, false, Dummy, Unsafe);
  2323. }
  2324. //---------------------------------------------------------------------
  2325. void __fastcall TSessionData::ConfigureTunnel(int APortNumber)
  2326. {
  2327. FOrigHostName = HostName;
  2328. FOrigPortNumber = PortNumber;
  2329. FOrigProxyMethod = ProxyMethod;
  2330. HostName = L"127.0.0.1";
  2331. PortNumber = APortNumber;
  2332. // proxy settings is used for tunnel
  2333. ProxyMethod = ::pmNone;
  2334. FLogicalHostName = FOrigHostName;
  2335. }
  2336. //---------------------------------------------------------------------
  2337. void __fastcall TSessionData::RollbackTunnel()
  2338. {
  2339. HostName = FOrigHostName;
  2340. PortNumber = FOrigPortNumber;
  2341. ProxyMethod = FOrigProxyMethod;
  2342. FLogicalHostName = L"";
  2343. }
  2344. //---------------------------------------------------------------------
  2345. TSessionData * TSessionData::CreateTunnelData(int TunnelLocalPortNumber)
  2346. {
  2347. std::unique_ptr<TSessionData> TunnelData(new TSessionData(EmptyStr));
  2348. TunnelData->Assign(StoredSessions->DefaultSettings);
  2349. TunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (SessionName));
  2350. TunnelData->Tunnel = false;
  2351. TunnelData->HostName = TunnelHostName;
  2352. TunnelData->PortNumber = TunnelPortNumber;
  2353. TunnelData->UserName = TunnelUserName;
  2354. TunnelData->Password = TunnelPassword;
  2355. TunnelData->PublicKeyFile = TunnelPublicKeyFile;
  2356. TunnelData->Passphrase = TunnelPassphrase;
  2357. UnicodeString AHostName = HostNameExpanded;
  2358. if (IsIPv6Literal(AHostName))
  2359. {
  2360. AHostName = EscapeIPv6Literal(AHostName);
  2361. }
  2362. TunnelData->TunnelPortFwd = FORMAT(L"L%d\t%s:%d",
  2363. (TunnelLocalPortNumber, AHostName, PortNumber));
  2364. TunnelData->HostKey = TunnelHostKey;
  2365. // inherit proxy options on the main session
  2366. TunnelData->ProxyMethod = ProxyMethod;
  2367. TunnelData->ProxyHost = ProxyHost;
  2368. TunnelData->ProxyPort = ProxyPort;
  2369. TunnelData->ProxyUsername = ProxyUsername;
  2370. TunnelData->ProxyPassword = ProxyPassword;
  2371. TunnelData->ProxyTelnetCommand = ProxyTelnetCommand;
  2372. TunnelData->ProxyLocalCommand = ProxyLocalCommand;
  2373. TunnelData->ProxyDNS = ProxyDNS;
  2374. TunnelData->ProxyLocalhost = ProxyLocalhost;
  2375. // inherit most SSH options of the main session (except for private key and bugs)
  2376. TunnelData->Compression = Compression;
  2377. TunnelData->CipherList = CipherList;
  2378. TunnelData->Ssh2DES = Ssh2DES;
  2379. TunnelData->KexList = KexList;
  2380. TunnelData->RekeyData = RekeyData;
  2381. TunnelData->RekeyTime = RekeyTime;
  2382. TunnelData->SshNoUserAuth = SshNoUserAuth;
  2383. TunnelData->AuthGSSAPI = AuthGSSAPI;
  2384. TunnelData->AuthGSSAPIKEX = AuthGSSAPIKEX;
  2385. TunnelData->GSSAPIFwdTGT = GSSAPIFwdTGT;
  2386. TunnelData->TryAgent = TryAgent;
  2387. TunnelData->AgentFwd = AgentFwd;
  2388. TunnelData->AuthKI = AuthKI;
  2389. TunnelData->AuthKIPassword = AuthKIPassword;
  2390. return TunnelData.release();
  2391. }
  2392. //---------------------------------------------------------------------
  2393. void __fastcall TSessionData::ExpandEnvironmentVariables()
  2394. {
  2395. HostName = HostNameExpanded;
  2396. UserName = UserNameExpanded;
  2397. PublicKeyFile = ::ExpandEnvironmentVariables(PublicKeyFile);
  2398. }
  2399. //---------------------------------------------------------------------
  2400. void __fastcall TSessionData::ValidatePath(const UnicodeString Path)
  2401. {
  2402. // noop
  2403. }
  2404. //---------------------------------------------------------------------
  2405. void __fastcall TSessionData::ValidateName(const UnicodeString Name)
  2406. {
  2407. // keep consistent with MakeValidName
  2408. if (Name.LastDelimiter(L"/") > 0)
  2409. {
  2410. throw Exception(FMTLOAD(ITEM_NAME_INVALID, (Name, L"/")));
  2411. }
  2412. }
  2413. //---------------------------------------------------------------------
  2414. UnicodeString __fastcall TSessionData::MakeValidName(const UnicodeString & Name)
  2415. {
  2416. // keep consistent with ValidateName
  2417. return ReplaceStr(Name, L"/", L"\\");
  2418. }
  2419. //---------------------------------------------------------------------
  2420. RawByteString __fastcall TSessionData::EncryptPassword(const UnicodeString & Password, UnicodeString Key)
  2421. {
  2422. return Configuration->EncryptPassword(Password, Key);
  2423. }
  2424. //---------------------------------------------------------------------
  2425. RawByteString __fastcall TSessionData::StronglyRecryptPassword(const RawByteString & Password, UnicodeString Key)
  2426. {
  2427. return Configuration->StronglyRecryptPassword(Password, Key);
  2428. }
  2429. //---------------------------------------------------------------------
  2430. UnicodeString __fastcall TSessionData::DecryptPassword(const RawByteString & Password, UnicodeString Key)
  2431. {
  2432. UnicodeString Result;
  2433. try
  2434. {
  2435. Result = Configuration->DecryptPassword(Password, Key);
  2436. }
  2437. catch(EAbort &)
  2438. {
  2439. // silently ignore aborted prompts for master password and return empty password
  2440. }
  2441. return Result;
  2442. }
  2443. //---------------------------------------------------------------------
  2444. bool __fastcall TSessionData::GetCanLogin()
  2445. {
  2446. return !FHostName.IsEmpty();
  2447. }
  2448. //---------------------------------------------------------------------
  2449. bool __fastcall TSessionData::GetIsLocalBrowser()
  2450. {
  2451. return !LocalDirectory.IsEmpty() && !OtherLocalDirectory.IsEmpty();
  2452. }
  2453. //---------------------------------------------------------------------
  2454. bool __fastcall TSessionData::GetCanOpen()
  2455. {
  2456. return CanLogin || IsLocalBrowser;
  2457. }
  2458. //---------------------------------------------------------------------------
  2459. int TSessionData::GetDefaultPort()
  2460. {
  2461. return DefaultPort(FSProtocol, Ftps);
  2462. }
  2463. //---------------------------------------------------------------------------
  2464. UnicodeString __fastcall TSessionData::GetSessionKey()
  2465. {
  2466. UnicodeString Result = FORMAT(L"%s@%s", (UserName, HostName));
  2467. if (PortNumber != GetDefaultPort())
  2468. {
  2469. Result += FORMAT(L":%d", (PortNumber));
  2470. }
  2471. return Result;
  2472. }
  2473. //---------------------------------------------------------------------
  2474. UnicodeString __fastcall TSessionData::GetInternalStorageKey()
  2475. {
  2476. // This is probably useless remnant of previous use of this method from OpenSessionInPutty
  2477. // that needs the method to return something even for ad-hoc sessions
  2478. if (Name.IsEmpty())
  2479. {
  2480. return SessionKey;
  2481. }
  2482. else
  2483. {
  2484. return Name;
  2485. }
  2486. }
  2487. //---------------------------------------------------------------------
  2488. UnicodeString __fastcall TSessionData::GetStorageKey()
  2489. {
  2490. return SessionName;
  2491. }
  2492. //---------------------------------------------------------------------
  2493. UnicodeString __fastcall TSessionData::FormatSiteKey(const UnicodeString & HostName, int PortNumber)
  2494. {
  2495. return FORMAT(L"%s:%d", (HostName, PortNumber));
  2496. }
  2497. //---------------------------------------------------------------------
  2498. UnicodeString __fastcall TSessionData::GetSiteKey()
  2499. {
  2500. return FormatSiteKey(HostNameExpanded, PortNumber);
  2501. }
  2502. //---------------------------------------------------------------------
  2503. void __fastcall TSessionData::SetHostName(UnicodeString value)
  2504. {
  2505. if (FHostName != value)
  2506. {
  2507. // HostName is key for password encryption
  2508. UnicodeString XPassword = Password;
  2509. UnicodeString XNewPassword = NewPassword;
  2510. UnicodeString XEncryptKey = EncryptKey;
  2511. // This is now hardly used as hostname is parsed directly on login dialog.
  2512. // But can be used when importing sites from PuTTY, as it allows same format too.
  2513. int P = value.LastDelimiter(L"@");
  2514. if (P > 0)
  2515. {
  2516. UserName = value.SubString(1, P - 1);
  2517. value = value.SubString(P + 1, value.Length() - P);
  2518. }
  2519. FHostName = value;
  2520. Modify();
  2521. Password = XPassword;
  2522. NewPassword = XNewPassword;
  2523. EncryptKey = XEncryptKey;
  2524. Shred(XPassword);
  2525. Shred(XNewPassword);
  2526. Shred(XEncryptKey);
  2527. }
  2528. }
  2529. //---------------------------------------------------------------------
  2530. UnicodeString __fastcall TSessionData::GetHostNameExpanded()
  2531. {
  2532. return ::ExpandEnvironmentVariables(HostName);
  2533. }
  2534. //---------------------------------------------------------------------
  2535. UnicodeString TSessionData::GetHostNameSource()
  2536. {
  2537. UnicodeString Result;
  2538. if (HostName != HostNameExpanded)
  2539. {
  2540. Result = HostName;
  2541. }
  2542. return Result;
  2543. }
  2544. //---------------------------------------------------------------------
  2545. void __fastcall TSessionData::SetPortNumber(int value)
  2546. {
  2547. SET_SESSION_PROPERTY(PortNumber);
  2548. }
  2549. //---------------------------------------------------------------------------
  2550. void __fastcall TSessionData::SetShell(UnicodeString value)
  2551. {
  2552. SET_SESSION_PROPERTY(Shell);
  2553. }
  2554. //---------------------------------------------------------------------------
  2555. void __fastcall TSessionData::SetSftpServer(UnicodeString value)
  2556. {
  2557. SET_SESSION_PROPERTY(SftpServer);
  2558. }
  2559. //---------------------------------------------------------------------------
  2560. void __fastcall TSessionData::SetClearAliases(bool value)
  2561. {
  2562. SET_SESSION_PROPERTY(ClearAliases);
  2563. }
  2564. //---------------------------------------------------------------------------
  2565. void __fastcall TSessionData::SetListingCommand(UnicodeString value)
  2566. {
  2567. SET_SESSION_PROPERTY(ListingCommand);
  2568. }
  2569. //---------------------------------------------------------------------------
  2570. void __fastcall TSessionData::SetIgnoreLsWarnings(bool value)
  2571. {
  2572. SET_SESSION_PROPERTY(IgnoreLsWarnings);
  2573. }
  2574. //---------------------------------------------------------------------------
  2575. void __fastcall TSessionData::SetUnsetNationalVars(bool value)
  2576. {
  2577. SET_SESSION_PROPERTY(UnsetNationalVars);
  2578. }
  2579. //---------------------------------------------------------------------
  2580. void __fastcall TSessionData::SetUserName(UnicodeString value)
  2581. {
  2582. // Avoid password recryption (what may popup master password prompt)
  2583. if (FUserName != value)
  2584. {
  2585. // UserName is key for password encryption
  2586. UnicodeString XPassword = Password;
  2587. UnicodeString XNewPassword = NewPassword;
  2588. UnicodeString XEncryptKey = EncryptKey;
  2589. SET_SESSION_PROPERTY(UserName);
  2590. Password = XPassword;
  2591. NewPassword = XNewPassword;
  2592. EncryptKey = XEncryptKey;
  2593. Shred(XPassword);
  2594. Shred(XNewPassword);
  2595. Shred(XEncryptKey);
  2596. }
  2597. }
  2598. //---------------------------------------------------------------------
  2599. UnicodeString __fastcall TSessionData::GetUserNameExpanded()
  2600. {
  2601. UnicodeString Result = ::ExpandEnvironmentVariables(UserName);
  2602. if (Result.IsEmpty() && HasS3AutoCredentials())
  2603. {
  2604. Result = S3EnvUserName();
  2605. }
  2606. return Result;
  2607. }
  2608. //---------------------------------------------------------------------
  2609. UnicodeString TSessionData::GetUserNameSource()
  2610. {
  2611. UnicodeString Result;
  2612. if (UserName.IsEmpty() && HasS3AutoCredentials())
  2613. {
  2614. S3EnvUserName(&Result);
  2615. }
  2616. if (Result.IsEmpty() && (UserName != UserNameExpanded))
  2617. {
  2618. Result = UserName;
  2619. }
  2620. return Result;
  2621. }
  2622. //---------------------------------------------------------------------
  2623. void __fastcall TSessionData::SetPassword(UnicodeString avalue)
  2624. {
  2625. RawByteString value = EncryptPassword(avalue, UserName+HostName);
  2626. SET_SESSION_PROPERTY(Password);
  2627. }
  2628. //---------------------------------------------------------------------
  2629. UnicodeString __fastcall TSessionData::GetPassword() const
  2630. {
  2631. return DecryptPassword(FPassword, UserName+HostName);
  2632. }
  2633. //---------------------------------------------------------------------
  2634. void __fastcall TSessionData::SetNewPassword(UnicodeString avalue)
  2635. {
  2636. RawByteString value = EncryptPassword(avalue, UserName+HostName);
  2637. SET_SESSION_PROPERTY(NewPassword);
  2638. }
  2639. //---------------------------------------------------------------------
  2640. UnicodeString __fastcall TSessionData::GetNewPassword() const
  2641. {
  2642. return DecryptPassword(FNewPassword, UserName+HostName);
  2643. }
  2644. //---------------------------------------------------------------------
  2645. void __fastcall TSessionData::SetChangePassword(bool value)
  2646. {
  2647. SET_SESSION_PROPERTY(ChangePassword);
  2648. }
  2649. //---------------------------------------------------------------------
  2650. void __fastcall TSessionData::SetPingInterval(int value)
  2651. {
  2652. SET_SESSION_PROPERTY(PingInterval);
  2653. }
  2654. //---------------------------------------------------------------------
  2655. void __fastcall TSessionData::SetTryAgent(bool value)
  2656. {
  2657. SET_SESSION_PROPERTY(TryAgent);
  2658. }
  2659. //---------------------------------------------------------------------
  2660. void __fastcall TSessionData::SetAgentFwd(bool value)
  2661. {
  2662. SET_SESSION_PROPERTY(AgentFwd);
  2663. }
  2664. //---------------------------------------------------------------------
  2665. void __fastcall TSessionData::SetAuthKI(bool value)
  2666. {
  2667. SET_SESSION_PROPERTY(AuthKI);
  2668. }
  2669. //---------------------------------------------------------------------
  2670. void __fastcall TSessionData::SetAuthKIPassword(bool value)
  2671. {
  2672. SET_SESSION_PROPERTY(AuthKIPassword);
  2673. }
  2674. //---------------------------------------------------------------------
  2675. void __fastcall TSessionData::SetAuthGSSAPI(bool value)
  2676. {
  2677. SET_SESSION_PROPERTY(AuthGSSAPI);
  2678. }
  2679. //---------------------------------------------------------------------
  2680. void __fastcall TSessionData::SetAuthGSSAPIKEX(bool value)
  2681. {
  2682. SET_SESSION_PROPERTY(AuthGSSAPIKEX);
  2683. }
  2684. //---------------------------------------------------------------------
  2685. void __fastcall TSessionData::SetGSSAPIFwdTGT(bool value)
  2686. {
  2687. SET_SESSION_PROPERTY(GSSAPIFwdTGT);
  2688. }
  2689. //---------------------------------------------------------------------
  2690. void __fastcall TSessionData::SetChangeUsername(bool value)
  2691. {
  2692. SET_SESSION_PROPERTY(ChangeUsername);
  2693. }
  2694. //---------------------------------------------------------------------
  2695. void __fastcall TSessionData::SetCompression(bool value)
  2696. {
  2697. SET_SESSION_PROPERTY(Compression);
  2698. }
  2699. //---------------------------------------------------------------------
  2700. void __fastcall TSessionData::SetSsh2DES(bool value)
  2701. {
  2702. SET_SESSION_PROPERTY(Ssh2DES);
  2703. }
  2704. //---------------------------------------------------------------------
  2705. void __fastcall TSessionData::SetSshNoUserAuth(bool value)
  2706. {
  2707. SET_SESSION_PROPERTY(SshNoUserAuth);
  2708. }
  2709. //---------------------------------------------------------------------
  2710. bool __fastcall TSessionData::GetUsesSsh()
  2711. {
  2712. return IsSshProtocol(FSProtocol);
  2713. }
  2714. //---------------------------------------------------------------------
  2715. void __fastcall TSessionData::SetCipher(int Index, TCipher value)
  2716. {
  2717. DebugAssert(Index >= 0 && Index < CIPHER_COUNT);
  2718. SET_SESSION_PROPERTY(Ciphers[Index]);
  2719. }
  2720. //---------------------------------------------------------------------
  2721. TCipher __fastcall TSessionData::GetCipher(int Index) const
  2722. {
  2723. DebugAssert(Index >= 0 && Index < CIPHER_COUNT);
  2724. return FCiphers[Index];
  2725. }
  2726. //---------------------------------------------------------------------
  2727. template<class AlgoT>
  2728. void __fastcall TSessionData::SetAlgoList(AlgoT * List, const AlgoT * DefaultList, const UnicodeString * Names,
  2729. int Count, AlgoT WarnAlgo, UnicodeString value)
  2730. {
  2731. std::vector<bool> Used(Count); // initialized to false
  2732. std::vector<AlgoT> NewList(Count);
  2733. bool HasWarnAlgo = (WarnAlgo >= AlgoT());
  2734. const AlgoT * WarnPtr;
  2735. int WarnDefaultIndex;
  2736. if (!HasWarnAlgo)
  2737. {
  2738. WarnPtr = NULL;
  2739. WarnDefaultIndex = -1;
  2740. }
  2741. else
  2742. {
  2743. WarnPtr = std::find(DefaultList, DefaultList + Count, WarnAlgo);
  2744. DebugAssert(WarnPtr != NULL);
  2745. WarnDefaultIndex = (WarnPtr - DefaultList);
  2746. }
  2747. int Index = 0;
  2748. while (!value.IsEmpty())
  2749. {
  2750. UnicodeString AlgoStr = CutToChar(value, L',', true);
  2751. for (int Algo = 0; Algo < Count; Algo++)
  2752. {
  2753. if (!AlgoStr.CompareIC(Names[Algo]) &&
  2754. !Used[Algo] && DebugAlwaysTrue(Index < Count))
  2755. {
  2756. NewList[Index] = (AlgoT)Algo;
  2757. Used[Algo] = true;
  2758. Index++;
  2759. break;
  2760. }
  2761. }
  2762. }
  2763. if (HasWarnAlgo && !Used[WarnAlgo] && DebugAlwaysTrue(Index < Count))
  2764. {
  2765. NewList[Index] = WarnAlgo;
  2766. Used[WarnAlgo] = true;
  2767. Index++;
  2768. }
  2769. int WarnIndex = -1;
  2770. if (HasWarnAlgo)
  2771. {
  2772. WarnIndex = std::find(NewList.begin(), NewList.end(), WarnAlgo) - NewList.begin();
  2773. }
  2774. bool Priority = true;
  2775. for (int DefaultIndex = 0; (DefaultIndex < Count); DefaultIndex++)
  2776. {
  2777. AlgoT DefaultAlgo = DefaultList[DefaultIndex];
  2778. if (!Used[DefaultAlgo] && DebugAlwaysTrue(Index < Count))
  2779. {
  2780. int TargetIndex;
  2781. // Unused algs that are prioritized in the default list,
  2782. // should be merged before the existing custom list
  2783. if (Priority)
  2784. {
  2785. TargetIndex = DefaultIndex;
  2786. }
  2787. else
  2788. {
  2789. if (HasWarnAlgo && (DefaultIndex < WarnDefaultIndex))
  2790. {
  2791. TargetIndex = WarnIndex;
  2792. }
  2793. else
  2794. {
  2795. TargetIndex = Index;
  2796. }
  2797. }
  2798. NewList.insert(NewList.begin() + TargetIndex, DefaultAlgo);
  2799. DebugAssert(NewList.back() == AlgoT());
  2800. NewList.pop_back();
  2801. if (HasWarnAlgo && (TargetIndex <= WarnIndex))
  2802. {
  2803. WarnIndex++;
  2804. }
  2805. Index++;
  2806. }
  2807. else
  2808. {
  2809. Priority = false;
  2810. }
  2811. }
  2812. if (!std::equal(NewList.begin(), NewList.end(), List))
  2813. {
  2814. std::copy(NewList.begin(), NewList.end(), List);
  2815. Modify();
  2816. }
  2817. }
  2818. //---------------------------------------------------------------------
  2819. void __fastcall TSessionData::SetCipherList(UnicodeString value)
  2820. {
  2821. SetAlgoList(FCiphers, DefaultCipherList, CipherNames, CIPHER_COUNT, cipWarn, value);
  2822. }
  2823. //---------------------------------------------------------------------
  2824. UnicodeString __fastcall TSessionData::GetCipherList() const
  2825. {
  2826. UnicodeString Result;
  2827. for (int Index = 0; Index < CIPHER_COUNT; Index++)
  2828. {
  2829. Result += UnicodeString(Index ? L"," : L"") + CipherNames[Cipher[Index]];
  2830. }
  2831. return Result;
  2832. }
  2833. //---------------------------------------------------------------------
  2834. void __fastcall TSessionData::SetKex(int Index, TKex value)
  2835. {
  2836. DebugAssert(Index >= 0 && Index < KEX_COUNT);
  2837. SET_SESSION_PROPERTY(Kex[Index]);
  2838. }
  2839. //---------------------------------------------------------------------
  2840. TKex __fastcall TSessionData::GetKex(int Index) const
  2841. {
  2842. DebugAssert(Index >= 0 && Index < KEX_COUNT);
  2843. return FKex[Index];
  2844. }
  2845. //---------------------------------------------------------------------
  2846. void __fastcall TSessionData::SetKexList(UnicodeString value)
  2847. {
  2848. SetAlgoList(FKex, DefaultKexList, KexNames, KEX_COUNT, kexWarn, value);
  2849. }
  2850. //---------------------------------------------------------------------
  2851. UnicodeString __fastcall TSessionData::GetKexList() const
  2852. {
  2853. UnicodeString Result;
  2854. for (int Index = 0; Index < KEX_COUNT; Index++)
  2855. {
  2856. Result += UnicodeString(Index ? L"," : L"") + KexNames[Kex[Index]];
  2857. }
  2858. return Result;
  2859. }
  2860. //---------------------------------------------------------------------
  2861. void __fastcall TSessionData::SetHostKeys(int Index, THostKey value)
  2862. {
  2863. DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);
  2864. SET_SESSION_PROPERTY(HostKeys[Index]);
  2865. }
  2866. //---------------------------------------------------------------------
  2867. THostKey __fastcall TSessionData::GetHostKeys(int Index) const
  2868. {
  2869. DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);
  2870. return FHostKeys[Index];
  2871. }
  2872. //---------------------------------------------------------------------
  2873. void __fastcall TSessionData::SetHostKeyList(UnicodeString value)
  2874. {
  2875. SetAlgoList(FHostKeys, DefaultHostKeyList, HostKeyNames, HOSTKEY_COUNT, hkWarn, value);
  2876. }
  2877. //---------------------------------------------------------------------
  2878. UnicodeString __fastcall TSessionData::GetHostKeyList() const
  2879. {
  2880. UnicodeString Result;
  2881. for (int Index = 0; Index < HOSTKEY_COUNT; Index++)
  2882. {
  2883. Result += UnicodeString(Index ? L"," : L"") + HostKeyNames[HostKeys[Index]];
  2884. }
  2885. return Result;
  2886. }
  2887. //---------------------------------------------------------------------
  2888. void __fastcall TSessionData::SetGssLib(int Index, TGssLib value)
  2889. {
  2890. DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);
  2891. SET_SESSION_PROPERTY(GssLib[Index]);
  2892. }
  2893. //---------------------------------------------------------------------
  2894. TGssLib __fastcall TSessionData::GetGssLib(int Index) const
  2895. {
  2896. DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);
  2897. return FGssLib[Index];
  2898. }
  2899. //---------------------------------------------------------------------
  2900. void __fastcall TSessionData::SetGssLibList(UnicodeString value)
  2901. {
  2902. SetAlgoList(FGssLib, DefaultGssLibList, GssLibNames, GSSLIB_COUNT, TGssLib(-1), value);
  2903. }
  2904. //---------------------------------------------------------------------
  2905. UnicodeString __fastcall TSessionData::GetGssLibList() const
  2906. {
  2907. UnicodeString Result;
  2908. for (int Index = 0; Index < GSSLIB_COUNT; Index++)
  2909. {
  2910. Result += UnicodeString(Index ? L"," : L"") + GssLibNames[GssLib[Index]];
  2911. }
  2912. return Result;
  2913. }
  2914. //---------------------------------------------------------------------
  2915. void __fastcall TSessionData::SetGssLibCustom(UnicodeString value)
  2916. {
  2917. SET_SESSION_PROPERTY(GssLibCustom);
  2918. }
  2919. //---------------------------------------------------------------------
  2920. void __fastcall TSessionData::SetPublicKeyFile(UnicodeString value)
  2921. {
  2922. if (FPublicKeyFile != value)
  2923. {
  2924. // PublicKeyFile is key for Passphrase encryption
  2925. UnicodeString XPassphrase = Passphrase;
  2926. // StripPathQuotes should not be needed as we do not feed quotes anymore
  2927. FPublicKeyFile = StripPathQuotes(value);
  2928. Modify();
  2929. Passphrase = XPassphrase;
  2930. Shred(XPassphrase);
  2931. }
  2932. }
  2933. //---------------------------------------------------------------------
  2934. void __fastcall TSessionData::SetPassphrase(UnicodeString avalue)
  2935. {
  2936. RawByteString value = EncryptPassword(avalue, PublicKeyFile);
  2937. SET_SESSION_PROPERTY(Passphrase);
  2938. }
  2939. //---------------------------------------------------------------------
  2940. UnicodeString __fastcall TSessionData::GetPassphrase() const
  2941. {
  2942. return DecryptPassword(FPassphrase, PublicKeyFile);
  2943. }
  2944. //---------------------------------------------------------------------
  2945. void __fastcall TSessionData::SetReturnVar(UnicodeString value)
  2946. {
  2947. SET_SESSION_PROPERTY(ReturnVar);
  2948. }
  2949. //---------------------------------------------------------------------
  2950. void __fastcall TSessionData::SetExitCode1IsError(bool value)
  2951. {
  2952. SET_SESSION_PROPERTY(ExitCode1IsError);
  2953. }
  2954. //---------------------------------------------------------------------------
  2955. void __fastcall TSessionData::SetLookupUserGroups(TAutoSwitch value)
  2956. {
  2957. SET_SESSION_PROPERTY(LookupUserGroups);
  2958. }
  2959. //---------------------------------------------------------------------------
  2960. void __fastcall TSessionData::SetEOLType(TEOLType value)
  2961. {
  2962. SET_SESSION_PROPERTY(EOLType);
  2963. }
  2964. //---------------------------------------------------------------------------
  2965. void __fastcall TSessionData::SetTrimVMSVersions(bool value)
  2966. {
  2967. SET_SESSION_PROPERTY(TrimVMSVersions);
  2968. }
  2969. //---------------------------------------------------------------------------
  2970. void __fastcall TSessionData::SetVMSAllRevisions(bool value)
  2971. {
  2972. SET_SESSION_PROPERTY(VMSAllRevisions);
  2973. }
  2974. //---------------------------------------------------------------------------
  2975. TDateTime __fastcall TSessionData::GetTimeoutDT()
  2976. {
  2977. return SecToDateTime(Timeout);
  2978. }
  2979. //---------------------------------------------------------------------------
  2980. void __fastcall TSessionData::SetTimeout(int value)
  2981. {
  2982. SET_SESSION_PROPERTY(Timeout);
  2983. }
  2984. //---------------------------------------------------------------------------
  2985. void __fastcall TSessionData::SetFSProtocol(TFSProtocol value)
  2986. {
  2987. SET_SESSION_PROPERTY(FSProtocol);
  2988. }
  2989. //---------------------------------------------------------------------
  2990. UnicodeString __fastcall TSessionData::GetFSProtocolStr()
  2991. {
  2992. DebugAssert(FSProtocol >= 0 && FSProtocol < FSPROTOCOL_COUNT);
  2993. return FSProtocolNames[FSProtocol];
  2994. }
  2995. //---------------------------------------------------------------------------
  2996. void __fastcall TSessionData::SetDetectReturnVar(bool value)
  2997. {
  2998. if (value != DetectReturnVar)
  2999. {
  3000. ReturnVar = value ? L"" : L"$?";
  3001. }
  3002. }
  3003. //---------------------------------------------------------------------------
  3004. bool __fastcall TSessionData::GetDetectReturnVar()
  3005. {
  3006. return ReturnVar.IsEmpty();
  3007. }
  3008. //---------------------------------------------------------------------------
  3009. void __fastcall TSessionData::SetDefaultShell(bool value)
  3010. {
  3011. if (value != DefaultShell)
  3012. {
  3013. Shell = value ? L"" : L"/bin/bash";
  3014. }
  3015. }
  3016. //---------------------------------------------------------------------------
  3017. bool __fastcall TSessionData::GetDefaultShell()
  3018. {
  3019. return Shell.IsEmpty();
  3020. }
  3021. //---------------------------------------------------------------------------
  3022. void __fastcall TSessionData::SetPuttyProtocol(UnicodeString value)
  3023. {
  3024. SET_SESSION_PROPERTY(PuttyProtocol);
  3025. }
  3026. //---------------------------------------------------------------------
  3027. UnicodeString __fastcall TSessionData::GetNormalizedPuttyProtocol() const
  3028. {
  3029. return DefaultStr(PuttyProtocol, PuttySshProtocol);
  3030. }
  3031. //---------------------------------------------------------------------
  3032. void __fastcall TSessionData::SetPingIntervalDT(TDateTime value)
  3033. {
  3034. unsigned short hour, min, sec, msec;
  3035. value.DecodeTime(&hour, &min, &sec, &msec);
  3036. PingInterval = ((int)hour)*SecsPerHour + ((int)min)*SecsPerMin + sec;
  3037. }
  3038. //---------------------------------------------------------------------------
  3039. TDateTime __fastcall TSessionData::GetPingIntervalDT()
  3040. {
  3041. return SecToDateTime(PingInterval);
  3042. }
  3043. //---------------------------------------------------------------------------
  3044. void __fastcall TSessionData::SetPingType(TPingType value)
  3045. {
  3046. SET_SESSION_PROPERTY(PingType);
  3047. }
  3048. //---------------------------------------------------------------------------
  3049. void __fastcall TSessionData::SetAddressFamily(TAddressFamily value)
  3050. {
  3051. SET_SESSION_PROPERTY(AddressFamily);
  3052. }
  3053. //---------------------------------------------------------------------------
  3054. void __fastcall TSessionData::SetRekeyData(UnicodeString value)
  3055. {
  3056. SET_SESSION_PROPERTY(RekeyData);
  3057. }
  3058. //---------------------------------------------------------------------------
  3059. void __fastcall TSessionData::SetRekeyTime(unsigned int value)
  3060. {
  3061. SET_SESSION_PROPERTY(RekeyTime);
  3062. }
  3063. //---------------------------------------------------------------------
  3064. UnicodeString __fastcall TSessionData::GetDefaultSessionName()
  3065. {
  3066. UnicodeString Result;
  3067. if (IsLocalBrowser)
  3068. {
  3069. // See also TScpCommanderForm::GetLocalBrowserSessionTitle
  3070. UnicodeString Path1 = ExtractShortName(LocalDirectory, false);
  3071. UnicodeString Path2 = ExtractShortName(OtherLocalDirectory, false);
  3072. Result = Path1 + TitleSeparator + Path2;
  3073. }
  3074. else if (!HostName.IsEmpty() && !UserName.IsEmpty())
  3075. {
  3076. // If we ever choose to include port number,
  3077. // we have to escape IPv6 literals in HostName
  3078. Result = FORMAT(L"%s@%s", (UserName, HostName));
  3079. }
  3080. else if (!HostName.IsEmpty())
  3081. {
  3082. Result = HostName;
  3083. }
  3084. else
  3085. {
  3086. Result = L"session";
  3087. }
  3088. Result = MakeValidName(Result);
  3089. return Result;
  3090. }
  3091. //---------------------------------------------------------------------
  3092. UnicodeString __fastcall TSessionData::GetNameWithoutHiddenPrefix()
  3093. {
  3094. UnicodeString Result = Name;
  3095. if (Hidden)
  3096. {
  3097. Result = Result.SubString(TNamedObjectList::HiddenPrefix.Length() + 1, Result.Length() - TNamedObjectList::HiddenPrefix.Length());
  3098. }
  3099. return Result;
  3100. }
  3101. //---------------------------------------------------------------------
  3102. bool __fastcall TSessionData::HasSessionName()
  3103. {
  3104. return (!GetNameWithoutHiddenPrefix().IsEmpty() && (Name != DefaultName));
  3105. }
  3106. //---------------------------------------------------------------------
  3107. UnicodeString __fastcall TSessionData::GetSessionName()
  3108. {
  3109. UnicodeString Result;
  3110. if (HasSessionName())
  3111. {
  3112. Result = GetNameWithoutHiddenPrefix();
  3113. }
  3114. else
  3115. {
  3116. Result = DefaultSessionName;
  3117. }
  3118. return Result;
  3119. }
  3120. //---------------------------------------------------------------------
  3121. bool __fastcall TSessionData::IsSecure()
  3122. {
  3123. bool Result;
  3124. switch (FSProtocol)
  3125. {
  3126. case fsSCPonly:
  3127. case fsSFTP:
  3128. case fsSFTPonly:
  3129. Result = true;
  3130. break;
  3131. case fsFTP:
  3132. case fsWebDAV:
  3133. case fsS3:
  3134. Result = (Ftps != ftpsNone);
  3135. break;
  3136. default:
  3137. DebugFail();
  3138. break;
  3139. }
  3140. return Result;
  3141. }
  3142. //---------------------------------------------------------------------
  3143. UnicodeString __fastcall TSessionData::GetProtocolUrl(bool HttpForWebDAV)
  3144. {
  3145. UnicodeString Url;
  3146. switch (FSProtocol)
  3147. {
  3148. case fsSCPonly:
  3149. Url = ScpProtocol;
  3150. break;
  3151. default:
  3152. DebugFail();
  3153. // fallback
  3154. case fsSFTP:
  3155. case fsSFTPonly:
  3156. Url = SftpProtocol;
  3157. break;
  3158. case fsFTP:
  3159. if (Ftps == ftpsImplicit)
  3160. {
  3161. Url = FtpsProtocol;
  3162. }
  3163. else if ((Ftps == ftpsExplicitTls) || (Ftps == ftpsExplicitSsl))
  3164. {
  3165. Url = FtpesProtocol;
  3166. }
  3167. else
  3168. {
  3169. Url = FtpProtocol;
  3170. }
  3171. break;
  3172. case fsWebDAV:
  3173. if (HttpForWebDAV)
  3174. {
  3175. if (Ftps == ftpsImplicit)
  3176. {
  3177. Url = HttpsProtocol;
  3178. }
  3179. else
  3180. {
  3181. Url = HttpProtocol;
  3182. }
  3183. }
  3184. else
  3185. {
  3186. if (Ftps == ftpsImplicit)
  3187. {
  3188. Url = WebDAVSProtocol;
  3189. }
  3190. else
  3191. {
  3192. Url = WebDAVProtocol;
  3193. }
  3194. }
  3195. break;
  3196. case fsS3:
  3197. Url = S3Protocol;
  3198. break;
  3199. }
  3200. Url += ProtocolSeparator;
  3201. return Url;
  3202. }
  3203. //---------------------------------------------------------------------
  3204. static bool HasIP6LiteralBrackets(const UnicodeString & HostName)
  3205. {
  3206. return
  3207. (HostName.Length() >= 2) &&
  3208. (HostName[1] == L'[') &&
  3209. (HostName[HostName.Length()] == L']');
  3210. }
  3211. //---------------------------------------------------------------------
  3212. static UnicodeString StripIP6LiteralBrackets(const UnicodeString & HostName)
  3213. {
  3214. UnicodeString Result = HostName;
  3215. if (DebugAlwaysTrue(HasIP6LiteralBrackets(Result)))
  3216. {
  3217. Result = Result.SubString(2, Result.Length() - 2);
  3218. }
  3219. return Result;
  3220. }
  3221. //---------------------------------------------------------------------
  3222. bool __fastcall IsIPv6Literal(const UnicodeString & HostName)
  3223. {
  3224. UnicodeString Buf = HostName;
  3225. if (HasIP6LiteralBrackets(Buf))
  3226. {
  3227. Buf = StripIP6LiteralBrackets(Buf);
  3228. }
  3229. int Colons = 0;
  3230. bool Result = true;
  3231. for (int Index = 1; Result && (Index <= Buf.Length()); Index++)
  3232. {
  3233. wchar_t C = Buf[Index];
  3234. if (C == L'%')
  3235. {
  3236. break;
  3237. }
  3238. else if (C == L':')
  3239. {
  3240. Colons++;
  3241. }
  3242. else
  3243. {
  3244. Result = IsHex(C);
  3245. }
  3246. }
  3247. Result = Result && (Colons >= 2);
  3248. return Result;
  3249. }
  3250. //---------------------------------------------------------------------
  3251. UnicodeString __fastcall EscapeIPv6Literal(const UnicodeString & IP)
  3252. {
  3253. UnicodeString Result = IP;
  3254. if (!HasIP6LiteralBrackets(Result))
  3255. {
  3256. Result = L"[" + IP + L"]";
  3257. }
  3258. return Result;
  3259. }
  3260. //---------------------------------------------------------------------
  3261. TStrings * __fastcall TSessionData::GetRawSettingsForUrl()
  3262. {
  3263. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3264. std::unique_ptr<TSessionData> SessionData(Clone());
  3265. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3266. SessionData->HostName = FactoryDefaults->HostName;
  3267. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3268. SessionData->UserName = FactoryDefaults->UserName;
  3269. SessionData->Password = FactoryDefaults->Password;
  3270. SessionData->Ftps = FactoryDefaults->Ftps;
  3271. SessionData->HostKey = FactoryDefaults->HostKey;
  3272. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3273. // Cannot be decided in SaveToOptions as it does not have HostName and UserName, so it cannot calculate DefaultSessionName.
  3274. bool SaveName = HasSessionName() && (Name != DefaultSessionName);
  3275. return SessionData->SaveToOptions(FactoryDefaults.get(), SaveName, false);
  3276. }
  3277. //---------------------------------------------------------------------
  3278. bool __fastcall TSessionData::HasRawSettingsForUrl()
  3279. {
  3280. std::unique_ptr<TStrings> RawSettings(GetRawSettingsForUrl());
  3281. return (RawSettings->Count > 0);
  3282. }
  3283. //---------------------------------------------------------------------
  3284. UnicodeString __fastcall TSessionData::GenerateSessionUrl(unsigned int Flags)
  3285. {
  3286. UnicodeString Url;
  3287. if (FLAGSET(Flags, sufSpecific))
  3288. {
  3289. Url += WinSCPProtocolPrefix;
  3290. }
  3291. Url += GetProtocolUrl(FLAGSET(Flags, sufHttpForWebDAV));
  3292. // Add username only if it was somehow explicitly specified (so not with S3CredentialsEnv), but if it was, add it in the expanded form.
  3293. // For scripting, we might use unexpanded form (keeping the environment variables),
  3294. // but for consistency with code generation (where explicit expansion code would need to be added), we do not.
  3295. if (FLAGSET(Flags, sufUserName) && !UserName.IsEmpty())
  3296. {
  3297. Url += EncodeUrlString(UserNameExpanded);
  3298. if (FLAGSET(Flags, sufPassword) && !Password.IsEmpty())
  3299. {
  3300. Url += L":" + EncodeUrlString(NormalizeString(Password));
  3301. }
  3302. if (FLAGSET(Flags, sufHostKey) && !HostKey.IsEmpty())
  3303. {
  3304. UnicodeString KeyName;
  3305. UnicodeString Fingerprint = HostKey;
  3306. NormalizeFingerprint(Fingerprint, KeyName);
  3307. UnicodeString S = Fingerprint;
  3308. if (!KeyName.IsEmpty())
  3309. {
  3310. S = KeyName + NormalizedFingerprintSeparator + S;
  3311. }
  3312. S = Base64ToUrlSafe(S); // Noop for MD5 (both in SSH host keys and TLS/SSL)
  3313. S = MD5ToUrlSafe(S); // TLS/SSL fingerprints
  3314. UnicodeString S2 = EncodeUrlString(S);
  3315. DebugAssert(S2 == S2); // There should be nothing left for encoding
  3316. Url +=
  3317. UnicodeString(UrlParamSeparator) + UrlHostKeyParamName +
  3318. UnicodeString(UrlParamValueSeparator) + S2;
  3319. }
  3320. if (FLAGSET(Flags, sufRawSettings))
  3321. {
  3322. std::unique_ptr<TStrings> RawSettings(GetRawSettingsForUrl());
  3323. for (int Index = 0; Index < RawSettings->Count; Index++)
  3324. {
  3325. Url +=
  3326. UnicodeString(UrlParamSeparator) +
  3327. UrlRawSettingsParamNamePrefix + EncodeUrlString(LowerCase(RawSettings->Names[Index])) +
  3328. UnicodeString(UrlParamValueSeparator) + EncodeUrlString(RawSettings->ValueFromIndex[Index]);
  3329. }
  3330. }
  3331. Url += L"@";
  3332. }
  3333. DebugAssert(!HostNameExpanded.IsEmpty());
  3334. if (IsIPv6Literal(HostNameExpanded))
  3335. {
  3336. Url += EscapeIPv6Literal(HostNameExpanded);
  3337. }
  3338. else
  3339. {
  3340. Url += EncodeUrlString(HostNameExpanded);
  3341. }
  3342. if (PortNumber != GetDefaultPort())
  3343. {
  3344. Url += L":" + IntToStr(PortNumber);
  3345. }
  3346. Url += L"/";
  3347. return Url;
  3348. }
  3349. //---------------------------------------------------------------------
  3350. UnicodeString ScriptCommandOpenLink(TraceInitStr(ScriptCommandLink(L"open")));
  3351. //---------------------------------------------------------------------
  3352. void __fastcall TSessionData::AddSwitch(
  3353. UnicodeString & Result, const UnicodeString & Name, bool Rtf)
  3354. {
  3355. Result += RtfSwitch(Name, ScriptCommandOpenLink, Rtf);
  3356. }
  3357. //---------------------------------------------------------------------
  3358. void __fastcall TSessionData::AddSwitch(
  3359. UnicodeString & Result, const UnicodeString & Name, const UnicodeString & Value, bool Rtf)
  3360. {
  3361. Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);
  3362. }
  3363. //---------------------------------------------------------------------
  3364. void __fastcall TSessionData::AddSwitch(
  3365. UnicodeString & Result, const UnicodeString & Name, int Value, bool Rtf)
  3366. {
  3367. Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);
  3368. }
  3369. //---------------------------------------------------------------------
  3370. void __fastcall TSessionData::LookupLastFingerprint()
  3371. {
  3372. UnicodeString FingerprintType;
  3373. if (IsSshProtocol(FSProtocol))
  3374. {
  3375. FingerprintType = SshFingerprintType;
  3376. }
  3377. else if (Ftps != ftpsNone)
  3378. {
  3379. FingerprintType = TlsFingerprintType;
  3380. }
  3381. if (!FingerprintType.IsEmpty())
  3382. {
  3383. HostKey = Configuration->LastFingerprint(SiteKey, FingerprintType);
  3384. }
  3385. if (Tunnel)
  3386. {
  3387. // not used anyway
  3388. int TunnelPortNumber = std::max(TunnelLocalPortNumber, Configuration->TunnelLocalPortNumberLow);
  3389. std::unique_ptr<TSessionData> TunnelData(CreateTunnelData(TunnelPortNumber));
  3390. TunnelHostKey = Configuration->LastFingerprint(TunnelData->SiteKey, SshFingerprintType);
  3391. }
  3392. }
  3393. //---------------------------------------------------------------------
  3394. UnicodeString __fastcall TSessionData::GenerateOpenCommandArgs(bool Rtf)
  3395. {
  3396. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3397. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  3398. SessionData->Assign(this);
  3399. UnicodeString Result = SessionData->GenerateSessionUrl(sufOpen);
  3400. // Before we reset the FSProtocol
  3401. bool AUsesSsh = SessionData->UsesSsh;
  3402. // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that
  3403. if (SessionData->FSProtocol != fsSFTPonly)
  3404. {
  3405. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3406. }
  3407. SessionData->HostName = FactoryDefaults->HostName;
  3408. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3409. SessionData->UserName = FactoryDefaults->UserName;
  3410. SessionData->Password = FactoryDefaults->Password;
  3411. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3412. SessionData->Ftps = FactoryDefaults->Ftps;
  3413. if (SessionData->HostKey != FactoryDefaults->HostKey)
  3414. {
  3415. UnicodeString SwitchName = AUsesSsh ? L"hostkey" : L"certificate";
  3416. AddSwitch(Result, SwitchName, SessionData->HostKey, Rtf);
  3417. SessionData->HostKey = FactoryDefaults->HostKey;
  3418. }
  3419. if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)
  3420. {
  3421. AddSwitch(Result, L"privatekey", SessionData->PublicKeyFile, Rtf);
  3422. SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;
  3423. }
  3424. if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)
  3425. {
  3426. AddSwitch(Result, L"clientcert", SessionData->TlsCertificateFile, Rtf);
  3427. SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;
  3428. }
  3429. if (SessionData->Passphrase != FactoryDefaults->Passphrase)
  3430. {
  3431. AddSwitch(Result, PassphraseOption, SessionData->Passphrase, Rtf);
  3432. SessionData->Passphrase = FactoryDefaults->Passphrase;
  3433. }
  3434. if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)
  3435. {
  3436. AddSwitch(Result, L"passive", SessionData->FtpPasvMode ? 1 : 0, Rtf);
  3437. SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;
  3438. }
  3439. if (SessionData->Timeout != FactoryDefaults->Timeout)
  3440. {
  3441. AddSwitch(Result, L"timeout", SessionData->Timeout, Rtf);
  3442. SessionData->Timeout = FactoryDefaults->Timeout;
  3443. }
  3444. std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get(), false, false));
  3445. if (RawSettings->Count > 0)
  3446. {
  3447. AddSwitch(Result, RawSettingsOption, Rtf);
  3448. Result += StringsToParams(RawSettings.get());
  3449. }
  3450. return Result;
  3451. }
  3452. //---------------------------------------------------------------------
  3453. UnicodeString SessionOptionsClassName(L"SessionOptions");
  3454. //---------------------------------------------------------------------
  3455. void __fastcall TSessionData::AddAssemblyProperty(
  3456. UnicodeString & Result, TAssemblyLanguage Language,
  3457. const UnicodeString & Name, const UnicodeString & Type,
  3458. const UnicodeString & Member)
  3459. {
  3460. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Type, Member, false);
  3461. }
  3462. //---------------------------------------------------------------------
  3463. void __fastcall TSessionData::AddAssemblyProperty(
  3464. UnicodeString & Result, TAssemblyLanguage Language,
  3465. const UnicodeString & Name, const UnicodeString & Value)
  3466. {
  3467. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3468. }
  3469. //---------------------------------------------------------------------
  3470. void __fastcall TSessionData::AddAssemblyProperty(
  3471. UnicodeString & Result, TAssemblyLanguage Language,
  3472. const UnicodeString & Name, int Value)
  3473. {
  3474. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3475. }
  3476. //---------------------------------------------------------------------
  3477. void __fastcall TSessionData::AddAssemblyProperty(
  3478. UnicodeString & Result, TAssemblyLanguage Language,
  3479. const UnicodeString & Name, bool Value)
  3480. {
  3481. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3482. }
  3483. //---------------------------------------------------------------------
  3484. void __fastcall TSessionData::GenerateAssemblyCode(
  3485. TAssemblyLanguage Language, UnicodeString & Head, UnicodeString & Tail, int & Indent)
  3486. {
  3487. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3488. std::unique_ptr<TSessionData> SessionData(Clone());
  3489. switch (Language)
  3490. {
  3491. case alCSharp:
  3492. case alVBNET:
  3493. // noop
  3494. break;
  3495. case alPowerShell:
  3496. Head +=
  3497. AssemblyCommentLine(Language, LoadStr(CODE_PS_ADD_TYPE)) +
  3498. RtfKeyword(L"Add-Type") + RtfText(" -Path ") + AssemblyString(Language, "WinSCPnet.dll") + RtfPara +
  3499. RtfPara;
  3500. break;
  3501. default:
  3502. DebugFail();
  3503. break;
  3504. }
  3505. Head +=
  3506. AssemblyCommentLine(Language, LoadStr(CODE_SESSION_OPTIONS)) +
  3507. AssemblyNewClassInstanceStart(Language, SessionOptionsClassName, false);
  3508. UnicodeString ProtocolMember;
  3509. switch (SessionData->FSProtocol)
  3510. {
  3511. case fsSCPonly:
  3512. ProtocolMember = "Scp";
  3513. break;
  3514. default:
  3515. DebugFail();
  3516. // fallback
  3517. case fsSFTP:
  3518. case fsSFTPonly:
  3519. ProtocolMember = "Sftp";
  3520. break;
  3521. case fsFTP:
  3522. ProtocolMember = "Ftp";
  3523. break;
  3524. case fsWebDAV:
  3525. ProtocolMember = "Webdav";
  3526. break;
  3527. case fsS3:
  3528. ProtocolMember = "S3";
  3529. break;
  3530. }
  3531. // Before we reset the FSProtocol
  3532. bool AUsesSsh = SessionData->UsesSsh;
  3533. // Protocol is set unconditionally, we want even the default SFTP
  3534. AddAssemblyProperty(Head, Language, L"Protocol", L"Protocol", ProtocolMember);
  3535. // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that
  3536. if (SessionData->FSProtocol != fsSFTPonly)
  3537. {
  3538. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3539. }
  3540. if (SessionData->HostName != FactoryDefaults->HostName)
  3541. {
  3542. AddAssemblyProperty(Head, Language, L"HostName", HostName);
  3543. SessionData->HostName = FactoryDefaults->HostName;
  3544. }
  3545. int ADefaultPort = GetDefaultPort();
  3546. if (SessionData->PortNumber != ADefaultPort)
  3547. {
  3548. AddAssemblyProperty(Head, Language, L"PortNumber", PortNumber);
  3549. }
  3550. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3551. if (SessionData->UserName != FactoryDefaults->UserName)
  3552. {
  3553. AddAssemblyProperty(Head, Language, L"UserName", UserName);
  3554. SessionData->UserName = FactoryDefaults->UserName;
  3555. }
  3556. if (SessionData->Password != FactoryDefaults->Password)
  3557. {
  3558. AddAssemblyProperty(Head, Language, L"Password", NormalizeString(Password));
  3559. SessionData->Password = FactoryDefaults->Password;
  3560. }
  3561. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3562. if (SessionData->Ftps != FactoryDefaults->Ftps)
  3563. {
  3564. // SessionData->FSProtocol is reset already
  3565. switch (FSProtocol)
  3566. {
  3567. case fsFTP:
  3568. {
  3569. UnicodeString FtpSecureMember;
  3570. switch (SessionData->Ftps)
  3571. {
  3572. case ftpsNone:
  3573. // noop
  3574. break;
  3575. case ftpsImplicit:
  3576. FtpSecureMember = L"Implicit";
  3577. break;
  3578. case ftpsExplicitTls:
  3579. case ftpsExplicitSsl:
  3580. FtpSecureMember = L"Explicit";
  3581. break;
  3582. default:
  3583. DebugFail();
  3584. break;
  3585. }
  3586. AddAssemblyProperty(Head, Language, L"FtpSecure", L"FtpSecure", FtpSecureMember);
  3587. }
  3588. break;
  3589. case fsWebDAV:
  3590. AddAssemblyProperty(Head, Language, L"WebdavSecure", (SessionData->Ftps != ftpsNone));
  3591. break;
  3592. case fsS3:
  3593. // implicit
  3594. break;
  3595. default:
  3596. DebugFail();
  3597. break;
  3598. }
  3599. SessionData->Ftps = FactoryDefaults->Ftps;
  3600. }
  3601. if (SessionData->HostKey != FactoryDefaults->HostKey)
  3602. {
  3603. UnicodeString PropertyName = AUsesSsh ? L"SshHostKeyFingerprint" : L"TlsHostCertificateFingerprint";
  3604. AddAssemblyProperty(Head, Language, PropertyName, SessionData->HostKey);
  3605. SessionData->HostKey = FactoryDefaults->HostKey;
  3606. }
  3607. if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)
  3608. {
  3609. AddAssemblyProperty(Head, Language, L"SshPrivateKeyPath", SessionData->PublicKeyFile);
  3610. SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;
  3611. }
  3612. if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)
  3613. {
  3614. AddAssemblyProperty(Head, Language, L"TlsClientCertificatePath", SessionData->TlsCertificateFile);
  3615. SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;
  3616. }
  3617. if (SessionData->Passphrase != FactoryDefaults->Passphrase)
  3618. {
  3619. AddAssemblyProperty(Head, Language, L"PrivateKeyPassphrase", SessionData->Passphrase);
  3620. SessionData->Passphrase = FactoryDefaults->Passphrase;
  3621. }
  3622. if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)
  3623. {
  3624. AddAssemblyProperty(Head, Language, L"FtpMode", L"FtpMode", (SessionData->FtpPasvMode ? L"Passive" : L"Active"));
  3625. SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;
  3626. }
  3627. if (SessionData->Timeout != FactoryDefaults->Timeout)
  3628. {
  3629. AddAssemblyProperty(Head, Language, L"TimeoutInMilliseconds", SessionData->Timeout * 1000);
  3630. SessionData->Timeout = FactoryDefaults->Timeout;
  3631. }
  3632. Head += AssemblyNewClassInstanceEnd(Language, false);
  3633. std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get(), false, false));
  3634. UnicodeString SessionOptionsVariableName = AssemblyVariableName(Language, SessionOptionsClassName);
  3635. if (RawSettings->Count > 0)
  3636. {
  3637. Head +=
  3638. RtfPara +
  3639. AssemblyAddRawSettings(Language, RawSettings.get(), SessionOptionsClassName, L"AddRawSettings");
  3640. }
  3641. Head += RtfPara;
  3642. UnicodeString Indentation = L" ";
  3643. UnicodeString SessionVariableName = AssemblyVariableName(Language, SessionClassName);
  3644. UnicodeString RtfSessionClass = RtfLibraryClass(SessionClassName);
  3645. UnicodeString RtfSessionOpenMethod = RtfLibraryMethod(SessionClassName, L"Open", false);
  3646. UnicodeString NewSessionInstance = AssemblyNewClassInstance(Language, SessionClassName, false);
  3647. UnicodeString OpenCall =
  3648. Indentation + AssemblyCommentLine(Language, LoadStr(CODE_CONNECT)) +
  3649. Indentation + RtfText(SessionVariableName + L".") + RtfSessionOpenMethod + RtfText(L"(" + SessionOptionsVariableName + L")") +
  3650. AssemblyStatementSeparator(Language) + RtfPara;
  3651. switch (Language)
  3652. {
  3653. case alCSharp:
  3654. Head +=
  3655. RtfKeyword(L"using") + RtfText(" (") + NewSessionInstance + RtfText(L"())") + RtfPara +
  3656. RtfText(L"{") + RtfPara +
  3657. OpenCall;
  3658. Tail =
  3659. RtfText(L"}") + RtfPara;
  3660. break;
  3661. case alVBNET:
  3662. Head +=
  3663. RtfKeyword(L"Using") + RtfText(L" ") + NewSessionInstance + RtfPara +
  3664. OpenCall;
  3665. Tail =
  3666. RtfKeyword(L"End Using") + RtfPara;
  3667. break;
  3668. case alPowerShell:
  3669. Head +=
  3670. NewSessionInstance + RtfPara +
  3671. RtfPara +
  3672. RtfKeyword(L"try") + RtfPara +
  3673. RtfText(L"{") + RtfPara +
  3674. OpenCall;
  3675. Tail =
  3676. RtfText(L"}") + RtfPara +
  3677. RtfKeyword(L"finally") + RtfPara +
  3678. RtfText(L"{") + RtfPara +
  3679. RtfText(Indentation + SessionVariableName + L".") +
  3680. RtfLibraryMethod(SessionClassName, L"Dispose", false) + RtfText(L"()") + RtfPara +
  3681. RtfText(L"}") + RtfPara;
  3682. break;
  3683. }
  3684. Head += RtfPara;
  3685. Indent = 4; // the same for all languages so far
  3686. }
  3687. //---------------------------------------------------------------------
  3688. void __fastcall TSessionData::SetTimeDifference(TDateTime value)
  3689. {
  3690. SET_SESSION_PROPERTY(TimeDifference);
  3691. }
  3692. //---------------------------------------------------------------------
  3693. void __fastcall TSessionData::SetTimeDifferenceAuto(bool value)
  3694. {
  3695. SET_SESSION_PROPERTY(TimeDifferenceAuto);
  3696. }
  3697. //---------------------------------------------------------------------
  3698. void __fastcall TSessionData::SetLocalDirectory(UnicodeString value)
  3699. {
  3700. SET_SESSION_PROPERTY(LocalDirectory);
  3701. }
  3702. //---------------------------------------------------------------------
  3703. void __fastcall TSessionData::SetOtherLocalDirectory(const UnicodeString & value)
  3704. {
  3705. SET_SESSION_PROPERTY(OtherLocalDirectory);
  3706. }
  3707. //---------------------------------------------------------------------
  3708. UnicodeString __fastcall TSessionData::GetLocalDirectoryExpanded()
  3709. {
  3710. return ExpandFileName(::ExpandEnvironmentVariables(LocalDirectory));
  3711. }
  3712. //---------------------------------------------------------------------
  3713. void __fastcall TSessionData::SetRemoteDirectory(UnicodeString value)
  3714. {
  3715. SET_SESSION_PROPERTY(RemoteDirectory);
  3716. }
  3717. //---------------------------------------------------------------------
  3718. void __fastcall TSessionData::SetSynchronizeBrowsing(bool value)
  3719. {
  3720. SET_SESSION_PROPERTY(SynchronizeBrowsing);
  3721. }
  3722. //---------------------------------------------------------------------
  3723. void __fastcall TSessionData::SetUpdateDirectories(bool value)
  3724. {
  3725. SET_SESSION_PROPERTY(UpdateDirectories);
  3726. }
  3727. //---------------------------------------------------------------------
  3728. void __fastcall TSessionData::SetCacheDirectories(bool value)
  3729. {
  3730. SET_SESSION_PROPERTY(CacheDirectories);
  3731. }
  3732. //---------------------------------------------------------------------
  3733. void __fastcall TSessionData::SetCacheDirectoryChanges(bool value)
  3734. {
  3735. SET_SESSION_PROPERTY(CacheDirectoryChanges);
  3736. }
  3737. //---------------------------------------------------------------------
  3738. void __fastcall TSessionData::SetPreserveDirectoryChanges(bool value)
  3739. {
  3740. SET_SESSION_PROPERTY(PreserveDirectoryChanges);
  3741. }
  3742. //---------------------------------------------------------------------
  3743. void __fastcall TSessionData::SetResolveSymlinks(bool value)
  3744. {
  3745. SET_SESSION_PROPERTY(ResolveSymlinks);
  3746. }
  3747. //---------------------------------------------------------------------
  3748. void __fastcall TSessionData::SetFollowDirectorySymlinks(bool value)
  3749. {
  3750. SET_SESSION_PROPERTY(FollowDirectorySymlinks);
  3751. }
  3752. //---------------------------------------------------------------------------
  3753. void __fastcall TSessionData::SetDSTMode(TDSTMode value)
  3754. {
  3755. SET_SESSION_PROPERTY(DSTMode);
  3756. }
  3757. //---------------------------------------------------------------------------
  3758. void __fastcall TSessionData::SetDeleteToRecycleBin(bool value)
  3759. {
  3760. SET_SESSION_PROPERTY(DeleteToRecycleBin);
  3761. }
  3762. //---------------------------------------------------------------------------
  3763. void __fastcall TSessionData::SetOverwrittenToRecycleBin(bool value)
  3764. {
  3765. SET_SESSION_PROPERTY(OverwrittenToRecycleBin);
  3766. }
  3767. //---------------------------------------------------------------------------
  3768. void __fastcall TSessionData::SetRecycleBinPath(UnicodeString value)
  3769. {
  3770. SET_SESSION_PROPERTY(RecycleBinPath);
  3771. }
  3772. //---------------------------------------------------------------------------
  3773. void __fastcall TSessionData::SetPostLoginCommands(UnicodeString value)
  3774. {
  3775. SET_SESSION_PROPERTY(PostLoginCommands);
  3776. }
  3777. //---------------------------------------------------------------------
  3778. void __fastcall TSessionData::SetSpecial(bool value)
  3779. {
  3780. SET_SESSION_PROPERTY(Special);
  3781. }
  3782. //---------------------------------------------------------------------------
  3783. void __fastcall TSessionData::SetScp1Compatibility(bool value)
  3784. {
  3785. SET_SESSION_PROPERTY(Scp1Compatibility);
  3786. }
  3787. //---------------------------------------------------------------------
  3788. void __fastcall TSessionData::SetTcpNoDelay(bool value)
  3789. {
  3790. SET_SESSION_PROPERTY(TcpNoDelay);
  3791. }
  3792. //---------------------------------------------------------------------
  3793. void __fastcall TSessionData::SetSendBuf(int value)
  3794. {
  3795. SET_SESSION_PROPERTY(SendBuf);
  3796. }
  3797. //---------------------------------------------------------------------
  3798. void __fastcall TSessionData::SetSourceAddress(const UnicodeString & value)
  3799. {
  3800. SET_SESSION_PROPERTY(SourceAddress);
  3801. }
  3802. //---------------------------------------------------------------------
  3803. void __fastcall TSessionData::SetProtocolFeatures(const UnicodeString & value)
  3804. {
  3805. SET_SESSION_PROPERTY(ProtocolFeatures);
  3806. }
  3807. //---------------------------------------------------------------------
  3808. void __fastcall TSessionData::SetSshSimple(bool value)
  3809. {
  3810. SET_SESSION_PROPERTY(SshSimple);
  3811. }
  3812. //---------------------------------------------------------------------
  3813. void __fastcall TSessionData::SetProxyMethod(TProxyMethod value)
  3814. {
  3815. SET_SESSION_PROPERTY(ProxyMethod);
  3816. }
  3817. //---------------------------------------------------------------------
  3818. void __fastcall TSessionData::SetProxyHost(UnicodeString value)
  3819. {
  3820. SET_SESSION_PROPERTY(ProxyHost);
  3821. }
  3822. //---------------------------------------------------------------------
  3823. void __fastcall TSessionData::SetProxyPort(int value)
  3824. {
  3825. SET_SESSION_PROPERTY(ProxyPort);
  3826. }
  3827. //---------------------------------------------------------------------
  3828. void __fastcall TSessionData::SetProxyUsername(UnicodeString value)
  3829. {
  3830. SET_SESSION_PROPERTY(ProxyUsername);
  3831. }
  3832. //---------------------------------------------------------------------
  3833. void __fastcall TSessionData::SetProxyPassword(UnicodeString avalue)
  3834. {
  3835. RawByteString value = EncryptPassword(avalue, ProxyUsername+ProxyHost);
  3836. SET_SESSION_PROPERTY(ProxyPassword);
  3837. }
  3838. //---------------------------------------------------------------------
  3839. UnicodeString __fastcall TSessionData::GetProxyPassword() const
  3840. {
  3841. return DecryptPassword(FProxyPassword, ProxyUsername+ProxyHost);
  3842. }
  3843. //---------------------------------------------------------------------
  3844. void __fastcall TSessionData::SetProxyTelnetCommand(UnicodeString value)
  3845. {
  3846. SET_SESSION_PROPERTY(ProxyTelnetCommand);
  3847. }
  3848. //---------------------------------------------------------------------
  3849. void __fastcall TSessionData::SetProxyLocalCommand(UnicodeString value)
  3850. {
  3851. SET_SESSION_PROPERTY(ProxyLocalCommand);
  3852. }
  3853. //---------------------------------------------------------------------
  3854. void __fastcall TSessionData::SetProxyDNS(TAutoSwitch value)
  3855. {
  3856. SET_SESSION_PROPERTY(ProxyDNS);
  3857. }
  3858. //---------------------------------------------------------------------
  3859. void __fastcall TSessionData::SetProxyLocalhost(bool value)
  3860. {
  3861. SET_SESSION_PROPERTY(ProxyLocalhost);
  3862. }
  3863. //---------------------------------------------------------------------
  3864. void __fastcall TSessionData::SetFtpProxyLogonType(int value)
  3865. {
  3866. SET_SESSION_PROPERTY(FtpProxyLogonType);
  3867. }
  3868. //---------------------------------------------------------------------
  3869. void __fastcall TSessionData::SetBug(TSshBug Bug, TAutoSwitch value)
  3870. {
  3871. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));
  3872. SET_SESSION_PROPERTY(Bugs[Bug]);
  3873. }
  3874. //---------------------------------------------------------------------
  3875. TAutoSwitch __fastcall TSessionData::GetBug(TSshBug Bug) const
  3876. {
  3877. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));
  3878. return FBugs[Bug];
  3879. }
  3880. //---------------------------------------------------------------------
  3881. void __fastcall TSessionData::SetPuttySettings(UnicodeString value)
  3882. {
  3883. SET_SESSION_PROPERTY(PuttySettings);
  3884. }
  3885. //---------------------------------------------------------------------
  3886. void __fastcall TSessionData::SetCustomParam1(UnicodeString value)
  3887. {
  3888. SET_SESSION_PROPERTY(CustomParam1);
  3889. }
  3890. //---------------------------------------------------------------------
  3891. void __fastcall TSessionData::SetCustomParam2(UnicodeString value)
  3892. {
  3893. SET_SESSION_PROPERTY(CustomParam2);
  3894. }
  3895. //---------------------------------------------------------------------
  3896. void __fastcall TSessionData::SetSFTPDownloadQueue(int value)
  3897. {
  3898. SET_SESSION_PROPERTY(SFTPDownloadQueue);
  3899. }
  3900. //---------------------------------------------------------------------
  3901. void __fastcall TSessionData::SetSFTPUploadQueue(int value)
  3902. {
  3903. SET_SESSION_PROPERTY(SFTPUploadQueue);
  3904. }
  3905. //---------------------------------------------------------------------
  3906. void __fastcall TSessionData::SetSFTPListingQueue(int value)
  3907. {
  3908. SET_SESSION_PROPERTY(SFTPListingQueue);
  3909. }
  3910. //---------------------------------------------------------------------
  3911. void __fastcall TSessionData::SetSFTPMaxVersion(int value)
  3912. {
  3913. SET_SESSION_PROPERTY(SFTPMaxVersion);
  3914. }
  3915. //---------------------------------------------------------------------
  3916. void __fastcall TSessionData::SetSFTPMaxPacketSize(unsigned long value)
  3917. {
  3918. SET_SESSION_PROPERTY(SFTPMaxPacketSize);
  3919. }
  3920. //---------------------------------------------------------------------
  3921. void __fastcall TSessionData::SetSFTPRealPath(TAutoSwitch value)
  3922. {
  3923. SET_SESSION_PROPERTY(SFTPRealPath);
  3924. }
  3925. //---------------------------------------------------------------------
  3926. void __fastcall TSessionData::SetSFTPBug(TSftpBug Bug, TAutoSwitch value)
  3927. {
  3928. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));
  3929. SET_SESSION_PROPERTY(SFTPBugs[Bug]);
  3930. }
  3931. //---------------------------------------------------------------------
  3932. TAutoSwitch __fastcall TSessionData::GetSFTPBug(TSftpBug Bug) const
  3933. {
  3934. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));
  3935. return FSFTPBugs[Bug];
  3936. }
  3937. //---------------------------------------------------------------------
  3938. void __fastcall TSessionData::SetSCPLsFullTime(TAutoSwitch value)
  3939. {
  3940. SET_SESSION_PROPERTY(SCPLsFullTime);
  3941. }
  3942. //---------------------------------------------------------------------------
  3943. void __fastcall TSessionData::SetColor(int value)
  3944. {
  3945. SET_SESSION_PROPERTY(Color);
  3946. }
  3947. //---------------------------------------------------------------------------
  3948. void __fastcall TSessionData::SetTunnel(bool value)
  3949. {
  3950. SET_SESSION_PROPERTY(Tunnel);
  3951. }
  3952. //---------------------------------------------------------------------
  3953. void __fastcall TSessionData::SetTunnelHostName(UnicodeString value)
  3954. {
  3955. if (FTunnelHostName != value)
  3956. {
  3957. // HostName is key for password encryption
  3958. UnicodeString XTunnelPassword = TunnelPassword;
  3959. int P = value.LastDelimiter(L"@");
  3960. if (P > 0)
  3961. {
  3962. TunnelUserName = value.SubString(1, P - 1);
  3963. value = value.SubString(P + 1, value.Length() - P);
  3964. }
  3965. FTunnelHostName = value;
  3966. Modify();
  3967. TunnelPassword = XTunnelPassword;
  3968. Shred(XTunnelPassword);
  3969. }
  3970. }
  3971. //---------------------------------------------------------------------
  3972. void __fastcall TSessionData::SetTunnelPortNumber(int value)
  3973. {
  3974. SET_SESSION_PROPERTY(TunnelPortNumber);
  3975. }
  3976. //---------------------------------------------------------------------
  3977. void __fastcall TSessionData::SetTunnelUserName(UnicodeString value)
  3978. {
  3979. // Avoid password recryption (what may popup master password prompt)
  3980. if (FTunnelUserName != value)
  3981. {
  3982. // TunnelUserName is key for password encryption
  3983. UnicodeString XTunnelPassword = TunnelPassword;
  3984. SET_SESSION_PROPERTY(TunnelUserName);
  3985. TunnelPassword = XTunnelPassword;
  3986. Shred(XTunnelPassword);
  3987. }
  3988. }
  3989. //---------------------------------------------------------------------
  3990. void __fastcall TSessionData::SetTunnelPassword(UnicodeString avalue)
  3991. {
  3992. RawByteString value = EncryptPassword(avalue, TunnelUserName+TunnelHostName);
  3993. SET_SESSION_PROPERTY(TunnelPassword);
  3994. }
  3995. //---------------------------------------------------------------------
  3996. UnicodeString __fastcall TSessionData::GetTunnelPassword() const
  3997. {
  3998. return DecryptPassword(FTunnelPassword, TunnelUserName+TunnelHostName);
  3999. }
  4000. //---------------------------------------------------------------------
  4001. void __fastcall TSessionData::SetTunnelPassphrase(UnicodeString avalue)
  4002. {
  4003. RawByteString value = EncryptPassword(avalue, TunnelPublicKeyFile);
  4004. SET_SESSION_PROPERTY(TunnelPassphrase);
  4005. }
  4006. //---------------------------------------------------------------------
  4007. UnicodeString __fastcall TSessionData::GetTunnelPassphrase() const
  4008. {
  4009. return DecryptPassword(FTunnelPassphrase, TunnelPublicKeyFile);
  4010. }
  4011. //---------------------------------------------------------------------
  4012. void __fastcall TSessionData::SetTunnelPublicKeyFile(UnicodeString value)
  4013. {
  4014. if (FTunnelPublicKeyFile != value)
  4015. {
  4016. // TunnelPublicKeyFile is key for TunnelPassphrase encryption
  4017. UnicodeString XTunnelPassphrase = TunnelPassphrase;
  4018. // StripPathQuotes should not be needed as we do not feed quotes anymore
  4019. FTunnelPublicKeyFile = StripPathQuotes(value);
  4020. Modify();
  4021. TunnelPassphrase = XTunnelPassphrase;
  4022. Shred(XTunnelPassphrase);
  4023. }
  4024. }
  4025. //---------------------------------------------------------------------
  4026. void __fastcall TSessionData::SetTunnelLocalPortNumber(int value)
  4027. {
  4028. SET_SESSION_PROPERTY(TunnelLocalPortNumber);
  4029. }
  4030. //---------------------------------------------------------------------
  4031. bool __fastcall TSessionData::GetTunnelAutoassignLocalPortNumber()
  4032. {
  4033. return (FTunnelLocalPortNumber <= 0);
  4034. }
  4035. //---------------------------------------------------------------------
  4036. void __fastcall TSessionData::SetTunnelPortFwd(UnicodeString value)
  4037. {
  4038. SET_SESSION_PROPERTY(TunnelPortFwd);
  4039. }
  4040. //---------------------------------------------------------------------
  4041. void __fastcall TSessionData::SetTunnelHostKey(UnicodeString value)
  4042. {
  4043. SET_SESSION_PROPERTY(TunnelHostKey);
  4044. }
  4045. //---------------------------------------------------------------------
  4046. void __fastcall TSessionData::SetFtpPasvMode(bool value)
  4047. {
  4048. SET_SESSION_PROPERTY(FtpPasvMode);
  4049. }
  4050. //---------------------------------------------------------------------
  4051. void __fastcall TSessionData::SetFtpForcePasvIp(TAutoSwitch value)
  4052. {
  4053. SET_SESSION_PROPERTY(FtpForcePasvIp);
  4054. }
  4055. //---------------------------------------------------------------------
  4056. void __fastcall TSessionData::SetFtpUseMlsd(TAutoSwitch value)
  4057. {
  4058. SET_SESSION_PROPERTY(FtpUseMlsd);
  4059. }
  4060. //---------------------------------------------------------------------
  4061. void __fastcall TSessionData::SetFtpAccount(UnicodeString value)
  4062. {
  4063. SET_SESSION_PROPERTY(FtpAccount);
  4064. }
  4065. //---------------------------------------------------------------------
  4066. void __fastcall TSessionData::SetFtpPingInterval(int value)
  4067. {
  4068. SET_SESSION_PROPERTY(FtpPingInterval);
  4069. }
  4070. //---------------------------------------------------------------------------
  4071. TDateTime __fastcall TSessionData::GetFtpPingIntervalDT()
  4072. {
  4073. return SecToDateTime(FtpPingInterval);
  4074. }
  4075. //---------------------------------------------------------------------------
  4076. void __fastcall TSessionData::SetFtpPingType(TPingType value)
  4077. {
  4078. SET_SESSION_PROPERTY(FtpPingType);
  4079. }
  4080. //---------------------------------------------------------------------------
  4081. void __fastcall TSessionData::SetFtpTransferActiveImmediately(TAutoSwitch value)
  4082. {
  4083. SET_SESSION_PROPERTY(FtpTransferActiveImmediately);
  4084. }
  4085. //---------------------------------------------------------------------------
  4086. void __fastcall TSessionData::SetFtps(TFtps value)
  4087. {
  4088. SET_SESSION_PROPERTY(Ftps);
  4089. }
  4090. //---------------------------------------------------------------------------
  4091. void __fastcall TSessionData::SetMinTlsVersion(TTlsVersion value)
  4092. {
  4093. SET_SESSION_PROPERTY(MinTlsVersion);
  4094. }
  4095. //---------------------------------------------------------------------------
  4096. void __fastcall TSessionData::SetMaxTlsVersion(TTlsVersion value)
  4097. {
  4098. SET_SESSION_PROPERTY(MaxTlsVersion);
  4099. }
  4100. //---------------------------------------------------------------------------
  4101. void __fastcall TSessionData::SetLogicalHostName(UnicodeString value)
  4102. {
  4103. SET_SESSION_PROPERTY(LogicalHostName);
  4104. }
  4105. //---------------------------------------------------------------------
  4106. void __fastcall TSessionData::SetFtpListAll(TAutoSwitch value)
  4107. {
  4108. SET_SESSION_PROPERTY(FtpListAll);
  4109. }
  4110. //---------------------------------------------------------------------
  4111. void __fastcall TSessionData::SetFtpHost(TAutoSwitch value)
  4112. {
  4113. SET_SESSION_PROPERTY(FtpHost);
  4114. }
  4115. //---------------------------------------------------------------------
  4116. void __fastcall TSessionData::SetFtpWorkFromCwd(TAutoSwitch value)
  4117. {
  4118. SET_SESSION_PROPERTY(FtpWorkFromCwd);
  4119. }
  4120. //---------------------------------------------------------------------
  4121. void __fastcall TSessionData::SetSslSessionReuse(bool value)
  4122. {
  4123. SET_SESSION_PROPERTY(SslSessionReuse);
  4124. }
  4125. //---------------------------------------------------------------------
  4126. void __fastcall TSessionData::SetTlsCertificateFile(UnicodeString value)
  4127. {
  4128. SET_SESSION_PROPERTY(TlsCertificateFile);
  4129. }
  4130. //---------------------------------------------------------------------
  4131. void __fastcall TSessionData::SetNotUtf(TAutoSwitch value)
  4132. {
  4133. SET_SESSION_PROPERTY(NotUtf);
  4134. }
  4135. //---------------------------------------------------------------------
  4136. void __fastcall TSessionData::SetInternalEditorEncoding(int value)
  4137. {
  4138. SET_SESSION_PROPERTY(InternalEditorEncoding);
  4139. }
  4140. //---------------------------------------------------------------------
  4141. void __fastcall TSessionData::SetS3DefaultRegion(UnicodeString value)
  4142. {
  4143. SET_SESSION_PROPERTY(S3DefaultRegion);
  4144. }
  4145. //---------------------------------------------------------------------
  4146. void __fastcall TSessionData::SetS3SessionToken(UnicodeString value)
  4147. {
  4148. SET_SESSION_PROPERTY(S3SessionToken);
  4149. }
  4150. //---------------------------------------------------------------------
  4151. void __fastcall TSessionData::SetS3UrlStyle(TS3UrlStyle value)
  4152. {
  4153. SET_SESSION_PROPERTY(S3UrlStyle);
  4154. }
  4155. //---------------------------------------------------------------------
  4156. void __fastcall TSessionData::SetS3MaxKeys(TAutoSwitch value)
  4157. {
  4158. SET_SESSION_PROPERTY(S3MaxKeys);
  4159. }
  4160. //---------------------------------------------------------------------
  4161. void __fastcall TSessionData::SetS3CredentialsEnv(bool value)
  4162. {
  4163. SET_SESSION_PROPERTY(S3CredentialsEnv);
  4164. }
  4165. //---------------------------------------------------------------------
  4166. void __fastcall TSessionData::SetIsWorkspace(bool value)
  4167. {
  4168. SET_SESSION_PROPERTY(IsWorkspace);
  4169. }
  4170. //---------------------------------------------------------------------
  4171. void __fastcall TSessionData::SetLink(UnicodeString value)
  4172. {
  4173. SET_SESSION_PROPERTY(Link);
  4174. }
  4175. //---------------------------------------------------------------------
  4176. void __fastcall TSessionData::SetNameOverride(UnicodeString value)
  4177. {
  4178. SET_SESSION_PROPERTY(NameOverride);
  4179. }
  4180. //---------------------------------------------------------------------
  4181. void __fastcall TSessionData::SetHostKey(UnicodeString value)
  4182. {
  4183. SET_SESSION_PROPERTY(HostKey);
  4184. }
  4185. //---------------------------------------------------------------------
  4186. void __fastcall TSessionData::SetNote(UnicodeString value)
  4187. {
  4188. SET_SESSION_PROPERTY(Note);
  4189. }
  4190. //---------------------------------------------------------------------
  4191. void __fastcall TSessionData::SetWinTitle(UnicodeString value)
  4192. {
  4193. SET_SESSION_PROPERTY(WinTitle);
  4194. }
  4195. //---------------------------------------------------------------------
  4196. UnicodeString __fastcall TSessionData::GetEncryptKey() const
  4197. {
  4198. return DecryptPassword(FEncryptKey, UserName+HostName);
  4199. }
  4200. //---------------------------------------------------------------------
  4201. void __fastcall TSessionData::SetEncryptKey(UnicodeString avalue)
  4202. {
  4203. RawByteString value = EncryptPassword(avalue, UserName+HostName);
  4204. SET_SESSION_PROPERTY(EncryptKey);
  4205. }
  4206. //---------------------------------------------------------------------
  4207. void __fastcall TSessionData::SetWebDavLiberalEscaping(bool value)
  4208. {
  4209. SET_SESSION_PROPERTY(WebDavLiberalEscaping);
  4210. }
  4211. //---------------------------------------------------------------------
  4212. UnicodeString __fastcall TSessionData::GetInfoTip()
  4213. {
  4214. if (UsesSsh)
  4215. {
  4216. return FMTLOAD(SESSION_INFO_TIP2,
  4217. (HostName, UserName,
  4218. (PublicKeyFile.IsEmpty() ? LoadStr(NO_STR) : LoadStr(YES_STR)),
  4219. FSProtocolStr));
  4220. }
  4221. else
  4222. {
  4223. return FMTLOAD(SESSION_INFO_TIP_NO_SSH,
  4224. (HostName, UserName, FSProtocolStr));
  4225. }
  4226. }
  4227. //---------------------------------------------------------------------
  4228. UnicodeString __fastcall TSessionData::ExtractLocalName(const UnicodeString & Name)
  4229. {
  4230. UnicodeString Result = Name;
  4231. int P = Result.LastDelimiter(L"/");
  4232. if (P > 0)
  4233. {
  4234. Result.Delete(1, P);
  4235. }
  4236. return Result;
  4237. }
  4238. //---------------------------------------------------------------------
  4239. UnicodeString __fastcall TSessionData::GetLocalName()
  4240. {
  4241. UnicodeString Result;
  4242. if (HasSessionName())
  4243. {
  4244. Result = ExtractLocalName(Name);
  4245. }
  4246. else
  4247. {
  4248. Result = DefaultSessionName;
  4249. }
  4250. return Result;
  4251. }
  4252. //---------------------------------------------------------------------
  4253. UnicodeString __fastcall TSessionData::ExtractFolderName(const UnicodeString & Name)
  4254. {
  4255. UnicodeString Result;
  4256. int P = Name.LastDelimiter(L"/");
  4257. if (P > 0)
  4258. {
  4259. Result = Name.SubString(1, P - 1);
  4260. }
  4261. return Result;
  4262. }
  4263. //---------------------------------------------------------------------
  4264. UnicodeString __fastcall TSessionData::GetFolderName()
  4265. {
  4266. UnicodeString Result;
  4267. if (HasSessionName() || IsWorkspace)
  4268. {
  4269. Result = ExtractFolderName(Name);
  4270. }
  4271. return Result;
  4272. }
  4273. //---------------------------------------------------------------------
  4274. UnicodeString __fastcall TSessionData::ComposePath(
  4275. const UnicodeString & Path, const UnicodeString & Name)
  4276. {
  4277. return UnixIncludeTrailingBackslash(Path) + Name;
  4278. }
  4279. //---------------------------------------------------------------------
  4280. void __fastcall TSessionData::DisableAuthentationsExceptPassword()
  4281. {
  4282. SshNoUserAuth = false;
  4283. AuthKI = false;
  4284. AuthKIPassword = false;
  4285. AuthGSSAPI = false;
  4286. AuthGSSAPIKEX = false;
  4287. PublicKeyFile = L"";
  4288. TlsCertificateFile = L"";
  4289. Passphrase = L"";
  4290. TryAgent = false;
  4291. }
  4292. //---------------------------------------------------------------------
  4293. TStrings * TSessionData::GetAllOptionNames(bool PuttyExport)
  4294. {
  4295. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  4296. return FactoryDefaults->SaveToOptions(NULL, false, PuttyExport);
  4297. }
  4298. //---------------------------------------------------------------------
  4299. bool TSessionData::HasS3AutoCredentials()
  4300. {
  4301. return (FSProtocol == fsS3) && S3CredentialsEnv;
  4302. }
  4303. //---------------------------------------------------------------------
  4304. bool TSessionData::HasAutoCredentials()
  4305. {
  4306. return HasS3AutoCredentials();
  4307. }
  4308. //=== TStoredSessionList ----------------------------------------------
  4309. __fastcall TStoredSessionList::TStoredSessionList(bool aReadOnly):
  4310. TNamedObjectList(), FReadOnly(aReadOnly)
  4311. {
  4312. DebugAssert(Configuration);
  4313. FDefaultSettings = new TSessionData(DefaultName);
  4314. FPendingRemovals.reset(new TStringList());
  4315. }
  4316. //---------------------------------------------------------------------
  4317. __fastcall TStoredSessionList::~TStoredSessionList()
  4318. {
  4319. DebugAssert(Configuration);
  4320. delete FDefaultSettings;
  4321. }
  4322. //---------------------------------------------------------------------
  4323. void __fastcall TStoredSessionList::Load(THierarchicalStorage * Storage,
  4324. bool AsModified, bool UseDefaults, bool PuttyImport)
  4325. {
  4326. TStringList *SubKeys = new TStringList();
  4327. TList * Loaded = new TList;
  4328. try
  4329. {
  4330. DebugAssert(AutoSort);
  4331. AutoSort = false;
  4332. bool WasEmpty = (Count == 0);
  4333. Storage->GetSubKeyNames(SubKeys);
  4334. for (int Index = 0; Index < SubKeys->Count; Index++)
  4335. {
  4336. UnicodeString SessionName = SubKeys->Strings[Index];
  4337. bool ValidName = true;
  4338. try
  4339. {
  4340. TSessionData::ValidatePath(SessionName);
  4341. }
  4342. catch(...)
  4343. {
  4344. ValidName = false;
  4345. }
  4346. if (ValidName)
  4347. {
  4348. TSessionData * SessionData;
  4349. if (SessionName == FDefaultSettings->Name)
  4350. {
  4351. SessionData = FDefaultSettings;
  4352. }
  4353. else
  4354. {
  4355. // if the list was empty before loading, do not waste time trying to
  4356. // find existing sites to overwrite (we rely on underlying storage
  4357. // to secure uniqueness of the key names)
  4358. if (WasEmpty)
  4359. {
  4360. SessionData = NULL;
  4361. }
  4362. else
  4363. {
  4364. SessionData = (TSessionData*)FindByName(SessionName);
  4365. }
  4366. }
  4367. if ((SessionData != FDefaultSettings) || !UseDefaults)
  4368. {
  4369. if (SessionData == NULL)
  4370. {
  4371. SessionData = new TSessionData(L"");
  4372. if (UseDefaults)
  4373. {
  4374. SessionData->CopyData(DefaultSettings);
  4375. }
  4376. SessionData->Name = SessionName;
  4377. Add(SessionData);
  4378. }
  4379. Loaded->Add(SessionData);
  4380. SessionData->Load(Storage, PuttyImport);
  4381. if (AsModified)
  4382. {
  4383. SessionData->Modified = true;
  4384. }
  4385. }
  4386. }
  4387. }
  4388. if (!AsModified)
  4389. {
  4390. for (int Index = 0; Index < TObjectList::Count; Index++)
  4391. {
  4392. if (Loaded->IndexOf(Items[Index]) < 0)
  4393. {
  4394. Delete(Index);
  4395. Index--;
  4396. }
  4397. }
  4398. }
  4399. }
  4400. __finally
  4401. {
  4402. AutoSort = true;
  4403. AlphaSort();
  4404. delete SubKeys;
  4405. delete Loaded;
  4406. }
  4407. }
  4408. //---------------------------------------------------------------------
  4409. void __fastcall TStoredSessionList::Reload()
  4410. {
  4411. if (Count <= Configuration->DontReloadMoreThanSessions)
  4412. {
  4413. bool SessionList = true;
  4414. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));
  4415. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, False))
  4416. {
  4417. Load(Storage.get());
  4418. }
  4419. }
  4420. }
  4421. //---------------------------------------------------------------------
  4422. void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,
  4423. TSessionData * Data, bool All, bool RecryptPasswordOnly,
  4424. TSessionData * FactoryDefaults)
  4425. {
  4426. if (All || Data->Modified)
  4427. {
  4428. if (RecryptPasswordOnly)
  4429. {
  4430. Data->SaveRecryptedPasswords(Storage);
  4431. }
  4432. else
  4433. {
  4434. Data->Save(Storage, false, FactoryDefaults);
  4435. }
  4436. }
  4437. }
  4438. //---------------------------------------------------------------------
  4439. void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,
  4440. bool All, bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)
  4441. {
  4442. TSessionData * FactoryDefaults = new TSessionData(L"");
  4443. try
  4444. {
  4445. while (FPendingRemovals->Count > 0)
  4446. {
  4447. TSessionData::Remove(Storage, FPendingRemovals->Strings[0]);
  4448. FPendingRemovals->Delete(0);
  4449. }
  4450. DoSave(Storage, FDefaultSettings, All, RecryptPasswordOnly, FactoryDefaults);
  4451. for (int Index = 0; Index < CountIncludingHidden; Index++)
  4452. {
  4453. TSessionData * SessionData = (TSessionData *)Items[Index];
  4454. try
  4455. {
  4456. DoSave(Storage, SessionData, All, RecryptPasswordOnly, FactoryDefaults);
  4457. }
  4458. catch (Exception & E)
  4459. {
  4460. UnicodeString Message;
  4461. if (RecryptPasswordOnly && DebugAlwaysTrue(RecryptPasswordErrors != NULL) &&
  4462. ExceptionMessage(&E, Message))
  4463. {
  4464. RecryptPasswordErrors->Add(FORMAT("%s: %s", (SessionData->SessionName, Message)));
  4465. }
  4466. else
  4467. {
  4468. throw;
  4469. }
  4470. }
  4471. }
  4472. }
  4473. __finally
  4474. {
  4475. delete FactoryDefaults;
  4476. }
  4477. }
  4478. //---------------------------------------------------------------------
  4479. void __fastcall TStoredSessionList::Save(THierarchicalStorage * Storage, bool All)
  4480. {
  4481. DoSave(Storage, All, false, NULL);
  4482. }
  4483. //---------------------------------------------------------------------
  4484. void __fastcall TStoredSessionList::DoSave(bool All, bool Explicit,
  4485. bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)
  4486. {
  4487. bool SessionList = true;
  4488. THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);
  4489. try
  4490. {
  4491. Storage->AccessMode = smReadWrite;
  4492. Storage->Explicit = Explicit;
  4493. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))
  4494. {
  4495. DoSave(Storage, All, RecryptPasswordOnly, RecryptPasswordErrors);
  4496. }
  4497. }
  4498. __finally
  4499. {
  4500. delete Storage;
  4501. }
  4502. Saved();
  4503. }
  4504. //---------------------------------------------------------------------
  4505. void __fastcall TStoredSessionList::Save(bool All, bool Explicit)
  4506. {
  4507. DoSave(All, Explicit, false, NULL);
  4508. }
  4509. //---------------------------------------------------------------------
  4510. void __fastcall TStoredSessionList::RecryptPasswords(TStrings * RecryptPasswordErrors)
  4511. {
  4512. DoSave(true, true, true, RecryptPasswordErrors);
  4513. }
  4514. //---------------------------------------------------------------------
  4515. void __fastcall TStoredSessionList::Saved()
  4516. {
  4517. FDefaultSettings->Modified = false;
  4518. for (int Index = 0; Index < CountIncludingHidden; Index++)
  4519. {
  4520. ((TSessionData *)Items[Index])->Modified = false;
  4521. }
  4522. }
  4523. //---------------------------------------------------------------------
  4524. void __fastcall TStoredSessionList::ImportLevelFromFilezilla(
  4525. _di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode)
  4526. {
  4527. for (int Index = 0; Index < Node->ChildNodes->Count; Index++)
  4528. {
  4529. _di_IXMLNode ChildNode = Node->ChildNodes->Get(Index);
  4530. if (ChildNode->NodeName == L"Server")
  4531. {
  4532. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  4533. SessionData->CopyData(DefaultSettings);
  4534. SessionData->ImportFromFilezilla(ChildNode, Path, SettingsNode);
  4535. Add(SessionData.release());
  4536. }
  4537. else if (ChildNode->NodeName == L"Folder")
  4538. {
  4539. UnicodeString Name;
  4540. for (int Index = 0; Index < ChildNode->ChildNodes->Count; Index++)
  4541. {
  4542. _di_IXMLNode PossibleTextMode = ChildNode->ChildNodes->Get(Index);
  4543. if (PossibleTextMode->NodeType == ntText)
  4544. {
  4545. UnicodeString NodeValue = PossibleTextMode->NodeValue;
  4546. AddToList(Name, NodeValue.Trim(), L" ");
  4547. }
  4548. }
  4549. Name = TSessionData::MakeValidName(Name).Trim();
  4550. ImportLevelFromFilezilla(ChildNode, TSessionData::ComposePath(Path, Name), SettingsNode);
  4551. }
  4552. }
  4553. }
  4554. //---------------------------------------------------------------------
  4555. void __fastcall TStoredSessionList::ImportFromFilezilla(
  4556. const UnicodeString FileName, const UnicodeString ConfigurationFileName)
  4557. {
  4558. // not sure if the document must exists if we want to use its node
  4559. _di_IXMLDocument ConfigurationDocument;
  4560. _di_IXMLNode SettingsNode;
  4561. if (FileExists(ApiPath(ConfigurationFileName)))
  4562. {
  4563. ConfigurationDocument = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));
  4564. ConfigurationDocument->LoadFromFile(ConfigurationFileName);
  4565. _di_IXMLNode FileZilla3Node = ConfigurationDocument->ChildNodes->FindNode(L"FileZilla3");
  4566. if (FileZilla3Node != NULL)
  4567. {
  4568. SettingsNode = FileZilla3Node->ChildNodes->FindNode(L"Settings");
  4569. }
  4570. }
  4571. const _di_IXMLDocument Document = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));
  4572. Document->LoadFromFile(FileName);
  4573. _di_IXMLNode FileZilla3Node = Document->ChildNodes->FindNode(L"FileZilla3");
  4574. if (FileZilla3Node != NULL)
  4575. {
  4576. _di_IXMLNode ServersNode = FileZilla3Node->ChildNodes->FindNode(L"Servers");
  4577. if (ServersNode != NULL)
  4578. {
  4579. ImportLevelFromFilezilla(ServersNode, L"", SettingsNode);
  4580. }
  4581. }
  4582. }
  4583. //---------------------------------------------------------------------
  4584. UnicodeString FormatKnownHostName(const UnicodeString & HostName, int PortNumber)
  4585. {
  4586. return FORMAT(L"%s:%d", (HostName, PortNumber));
  4587. }
  4588. //---------------------------------------------------------------------
  4589. void __fastcall TStoredSessionList::ImportFromKnownHosts(TStrings * Lines)
  4590. {
  4591. bool SessionList = false;
  4592. std::unique_ptr<THierarchicalStorage> HostKeyStorage(Configuration->CreateScpStorage(SessionList));
  4593. std::unique_ptr<TStrings> KeyList(new TStringList());
  4594. if (OpenHostKeysSubKey(HostKeyStorage.get(), false))
  4595. {
  4596. HostKeyStorage->GetValueNames(KeyList.get());
  4597. }
  4598. HostKeyStorage.reset(NULL);
  4599. UnicodeString FirstError;
  4600. for (int Index = 0; Index < Lines->Count; Index++)
  4601. {
  4602. try
  4603. {
  4604. UnicodeString Line = Lines->Strings[Index];
  4605. Line = Trim(Line);
  4606. if (IsValidOpensshLine(Line))
  4607. {
  4608. int P = Pos(L' ', Line);
  4609. if (P > 0)
  4610. {
  4611. UnicodeString HostNameStr = Line.SubString(1, P - 1);
  4612. Line = Line.SubString(P + 1, Line.Length() - P);
  4613. P = Pos(L',', HostNameStr);
  4614. if (P > 0)
  4615. {
  4616. HostNameStr.SetLength(P - 1);
  4617. }
  4618. P = Pos(L':', HostNameStr);
  4619. int PortNumber = -1;
  4620. if (P > 0)
  4621. {
  4622. UnicodeString PortNumberStr = HostNameStr.SubString(P + 1, HostNameStr.Length() - P);
  4623. PortNumber = StrToInt(PortNumberStr);
  4624. HostNameStr.SetLength(P - 1);
  4625. }
  4626. if (HasIP6LiteralBrackets(HostNameStr))
  4627. {
  4628. HostNameStr = StripIP6LiteralBrackets(HostNameStr);
  4629. }
  4630. UnicodeString NameStr = HostNameStr;
  4631. if (PortNumber >= 0)
  4632. {
  4633. NameStr = FormatKnownHostName(NameStr, PortNumber);
  4634. }
  4635. std::unique_ptr<TSessionData> SessionDataOwner;
  4636. TSessionData * SessionData = dynamic_cast<TSessionData *>(FindByName(NameStr));
  4637. if (SessionData == NULL)
  4638. {
  4639. SessionData = new TSessionData(L"");
  4640. SessionDataOwner.reset(SessionData);
  4641. SessionData->CopyData(DefaultSettings);
  4642. SessionData->Name = NameStr;
  4643. SessionData->HostName = HostNameStr;
  4644. if (PortNumber >= 0)
  4645. {
  4646. SessionData->PortNumber = PortNumber;
  4647. }
  4648. }
  4649. const struct ssh_keyalg * Algorithm;
  4650. UnicodeString Key = ParseOpenSshPubLine(Line, Algorithm);
  4651. UnicodeString KeyKey =
  4652. FORMAT(L"%s@%d:%s", (Algorithm->cache_id, SessionData->PortNumber, HostNameStr));
  4653. UnicodeString HostKey =
  4654. FORMAT(L"%s:%s=%s", (Algorithm->ssh_id, KeyKey, Key));
  4655. UnicodeString HostKeyList = SessionData->HostKey;
  4656. AddToList(HostKeyList, HostKey, L";");
  4657. SessionData->HostKey = HostKeyList;
  4658. // If there's at least one unknown key type for this host, select it
  4659. if (KeyList->IndexOf(KeyKey) < 0)
  4660. {
  4661. SessionData->Selected = true;
  4662. }
  4663. if (SessionDataOwner.get() != NULL)
  4664. {
  4665. Add(SessionDataOwner.release());
  4666. }
  4667. }
  4668. }
  4669. }
  4670. catch (Exception & E)
  4671. {
  4672. if (FirstError.IsEmpty())
  4673. {
  4674. FirstError = E.Message;
  4675. }
  4676. }
  4677. }
  4678. if (Count == 0)
  4679. {
  4680. UnicodeString Message = LoadStr(KNOWN_HOSTS_NO_SITES);
  4681. if (!FirstError.IsEmpty())
  4682. {
  4683. Message = FORMAT(L"%s\n(%s)", (Message, FirstError));
  4684. }
  4685. throw Exception(Message);
  4686. }
  4687. }
  4688. //---------------------------------------------------------------------
  4689. void TStoredSessionList::ImportFromOpenssh(TStrings * Lines)
  4690. {
  4691. std::unique_ptr<TStrings> Hosts(CreateSortedStringList());
  4692. for (int Index = 0; Index < Lines->Count; Index++)
  4693. {
  4694. UnicodeString Line = Lines->Strings[Index];
  4695. UnicodeString Directive, Value;
  4696. if (ParseOpensshDirective(Line, Directive, Value) &&
  4697. SameText(Directive, OpensshHostDirective))
  4698. {
  4699. while (!Value.IsEmpty())
  4700. {
  4701. UnicodeString Name = CutOpensshToken(Value);
  4702. if ((Hosts->IndexOf(Name) < 0) && (Name.LastDelimiter(L"*?") == 0))
  4703. {
  4704. std::unique_ptr<TSessionData> Data(new TSessionData(EmptyStr));
  4705. Data->CopyData(DefaultSettings);
  4706. Data->Name = Name;
  4707. Data->HostName = Name;
  4708. Data->ImportFromOpenssh(Lines);
  4709. Add(Data.release());
  4710. Hosts->Add(Name);
  4711. }
  4712. }
  4713. }
  4714. }
  4715. }
  4716. //---------------------------------------------------------------------
  4717. void __fastcall TStoredSessionList::Export(const UnicodeString FileName)
  4718. {
  4719. THierarchicalStorage * Storage = TIniFileStorage::CreateFromPath(FileName);
  4720. try
  4721. {
  4722. Storage->AccessMode = smReadWrite;
  4723. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))
  4724. {
  4725. Save(Storage, true);
  4726. }
  4727. }
  4728. __finally
  4729. {
  4730. delete Storage;
  4731. }
  4732. }
  4733. //---------------------------------------------------------------------
  4734. void __fastcall TStoredSessionList::SelectAll(bool Select)
  4735. {
  4736. for (int Index = 0; Index < Count; Index++)
  4737. Sessions[Index]->Selected = Select;
  4738. }
  4739. //---------------------------------------------------------------------
  4740. void __fastcall TStoredSessionList::Import(TStoredSessionList * From,
  4741. bool OnlySelected, TList * Imported)
  4742. {
  4743. for (int Index = 0; Index < From->Count; Index++)
  4744. {
  4745. if (!OnlySelected || From->Sessions[Index]->Selected)
  4746. {
  4747. TSessionData *Session = new TSessionData(L"");
  4748. Session->Assign(From->Sessions[Index]);
  4749. Session->Modified = true;
  4750. Session->MakeUniqueIn(this);
  4751. Add(Session);
  4752. if (Imported != NULL)
  4753. {
  4754. Imported->Add(Session);
  4755. }
  4756. }
  4757. }
  4758. // only modified, explicit
  4759. Save(false, true);
  4760. }
  4761. //---------------------------------------------------------------------
  4762. void __fastcall TStoredSessionList::SelectSessionsToImport
  4763. (TStoredSessionList * Dest, bool SSHOnly)
  4764. {
  4765. for (int Index = 0; Index < Count; Index++)
  4766. {
  4767. Sessions[Index]->Selected =
  4768. (!SSHOnly || (Sessions[Index]->GetNormalizedPuttyProtocol() == PuttySshProtocol)) &&
  4769. !Dest->FindByName(Sessions[Index]->Name);
  4770. }
  4771. }
  4772. //---------------------------------------------------------------------
  4773. void __fastcall TStoredSessionList::Cleanup()
  4774. {
  4775. try
  4776. {
  4777. if (Configuration->Storage == stRegistry) Clear();
  4778. TRegistryStorage * Storage = new TRegistryStorage(Configuration->RegistryStorageKey);
  4779. try
  4780. {
  4781. Storage->AccessMode = smReadWrite;
  4782. if (Storage->OpenRootKey(False))
  4783. Storage->RecursiveDeleteSubKey(Configuration->StoredSessionsSubKey);
  4784. }
  4785. __finally
  4786. {
  4787. delete Storage;
  4788. }
  4789. }
  4790. catch (Exception &E)
  4791. {
  4792. throw ExtException(&E, LoadStr(CLEANUP_SESSIONS_ERROR));
  4793. }
  4794. }
  4795. //---------------------------------------------------------------------------
  4796. void __fastcall TStoredSessionList::UpdateStaticUsage()
  4797. {
  4798. int SCP = 0;
  4799. int SFTP = 0;
  4800. int FTP = 0;
  4801. int FTPS = 0;
  4802. int WebDAV = 0;
  4803. int WebDAVS = 0;
  4804. int S3 = 0;
  4805. int Password = 0;
  4806. int Advanced = 0;
  4807. int Color = 0;
  4808. int Note = 0;
  4809. int Tunnel = 0;
  4810. bool Folders = false;
  4811. bool Workspaces = false;
  4812. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  4813. std::unique_ptr<TStringList> DifferentAdvancedProperties(CreateSortedStringList());
  4814. for (int Index = 0; Index < Count; Index++)
  4815. {
  4816. TSessionData * Data = Sessions[Index];
  4817. if (Data->IsWorkspace)
  4818. {
  4819. Workspaces = true;
  4820. }
  4821. else
  4822. {
  4823. switch (Data->FSProtocol)
  4824. {
  4825. case fsSCPonly:
  4826. SCP++;
  4827. break;
  4828. case fsSFTP:
  4829. case fsSFTPonly:
  4830. SFTP++;
  4831. break;
  4832. case fsFTP:
  4833. if (Data->Ftps == ftpsNone)
  4834. {
  4835. FTP++;
  4836. }
  4837. else
  4838. {
  4839. FTPS++;
  4840. }
  4841. break;
  4842. case fsWebDAV:
  4843. if (Data->Ftps == ftpsNone)
  4844. {
  4845. WebDAV++;
  4846. }
  4847. else
  4848. {
  4849. WebDAVS++;
  4850. }
  4851. break;
  4852. case fsS3:
  4853. S3++;
  4854. break;
  4855. }
  4856. if (Data->HasAnySessionPassword())
  4857. {
  4858. Password++;
  4859. }
  4860. if (Data->Color != 0)
  4861. {
  4862. Color++;
  4863. }
  4864. if (!Data->Note.IsEmpty())
  4865. {
  4866. Note++;
  4867. }
  4868. // This would not work for passwords, as they are compared in their encrypted form.
  4869. // But there are no passwords set in factory defaults anyway.
  4870. if (!Data->IsSame(FactoryDefaults.get(), true, DifferentAdvancedProperties.get(), false))
  4871. {
  4872. Advanced++;
  4873. }
  4874. if (Data->Tunnel)
  4875. {
  4876. Tunnel++;
  4877. }
  4878. if (!Data->FolderName.IsEmpty())
  4879. {
  4880. Folders = true;
  4881. }
  4882. }
  4883. }
  4884. Configuration->Usage->Set(L"StoredSessionsCountSCP", SCP);
  4885. Configuration->Usage->Set(L"StoredSessionsCountSFTP", SFTP);
  4886. Configuration->Usage->Set(L"StoredSessionsCountFTP", FTP);
  4887. Configuration->Usage->Set(L"StoredSessionsCountFTPS", FTPS);
  4888. Configuration->Usage->Set(L"StoredSessionsCountWebDAV", WebDAV);
  4889. Configuration->Usage->Set(L"StoredSessionsCountWebDAVS", WebDAVS);
  4890. Configuration->Usage->Set(L"StoredSessionsCountS3", S3);
  4891. Configuration->Usage->Set(L"StoredSessionsCountPassword", Password);
  4892. Configuration->Usage->Set(L"StoredSessionsCountColor", Color);
  4893. Configuration->Usage->Set(L"StoredSessionsCountNote", Note);
  4894. Configuration->Usage->Set(L"StoredSessionsCountAdvanced", Advanced);
  4895. DifferentAdvancedProperties->Delimiter = L',';
  4896. Configuration->Usage->Set(L"StoredSessionsAdvancedSettings", DifferentAdvancedProperties->DelimitedText);
  4897. Configuration->Usage->Set(L"StoredSessionsCountTunnel", Tunnel);
  4898. // actually default might be true, see below for when the default is actually used
  4899. bool CustomDefaultStoredSession = false;
  4900. try
  4901. {
  4902. // this can throw, when the default session settings have password set
  4903. // (and no other basic property, like hostname/username),
  4904. // and master password is enabled as we are called before master password
  4905. // handler is set
  4906. CustomDefaultStoredSession = !FDefaultSettings->IsSame(FactoryDefaults.get(), false);
  4907. }
  4908. catch (...)
  4909. {
  4910. }
  4911. Configuration->Usage->Set(L"UsingDefaultStoredSession", CustomDefaultStoredSession);
  4912. Configuration->Usage->Set(L"UsingStoredSessionsFolders", Folders);
  4913. Configuration->Usage->Set(L"UsingWorkspaces", Workspaces);
  4914. }
  4915. //---------------------------------------------------------------------------
  4916. TSessionData * __fastcall TStoredSessionList::FindSame(TSessionData * Data)
  4917. {
  4918. TSessionData * Result;
  4919. if (Data->Hidden || Data->Name.IsEmpty() || Data->IsWorkspace)
  4920. {
  4921. Result = NULL;
  4922. }
  4923. else
  4924. {
  4925. Result = dynamic_cast<TSessionData *>(FindByName(Data->Name));
  4926. }
  4927. return Result;
  4928. }
  4929. //---------------------------------------------------------------------------
  4930. int __fastcall TStoredSessionList::IndexOf(TSessionData * Data)
  4931. {
  4932. for (int Index = 0; Index < Count; Index++)
  4933. if (Data == Sessions[Index]) return Index;
  4934. return -1;
  4935. }
  4936. //---------------------------------------------------------------------------
  4937. TSessionData * __fastcall TStoredSessionList::NewSession(
  4938. UnicodeString SessionName, TSessionData * Session)
  4939. {
  4940. TSessionData * DuplicateSession = (TSessionData*)FindByName(SessionName);
  4941. if (!DuplicateSession)
  4942. {
  4943. DuplicateSession = new TSessionData(L"");
  4944. DuplicateSession->Assign(Session);
  4945. DuplicateSession->Name = SessionName;
  4946. // make sure, that new stored session is saved to registry
  4947. DuplicateSession->Modified = true;
  4948. Add(DuplicateSession);
  4949. }
  4950. else
  4951. {
  4952. DuplicateSession->Assign(Session);
  4953. DuplicateSession->Name = SessionName;
  4954. DuplicateSession->Modified = true;
  4955. }
  4956. // list was saved here before to default storage, but it would not allow
  4957. // to work with special lists (export/import) not using default storage
  4958. return DuplicateSession;
  4959. }
  4960. //---------------------------------------------------------------------------
  4961. void __fastcall TStoredSessionList::SetDefaultSettings(TSessionData * value)
  4962. {
  4963. DebugAssert(FDefaultSettings);
  4964. if (FDefaultSettings != value)
  4965. {
  4966. FDefaultSettings->Assign(value);
  4967. // make sure default settings are saved
  4968. FDefaultSettings->Modified = true;
  4969. FDefaultSettings->Name = DefaultName;
  4970. if (!FReadOnly)
  4971. {
  4972. // only modified, explicit
  4973. Save(false, true);
  4974. }
  4975. }
  4976. }
  4977. //---------------------------------------------------------------------------
  4978. bool __fastcall TStoredSessionList::OpenHostKeysSubKey(THierarchicalStorage * Storage, bool CanCreate)
  4979. {
  4980. return
  4981. Storage->OpenRootKey(CanCreate) &&
  4982. Storage->OpenSubKey(Configuration->SshHostKeysSubKey, CanCreate);
  4983. }
  4984. //---------------------------------------------------------------------------
  4985. THierarchicalStorage * __fastcall TStoredSessionList::CreateHostKeysStorageForWritting()
  4986. {
  4987. bool SessionList = false;
  4988. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));
  4989. Storage->Explicit = true;
  4990. Storage->AccessMode = smReadWrite;
  4991. return Storage.release();
  4992. }
  4993. //---------------------------------------------------------------------------
  4994. void __fastcall TStoredSessionList::ImportHostKeys(
  4995. THierarchicalStorage * SourceStorage, THierarchicalStorage * TargetStorage, TStoredSessionList * Sessions, bool OnlySelected)
  4996. {
  4997. if (OpenHostKeysSubKey(SourceStorage, false) &&
  4998. OpenHostKeysSubKey(TargetStorage, true))
  4999. {
  5000. std::auto_ptr<TStringList> KeyList(new TStringList());
  5001. SourceStorage->GetValueNames(KeyList.get());
  5002. DebugAssert(Sessions != NULL);
  5003. for (int Index = 0; Index < Sessions->Count; Index++)
  5004. {
  5005. TSessionData * Session = Sessions->Sessions[Index];
  5006. if (!OnlySelected || Session->Selected)
  5007. {
  5008. UnicodeString HostKeyName = PuttyMungeStr(FORMAT(L"@%d:%s", (Session->PortNumber, Session->HostNameExpanded)));
  5009. for (int KeyIndex = 0; KeyIndex < KeyList->Count; KeyIndex++)
  5010. {
  5011. UnicodeString KeyName = KeyList->Strings[KeyIndex];
  5012. if (EndsText(HostKeyName, KeyName))
  5013. {
  5014. TargetStorage->WriteStringRaw(KeyName, SourceStorage->ReadStringRaw(KeyName, L""));
  5015. }
  5016. }
  5017. }
  5018. }
  5019. }
  5020. }
  5021. //---------------------------------------------------------------------------
  5022. void __fastcall TStoredSessionList::ImportHostKeys(
  5023. const UnicodeString & SourceKey, TStoredSessionList * Sessions, bool OnlySelected)
  5024. {
  5025. std::auto_ptr<THierarchicalStorage> TargetStorage(CreateHostKeysStorageForWritting());
  5026. std::auto_ptr<THierarchicalStorage> SourceStorage(new TRegistryStorage(SourceKey));
  5027. ImportHostKeys(SourceStorage.get(), TargetStorage.get(), Sessions, OnlySelected);
  5028. }
  5029. //---------------------------------------------------------------------------
  5030. void __fastcall TStoredSessionList::ImportSelectedKnownHosts(TStoredSessionList * Sessions)
  5031. {
  5032. std::unique_ptr<THierarchicalStorage> Storage(CreateHostKeysStorageForWritting());
  5033. if (OpenHostKeysSubKey(Storage.get(), true))
  5034. {
  5035. for (int Index = 0; Index < Sessions->Count; Index++)
  5036. {
  5037. TSessionData * Session = Sessions->Sessions[Index];
  5038. if (Session->Selected)
  5039. {
  5040. UnicodeString Algs;
  5041. UnicodeString HostKeys = Session->HostKey;
  5042. while (!HostKeys.IsEmpty())
  5043. {
  5044. UnicodeString HostKey = CutToChar(HostKeys, L';', true);
  5045. // skip alg
  5046. CutToChar(HostKey, L':', true);
  5047. UnicodeString Key = CutToChar(HostKey, L'=', true);
  5048. Storage->WriteStringRaw(Key, HostKey);
  5049. }
  5050. }
  5051. }
  5052. }
  5053. }
  5054. //---------------------------------------------------------------------------
  5055. void TStoredSessionList::SelectKnownHostsForSelectedSessions(
  5056. TStoredSessionList * KnownHosts, TStoredSessionList * Sessions)
  5057. {
  5058. for (int SessionIndex = 0; SessionIndex < Sessions->Count; SessionIndex++)
  5059. {
  5060. TSessionData * Session = Sessions->Sessions[SessionIndex];
  5061. if (Session->Selected)
  5062. {
  5063. UnicodeString Key = Session->HostName;
  5064. if (Session->PortNumber != Session->GetDefaultPort())
  5065. {
  5066. Key = FormatKnownHostName(Key, Session->PortNumber);
  5067. }
  5068. TSessionData * KnownHost = dynamic_cast<TSessionData *>(KnownHosts->FindByName(Key));
  5069. if (KnownHost != NULL)
  5070. {
  5071. KnownHost->Selected = true;
  5072. }
  5073. }
  5074. }
  5075. }
  5076. //---------------------------------------------------------------------------
  5077. bool __fastcall TStoredSessionList::IsFolderOrWorkspace(
  5078. const UnicodeString & Name, bool Workspace)
  5079. {
  5080. bool Result = false;
  5081. TSessionData * FirstData = NULL;
  5082. if (!Name.IsEmpty())
  5083. {
  5084. for (int Index = 0; !Result && (Index < Count); Index++)
  5085. {
  5086. Result = Sessions[Index]->IsInFolderOrWorkspace(Name);
  5087. if (Result)
  5088. {
  5089. FirstData = Sessions[Index];
  5090. }
  5091. }
  5092. }
  5093. return
  5094. Result &&
  5095. DebugAlwaysTrue(FirstData != NULL) &&
  5096. (FirstData->IsWorkspace == Workspace);
  5097. }
  5098. //---------------------------------------------------------------------------
  5099. bool __fastcall TStoredSessionList::IsFolder(const UnicodeString & Name)
  5100. {
  5101. return IsFolderOrWorkspace(Name, false);
  5102. }
  5103. //---------------------------------------------------------------------------
  5104. bool __fastcall TStoredSessionList::IsWorkspace(const UnicodeString & Name)
  5105. {
  5106. return IsFolderOrWorkspace(Name, true);
  5107. }
  5108. //---------------------------------------------------------------------------
  5109. TSessionData * __fastcall TStoredSessionList::CheckIsInFolderOrWorkspaceAndResolve(
  5110. TSessionData * Data, const UnicodeString & Name)
  5111. {
  5112. if (Data->IsInFolderOrWorkspace(Name))
  5113. {
  5114. Data = ResolveWorkspaceData(Data);
  5115. if ((Data != NULL) && Data->CanOpen &&
  5116. DebugAlwaysTrue(Data->Link.IsEmpty()))
  5117. {
  5118. return Data;
  5119. }
  5120. }
  5121. return NULL;
  5122. }
  5123. //---------------------------------------------------------------------------
  5124. void __fastcall TStoredSessionList::GetFolderOrWorkspace(const UnicodeString & Name, TList * List)
  5125. {
  5126. DoGetFolderOrWorkspace(Name, List, false);
  5127. }
  5128. //---------------------------------------------------------------------------
  5129. void __fastcall TStoredSessionList::DoGetFolderOrWorkspace(const UnicodeString & Name, TList * List, bool NoRecrypt)
  5130. {
  5131. for (int Index = 0; (Index < Count); Index++)
  5132. {
  5133. TSessionData * RawData = Sessions[Index];
  5134. TSessionData * Data =
  5135. CheckIsInFolderOrWorkspaceAndResolve(RawData, Name);
  5136. if (Data != NULL)
  5137. {
  5138. TSessionData * Data2 = new TSessionData(L"");
  5139. if (NoRecrypt)
  5140. {
  5141. Data2->CopyDataNoRecrypt(Data);
  5142. }
  5143. else
  5144. {
  5145. Data2->Assign(Data);
  5146. }
  5147. if (!RawData->Link.IsEmpty() && (DebugAlwaysTrue(Data != RawData)) &&
  5148. // BACKWARD COMPATIBILITY
  5149. // When loading pre-5.6.4 workspace, that does not have state saved,
  5150. // do not overwrite the site "state" defaults
  5151. // with (empty) workspace state
  5152. RawData->HasStateData())
  5153. {
  5154. Data2->CopyStateData(RawData);
  5155. }
  5156. if (!RawData->NameOverride.IsEmpty())
  5157. {
  5158. Data2->Name = RawData->NameOverride;
  5159. }
  5160. else if (RawData->Link.IsEmpty() && RawData->IsWorkspace)
  5161. {
  5162. // Newly opened ad-hoc session has no name, so restore the workspace that way too.
  5163. // Otherwise we would persist the generated internal workspace name as a real name.
  5164. Data2->Name = UnicodeString();
  5165. }
  5166. List->Add(Data2);
  5167. }
  5168. }
  5169. }
  5170. //---------------------------------------------------------------------------
  5171. TStrings * __fastcall TStoredSessionList::GetFolderOrWorkspaceList(
  5172. const UnicodeString & Name)
  5173. {
  5174. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5175. DoGetFolderOrWorkspace(Name, DataList.get(), true);
  5176. std::unique_ptr<TStringList> Result(new TStringList());
  5177. for (int Index = 0; (Index < DataList->Count); Index++)
  5178. {
  5179. Result->Add(dynamic_cast<TSessionData *>(DataList->Items[Index])->SessionName);
  5180. }
  5181. return Result.release();
  5182. }
  5183. //---------------------------------------------------------------------------
  5184. TStrings * __fastcall TStoredSessionList::GetWorkspaces()
  5185. {
  5186. std::unique_ptr<TStringList> Result(CreateSortedStringList());
  5187. for (int Index = 0; (Index < Count); Index++)
  5188. {
  5189. TSessionData * Data = Sessions[Index];
  5190. if (Data->IsWorkspace)
  5191. {
  5192. Result->Add(Data->FolderName);
  5193. }
  5194. }
  5195. return Result.release();
  5196. }
  5197. //---------------------------------------------------------------------------
  5198. void __fastcall TStoredSessionList::NewWorkspace(
  5199. UnicodeString Name, TList * DataList)
  5200. {
  5201. for (int Index = 0; (Index < Count); Index++)
  5202. {
  5203. TSessionData * Data = Sessions[Index];
  5204. if (Data->IsInFolderOrWorkspace(Name))
  5205. {
  5206. FPendingRemovals->Add(Data->Name);
  5207. Remove(Data);
  5208. Index--;
  5209. }
  5210. }
  5211. for (int Index = 0; (Index < DataList->Count); Index++)
  5212. {
  5213. TSessionData * Data = static_cast<TSessionData *>(DataList->Items[Index]);
  5214. TSessionData * Data2 = new TSessionData(L"");
  5215. Data2->Assign(Data);
  5216. Data2->Name = TSessionData::ComposePath(Name, Data->Name);
  5217. // make sure, that new stored session is saved to registry
  5218. Data2->Modified = true;
  5219. Add(Data2);
  5220. }
  5221. }
  5222. //---------------------------------------------------------------------------
  5223. bool __fastcall TStoredSessionList::HasAnyWorkspace()
  5224. {
  5225. bool Result = false;
  5226. for (int Index = 0; !Result && (Index < Count); Index++)
  5227. {
  5228. TSessionData * Data = Sessions[Index];
  5229. Result = Data->IsWorkspace;
  5230. }
  5231. return Result;
  5232. }
  5233. //---------------------------------------------------------------------------
  5234. TSessionData * __fastcall TStoredSessionList::ParseUrl(UnicodeString Url,
  5235. TOptions * Options, bool & DefaultsOnly, UnicodeString * FileName,
  5236. bool * AProtocolDefined, UnicodeString * MaskedUrl, int Flags)
  5237. {
  5238. TSessionData * Data = new TSessionData(L"");
  5239. try
  5240. {
  5241. Data->ParseUrl(Url, Options, this, DefaultsOnly, FileName, AProtocolDefined, MaskedUrl, Flags);
  5242. }
  5243. catch(...)
  5244. {
  5245. delete Data;
  5246. throw;
  5247. }
  5248. return Data;
  5249. }
  5250. //---------------------------------------------------------------------
  5251. bool __fastcall TStoredSessionList::IsUrl(UnicodeString Url)
  5252. {
  5253. bool DefaultsOnly;
  5254. bool ProtocolDefined = false;
  5255. std::unique_ptr<TSessionData> ParsedData(ParseUrl(Url, NULL, DefaultsOnly, NULL, &ProtocolDefined));
  5256. bool Result = ProtocolDefined;
  5257. return Result;
  5258. }
  5259. //---------------------------------------------------------------------
  5260. TSessionData * __fastcall TStoredSessionList::ResolveWorkspaceData(TSessionData * Data)
  5261. {
  5262. if (!Data->Link.IsEmpty())
  5263. {
  5264. Data = dynamic_cast<TSessionData *>(FindByName(Data->Link));
  5265. if (Data != NULL)
  5266. {
  5267. Data = ResolveWorkspaceData(Data);
  5268. }
  5269. }
  5270. return Data;
  5271. }
  5272. //---------------------------------------------------------------------
  5273. TSessionData * __fastcall TStoredSessionList::SaveWorkspaceData(TSessionData * Data, int Index)
  5274. {
  5275. std::unique_ptr<TSessionData> Result(new TSessionData(L""));
  5276. TSessionData * SameData = StoredSessions->FindSame(Data);
  5277. if (SameData != NULL)
  5278. {
  5279. Result->CopyStateData(Data);
  5280. Result->Link = Data->Name;
  5281. }
  5282. else
  5283. {
  5284. Result->Assign(Data);
  5285. Result->NameOverride = Data->Name;
  5286. }
  5287. Result->IsWorkspace = true;
  5288. Result->Name = IntToHex(Index, 4); // See HasSessionName()
  5289. return Result.release();
  5290. }
  5291. //---------------------------------------------------------------------
  5292. bool __fastcall TStoredSessionList::CanOpen(TSessionData * Data)
  5293. {
  5294. Data = ResolveWorkspaceData(Data);
  5295. return (Data != NULL) && Data->CanOpen;
  5296. }
  5297. //---------------------------------------------------------------------
  5298. UnicodeString GetExpandedLogFileName(UnicodeString LogFileName, TDateTime Started, TSessionData * SessionData)
  5299. {
  5300. // StripPathQuotes should not be needed as we do not feed quotes anymore
  5301. UnicodeString ANewFileName = StripPathQuotes(ExpandEnvironmentVariables(LogFileName));
  5302. for (int Index = 1; Index < ANewFileName.Length(); Index++)
  5303. {
  5304. if (ANewFileName[Index] == L'!')
  5305. {
  5306. UnicodeString Replacement;
  5307. // keep consistent with TFileCustomCommand::PatternReplacement
  5308. switch (tolower(ANewFileName[Index + 1]))
  5309. {
  5310. case L'y':
  5311. Replacement = FormatDateTime(L"yyyy", Started);
  5312. break;
  5313. case L'm':
  5314. Replacement = FormatDateTime(L"mm", Started);
  5315. break;
  5316. case L'd':
  5317. Replacement = FormatDateTime(L"dd", Started);
  5318. break;
  5319. case L't':
  5320. Replacement = FormatDateTime(L"hhnnss", Started);
  5321. break;
  5322. case 'p':
  5323. Replacement = IntToStr(static_cast<int>(GetCurrentProcessId()));
  5324. break;
  5325. case L'@':
  5326. if (SessionData != NULL)
  5327. {
  5328. Replacement = MakeValidFileName(SessionData->HostNameExpanded);
  5329. }
  5330. else
  5331. {
  5332. Replacement = L"nohost";
  5333. }
  5334. break;
  5335. case L's':
  5336. if (SessionData != NULL)
  5337. {
  5338. Replacement = MakeValidFileName(SessionData->SessionName);
  5339. }
  5340. else
  5341. {
  5342. Replacement = L"nosession";
  5343. }
  5344. break;
  5345. case L'!':
  5346. Replacement = L"!";
  5347. break;
  5348. default:
  5349. Replacement = UnicodeString(L"!") + ANewFileName[Index + 1];
  5350. break;
  5351. }
  5352. ANewFileName.Delete(Index, 2);
  5353. ANewFileName.Insert(Replacement, Index);
  5354. Index += Replacement.Length() - 1;
  5355. }
  5356. }
  5357. return ANewFileName;
  5358. }
  5359. //---------------------------------------------------------------------
  5360. bool __fastcall IsSshProtocol(TFSProtocol FSProtocol)
  5361. {
  5362. return
  5363. (FSProtocol == fsSFTPonly) || (FSProtocol == fsSFTP) ||
  5364. (FSProtocol == fsSCPonly);
  5365. }
  5366. //---------------------------------------------------------------------------
  5367. int __fastcall DefaultPort(TFSProtocol FSProtocol, TFtps Ftps)
  5368. {
  5369. int Result;
  5370. switch (FSProtocol)
  5371. {
  5372. case fsFTP:
  5373. if (Ftps == ftpsImplicit)
  5374. {
  5375. Result = FtpsImplicitPortNumber;
  5376. }
  5377. else
  5378. {
  5379. Result = FtpPortNumber;
  5380. }
  5381. break;
  5382. case fsWebDAV:
  5383. case fsS3:
  5384. if (Ftps == ftpsNone)
  5385. {
  5386. Result = HTTPPortNumber;
  5387. }
  5388. else
  5389. {
  5390. Result = HTTPSPortNumber;
  5391. }
  5392. break;
  5393. default:
  5394. if (IsSshProtocol(FSProtocol))
  5395. {
  5396. Result = SshPortNumber;
  5397. }
  5398. else
  5399. {
  5400. DebugFail();
  5401. Result = -1;
  5402. }
  5403. break;
  5404. }
  5405. return Result;
  5406. }
  5407. //---------------------------------------------------------------------