SessionData.cpp 195 KB

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