SessionData.cpp 193 KB

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