SessionData.cpp 184 KB

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