SessionData.cpp 183 KB

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