SessionData.cpp 192 KB

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