SessionData.cpp 192 KB

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