SessionData.cpp 193 KB

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