SessionData.cpp 191 KB

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