SessionData.cpp 194 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "SessionData.h"
  5. #include "Common.h"
  6. #include "Exceptions.h"
  7. #include "FileBuffer.h"
  8. #include "CoreMain.h"
  9. #include "TextsCore.h"
  10. #include "PuttyIntf.h"
  11. #include "RemoteFiles.h"
  12. #include "SFTPFileSystem.h"
  13. #include "S3FileSystem.h"
  14. #include "FileMasks.h"
  15. #include <Soap.EncdDecd.hpp>
  16. #include <StrUtils.hpp>
  17. #include <XMLDoc.hpp>
  18. #include <System.IOUtils.hpp>
  19. #include <algorithm>
  20. //---------------------------------------------------------------------------
  21. #pragma package(smart_init)
  22. //---------------------------------------------------------------------------
  23. #define SET_SESSION_PROPERTY_FROM(PROPERTY, FROM) \
  24. if (F##PROPERTY != FROM) { F##PROPERTY = FROM; Modify(); }
  25. //---------------------------------------------------------------------------
  26. #define SET_SESSION_PROPERTY(PROPERTY) \
  27. SET_SESSION_PROPERTY_FROM(PROPERTY, value)
  28. //---------------------------------------------------------------------------
  29. const wchar_t * PingTypeNames = L"Off;Null;Dummy";
  30. const wchar_t * FtpPingTypeNames = L"Off;Dummy;Dummy;List";
  31. const wchar_t * ProxyMethodNames = L"None;SOCKS4;SOCKS5;HTTP;Telnet;Cmd";
  32. TIntMapping ProxyMethodMapping = CreateIntMappingFromEnumNames(LowerCase(ProxyMethodNames));
  33. const wchar_t * DefaultName = L"Default Settings";
  34. const UnicodeString CipherNames[CIPHER_COUNT] = {L"WARN", L"3des", L"blowfish", L"aes", L"des", L"arcfour", L"chacha20", "aesgcm"};
  35. const UnicodeString KexNames[KEX_COUNT] = {L"WARN", L"dh-group1-sha1", L"dh-group14-sha1", L"dh-group15-sha512", L"dh-group16-sha512", L"dh-group17-sha512", L"dh-group18-sha512", L"dh-gex-sha1", L"rsa", L"ecdh", L"ntru-curve25519"};
  36. const UnicodeString HostKeyNames[HOSTKEY_COUNT] = {L"WARN", L"rsa", L"dsa", L"ecdsa", L"ed25519", L"ed448"};
  37. const UnicodeString GssLibNames[GSSLIB_COUNT] = {L"gssapi32", L"sspi", L"custom"};
  38. // Update also order in SshCipherList()
  39. const TCipher DefaultCipherList[CIPHER_COUNT] =
  40. { cipAES, cipChaCha20, cipAESGCM, cip3DES, cipWarn, cipDES, cipBlowfish, cipArcfour };
  41. // Update also order in SshKexList()
  42. const TKex DefaultKexList[KEX_COUNT] =
  43. { kexNTRUHybrid, kexECDH, kexDHGEx, kexDHGroup18, kexDHGroup17, kexDHGroup16, kexDHGroup15, kexDHGroup14, kexRSA, kexWarn, kexDHGroup1 };
  44. const THostKey DefaultHostKeyList[HOSTKEY_COUNT] =
  45. { hkED448, hkED25519, hkECDSA, hkRSA, hkDSA, hkWarn };
  46. const TGssLib DefaultGssLibList[GSSLIB_COUNT] =
  47. { gssGssApi32, gssSspi, gssCustom };
  48. const wchar_t FSProtocolNames[FSPROTOCOL_COUNT][16] = { L"SCP", L"SFTP (SCP)", L"SFTP", L"", L"", L"FTP", L"WebDAV", L"S3" };
  49. const int SshPortNumber = 22;
  50. const int FtpPortNumber = 21;
  51. const int FtpsImplicitPortNumber = 990;
  52. const int HTTPPortNumber = 80;
  53. const int HTTPSPortNumber = 443;
  54. const int TelnetPortNumber = 23;
  55. const int DefaultSendBuf = 262144;
  56. const int ProxyPortNumber = 80;
  57. const UnicodeString AnonymousUserName(L"anonymous");
  58. const UnicodeString AnonymousPassword(L"[email protected]");
  59. const UnicodeString PuttySshProtocol(L"ssh");
  60. const UnicodeString PuttyTelnetProtocol(L"telnet");
  61. const UnicodeString SftpProtocol(L"sftp");
  62. const UnicodeString ScpProtocol(L"scp");
  63. const UnicodeString FtpProtocol(L"ftp");
  64. const UnicodeString FtpsProtocol(L"ftps");
  65. const UnicodeString FtpesProtocol(L"ftpes");
  66. const UnicodeString WebDAVProtocol(L"dav");
  67. const UnicodeString WebDAVSProtocol(L"davs");
  68. const UnicodeString S3Protocol(L"s3");
  69. const UnicodeString S3PlainProtocol(L"s3plain");
  70. const UnicodeString SshProtocol(L"ssh");
  71. const UnicodeString WinSCPProtocolPrefix(L"winscp-");
  72. const wchar_t UrlParamSeparator = L';';
  73. const wchar_t UrlParamValueSeparator = L'=';
  74. const UnicodeString UrlHostKeyParamName(L"fingerprint");
  75. const UnicodeString UrlSaveParamName(L"save");
  76. const UnicodeString UrlRawSettingsParamNamePrefix(L"x-");
  77. const UnicodeString PassphraseOption(L"passphrase");
  78. const UnicodeString RawSettingsOption(L"rawsettings");
  79. const UnicodeString S3HostName(S3LibDefaultHostName());
  80. const UnicodeString S3GoogleCloudHostName(L"storage.googleapis.com");
  81. const UnicodeString OpensshHostDirective(L"Host");
  82. //---------------------------------------------------------------------
  83. TDateTime __fastcall SecToDateTime(int Sec)
  84. {
  85. return TDateTime(double(Sec) / SecsPerDay);
  86. }
  87. //---------------------------------------------------------------------
  88. static bool IsValidOpensshLine(const UnicodeString & Line)
  89. {
  90. return !Line.IsEmpty() && (Line[1] != L'#');
  91. }
  92. //---------------------------------------------------------------------
  93. bool ParseOpensshDirective(const UnicodeString & ALine, UnicodeString & Directive, UnicodeString & Value)
  94. {
  95. bool Result = IsValidOpensshLine(ALine);
  96. if (Result)
  97. {
  98. UnicodeString Line = Trim(ALine);
  99. if (Line.SubString(1, 1) == "\"")
  100. {
  101. Line.Delete(1, 1);
  102. int P = Line.Pos("\"");
  103. Result = (P > 0);
  104. if (Result)
  105. {
  106. Directive = Line.SubString(1, P - 1);
  107. Line = MidStr(Line, P + 1).Trim();
  108. }
  109. }
  110. else
  111. {
  112. wchar_t Equal = L'=';
  113. UnicodeString Whitespaces(L" \t");
  114. UnicodeString Delimiters(Whitespaces + Equal);
  115. int P = FindDelimiter(Delimiters, Line);
  116. Result = (P > 0);
  117. if (Result)
  118. {
  119. Directive = Line.SubString(1, P - 1);
  120. Line.Delete(1, P - 1);
  121. UnicodeString TrimChars = Delimiters;
  122. while (!Line.IsEmpty() && Line.IsDelimiter(TrimChars, 1))
  123. {
  124. if (Line[1] == Equal)
  125. {
  126. TrimChars = Whitespaces;
  127. }
  128. Line.Delete(1, 1);
  129. }
  130. }
  131. }
  132. Value = Line;
  133. Result = !Value.IsEmpty();
  134. }
  135. return Result;
  136. }
  137. //--- TSessionData ----------------------------------------------------
  138. __fastcall TSessionData::TSessionData(UnicodeString aName):
  139. TNamedObject(aName)
  140. {
  141. Default();
  142. FModified = true;
  143. }
  144. //---------------------------------------------------------------------
  145. _fastcall TSessionData::~TSessionData()
  146. {
  147. }
  148. //---------------------------------------------------------------------
  149. int __fastcall TSessionData::Compare(TNamedObject * Other)
  150. {
  151. int Result;
  152. // To avoid using CompareLogicalText on hex names of sessions in workspace.
  153. // The session 000A would be sorted before 0001.
  154. if (IsWorkspace && DebugNotNull(dynamic_cast<TSessionData *>(Other))->IsWorkspace)
  155. {
  156. Result = CompareText(Name, Other->Name);
  157. }
  158. else
  159. {
  160. Result = TNamedObject::Compare(Other);
  161. }
  162. return Result;
  163. }
  164. //---------------------------------------------------------------------
  165. TSessionData * __fastcall TSessionData::Clone()
  166. {
  167. std::unique_ptr<TSessionData> Data(new TSessionData(L""));
  168. Data->Assign(this);
  169. return Data.release();
  170. }
  171. //---------------------------------------------------------------------
  172. void __fastcall TSessionData::DefaultSettings()
  173. {
  174. HostName = L"";
  175. PortNumber = SshPortNumber;
  176. UserName = L"";
  177. Password = L"";
  178. NewPassword = L"";
  179. ChangePassword = false;
  180. PingInterval = 30;
  181. PingType = ptOff;
  182. Timeout = 15;
  183. TryAgent = true;
  184. AgentFwd = false;
  185. AuthKI = true;
  186. AuthKIPassword = true;
  187. AuthGSSAPI = true;
  188. AuthGSSAPIKEX = false;
  189. GSSAPIFwdTGT = false;
  190. LogicalHostName = L"";
  191. ChangeUsername = false;
  192. Compression = false;
  193. Ssh2DES = false;
  194. SshNoUserAuth = false;
  195. for (int Index = 0; Index < CIPHER_COUNT; Index++)
  196. {
  197. Cipher[Index] = DefaultCipherList[Index];
  198. }
  199. for (int Index = 0; Index < KEX_COUNT; Index++)
  200. {
  201. Kex[Index] = DefaultKexList[Index];
  202. }
  203. for (int Index = 0; Index < HOSTKEY_COUNT; Index++)
  204. {
  205. HostKeys[Index] = DefaultHostKeyList[Index];
  206. }
  207. for (int Index = 0; Index < GSSLIB_COUNT; Index++)
  208. {
  209. GssLib[Index] = DefaultGssLibList[Index];
  210. }
  211. GssLibCustom = L"";
  212. PublicKeyFile = EmptyStr;
  213. DetachedCertificate = EmptyStr;
  214. Passphrase = L"";
  215. FPuttyProtocol = L"";
  216. TcpNoDelay = false;
  217. SendBuf = DefaultSendBuf;
  218. SourceAddress = L"";
  219. ProtocolFeatures = L"";
  220. SshSimple = true;
  221. HostKey = L"";
  222. FingerprintScan = false;
  223. FOverrideCachedHostKey = true;
  224. Note = L"";
  225. WinTitle = L"";
  226. InternalEditorEncoding = -1;
  227. EncryptKey = UnicodeString();
  228. WebDavLiberalEscaping = false;
  229. WebDavAuthLegacy = false;
  230. ProxyMethod = ::pmNone;
  231. ProxyHost = L"proxy";
  232. ProxyPort = ProxyPortNumber;
  233. ProxyUsername = L"";
  234. ProxyPassword = L"";
  235. ProxyTelnetCommand = L"connect %host %port\\n";
  236. ProxyLocalCommand = L"";
  237. ProxyDNS = asAuto;
  238. ProxyLocalhost = false;
  239. for (unsigned int Index = 0; Index < LENOF(FBugs); Index++)
  240. {
  241. Bug[(TSshBug)Index] = asAuto;
  242. }
  243. Special = false;
  244. FSProtocol = fsSFTP;
  245. AddressFamily = afAuto;
  246. RekeyData = L"1G";
  247. RekeyTime = MinsPerHour;
  248. // FS common
  249. LocalDirectory = L"";
  250. OtherLocalDirectory = L"";
  251. RemoteDirectory = L"";
  252. SynchronizeBrowsing = false;
  253. UpdateDirectories = true;
  254. RequireDirectories = false;
  255. CacheDirectories = true;
  256. CacheDirectoryChanges = true;
  257. PreserveDirectoryChanges = true;
  258. ResolveSymlinks = true;
  259. FollowDirectorySymlinks = false;
  260. DSTMode = dstmUnix;
  261. DeleteToRecycleBin = false;
  262. OverwrittenToRecycleBin = false;
  263. RecycleBinPath = L"";
  264. Color = 0;
  265. PostLoginCommands = L"";
  266. // SCP
  267. LookupUserGroups = asAuto;
  268. EOLType = eolLF;
  269. TrimVMSVersions = false;
  270. VMSAllRevisions = false;
  271. Shell = L""; //default shell
  272. ReturnVar = L"";
  273. ExitCode1IsError = false;
  274. ClearAliases = true;
  275. UnsetNationalVars = true;
  276. ListingCommand = L"ls -la";
  277. IgnoreLsWarnings = true;
  278. Scp1Compatibility = false;
  279. TimeDifference = 0;
  280. TimeDifferenceAuto = true;
  281. SCPLsFullTime = asAuto;
  282. NotUtf = asAuto;
  283. // S3
  284. S3DefaultRegion = EmptyStr;
  285. S3SessionToken = EmptyStr;
  286. 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 = ::SFTPMaxVersion;
  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::NonPersistant()
  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_str(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;
  2037. int DefaultProtocolPortNumber;
  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. {
  2248. AFSProtocol = fsS3;
  2249. }
  2250. PortNumber = DefaultProtocolPortNumber;
  2251. }
  2252. if (ProtocolDefined)
  2253. {
  2254. Ftps = AFtps;
  2255. }
  2256. UnicodeString UserInfoWithoutConnectionParams = CutToChar(UserInfo, UrlParamSeparator, false);
  2257. UnicodeString ConnectionParams = UserInfo;
  2258. UserInfo = UserInfoWithoutConnectionParams;
  2259. std::unique_ptr<TStrings> RawSettings(new TStringList());
  2260. while (!ConnectionParams.IsEmpty())
  2261. {
  2262. UnicodeString ConnectionParam = CutToChar(ConnectionParams, UrlParamSeparator, false);
  2263. UnicodeString ConnectionParamName = CutToChar(ConnectionParam, UrlParamValueSeparator, false);
  2264. if (SameText(ConnectionParamName, UrlHostKeyParamName))
  2265. {
  2266. HostKey = DecodeUrlChars(ConnectionParam);
  2267. FOverrideCachedHostKey = false;
  2268. }
  2269. else if (StartsText(UrlRawSettingsParamNamePrefix, ConnectionParamName))
  2270. {
  2271. UnicodeString AName = RightStr(ConnectionParamName, ConnectionParamName.Length() - UrlRawSettingsParamNamePrefix.Length());
  2272. AName = DecodeUrlChars(AName);
  2273. UnicodeString Value = DecodeUrlChars(ConnectionParam);
  2274. if (SameText(AName, L"Name"))
  2275. {
  2276. Name = Value;
  2277. }
  2278. else
  2279. {
  2280. RawSettings->Values[AName] = Value;
  2281. }
  2282. }
  2283. }
  2284. if (RawSettings->Count > 0) // optimization
  2285. {
  2286. ApplyRawSettings(RawSettings.get(), Unsafe);
  2287. }
  2288. bool HasPassword = (UserInfo.Pos(L':') > 0);
  2289. UnicodeString RawUserName = CutToChar(UserInfo, L':', false);
  2290. UserName = DecodeUrlChars(RawUserName);
  2291. Password = DecodeUrlChars(UserInfo);
  2292. if (HasPassword && Password.IsEmpty())
  2293. {
  2294. Password = EmptyString;
  2295. }
  2296. UnicodeString RemoteDirectoryWithSessionParams = Url.SubString(PSlash, Url.Length() - PSlash + 1);
  2297. ARemoteDirectory = CutToChar(RemoteDirectoryWithSessionParams, UrlParamSeparator, false);
  2298. UnicodeString SessionParams = RemoteDirectoryWithSessionParams;
  2299. // We should handle session params in "stored session" branch too.
  2300. // And particularly if there's a "save" param, we should actually not try to match the
  2301. // URL against site names
  2302. while (!SessionParams.IsEmpty())
  2303. {
  2304. UnicodeString SessionParam = CutToChar(SessionParams, UrlParamSeparator, false);
  2305. UnicodeString SessionParamName = CutToChar(SessionParam, UrlParamValueSeparator, false);
  2306. if (SameText(SessionParamName, UrlSaveParamName))
  2307. {
  2308. FSaveOnly = (StrToIntDef(SessionParam, 1) != 0);
  2309. }
  2310. }
  2311. if (MaskedUrl != NULL)
  2312. {
  2313. (*MaskedUrl) += RawUserName;
  2314. if (HasPassword)
  2315. {
  2316. (*MaskedUrl) += L":" + PasswordMask;
  2317. }
  2318. if (!RawUserName.IsEmpty() || HasPassword)
  2319. {
  2320. (*MaskedUrl) += L"@";
  2321. }
  2322. (*MaskedUrl) += OrigHostInfo + ARemoteDirectory;
  2323. }
  2324. }
  2325. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory != L"/"))
  2326. {
  2327. if ((ARemoteDirectory[ARemoteDirectory.Length()] != L'/') &&
  2328. (FileName != NULL))
  2329. {
  2330. *FileName = DecodeUrlChars(UnixExtractFileName(ARemoteDirectory));
  2331. ARemoteDirectory = UnixExtractFilePath(ARemoteDirectory);
  2332. }
  2333. RemoteDirectory = DecodeUrlChars(ARemoteDirectory);
  2334. // Is already true for ad-hoc URL, but we want to error even for "storedsite/path/"-style URL.
  2335. RequireDirectories = true;
  2336. }
  2337. DefaultsOnly = false;
  2338. }
  2339. else
  2340. {
  2341. // This happens when pasting URL on Login dialog
  2342. if (StoredSessions != NULL)
  2343. {
  2344. CopyData(StoredSessions->DefaultSettings);
  2345. }
  2346. DefaultsOnly = true;
  2347. }
  2348. if (ProtocolDefined)
  2349. {
  2350. FSProtocol = AFSProtocol;
  2351. }
  2352. if (Options != NULL)
  2353. {
  2354. // we deliberately do keep defaultonly to false, in presence of any option,
  2355. // as the option should not make session "connectable"
  2356. UnicodeString Value;
  2357. if (Options->FindSwitch(USERNAME_SWITCH, Value))
  2358. {
  2359. UserName = Value;
  2360. }
  2361. if (Options->FindSwitch(PASSWORD_SWITCH, Value))
  2362. {
  2363. Password = Value;
  2364. }
  2365. if (Options->FindSwitch(SESSIONNAME_SWICH, Value))
  2366. {
  2367. Name = Value;
  2368. }
  2369. if (Options->FindSwitch(NEWPASSWORD_SWITCH, Value))
  2370. {
  2371. ChangePassword = true;
  2372. NewPassword = Value;
  2373. }
  2374. if (Options->FindSwitch(PRIVATEKEY_SWITCH, Value))
  2375. {
  2376. PublicKeyFile = Value;
  2377. }
  2378. if (Options->FindSwitch(L"clientcert", Value))
  2379. {
  2380. TlsCertificateFile = Value;
  2381. }
  2382. if (Options->FindSwitch(PassphraseOption, Value))
  2383. {
  2384. Passphrase = Value;
  2385. }
  2386. if (Options->FindSwitch(L"timeout", Value))
  2387. {
  2388. Timeout = StrToInt(Value);
  2389. }
  2390. if (Options->FindSwitch(L"hostkey", Value) ||
  2391. Options->FindSwitch(L"certificate", Value))
  2392. {
  2393. HostKey = Value;
  2394. FOverrideCachedHostKey = true;
  2395. }
  2396. FtpPasvMode = Options->SwitchValue(L"passive", FtpPasvMode);
  2397. if (Options->FindSwitch(L"implicit"))
  2398. {
  2399. bool Enabled = Options->SwitchValue(L"implicit", true);
  2400. Ftps = Enabled ? ftpsImplicit : ftpsNone;
  2401. if (!PortNumberDefined && Enabled)
  2402. {
  2403. PortNumber = FtpsImplicitPortNumber;
  2404. }
  2405. }
  2406. // BACKWARD COMPATIBILITY with 5.5.x
  2407. if (Options->FindSwitch(L"explicitssl"))
  2408. {
  2409. bool Enabled = Options->SwitchValue(L"explicitssl", true);
  2410. Ftps = Enabled ? ftpsExplicitSsl : ftpsNone;
  2411. if (!PortNumberDefined && Enabled)
  2412. {
  2413. PortNumber = FtpPortNumber;
  2414. }
  2415. }
  2416. if (Options->FindSwitch(L"explicit") ||
  2417. // BACKWARD COMPATIBILITY with 5.5.x
  2418. Options->FindSwitch(L"explicittls"))
  2419. {
  2420. UnicodeString SwitchName =
  2421. Options->FindSwitch(L"explicit") ? L"explicit" : L"explicittls";
  2422. bool Enabled = Options->SwitchValue(SwitchName, true);
  2423. Ftps = Enabled ? ftpsExplicitTls : ftpsNone;
  2424. if (!PortNumberDefined && Enabled)
  2425. {
  2426. PortNumber = FtpPortNumber;
  2427. }
  2428. }
  2429. if (Options->FindSwitch(RawSettingsOption))
  2430. {
  2431. std::unique_ptr<TStrings> RawSettings(new TStringList());
  2432. if (Options->FindSwitch(RawSettingsOption, RawSettings.get()))
  2433. {
  2434. ApplyRawSettings(RawSettings.get(), Unsafe);
  2435. }
  2436. }
  2437. if (Options->FindSwitch(PASSWORDSFROMFILES_SWITCH) &&
  2438. // Ad-hoc condition for the current only specific use of pufParseOnly
  2439. // (when we do not want to consume the password pipe by the current instance,
  2440. // in case the URL needs to be passed to another instance)
  2441. !ParseOnly)
  2442. {
  2443. ReadPasswordsFromFiles();
  2444. }
  2445. }
  2446. return true;
  2447. }
  2448. //---------------------------------------------------------------------
  2449. void __fastcall TSessionData::ApplyRawSettings(TStrings * RawSettings, bool Unsafe)
  2450. {
  2451. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings, false));
  2452. ApplyRawSettings(OptionsStorage.get(), Unsafe, false);
  2453. }
  2454. //---------------------------------------------------------------------
  2455. void __fastcall TSessionData::ApplyRawSettings(THierarchicalStorage * Storage, bool Unsafe, bool RespectDisablePasswordStoring)
  2456. {
  2457. bool Dummy;
  2458. DoLoad(Storage, false, Dummy, Unsafe, RespectDisablePasswordStoring);
  2459. }
  2460. //---------------------------------------------------------------------
  2461. void __fastcall TSessionData::ConfigureTunnel(int APortNumber)
  2462. {
  2463. FOrigHostName = HostName;
  2464. FOrigPortNumber = PortNumber;
  2465. FOrigProxyMethod = ProxyMethod;
  2466. HostName = L"127.0.0.1";
  2467. PortNumber = APortNumber;
  2468. // proxy settings is used for tunnel
  2469. ProxyMethod = ::pmNone;
  2470. FLogicalHostName = FOrigHostName;
  2471. }
  2472. //---------------------------------------------------------------------
  2473. void __fastcall TSessionData::RollbackTunnel()
  2474. {
  2475. HostName = FOrigHostName;
  2476. PortNumber = FOrigPortNumber;
  2477. ProxyMethod = FOrigProxyMethod;
  2478. FLogicalHostName = L"";
  2479. }
  2480. //---------------------------------------------------------------------
  2481. TSessionData * TSessionData::CreateTunnelData(int TunnelLocalPortNumber)
  2482. {
  2483. std::unique_ptr<TSessionData> TunnelData(new TSessionData(EmptyStr));
  2484. TunnelData->Assign(StoredSessions->DefaultSettings);
  2485. TunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (SessionName));
  2486. TunnelData->Tunnel = false;
  2487. TunnelData->HostName = TunnelHostName;
  2488. TunnelData->PortNumber = TunnelPortNumber;
  2489. TunnelData->UserName = TunnelUserName;
  2490. TunnelData->Password = TunnelPassword;
  2491. TunnelData->PublicKeyFile = TunnelPublicKeyFile;
  2492. TunnelData->DetachedCertificate = EmptyStr;
  2493. TunnelData->Passphrase = TunnelPassphrase;
  2494. UnicodeString AHostName = HostNameExpanded;
  2495. if (IsIPv6Literal(AHostName))
  2496. {
  2497. AHostName = EscapeIPv6Literal(AHostName);
  2498. }
  2499. TunnelData->TunnelPortFwd = FORMAT(L"L%d\t%s:%d",
  2500. (TunnelLocalPortNumber, AHostName, PortNumber));
  2501. TunnelData->HostKey = TunnelHostKey;
  2502. // inherit proxy options on the main session
  2503. TunnelData->ProxyMethod = ProxyMethod;
  2504. TunnelData->ProxyHost = ProxyHost;
  2505. TunnelData->ProxyPort = ProxyPort;
  2506. TunnelData->ProxyUsername = ProxyUsername;
  2507. TunnelData->ProxyPassword = ProxyPassword;
  2508. TunnelData->ProxyTelnetCommand = ProxyTelnetCommand;
  2509. TunnelData->ProxyLocalCommand = ProxyLocalCommand;
  2510. TunnelData->ProxyDNS = ProxyDNS;
  2511. TunnelData->ProxyLocalhost = ProxyLocalhost;
  2512. // inherit most SSH options of the main session (except for private key and bugs)
  2513. TunnelData->Compression = Compression;
  2514. TunnelData->CipherList = CipherList;
  2515. TunnelData->Ssh2DES = Ssh2DES;
  2516. TunnelData->KexList = KexList;
  2517. TunnelData->RekeyData = RekeyData;
  2518. TunnelData->RekeyTime = RekeyTime;
  2519. TunnelData->SshNoUserAuth = SshNoUserAuth;
  2520. TunnelData->AuthGSSAPI = AuthGSSAPI;
  2521. TunnelData->AuthGSSAPIKEX = AuthGSSAPIKEX;
  2522. TunnelData->GSSAPIFwdTGT = GSSAPIFwdTGT;
  2523. TunnelData->TryAgent = TryAgent;
  2524. TunnelData->AgentFwd = AgentFwd;
  2525. TunnelData->AuthKI = AuthKI;
  2526. TunnelData->AuthKIPassword = AuthKIPassword;
  2527. return TunnelData.release();
  2528. }
  2529. //---------------------------------------------------------------------
  2530. void __fastcall TSessionData::ExpandEnvironmentVariables()
  2531. {
  2532. HostName = HostNameExpanded;
  2533. UserName = UserNameExpanded;
  2534. PublicKeyFile = ::ExpandEnvironmentVariables(PublicKeyFile);
  2535. DetachedCertificate = ::ExpandEnvironmentVariables(DetachedCertificate);
  2536. }
  2537. //---------------------------------------------------------------------
  2538. void __fastcall TSessionData::ValidatePath(const UnicodeString Path)
  2539. {
  2540. // noop
  2541. }
  2542. //---------------------------------------------------------------------
  2543. void __fastcall TSessionData::ValidateName(const UnicodeString Name)
  2544. {
  2545. // keep consistent with MakeValidName
  2546. if (Name.LastDelimiter(L"/") > 0)
  2547. {
  2548. throw Exception(FMTLOAD(ITEM_NAME_INVALID, (Name, L"/")));
  2549. }
  2550. }
  2551. //---------------------------------------------------------------------
  2552. UnicodeString __fastcall TSessionData::MakeValidName(const UnicodeString & Name)
  2553. {
  2554. // keep consistent with ValidateName
  2555. return ReplaceStr(Name, L"/", L"\\");
  2556. }
  2557. //---------------------------------------------------------------------
  2558. RawByteString __fastcall TSessionData::EncryptPassword(const UnicodeString & Password, UnicodeString Key)
  2559. {
  2560. return Configuration->EncryptPassword(Password, Key);
  2561. }
  2562. //---------------------------------------------------------------------
  2563. RawByteString __fastcall TSessionData::StronglyRecryptPassword(const RawByteString & Password, UnicodeString Key)
  2564. {
  2565. return Configuration->StronglyRecryptPassword(Password, Key);
  2566. }
  2567. //---------------------------------------------------------------------
  2568. UnicodeString __fastcall TSessionData::DecryptPassword(const RawByteString & Password, UnicodeString Key)
  2569. {
  2570. UnicodeString Result;
  2571. try
  2572. {
  2573. Result = Configuration->DecryptPassword(Password, Key);
  2574. }
  2575. catch(EAbort &)
  2576. {
  2577. // silently ignore aborted prompts for master password and return empty password
  2578. }
  2579. return Result;
  2580. }
  2581. //---------------------------------------------------------------------
  2582. UnicodeString TSessionData::GetSessionPasswordEncryptionKey() const
  2583. {
  2584. return UserName + HostName;
  2585. }
  2586. //---------------------------------------------------------------------
  2587. bool __fastcall TSessionData::GetCanLogin()
  2588. {
  2589. return !FHostName.IsEmpty();
  2590. }
  2591. //---------------------------------------------------------------------
  2592. bool __fastcall TSessionData::GetIsLocalBrowser()
  2593. {
  2594. return !LocalDirectory.IsEmpty() && !OtherLocalDirectory.IsEmpty();
  2595. }
  2596. //---------------------------------------------------------------------
  2597. bool __fastcall TSessionData::GetCanOpen()
  2598. {
  2599. return CanLogin || IsLocalBrowser;
  2600. }
  2601. //---------------------------------------------------------------------------
  2602. int TSessionData::GetDefaultPort()
  2603. {
  2604. return DefaultPort(FSProtocol, Ftps);
  2605. }
  2606. //---------------------------------------------------------------------------
  2607. UnicodeString __fastcall TSessionData::GetSessionKey()
  2608. {
  2609. UnicodeString Result = FORMAT(L"%s@%s", (UserName, HostName));
  2610. if (PortNumber != GetDefaultPort())
  2611. {
  2612. Result += FORMAT(L":%d", (PortNumber));
  2613. }
  2614. return Result;
  2615. }
  2616. //---------------------------------------------------------------------
  2617. UnicodeString __fastcall TSessionData::GetInternalStorageKey()
  2618. {
  2619. // This is probably useless remnant of previous use of this method from OpenSessionInPutty
  2620. // that needs the method to return something even for ad-hoc sessions
  2621. if (Name.IsEmpty())
  2622. {
  2623. return SessionKey;
  2624. }
  2625. else
  2626. {
  2627. return Name;
  2628. }
  2629. }
  2630. //---------------------------------------------------------------------
  2631. UnicodeString __fastcall TSessionData::GetStorageKey()
  2632. {
  2633. return SessionName;
  2634. }
  2635. //---------------------------------------------------------------------
  2636. UnicodeString __fastcall TSessionData::FormatSiteKey(const UnicodeString & HostName, int PortNumber)
  2637. {
  2638. return FORMAT(L"%s:%d", (HostName, PortNumber));
  2639. }
  2640. //---------------------------------------------------------------------
  2641. UnicodeString __fastcall TSessionData::GetSiteKey()
  2642. {
  2643. return FormatSiteKey(HostNameExpanded, PortNumber);
  2644. }
  2645. //---------------------------------------------------------------------
  2646. void __fastcall TSessionData::SetHostName(UnicodeString value)
  2647. {
  2648. if (FHostName != value)
  2649. {
  2650. // HostName is key for password encryption
  2651. UnicodeString XPassword = Password;
  2652. UnicodeString XNewPassword = NewPassword;
  2653. UnicodeString XEncryptKey = EncryptKey;
  2654. // This is now hardly used as hostname is parsed directly on login dialog.
  2655. // But can be used when importing sites from PuTTY, as it allows same format too.
  2656. int P = value.LastDelimiter(L"@");
  2657. if (P > 0)
  2658. {
  2659. UserName = value.SubString(1, P - 1);
  2660. value = value.SubString(P + 1, value.Length() - P);
  2661. }
  2662. FHostName = value;
  2663. Modify();
  2664. Password = XPassword;
  2665. NewPassword = XNewPassword;
  2666. EncryptKey = XEncryptKey;
  2667. Shred(XPassword);
  2668. Shred(XNewPassword);
  2669. Shred(XEncryptKey);
  2670. }
  2671. }
  2672. //---------------------------------------------------------------------
  2673. UnicodeString __fastcall TSessionData::GetHostNameExpanded()
  2674. {
  2675. return ::ExpandEnvironmentVariables(HostName);
  2676. }
  2677. //---------------------------------------------------------------------
  2678. UnicodeString TSessionData::GetHostNameSource()
  2679. {
  2680. UnicodeString Result;
  2681. if (HostName != HostNameExpanded)
  2682. {
  2683. Result = HostName;
  2684. }
  2685. return Result;
  2686. }
  2687. //---------------------------------------------------------------------
  2688. void __fastcall TSessionData::SetPortNumber(int value)
  2689. {
  2690. SET_SESSION_PROPERTY(PortNumber);
  2691. }
  2692. //---------------------------------------------------------------------------
  2693. void __fastcall TSessionData::SetShell(UnicodeString value)
  2694. {
  2695. SET_SESSION_PROPERTY(Shell);
  2696. }
  2697. //---------------------------------------------------------------------------
  2698. void __fastcall TSessionData::SetSftpServer(UnicodeString value)
  2699. {
  2700. SET_SESSION_PROPERTY(SftpServer);
  2701. }
  2702. //---------------------------------------------------------------------------
  2703. void __fastcall TSessionData::SetClearAliases(bool value)
  2704. {
  2705. SET_SESSION_PROPERTY(ClearAliases);
  2706. }
  2707. //---------------------------------------------------------------------------
  2708. void __fastcall TSessionData::SetListingCommand(UnicodeString value)
  2709. {
  2710. SET_SESSION_PROPERTY(ListingCommand);
  2711. }
  2712. //---------------------------------------------------------------------------
  2713. void __fastcall TSessionData::SetIgnoreLsWarnings(bool value)
  2714. {
  2715. SET_SESSION_PROPERTY(IgnoreLsWarnings);
  2716. }
  2717. //---------------------------------------------------------------------------
  2718. void __fastcall TSessionData::SetUnsetNationalVars(bool value)
  2719. {
  2720. SET_SESSION_PROPERTY(UnsetNationalVars);
  2721. }
  2722. //---------------------------------------------------------------------
  2723. void __fastcall TSessionData::SetUserName(UnicodeString value)
  2724. {
  2725. // Avoid password recryption (what may popup master password prompt)
  2726. if (FUserName != value)
  2727. {
  2728. // UserName is key for password encryption
  2729. UnicodeString XPassword = Password;
  2730. UnicodeString XNewPassword = NewPassword;
  2731. UnicodeString XEncryptKey = EncryptKey;
  2732. SET_SESSION_PROPERTY(UserName);
  2733. Password = XPassword;
  2734. NewPassword = XNewPassword;
  2735. EncryptKey = XEncryptKey;
  2736. Shred(XPassword);
  2737. Shred(XNewPassword);
  2738. Shred(XEncryptKey);
  2739. }
  2740. }
  2741. //---------------------------------------------------------------------
  2742. UnicodeString __fastcall TSessionData::GetUserNameExpanded()
  2743. {
  2744. UnicodeString Result = ::ExpandEnvironmentVariables(UserName);
  2745. if (Result.IsEmpty() && HasS3AutoCredentials())
  2746. {
  2747. Result = S3EnvUserName(S3Profile);
  2748. }
  2749. return Result;
  2750. }
  2751. //---------------------------------------------------------------------
  2752. UnicodeString TSessionData::GetUserNameSource()
  2753. {
  2754. UnicodeString Result;
  2755. if (UserName.IsEmpty() && HasS3AutoCredentials())
  2756. {
  2757. S3EnvUserName(S3Profile, &Result);
  2758. }
  2759. if (Result.IsEmpty() && (UserName != UserNameExpanded))
  2760. {
  2761. Result = UserName;
  2762. }
  2763. return Result;
  2764. }
  2765. //---------------------------------------------------------------------
  2766. void __fastcall TSessionData::SetPassword(UnicodeString avalue)
  2767. {
  2768. RawByteString value = EncryptPassword(avalue, GetSessionPasswordEncryptionKey());
  2769. SET_SESSION_PROPERTY(Password);
  2770. }
  2771. //---------------------------------------------------------------------
  2772. UnicodeString __fastcall TSessionData::GetPassword() const
  2773. {
  2774. return DecryptPassword(FPassword, GetSessionPasswordEncryptionKey());
  2775. }
  2776. //---------------------------------------------------------------------
  2777. void __fastcall TSessionData::SetNewPassword(UnicodeString avalue)
  2778. {
  2779. RawByteString value = EncryptPassword(avalue, GetSessionPasswordEncryptionKey());
  2780. SET_SESSION_PROPERTY(NewPassword);
  2781. }
  2782. //---------------------------------------------------------------------
  2783. UnicodeString __fastcall TSessionData::GetNewPassword() const
  2784. {
  2785. return DecryptPassword(FNewPassword, GetSessionPasswordEncryptionKey());
  2786. }
  2787. //---------------------------------------------------------------------
  2788. void __fastcall TSessionData::SetChangePassword(bool value)
  2789. {
  2790. SET_SESSION_PROPERTY(ChangePassword);
  2791. }
  2792. //---------------------------------------------------------------------
  2793. void __fastcall TSessionData::SetPingInterval(int value)
  2794. {
  2795. SET_SESSION_PROPERTY(PingInterval);
  2796. }
  2797. //---------------------------------------------------------------------
  2798. void __fastcall TSessionData::SetTryAgent(bool value)
  2799. {
  2800. SET_SESSION_PROPERTY(TryAgent);
  2801. }
  2802. //---------------------------------------------------------------------
  2803. void __fastcall TSessionData::SetAgentFwd(bool value)
  2804. {
  2805. SET_SESSION_PROPERTY(AgentFwd);
  2806. }
  2807. //---------------------------------------------------------------------
  2808. void __fastcall TSessionData::SetAuthKI(bool value)
  2809. {
  2810. SET_SESSION_PROPERTY(AuthKI);
  2811. }
  2812. //---------------------------------------------------------------------
  2813. void __fastcall TSessionData::SetAuthKIPassword(bool value)
  2814. {
  2815. SET_SESSION_PROPERTY(AuthKIPassword);
  2816. }
  2817. //---------------------------------------------------------------------
  2818. void __fastcall TSessionData::SetAuthGSSAPI(bool value)
  2819. {
  2820. SET_SESSION_PROPERTY(AuthGSSAPI);
  2821. }
  2822. //---------------------------------------------------------------------
  2823. void __fastcall TSessionData::SetAuthGSSAPIKEX(bool value)
  2824. {
  2825. SET_SESSION_PROPERTY(AuthGSSAPIKEX);
  2826. }
  2827. //---------------------------------------------------------------------
  2828. void __fastcall TSessionData::SetGSSAPIFwdTGT(bool value)
  2829. {
  2830. SET_SESSION_PROPERTY(GSSAPIFwdTGT);
  2831. }
  2832. //---------------------------------------------------------------------
  2833. void __fastcall TSessionData::SetChangeUsername(bool value)
  2834. {
  2835. SET_SESSION_PROPERTY(ChangeUsername);
  2836. }
  2837. //---------------------------------------------------------------------
  2838. void __fastcall TSessionData::SetCompression(bool value)
  2839. {
  2840. SET_SESSION_PROPERTY(Compression);
  2841. }
  2842. //---------------------------------------------------------------------
  2843. void __fastcall TSessionData::SetSsh2DES(bool value)
  2844. {
  2845. SET_SESSION_PROPERTY(Ssh2DES);
  2846. }
  2847. //---------------------------------------------------------------------
  2848. void __fastcall TSessionData::SetSshNoUserAuth(bool value)
  2849. {
  2850. SET_SESSION_PROPERTY(SshNoUserAuth);
  2851. }
  2852. //---------------------------------------------------------------------
  2853. bool __fastcall TSessionData::GetUsesSsh()
  2854. {
  2855. return IsSshProtocol(FSProtocol);
  2856. }
  2857. //---------------------------------------------------------------------
  2858. void __fastcall TSessionData::SetCipher(int Index, TCipher value)
  2859. {
  2860. DebugAssert(Index >= 0 && Index < CIPHER_COUNT);
  2861. SET_SESSION_PROPERTY(Ciphers[Index]);
  2862. }
  2863. //---------------------------------------------------------------------
  2864. TCipher __fastcall TSessionData::GetCipher(int Index) const
  2865. {
  2866. DebugAssert(Index >= 0 && Index < CIPHER_COUNT);
  2867. return FCiphers[Index];
  2868. }
  2869. //---------------------------------------------------------------------
  2870. template<class AlgoT>
  2871. void __fastcall TSessionData::SetAlgoList(AlgoT * List, const AlgoT * DefaultList, const UnicodeString * Names,
  2872. int Count, AlgoT WarnAlgo, UnicodeString value)
  2873. {
  2874. std::vector<bool> Used(Count); // initialized to false
  2875. std::vector<AlgoT> NewList(Count);
  2876. bool HasWarnAlgo = (WarnAlgo >= AlgoT());
  2877. const AlgoT * WarnPtr;
  2878. int WarnDefaultIndex;
  2879. if (!HasWarnAlgo)
  2880. {
  2881. WarnPtr = NULL;
  2882. WarnDefaultIndex = -1;
  2883. }
  2884. else
  2885. {
  2886. WarnPtr = std::find(DefaultList, DefaultList + Count, WarnAlgo);
  2887. DebugAssert(WarnPtr != NULL);
  2888. WarnDefaultIndex = (WarnPtr - DefaultList);
  2889. }
  2890. int Index = 0;
  2891. while (!value.IsEmpty())
  2892. {
  2893. UnicodeString AlgoStr = CutToChar(value, L',', true);
  2894. for (int Algo = 0; Algo < Count; Algo++)
  2895. {
  2896. if (!AlgoStr.CompareIC(Names[Algo]) &&
  2897. !Used[Algo] && DebugAlwaysTrue(Index < Count))
  2898. {
  2899. NewList[Index] = (AlgoT)Algo;
  2900. Used[Algo] = true;
  2901. Index++;
  2902. break;
  2903. }
  2904. }
  2905. }
  2906. if (HasWarnAlgo && !Used[WarnAlgo] && DebugAlwaysTrue(Index < Count))
  2907. {
  2908. NewList[Index] = WarnAlgo;
  2909. Used[WarnAlgo] = true;
  2910. Index++;
  2911. }
  2912. int WarnIndex = -1;
  2913. if (HasWarnAlgo)
  2914. {
  2915. WarnIndex = std::find(NewList.begin(), NewList.end(), WarnAlgo) - NewList.begin();
  2916. }
  2917. bool Priority = true;
  2918. for (int DefaultIndex = 0; (DefaultIndex < Count); DefaultIndex++)
  2919. {
  2920. AlgoT DefaultAlgo = DefaultList[DefaultIndex];
  2921. if (!Used[DefaultAlgo] && DebugAlwaysTrue(Index < Count))
  2922. {
  2923. int TargetIndex;
  2924. // Unused algs that are prioritized in the default list,
  2925. // should be merged before the existing custom list
  2926. if (Priority)
  2927. {
  2928. TargetIndex = DefaultIndex;
  2929. }
  2930. else
  2931. {
  2932. if (HasWarnAlgo && (DefaultIndex < WarnDefaultIndex))
  2933. {
  2934. TargetIndex = WarnIndex;
  2935. }
  2936. else
  2937. {
  2938. TargetIndex = Index;
  2939. }
  2940. }
  2941. NewList.insert(NewList.begin() + TargetIndex, DefaultAlgo);
  2942. DebugAssert(NewList.back() == AlgoT());
  2943. NewList.pop_back();
  2944. if (HasWarnAlgo && (TargetIndex <= WarnIndex))
  2945. {
  2946. WarnIndex++;
  2947. }
  2948. Index++;
  2949. }
  2950. else
  2951. {
  2952. Priority = false;
  2953. }
  2954. }
  2955. if (!std::equal(NewList.begin(), NewList.end(), List))
  2956. {
  2957. std::copy(NewList.begin(), NewList.end(), List);
  2958. Modify();
  2959. }
  2960. }
  2961. //---------------------------------------------------------------------
  2962. void __fastcall TSessionData::SetCipherList(UnicodeString value)
  2963. {
  2964. SetAlgoList(FCiphers, DefaultCipherList, CipherNames, CIPHER_COUNT, cipWarn, value);
  2965. }
  2966. //---------------------------------------------------------------------
  2967. UnicodeString __fastcall TSessionData::GetCipherList() const
  2968. {
  2969. UnicodeString Result;
  2970. for (int Index = 0; Index < CIPHER_COUNT; Index++)
  2971. {
  2972. Result += UnicodeString(Index ? L"," : L"") + CipherNames[Cipher[Index]];
  2973. }
  2974. return Result;
  2975. }
  2976. //---------------------------------------------------------------------
  2977. void __fastcall TSessionData::SetKex(int Index, TKex value)
  2978. {
  2979. DebugAssert(Index >= 0 && Index < KEX_COUNT);
  2980. SET_SESSION_PROPERTY(Kex[Index]);
  2981. }
  2982. //---------------------------------------------------------------------
  2983. TKex __fastcall TSessionData::GetKex(int Index) const
  2984. {
  2985. DebugAssert(Index >= 0 && Index < KEX_COUNT);
  2986. return FKex[Index];
  2987. }
  2988. //---------------------------------------------------------------------
  2989. void __fastcall TSessionData::SetKexList(UnicodeString value)
  2990. {
  2991. SetAlgoList(FKex, DefaultKexList, KexNames, KEX_COUNT, kexWarn, value);
  2992. }
  2993. //---------------------------------------------------------------------
  2994. UnicodeString __fastcall TSessionData::GetKexList() const
  2995. {
  2996. UnicodeString Result;
  2997. for (int Index = 0; Index < KEX_COUNT; Index++)
  2998. {
  2999. Result += UnicodeString(Index ? L"," : L"") + KexNames[Kex[Index]];
  3000. }
  3001. return Result;
  3002. }
  3003. //---------------------------------------------------------------------
  3004. void __fastcall TSessionData::SetHostKeys(int Index, THostKey value)
  3005. {
  3006. DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);
  3007. SET_SESSION_PROPERTY(HostKeys[Index]);
  3008. }
  3009. //---------------------------------------------------------------------
  3010. THostKey __fastcall TSessionData::GetHostKeys(int Index) const
  3011. {
  3012. DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);
  3013. return FHostKeys[Index];
  3014. }
  3015. //---------------------------------------------------------------------
  3016. void __fastcall TSessionData::SetHostKeyList(UnicodeString value)
  3017. {
  3018. SetAlgoList(FHostKeys, DefaultHostKeyList, HostKeyNames, HOSTKEY_COUNT, hkWarn, value);
  3019. }
  3020. //---------------------------------------------------------------------
  3021. UnicodeString __fastcall TSessionData::GetHostKeyList() const
  3022. {
  3023. UnicodeString Result;
  3024. for (int Index = 0; Index < HOSTKEY_COUNT; Index++)
  3025. {
  3026. Result += UnicodeString(Index ? L"," : L"") + HostKeyNames[HostKeys[Index]];
  3027. }
  3028. return Result;
  3029. }
  3030. //---------------------------------------------------------------------
  3031. void __fastcall TSessionData::SetGssLib(int Index, TGssLib value)
  3032. {
  3033. DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);
  3034. SET_SESSION_PROPERTY(GssLib[Index]);
  3035. }
  3036. //---------------------------------------------------------------------
  3037. TGssLib __fastcall TSessionData::GetGssLib(int Index) const
  3038. {
  3039. DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);
  3040. return FGssLib[Index];
  3041. }
  3042. //---------------------------------------------------------------------
  3043. void __fastcall TSessionData::SetGssLibList(UnicodeString value)
  3044. {
  3045. SetAlgoList(FGssLib, DefaultGssLibList, GssLibNames, GSSLIB_COUNT, TGssLib(-1), value);
  3046. }
  3047. //---------------------------------------------------------------------
  3048. UnicodeString __fastcall TSessionData::GetGssLibList() const
  3049. {
  3050. UnicodeString Result;
  3051. for (int Index = 0; Index < GSSLIB_COUNT; Index++)
  3052. {
  3053. Result += UnicodeString(Index ? L"," : L"") + GssLibNames[GssLib[Index]];
  3054. }
  3055. return Result;
  3056. }
  3057. //---------------------------------------------------------------------
  3058. void __fastcall TSessionData::SetGssLibCustom(UnicodeString value)
  3059. {
  3060. SET_SESSION_PROPERTY(GssLibCustom);
  3061. }
  3062. //---------------------------------------------------------------------
  3063. void __fastcall TSessionData::SetPublicKeyFile(UnicodeString value)
  3064. {
  3065. if (FPublicKeyFile != value)
  3066. {
  3067. // PublicKeyFile is key for Passphrase encryption
  3068. UnicodeString XPassphrase = Passphrase;
  3069. // StripPathQuotes should not be needed as we do not feed quotes anymore
  3070. FPublicKeyFile = StripPathQuotes(value);
  3071. Modify();
  3072. Passphrase = XPassphrase;
  3073. Shred(XPassphrase);
  3074. }
  3075. }
  3076. //---------------------------------------------------------------------
  3077. void __fastcall TSessionData::SetDetachedCertificate(UnicodeString value)
  3078. {
  3079. SET_SESSION_PROPERTY(DetachedCertificate);
  3080. }
  3081. //---------------------------------------------------------------------
  3082. UnicodeString TSessionData::ResolvePublicKeyFile()
  3083. {
  3084. UnicodeString Result = PublicKeyFile;
  3085. if (Result.IsEmpty())
  3086. {
  3087. Result = Configuration->DefaultKeyFile;
  3088. }
  3089. // StripPathQuotes should not be needed as we do not feed quotes anymore
  3090. Result = StripPathQuotes(::ExpandEnvironmentVariables(Result));
  3091. return Result;
  3092. }
  3093. //---------------------------------------------------------------------
  3094. void __fastcall TSessionData::SetPassphrase(UnicodeString avalue)
  3095. {
  3096. RawByteString value = EncryptPassword(avalue, PublicKeyFile);
  3097. SET_SESSION_PROPERTY(Passphrase);
  3098. }
  3099. //---------------------------------------------------------------------
  3100. UnicodeString __fastcall TSessionData::GetPassphrase() const
  3101. {
  3102. return DecryptPassword(FPassphrase, PublicKeyFile);
  3103. }
  3104. //---------------------------------------------------------------------
  3105. void __fastcall TSessionData::SetReturnVar(UnicodeString value)
  3106. {
  3107. SET_SESSION_PROPERTY(ReturnVar);
  3108. }
  3109. //---------------------------------------------------------------------
  3110. void __fastcall TSessionData::SetExitCode1IsError(bool value)
  3111. {
  3112. SET_SESSION_PROPERTY(ExitCode1IsError);
  3113. }
  3114. //---------------------------------------------------------------------------
  3115. void __fastcall TSessionData::SetLookupUserGroups(TAutoSwitch value)
  3116. {
  3117. SET_SESSION_PROPERTY(LookupUserGroups);
  3118. }
  3119. //---------------------------------------------------------------------------
  3120. void __fastcall TSessionData::SetEOLType(TEOLType value)
  3121. {
  3122. SET_SESSION_PROPERTY(EOLType);
  3123. }
  3124. //---------------------------------------------------------------------------
  3125. void __fastcall TSessionData::SetTrimVMSVersions(bool value)
  3126. {
  3127. SET_SESSION_PROPERTY(TrimVMSVersions);
  3128. }
  3129. //---------------------------------------------------------------------------
  3130. void __fastcall TSessionData::SetVMSAllRevisions(bool value)
  3131. {
  3132. SET_SESSION_PROPERTY(VMSAllRevisions);
  3133. }
  3134. //---------------------------------------------------------------------------
  3135. TDateTime __fastcall TSessionData::GetTimeoutDT()
  3136. {
  3137. return SecToDateTime(Timeout);
  3138. }
  3139. //---------------------------------------------------------------------------
  3140. void __fastcall TSessionData::SetTimeout(int value)
  3141. {
  3142. SET_SESSION_PROPERTY(Timeout);
  3143. }
  3144. //---------------------------------------------------------------------------
  3145. void __fastcall TSessionData::SetFSProtocol(TFSProtocol value)
  3146. {
  3147. SET_SESSION_PROPERTY(FSProtocol);
  3148. }
  3149. //---------------------------------------------------------------------
  3150. UnicodeString __fastcall TSessionData::GetFSProtocolStr()
  3151. {
  3152. DebugAssert(FSProtocol >= 0 && FSProtocol < FSPROTOCOL_COUNT);
  3153. return FSProtocolNames[FSProtocol];
  3154. }
  3155. //---------------------------------------------------------------------------
  3156. void __fastcall TSessionData::SetDetectReturnVar(bool value)
  3157. {
  3158. if (value != DetectReturnVar)
  3159. {
  3160. ReturnVar = value ? L"" : L"$?";
  3161. }
  3162. }
  3163. //---------------------------------------------------------------------------
  3164. bool __fastcall TSessionData::GetDetectReturnVar()
  3165. {
  3166. return ReturnVar.IsEmpty();
  3167. }
  3168. //---------------------------------------------------------------------------
  3169. void __fastcall TSessionData::SetDefaultShell(bool value)
  3170. {
  3171. if (value != DefaultShell)
  3172. {
  3173. Shell = value ? L"" : L"/bin/bash";
  3174. }
  3175. }
  3176. //---------------------------------------------------------------------------
  3177. bool __fastcall TSessionData::GetDefaultShell()
  3178. {
  3179. return Shell.IsEmpty();
  3180. }
  3181. //---------------------------------------------------------------------------
  3182. void __fastcall TSessionData::SetPuttyProtocol(UnicodeString value)
  3183. {
  3184. SET_SESSION_PROPERTY(PuttyProtocol);
  3185. }
  3186. //---------------------------------------------------------------------
  3187. UnicodeString __fastcall TSessionData::GetNormalizedPuttyProtocol() const
  3188. {
  3189. return DefaultStr(PuttyProtocol, PuttySshProtocol);
  3190. }
  3191. //---------------------------------------------------------------------
  3192. void __fastcall TSessionData::SetPingIntervalDT(TDateTime value)
  3193. {
  3194. unsigned short hour, min, sec, msec;
  3195. value.DecodeTime(&hour, &min, &sec, &msec);
  3196. PingInterval = ((int)hour)*SecsPerHour + ((int)min)*SecsPerMin + sec;
  3197. }
  3198. //---------------------------------------------------------------------------
  3199. TDateTime __fastcall TSessionData::GetPingIntervalDT()
  3200. {
  3201. return SecToDateTime(PingInterval);
  3202. }
  3203. //---------------------------------------------------------------------------
  3204. void __fastcall TSessionData::SetPingType(TPingType value)
  3205. {
  3206. SET_SESSION_PROPERTY(PingType);
  3207. }
  3208. //---------------------------------------------------------------------------
  3209. void __fastcall TSessionData::SetAddressFamily(TAddressFamily value)
  3210. {
  3211. SET_SESSION_PROPERTY(AddressFamily);
  3212. }
  3213. //---------------------------------------------------------------------------
  3214. void __fastcall TSessionData::SetRekeyData(UnicodeString value)
  3215. {
  3216. SET_SESSION_PROPERTY(RekeyData);
  3217. }
  3218. //---------------------------------------------------------------------------
  3219. void __fastcall TSessionData::SetRekeyTime(unsigned int value)
  3220. {
  3221. SET_SESSION_PROPERTY(RekeyTime);
  3222. }
  3223. //---------------------------------------------------------------------
  3224. UnicodeString __fastcall TSessionData::GetDefaultSessionName()
  3225. {
  3226. UnicodeString Result;
  3227. if (IsLocalBrowser)
  3228. {
  3229. // See also TScpCommanderForm::GetLocalBrowserSessionTitle
  3230. UnicodeString Path1 = ExtractShortName(LocalDirectory, false);
  3231. UnicodeString Path2 = ExtractShortName(OtherLocalDirectory, false);
  3232. Result = Path1 + TitleSeparator + Path2;
  3233. }
  3234. else if (!HostName.IsEmpty() && !UserName.IsEmpty())
  3235. {
  3236. // If we ever choose to include port number,
  3237. // we have to escape IPv6 literals in HostName
  3238. Result = FORMAT(L"%s@%s", (UserName, HostName));
  3239. }
  3240. else if (!HostName.IsEmpty())
  3241. {
  3242. Result = HostName;
  3243. }
  3244. else
  3245. {
  3246. Result = L"session";
  3247. }
  3248. Result = MakeValidName(Result);
  3249. return Result;
  3250. }
  3251. //---------------------------------------------------------------------
  3252. UnicodeString __fastcall TSessionData::GetNameWithoutHiddenPrefix()
  3253. {
  3254. UnicodeString Result = Name;
  3255. if (Hidden)
  3256. {
  3257. Result = Result.SubString(TNamedObjectList::HiddenPrefix.Length() + 1, Result.Length() - TNamedObjectList::HiddenPrefix.Length());
  3258. }
  3259. return Result;
  3260. }
  3261. //---------------------------------------------------------------------
  3262. bool __fastcall TSessionData::HasSessionName()
  3263. {
  3264. return (!GetNameWithoutHiddenPrefix().IsEmpty() && (Name != DefaultName));
  3265. }
  3266. //---------------------------------------------------------------------
  3267. UnicodeString __fastcall TSessionData::GetSessionName()
  3268. {
  3269. UnicodeString Result;
  3270. if (HasSessionName())
  3271. {
  3272. Result = GetNameWithoutHiddenPrefix();
  3273. }
  3274. else
  3275. {
  3276. Result = DefaultSessionName;
  3277. }
  3278. return Result;
  3279. }
  3280. //---------------------------------------------------------------------
  3281. bool __fastcall TSessionData::IsSecure()
  3282. {
  3283. bool Result;
  3284. switch (FSProtocol)
  3285. {
  3286. case fsSCPonly:
  3287. case fsSFTP:
  3288. case fsSFTPonly:
  3289. Result = true;
  3290. break;
  3291. case fsFTP:
  3292. case fsWebDAV:
  3293. case fsS3:
  3294. Result = (Ftps != ftpsNone);
  3295. break;
  3296. default:
  3297. DebugFail();
  3298. break;
  3299. }
  3300. return Result;
  3301. }
  3302. //---------------------------------------------------------------------
  3303. UnicodeString __fastcall TSessionData::GetProtocolUrl(bool HttpForWebDAV)
  3304. {
  3305. UnicodeString Url;
  3306. switch (FSProtocol)
  3307. {
  3308. case fsSCPonly:
  3309. Url = ScpProtocol;
  3310. break;
  3311. default:
  3312. DebugFail();
  3313. // fallback
  3314. case fsSFTP:
  3315. case fsSFTPonly:
  3316. Url = SftpProtocol;
  3317. break;
  3318. case fsFTP:
  3319. if (Ftps == ftpsImplicit)
  3320. {
  3321. Url = FtpsProtocol;
  3322. }
  3323. else if ((Ftps == ftpsExplicitTls) || (Ftps == ftpsExplicitSsl))
  3324. {
  3325. Url = FtpesProtocol;
  3326. }
  3327. else
  3328. {
  3329. Url = FtpProtocol;
  3330. }
  3331. break;
  3332. case fsWebDAV:
  3333. if (HttpForWebDAV)
  3334. {
  3335. if (Ftps == ftpsImplicit)
  3336. {
  3337. Url = HttpsProtocol;
  3338. }
  3339. else
  3340. {
  3341. Url = HttpProtocol;
  3342. }
  3343. }
  3344. else
  3345. {
  3346. if (Ftps == ftpsImplicit)
  3347. {
  3348. Url = WebDAVSProtocol;
  3349. }
  3350. else
  3351. {
  3352. Url = WebDAVProtocol;
  3353. }
  3354. }
  3355. break;
  3356. case fsS3:
  3357. if (Ftps == ftpsImplicit)
  3358. {
  3359. Url = S3Protocol;
  3360. }
  3361. else
  3362. {
  3363. Url = S3PlainProtocol;
  3364. }
  3365. break;
  3366. }
  3367. Url += ProtocolSeparator;
  3368. return Url;
  3369. }
  3370. //---------------------------------------------------------------------
  3371. bool HasIP6LiteralBrackets(const UnicodeString & HostName)
  3372. {
  3373. return
  3374. (HostName.Length() >= 2) &&
  3375. (HostName[1] == L'[') &&
  3376. (HostName[HostName.Length()] == L']');
  3377. }
  3378. //---------------------------------------------------------------------
  3379. UnicodeString StripIP6LiteralBrackets(const UnicodeString & HostName)
  3380. {
  3381. UnicodeString Result = HostName;
  3382. if (DebugAlwaysTrue(HasIP6LiteralBrackets(Result)))
  3383. {
  3384. Result = Result.SubString(2, Result.Length() - 2);
  3385. }
  3386. return Result;
  3387. }
  3388. //---------------------------------------------------------------------
  3389. bool __fastcall IsIPv6Literal(const UnicodeString & HostName)
  3390. {
  3391. UnicodeString Buf = HostName;
  3392. if (HasIP6LiteralBrackets(Buf))
  3393. {
  3394. Buf = StripIP6LiteralBrackets(Buf);
  3395. }
  3396. int Colons = 0;
  3397. bool Result = true;
  3398. for (int Index = 1; Result && (Index <= Buf.Length()); Index++)
  3399. {
  3400. wchar_t C = Buf[Index];
  3401. if (C == L'%')
  3402. {
  3403. break;
  3404. }
  3405. else if (C == L':')
  3406. {
  3407. Colons++;
  3408. }
  3409. else
  3410. {
  3411. Result = IsHex(C);
  3412. }
  3413. }
  3414. Result = Result && (Colons >= 2);
  3415. return Result;
  3416. }
  3417. //---------------------------------------------------------------------
  3418. UnicodeString __fastcall EscapeIPv6Literal(const UnicodeString & IP)
  3419. {
  3420. UnicodeString Result = IP;
  3421. if (!HasIP6LiteralBrackets(Result))
  3422. {
  3423. Result = L"[" + IP + L"]";
  3424. }
  3425. return Result;
  3426. }
  3427. //---------------------------------------------------------------------
  3428. TStrings * __fastcall TSessionData::GetRawSettingsForUrl()
  3429. {
  3430. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3431. std::unique_ptr<TSessionData> SessionData(Clone());
  3432. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3433. SessionData->HostName = FactoryDefaults->HostName;
  3434. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3435. SessionData->UserName = FactoryDefaults->UserName;
  3436. SessionData->Password = FactoryDefaults->Password;
  3437. SessionData->Ftps = FactoryDefaults->Ftps;
  3438. SessionData->HostKey = FactoryDefaults->HostKey;
  3439. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3440. // Cannot be decided in SaveToOptions as it does not have HostName and UserName, so it cannot calculate DefaultSessionName.
  3441. bool SaveName = HasSessionName() && (Name != DefaultSessionName);
  3442. return SessionData->SaveToOptions(FactoryDefaults.get(), SaveName, false);
  3443. }
  3444. //---------------------------------------------------------------------
  3445. bool __fastcall TSessionData::HasRawSettingsForUrl()
  3446. {
  3447. std::unique_ptr<TStrings> RawSettings(GetRawSettingsForUrl());
  3448. return (RawSettings->Count > 0);
  3449. }
  3450. //---------------------------------------------------------------------
  3451. UnicodeString __fastcall TSessionData::GenerateSessionUrl(unsigned int Flags)
  3452. {
  3453. UnicodeString Url;
  3454. if (FLAGSET(Flags, sufSpecific))
  3455. {
  3456. Url += WinSCPProtocolPrefix;
  3457. }
  3458. Url += GetProtocolUrl(FLAGSET(Flags, sufHttpForWebDAV));
  3459. // Add username only if it was somehow explicitly specified (so not with S3CredentialsEnv), but if it was, add it in the expanded form.
  3460. // For scripting, we might use unexpanded form (keeping the environment variables),
  3461. // but for consistency with code generation (where explicit expansion code would need to be added), we do not.
  3462. if (FLAGSET(Flags, sufUserName) && !UserName.IsEmpty())
  3463. {
  3464. Url += EncodeUrlString(UserNameExpanded);
  3465. if (FLAGSET(Flags, sufPassword) && !Password.IsEmpty())
  3466. {
  3467. Url += L":" + EncodeUrlString(NormalizeString(Password));
  3468. }
  3469. if (FLAGSET(Flags, sufHostKey) && !HostKey.IsEmpty())
  3470. {
  3471. UnicodeString KeyName;
  3472. UnicodeString Fingerprint = HostKey;
  3473. NormalizeFingerprint(Fingerprint, KeyName);
  3474. UnicodeString S = Fingerprint;
  3475. if (!KeyName.IsEmpty())
  3476. {
  3477. S = KeyName + NormalizedFingerprintSeparator + S;
  3478. }
  3479. S = Base64ToUrlSafe(S); // Noop for MD5 (both in SSH host keys and TLS/SSL)
  3480. S = MD5ToUrlSafe(S); // TLS/SSL fingerprints
  3481. UnicodeString S2 = EncodeUrlString(S);
  3482. DebugAssert(S2 == S2); // There should be nothing left for encoding
  3483. Url +=
  3484. UnicodeString(UrlParamSeparator) + UrlHostKeyParamName +
  3485. UnicodeString(UrlParamValueSeparator) + S2;
  3486. }
  3487. if (FLAGSET(Flags, sufRawSettings))
  3488. {
  3489. std::unique_ptr<TStrings> RawSettings(GetRawSettingsForUrl());
  3490. for (int Index = 0; Index < RawSettings->Count; Index++)
  3491. {
  3492. Url +=
  3493. UnicodeString(UrlParamSeparator) +
  3494. UrlRawSettingsParamNamePrefix + EncodeUrlString(LowerCase(RawSettings->Names[Index])) +
  3495. UnicodeString(UrlParamValueSeparator) + EncodeUrlString(RawSettings->ValueFromIndex[Index]);
  3496. }
  3497. }
  3498. Url += L"@";
  3499. }
  3500. DebugAssert(!HostNameExpanded.IsEmpty());
  3501. if (IsIPv6Literal(HostNameExpanded))
  3502. {
  3503. Url += EscapeIPv6Literal(HostNameExpanded);
  3504. }
  3505. else
  3506. {
  3507. Url += EncodeUrlString(HostNameExpanded);
  3508. }
  3509. if (PortNumber != GetDefaultPort())
  3510. {
  3511. Url += L":" + IntToStr(PortNumber);
  3512. }
  3513. Url += L"/";
  3514. return Url;
  3515. }
  3516. //---------------------------------------------------------------------
  3517. UnicodeString ScriptCommandOpenLink(TraceInitStr(ScriptCommandLink(L"open")));
  3518. //---------------------------------------------------------------------
  3519. void __fastcall TSessionData::AddSwitch(
  3520. UnicodeString & Result, const UnicodeString & Name, bool Rtf)
  3521. {
  3522. Result += RtfSwitch(Name, ScriptCommandOpenLink, Rtf);
  3523. }
  3524. //---------------------------------------------------------------------
  3525. void __fastcall TSessionData::AddSwitch(
  3526. UnicodeString & Result, const UnicodeString & Name, const UnicodeString & Value, bool Rtf)
  3527. {
  3528. Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);
  3529. }
  3530. //---------------------------------------------------------------------
  3531. void __fastcall TSessionData::AddSwitch(
  3532. UnicodeString & Result, const UnicodeString & Name, int Value, bool Rtf)
  3533. {
  3534. Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);
  3535. }
  3536. //---------------------------------------------------------------------
  3537. void __fastcall TSessionData::LookupLastFingerprint()
  3538. {
  3539. UnicodeString FingerprintType;
  3540. if (IsSshProtocol(FSProtocol))
  3541. {
  3542. FingerprintType = SshFingerprintType;
  3543. }
  3544. else if (Ftps != ftpsNone)
  3545. {
  3546. FingerprintType = TlsFingerprintType;
  3547. }
  3548. if (!FingerprintType.IsEmpty())
  3549. {
  3550. HostKey = Configuration->LastFingerprint(SiteKey, FingerprintType);
  3551. }
  3552. if (Tunnel)
  3553. {
  3554. // not used anyway
  3555. int TunnelPortNumber = std::max(TunnelLocalPortNumber, Configuration->TunnelLocalPortNumberLow);
  3556. std::unique_ptr<TSessionData> TunnelData(CreateTunnelData(TunnelPortNumber));
  3557. TunnelHostKey = Configuration->LastFingerprint(TunnelData->SiteKey, SshFingerprintType);
  3558. }
  3559. }
  3560. //---------------------------------------------------------------------
  3561. UnicodeString __fastcall TSessionData::GenerateOpenCommandArgs(bool Rtf)
  3562. {
  3563. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3564. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  3565. SessionData->Assign(this);
  3566. UnicodeString Result = SessionData->GenerateSessionUrl(sufOpen);
  3567. // Before we reset the FSProtocol
  3568. bool AUsesSsh = SessionData->UsesSsh;
  3569. // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that
  3570. if (SessionData->FSProtocol != fsSFTPonly)
  3571. {
  3572. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3573. }
  3574. SessionData->HostName = FactoryDefaults->HostName;
  3575. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3576. SessionData->UserName = FactoryDefaults->UserName;
  3577. SessionData->Password = FactoryDefaults->Password;
  3578. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3579. SessionData->Ftps = FactoryDefaults->Ftps;
  3580. if (SessionData->HostKey != FactoryDefaults->HostKey)
  3581. {
  3582. UnicodeString SwitchName = AUsesSsh ? L"hostkey" : L"certificate";
  3583. AddSwitch(Result, SwitchName, SessionData->HostKey, Rtf);
  3584. SessionData->HostKey = FactoryDefaults->HostKey;
  3585. }
  3586. if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)
  3587. {
  3588. AddSwitch(Result, PRIVATEKEY_SWITCH, SessionData->PublicKeyFile, Rtf);
  3589. SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;
  3590. }
  3591. if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)
  3592. {
  3593. AddSwitch(Result, L"clientcert", SessionData->TlsCertificateFile, Rtf);
  3594. SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;
  3595. }
  3596. if (SessionData->Passphrase != FactoryDefaults->Passphrase)
  3597. {
  3598. AddSwitch(Result, PassphraseOption, SessionData->Passphrase, Rtf);
  3599. SessionData->Passphrase = FactoryDefaults->Passphrase;
  3600. }
  3601. if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)
  3602. {
  3603. AddSwitch(Result, L"passive", SessionData->FtpPasvMode ? 1 : 0, Rtf);
  3604. SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;
  3605. }
  3606. if (SessionData->Timeout != FactoryDefaults->Timeout)
  3607. {
  3608. AddSwitch(Result, L"timeout", SessionData->Timeout, Rtf);
  3609. SessionData->Timeout = FactoryDefaults->Timeout;
  3610. }
  3611. std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get(), false, false));
  3612. if (RawSettings->Count > 0)
  3613. {
  3614. AddSwitch(Result, RawSettingsOption, Rtf);
  3615. Result += StringsToParams(RawSettings.get());
  3616. }
  3617. return Result;
  3618. }
  3619. //---------------------------------------------------------------------
  3620. UnicodeString SessionOptionsClassName(L"SessionOptions");
  3621. //---------------------------------------------------------------------
  3622. void __fastcall TSessionData::AddAssemblyProperty(
  3623. UnicodeString & Result, TAssemblyLanguage Language,
  3624. const UnicodeString & Name, const UnicodeString & Type,
  3625. const UnicodeString & Member)
  3626. {
  3627. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Type, Member, false);
  3628. }
  3629. //---------------------------------------------------------------------
  3630. void __fastcall TSessionData::AddAssemblyProperty(
  3631. UnicodeString & Result, TAssemblyLanguage Language,
  3632. const UnicodeString & Name, const UnicodeString & Value)
  3633. {
  3634. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3635. }
  3636. //---------------------------------------------------------------------
  3637. void __fastcall TSessionData::AddAssemblyProperty(
  3638. UnicodeString & Result, TAssemblyLanguage Language,
  3639. const UnicodeString & Name, int Value)
  3640. {
  3641. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3642. }
  3643. //---------------------------------------------------------------------
  3644. void __fastcall TSessionData::AddAssemblyProperty(
  3645. UnicodeString & Result, TAssemblyLanguage Language,
  3646. const UnicodeString & Name, bool Value)
  3647. {
  3648. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3649. }
  3650. //---------------------------------------------------------------------
  3651. void __fastcall TSessionData::GenerateAssemblyCode(
  3652. TAssemblyLanguage Language, UnicodeString & Head, UnicodeString & Tail, int & Indent)
  3653. {
  3654. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3655. std::unique_ptr<TSessionData> SessionData(Clone());
  3656. switch (Language)
  3657. {
  3658. case alCSharp:
  3659. case alVBNET:
  3660. // noop
  3661. break;
  3662. case alPowerShell:
  3663. Head +=
  3664. AssemblyCommentLine(Language, LoadStr(CODE_PS_ADD_TYPE)) +
  3665. RtfKeyword(L"Add-Type") + RtfText(" -Path ") + AssemblyString(Language, "WinSCPnet.dll") + RtfPara +
  3666. RtfPara;
  3667. break;
  3668. default:
  3669. DebugFail();
  3670. break;
  3671. }
  3672. Head +=
  3673. AssemblyCommentLine(Language, LoadStr(CODE_SESSION_OPTIONS)) +
  3674. AssemblyNewClassInstanceStart(Language, SessionOptionsClassName, false);
  3675. UnicodeString ProtocolMember;
  3676. switch (SessionData->FSProtocol)
  3677. {
  3678. case fsSCPonly:
  3679. ProtocolMember = "Scp";
  3680. break;
  3681. default:
  3682. DebugFail();
  3683. // fallback
  3684. case fsSFTP:
  3685. case fsSFTPonly:
  3686. ProtocolMember = "Sftp";
  3687. break;
  3688. case fsFTP:
  3689. ProtocolMember = "Ftp";
  3690. break;
  3691. case fsWebDAV:
  3692. ProtocolMember = "Webdav";
  3693. break;
  3694. case fsS3:
  3695. ProtocolMember = "S3";
  3696. break;
  3697. }
  3698. // Before we reset the FSProtocol
  3699. bool AUsesSsh = SessionData->UsesSsh;
  3700. // Protocol is set unconditionally, we want even the default SFTP
  3701. AddAssemblyProperty(Head, Language, L"Protocol", L"Protocol", ProtocolMember);
  3702. // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that
  3703. if (SessionData->FSProtocol != fsSFTPonly)
  3704. {
  3705. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3706. }
  3707. if (SessionData->HostName != FactoryDefaults->HostName)
  3708. {
  3709. AddAssemblyProperty(Head, Language, L"HostName", HostName);
  3710. SessionData->HostName = FactoryDefaults->HostName;
  3711. }
  3712. int ADefaultPort = GetDefaultPort();
  3713. if (SessionData->PortNumber != ADefaultPort)
  3714. {
  3715. AddAssemblyProperty(Head, Language, L"PortNumber", PortNumber);
  3716. }
  3717. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3718. if (SessionData->UserName != FactoryDefaults->UserName)
  3719. {
  3720. AddAssemblyProperty(Head, Language, L"UserName", UserName);
  3721. SessionData->UserName = FactoryDefaults->UserName;
  3722. }
  3723. if (SessionData->Password != FactoryDefaults->Password)
  3724. {
  3725. AddAssemblyProperty(Head, Language, L"Password", NormalizeString(Password));
  3726. SessionData->Password = FactoryDefaults->Password;
  3727. }
  3728. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3729. TFtps DefaultFtps = FactoryDefaults->Ftps;
  3730. if (FSProtocol == fsS3)
  3731. {
  3732. DefaultFtps = ftpsImplicit;
  3733. }
  3734. if (SessionData->Ftps != DefaultFtps)
  3735. {
  3736. // SessionData->FSProtocol is reset already
  3737. switch (FSProtocol)
  3738. {
  3739. case fsFTP:
  3740. {
  3741. UnicodeString FtpSecureMember;
  3742. switch (SessionData->Ftps)
  3743. {
  3744. case ftpsNone:
  3745. DebugFail();
  3746. FtpSecureMember = L"None";
  3747. break;
  3748. case ftpsImplicit:
  3749. FtpSecureMember = L"Implicit";
  3750. break;
  3751. case ftpsExplicitTls:
  3752. case ftpsExplicitSsl:
  3753. FtpSecureMember = L"Explicit";
  3754. break;
  3755. default:
  3756. DebugFail();
  3757. break;
  3758. }
  3759. AddAssemblyProperty(Head, Language, L"FtpSecure", L"FtpSecure", FtpSecureMember);
  3760. }
  3761. break;
  3762. case fsWebDAV:
  3763. case fsS3:
  3764. AddAssemblyProperty(Head, Language, L"Secure", (SessionData->Ftps != ftpsNone));
  3765. break;
  3766. default:
  3767. DebugFail();
  3768. break;
  3769. }
  3770. }
  3771. SessionData->Ftps = FactoryDefaults->Ftps;
  3772. if (SessionData->HostKey != FactoryDefaults->HostKey)
  3773. {
  3774. UnicodeString PropertyName = AUsesSsh ? L"SshHostKeyFingerprint" : L"TlsHostCertificateFingerprint";
  3775. AddAssemblyProperty(Head, Language, PropertyName, SessionData->HostKey);
  3776. SessionData->HostKey = FactoryDefaults->HostKey;
  3777. }
  3778. if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)
  3779. {
  3780. AddAssemblyProperty(Head, Language, L"SshPrivateKeyPath", SessionData->PublicKeyFile);
  3781. SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;
  3782. }
  3783. if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)
  3784. {
  3785. AddAssemblyProperty(Head, Language, L"TlsClientCertificatePath", SessionData->TlsCertificateFile);
  3786. SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;
  3787. }
  3788. if (SessionData->Passphrase != FactoryDefaults->Passphrase)
  3789. {
  3790. AddAssemblyProperty(Head, Language, L"PrivateKeyPassphrase", SessionData->Passphrase);
  3791. SessionData->Passphrase = FactoryDefaults->Passphrase;
  3792. }
  3793. if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)
  3794. {
  3795. AddAssemblyProperty(Head, Language, L"FtpMode", L"FtpMode", (SessionData->FtpPasvMode ? L"Passive" : L"Active"));
  3796. SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;
  3797. }
  3798. if (SessionData->Timeout != FactoryDefaults->Timeout)
  3799. {
  3800. AddAssemblyProperty(Head, Language, L"TimeoutInMilliseconds", SessionData->Timeout * 1000);
  3801. SessionData->Timeout = FactoryDefaults->Timeout;
  3802. }
  3803. Head += AssemblyNewClassInstanceEnd(Language, false);
  3804. std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get(), false, false));
  3805. UnicodeString SessionOptionsVariableName = AssemblyVariableName(Language, SessionOptionsClassName);
  3806. if (RawSettings->Count > 0)
  3807. {
  3808. Head +=
  3809. RtfPara +
  3810. AssemblyAddRawSettings(Language, RawSettings.get(), SessionOptionsClassName, L"AddRawSettings");
  3811. }
  3812. Head += RtfPara;
  3813. UnicodeString Indentation = L" ";
  3814. UnicodeString SessionVariableName = AssemblyVariableName(Language, SessionClassName);
  3815. UnicodeString RtfSessionClass = RtfLibraryClass(SessionClassName);
  3816. UnicodeString RtfSessionOpenMethod = RtfLibraryMethod(SessionClassName, L"Open", false);
  3817. UnicodeString NewSessionInstance = AssemblyNewClassInstance(Language, SessionClassName, false);
  3818. UnicodeString OpenCall =
  3819. Indentation + AssemblyCommentLine(Language, LoadStr(CODE_CONNECT)) +
  3820. Indentation + RtfText(SessionVariableName + L".") + RtfSessionOpenMethod + RtfText(L"(" + SessionOptionsVariableName + L")") +
  3821. AssemblyStatementSeparator(Language) + RtfPara;
  3822. switch (Language)
  3823. {
  3824. case alCSharp:
  3825. Head +=
  3826. RtfKeyword(L"using") + RtfText(" (") + NewSessionInstance + RtfText(L"())") + RtfPara +
  3827. RtfText(L"{") + RtfPara +
  3828. OpenCall;
  3829. Tail =
  3830. RtfText(L"}") + RtfPara;
  3831. break;
  3832. case alVBNET:
  3833. Head +=
  3834. RtfKeyword(L"Using") + RtfText(L" ") + NewSessionInstance + RtfPara +
  3835. OpenCall;
  3836. Tail =
  3837. RtfKeyword(L"End Using") + RtfPara;
  3838. break;
  3839. case alPowerShell:
  3840. Head +=
  3841. NewSessionInstance + RtfPara +
  3842. RtfPara +
  3843. RtfKeyword(L"try") + RtfPara +
  3844. RtfText(L"{") + RtfPara +
  3845. OpenCall;
  3846. Tail =
  3847. RtfText(L"}") + RtfPara +
  3848. RtfKeyword(L"finally") + RtfPara +
  3849. RtfText(L"{") + RtfPara +
  3850. RtfText(Indentation + SessionVariableName + L".") +
  3851. RtfLibraryMethod(SessionClassName, L"Dispose", false) + RtfText(L"()") + RtfPara +
  3852. RtfText(L"}") + RtfPara;
  3853. break;
  3854. }
  3855. Head += RtfPara;
  3856. Indent = 4; // the same for all languages so far
  3857. }
  3858. //---------------------------------------------------------------------
  3859. void __fastcall TSessionData::SetTimeDifference(TDateTime value)
  3860. {
  3861. SET_SESSION_PROPERTY(TimeDifference);
  3862. }
  3863. //---------------------------------------------------------------------
  3864. void __fastcall TSessionData::SetTimeDifferenceAuto(bool value)
  3865. {
  3866. SET_SESSION_PROPERTY(TimeDifferenceAuto);
  3867. }
  3868. //---------------------------------------------------------------------
  3869. void __fastcall TSessionData::SetLocalDirectory(UnicodeString value)
  3870. {
  3871. SET_SESSION_PROPERTY(LocalDirectory);
  3872. }
  3873. //---------------------------------------------------------------------
  3874. void __fastcall TSessionData::SetOtherLocalDirectory(const UnicodeString & value)
  3875. {
  3876. SET_SESSION_PROPERTY(OtherLocalDirectory);
  3877. }
  3878. //---------------------------------------------------------------------
  3879. UnicodeString __fastcall TSessionData::GetLocalDirectoryExpanded()
  3880. {
  3881. return ExpandFileName(::ExpandEnvironmentVariables(LocalDirectory));
  3882. }
  3883. //---------------------------------------------------------------------
  3884. void __fastcall TSessionData::SetRemoteDirectory(UnicodeString value)
  3885. {
  3886. SET_SESSION_PROPERTY(RemoteDirectory);
  3887. }
  3888. //---------------------------------------------------------------------
  3889. void __fastcall TSessionData::SetSynchronizeBrowsing(bool value)
  3890. {
  3891. SET_SESSION_PROPERTY(SynchronizeBrowsing);
  3892. }
  3893. //---------------------------------------------------------------------
  3894. void __fastcall TSessionData::SetUpdateDirectories(bool value)
  3895. {
  3896. SET_SESSION_PROPERTY(UpdateDirectories);
  3897. }
  3898. //---------------------------------------------------------------------
  3899. void __fastcall TSessionData::SetCacheDirectories(bool value)
  3900. {
  3901. SET_SESSION_PROPERTY(CacheDirectories);
  3902. }
  3903. //---------------------------------------------------------------------
  3904. void __fastcall TSessionData::SetCacheDirectoryChanges(bool value)
  3905. {
  3906. SET_SESSION_PROPERTY(CacheDirectoryChanges);
  3907. }
  3908. //---------------------------------------------------------------------
  3909. void __fastcall TSessionData::SetPreserveDirectoryChanges(bool value)
  3910. {
  3911. SET_SESSION_PROPERTY(PreserveDirectoryChanges);
  3912. }
  3913. //---------------------------------------------------------------------
  3914. void __fastcall TSessionData::SetResolveSymlinks(bool value)
  3915. {
  3916. SET_SESSION_PROPERTY(ResolveSymlinks);
  3917. }
  3918. //---------------------------------------------------------------------
  3919. void __fastcall TSessionData::SetFollowDirectorySymlinks(bool value)
  3920. {
  3921. SET_SESSION_PROPERTY(FollowDirectorySymlinks);
  3922. }
  3923. //---------------------------------------------------------------------------
  3924. void __fastcall TSessionData::SetDSTMode(TDSTMode value)
  3925. {
  3926. SET_SESSION_PROPERTY(DSTMode);
  3927. }
  3928. //---------------------------------------------------------------------------
  3929. void __fastcall TSessionData::SetDeleteToRecycleBin(bool value)
  3930. {
  3931. SET_SESSION_PROPERTY(DeleteToRecycleBin);
  3932. }
  3933. //---------------------------------------------------------------------------
  3934. void __fastcall TSessionData::SetOverwrittenToRecycleBin(bool value)
  3935. {
  3936. SET_SESSION_PROPERTY(OverwrittenToRecycleBin);
  3937. }
  3938. //---------------------------------------------------------------------------
  3939. void __fastcall TSessionData::SetRecycleBinPath(UnicodeString value)
  3940. {
  3941. SET_SESSION_PROPERTY(RecycleBinPath);
  3942. }
  3943. //---------------------------------------------------------------------------
  3944. void __fastcall TSessionData::SetPostLoginCommands(UnicodeString value)
  3945. {
  3946. SET_SESSION_PROPERTY(PostLoginCommands);
  3947. }
  3948. //---------------------------------------------------------------------
  3949. void __fastcall TSessionData::SetSpecial(bool value)
  3950. {
  3951. SET_SESSION_PROPERTY(Special);
  3952. }
  3953. //---------------------------------------------------------------------------
  3954. void __fastcall TSessionData::SetScp1Compatibility(bool value)
  3955. {
  3956. SET_SESSION_PROPERTY(Scp1Compatibility);
  3957. }
  3958. //---------------------------------------------------------------------
  3959. void __fastcall TSessionData::SetTcpNoDelay(bool value)
  3960. {
  3961. SET_SESSION_PROPERTY(TcpNoDelay);
  3962. }
  3963. //---------------------------------------------------------------------
  3964. void __fastcall TSessionData::SetSendBuf(int value)
  3965. {
  3966. SET_SESSION_PROPERTY(SendBuf);
  3967. }
  3968. //---------------------------------------------------------------------
  3969. void __fastcall TSessionData::SetSourceAddress(const UnicodeString & value)
  3970. {
  3971. SET_SESSION_PROPERTY(SourceAddress);
  3972. }
  3973. //---------------------------------------------------------------------
  3974. void __fastcall TSessionData::SetProtocolFeatures(const UnicodeString & value)
  3975. {
  3976. SET_SESSION_PROPERTY(ProtocolFeatures);
  3977. }
  3978. //---------------------------------------------------------------------
  3979. void __fastcall TSessionData::SetSshSimple(bool value)
  3980. {
  3981. SET_SESSION_PROPERTY(SshSimple);
  3982. }
  3983. //---------------------------------------------------------------------
  3984. void __fastcall TSessionData::SetProxyMethod(TProxyMethod value)
  3985. {
  3986. SET_SESSION_PROPERTY(ProxyMethod);
  3987. }
  3988. //---------------------------------------------------------------------
  3989. void __fastcall TSessionData::SetProxyHost(UnicodeString value)
  3990. {
  3991. SET_SESSION_PROPERTY(ProxyHost);
  3992. }
  3993. //---------------------------------------------------------------------
  3994. void __fastcall TSessionData::SetProxyPort(int value)
  3995. {
  3996. SET_SESSION_PROPERTY(ProxyPort);
  3997. }
  3998. //---------------------------------------------------------------------
  3999. void __fastcall TSessionData::SetProxyUsername(UnicodeString value)
  4000. {
  4001. SET_SESSION_PROPERTY(ProxyUsername);
  4002. }
  4003. //---------------------------------------------------------------------
  4004. void __fastcall TSessionData::SetProxyPassword(UnicodeString avalue)
  4005. {
  4006. RawByteString value = EncryptPassword(avalue, ProxyUsername+ProxyHost);
  4007. SET_SESSION_PROPERTY(ProxyPassword);
  4008. }
  4009. //---------------------------------------------------------------------
  4010. UnicodeString __fastcall TSessionData::GetProxyPassword() const
  4011. {
  4012. return DecryptPassword(FProxyPassword, ProxyUsername+ProxyHost);
  4013. }
  4014. //---------------------------------------------------------------------
  4015. void __fastcall TSessionData::SetProxyTelnetCommand(UnicodeString value)
  4016. {
  4017. SET_SESSION_PROPERTY(ProxyTelnetCommand);
  4018. }
  4019. //---------------------------------------------------------------------
  4020. void __fastcall TSessionData::SetProxyLocalCommand(UnicodeString value)
  4021. {
  4022. SET_SESSION_PROPERTY(ProxyLocalCommand);
  4023. }
  4024. //---------------------------------------------------------------------
  4025. void __fastcall TSessionData::SetProxyDNS(TAutoSwitch value)
  4026. {
  4027. SET_SESSION_PROPERTY(ProxyDNS);
  4028. }
  4029. //---------------------------------------------------------------------
  4030. void __fastcall TSessionData::SetProxyLocalhost(bool value)
  4031. {
  4032. SET_SESSION_PROPERTY(ProxyLocalhost);
  4033. }
  4034. //---------------------------------------------------------------------
  4035. void __fastcall TSessionData::SetFtpProxyLogonType(int value)
  4036. {
  4037. SET_SESSION_PROPERTY(FtpProxyLogonType);
  4038. }
  4039. //---------------------------------------------------------------------
  4040. void __fastcall TSessionData::SetBug(TSshBug Bug, TAutoSwitch value)
  4041. {
  4042. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));
  4043. SET_SESSION_PROPERTY(Bugs[Bug]);
  4044. }
  4045. //---------------------------------------------------------------------
  4046. TAutoSwitch __fastcall TSessionData::GetBug(TSshBug Bug) const
  4047. {
  4048. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));
  4049. return FBugs[Bug];
  4050. }
  4051. //---------------------------------------------------------------------
  4052. void __fastcall TSessionData::SetPuttySettings(UnicodeString value)
  4053. {
  4054. SET_SESSION_PROPERTY(PuttySettings);
  4055. }
  4056. //---------------------------------------------------------------------
  4057. void __fastcall TSessionData::SetCustomParam1(UnicodeString value)
  4058. {
  4059. SET_SESSION_PROPERTY(CustomParam1);
  4060. }
  4061. //---------------------------------------------------------------------
  4062. void __fastcall TSessionData::SetCustomParam2(UnicodeString value)
  4063. {
  4064. SET_SESSION_PROPERTY(CustomParam2);
  4065. }
  4066. //---------------------------------------------------------------------
  4067. void __fastcall TSessionData::SetSFTPDownloadQueue(int value)
  4068. {
  4069. SET_SESSION_PROPERTY(SFTPDownloadQueue);
  4070. }
  4071. //---------------------------------------------------------------------
  4072. void __fastcall TSessionData::SetSFTPUploadQueue(int value)
  4073. {
  4074. SET_SESSION_PROPERTY(SFTPUploadQueue);
  4075. }
  4076. //---------------------------------------------------------------------
  4077. void __fastcall TSessionData::SetSFTPListingQueue(int value)
  4078. {
  4079. SET_SESSION_PROPERTY(SFTPListingQueue);
  4080. }
  4081. //---------------------------------------------------------------------
  4082. void __fastcall TSessionData::SetSFTPMaxVersion(int value)
  4083. {
  4084. SET_SESSION_PROPERTY(SFTPMaxVersion);
  4085. }
  4086. //---------------------------------------------------------------------
  4087. void __fastcall TSessionData::SetSFTPMaxPacketSize(unsigned long value)
  4088. {
  4089. SET_SESSION_PROPERTY(SFTPMaxPacketSize);
  4090. }
  4091. //---------------------------------------------------------------------
  4092. void __fastcall TSessionData::SetSFTPRealPath(TAutoSwitch value)
  4093. {
  4094. SET_SESSION_PROPERTY(SFTPRealPath);
  4095. }
  4096. //---------------------------------------------------------------------
  4097. void TSessionData::SetUsePosixRename(bool value)
  4098. {
  4099. SET_SESSION_PROPERTY(UsePosixRename);
  4100. }
  4101. //---------------------------------------------------------------------
  4102. void __fastcall TSessionData::SetSFTPBug(TSftpBug Bug, TAutoSwitch value)
  4103. {
  4104. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));
  4105. SET_SESSION_PROPERTY(SFTPBugs[Bug]);
  4106. }
  4107. //---------------------------------------------------------------------
  4108. TAutoSwitch __fastcall TSessionData::GetSFTPBug(TSftpBug Bug) const
  4109. {
  4110. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));
  4111. return FSFTPBugs[Bug];
  4112. }
  4113. //---------------------------------------------------------------------
  4114. void __fastcall TSessionData::SetSCPLsFullTime(TAutoSwitch value)
  4115. {
  4116. SET_SESSION_PROPERTY(SCPLsFullTime);
  4117. }
  4118. //---------------------------------------------------------------------------
  4119. void __fastcall TSessionData::SetColor(int value)
  4120. {
  4121. SET_SESSION_PROPERTY(Color);
  4122. }
  4123. //---------------------------------------------------------------------------
  4124. void __fastcall TSessionData::SetTunnel(bool value)
  4125. {
  4126. SET_SESSION_PROPERTY(Tunnel);
  4127. }
  4128. //---------------------------------------------------------------------
  4129. void __fastcall TSessionData::SetTunnelHostName(UnicodeString value)
  4130. {
  4131. if (FTunnelHostName != value)
  4132. {
  4133. // HostName is key for password encryption
  4134. UnicodeString XTunnelPassword = TunnelPassword;
  4135. int P = value.LastDelimiter(L"@");
  4136. if (P > 0)
  4137. {
  4138. TunnelUserName = value.SubString(1, P - 1);
  4139. value = value.SubString(P + 1, value.Length() - P);
  4140. }
  4141. FTunnelHostName = value;
  4142. Modify();
  4143. TunnelPassword = XTunnelPassword;
  4144. Shred(XTunnelPassword);
  4145. }
  4146. }
  4147. //---------------------------------------------------------------------
  4148. void __fastcall TSessionData::SetTunnelPortNumber(int value)
  4149. {
  4150. SET_SESSION_PROPERTY(TunnelPortNumber);
  4151. }
  4152. //---------------------------------------------------------------------
  4153. void __fastcall TSessionData::SetTunnelUserName(UnicodeString value)
  4154. {
  4155. // Avoid password recryption (what may popup master password prompt)
  4156. if (FTunnelUserName != value)
  4157. {
  4158. // TunnelUserName is key for password encryption
  4159. UnicodeString XTunnelPassword = TunnelPassword;
  4160. SET_SESSION_PROPERTY(TunnelUserName);
  4161. TunnelPassword = XTunnelPassword;
  4162. Shred(XTunnelPassword);
  4163. }
  4164. }
  4165. //---------------------------------------------------------------------
  4166. void __fastcall TSessionData::SetTunnelPassword(UnicodeString avalue)
  4167. {
  4168. RawByteString value = EncryptPassword(avalue, TunnelUserName+TunnelHostName);
  4169. SET_SESSION_PROPERTY(TunnelPassword);
  4170. }
  4171. //---------------------------------------------------------------------
  4172. UnicodeString __fastcall TSessionData::GetTunnelPassword() const
  4173. {
  4174. return DecryptPassword(FTunnelPassword, TunnelUserName+TunnelHostName);
  4175. }
  4176. //---------------------------------------------------------------------
  4177. void __fastcall TSessionData::SetTunnelPassphrase(UnicodeString avalue)
  4178. {
  4179. RawByteString value = EncryptPassword(avalue, TunnelPublicKeyFile);
  4180. SET_SESSION_PROPERTY(TunnelPassphrase);
  4181. }
  4182. //---------------------------------------------------------------------
  4183. UnicodeString __fastcall TSessionData::GetTunnelPassphrase() const
  4184. {
  4185. return DecryptPassword(FTunnelPassphrase, TunnelPublicKeyFile);
  4186. }
  4187. //---------------------------------------------------------------------
  4188. void __fastcall TSessionData::SetTunnelPublicKeyFile(UnicodeString value)
  4189. {
  4190. if (FTunnelPublicKeyFile != value)
  4191. {
  4192. // TunnelPublicKeyFile is key for TunnelPassphrase encryption
  4193. UnicodeString XTunnelPassphrase = TunnelPassphrase;
  4194. // StripPathQuotes should not be needed as we do not feed quotes anymore
  4195. FTunnelPublicKeyFile = StripPathQuotes(value);
  4196. Modify();
  4197. TunnelPassphrase = XTunnelPassphrase;
  4198. Shred(XTunnelPassphrase);
  4199. }
  4200. }
  4201. //---------------------------------------------------------------------
  4202. void __fastcall TSessionData::SetTunnelLocalPortNumber(int value)
  4203. {
  4204. SET_SESSION_PROPERTY(TunnelLocalPortNumber);
  4205. }
  4206. //---------------------------------------------------------------------
  4207. bool __fastcall TSessionData::GetTunnelAutoassignLocalPortNumber()
  4208. {
  4209. return (FTunnelLocalPortNumber <= 0);
  4210. }
  4211. //---------------------------------------------------------------------
  4212. void __fastcall TSessionData::SetTunnelPortFwd(UnicodeString value)
  4213. {
  4214. SET_SESSION_PROPERTY(TunnelPortFwd);
  4215. }
  4216. //---------------------------------------------------------------------
  4217. void __fastcall TSessionData::SetTunnelHostKey(UnicodeString value)
  4218. {
  4219. SET_SESSION_PROPERTY(TunnelHostKey);
  4220. }
  4221. //---------------------------------------------------------------------
  4222. void __fastcall TSessionData::SetFtpPasvMode(bool value)
  4223. {
  4224. SET_SESSION_PROPERTY(FtpPasvMode);
  4225. }
  4226. //---------------------------------------------------------------------
  4227. void __fastcall TSessionData::SetFtpForcePasvIp(TAutoSwitch value)
  4228. {
  4229. SET_SESSION_PROPERTY(FtpForcePasvIp);
  4230. }
  4231. //---------------------------------------------------------------------
  4232. void __fastcall TSessionData::SetFtpUseMlsd(TAutoSwitch value)
  4233. {
  4234. SET_SESSION_PROPERTY(FtpUseMlsd);
  4235. }
  4236. //---------------------------------------------------------------------
  4237. void __fastcall TSessionData::SetFtpAccount(UnicodeString value)
  4238. {
  4239. SET_SESSION_PROPERTY(FtpAccount);
  4240. }
  4241. //---------------------------------------------------------------------
  4242. void __fastcall TSessionData::SetFtpPingInterval(int value)
  4243. {
  4244. SET_SESSION_PROPERTY(FtpPingInterval);
  4245. }
  4246. //---------------------------------------------------------------------------
  4247. TDateTime __fastcall TSessionData::GetFtpPingIntervalDT()
  4248. {
  4249. return SecToDateTime(FtpPingInterval);
  4250. }
  4251. //---------------------------------------------------------------------------
  4252. void __fastcall TSessionData::SetFtpPingType(TFtpPingType value)
  4253. {
  4254. SET_SESSION_PROPERTY(FtpPingType);
  4255. }
  4256. //---------------------------------------------------------------------------
  4257. void __fastcall TSessionData::SetFtpTransferActiveImmediately(TAutoSwitch value)
  4258. {
  4259. SET_SESSION_PROPERTY(FtpTransferActiveImmediately);
  4260. }
  4261. //---------------------------------------------------------------------------
  4262. void __fastcall TSessionData::SetFtps(TFtps value)
  4263. {
  4264. SET_SESSION_PROPERTY(Ftps);
  4265. }
  4266. //---------------------------------------------------------------------------
  4267. void __fastcall TSessionData::SetMinTlsVersion(TTlsVersion value)
  4268. {
  4269. SET_SESSION_PROPERTY(MinTlsVersion);
  4270. }
  4271. //---------------------------------------------------------------------------
  4272. void __fastcall TSessionData::SetMaxTlsVersion(TTlsVersion value)
  4273. {
  4274. SET_SESSION_PROPERTY(MaxTlsVersion);
  4275. }
  4276. //---------------------------------------------------------------------------
  4277. void __fastcall TSessionData::SetLogicalHostName(UnicodeString value)
  4278. {
  4279. SET_SESSION_PROPERTY(LogicalHostName);
  4280. }
  4281. //---------------------------------------------------------------------------
  4282. void TSessionData::SetCompleteTlsShutdown(TAutoSwitch value)
  4283. {
  4284. SET_SESSION_PROPERTY(CompleteTlsShutdown);
  4285. }
  4286. //---------------------------------------------------------------------
  4287. void __fastcall TSessionData::SetFtpListAll(TAutoSwitch value)
  4288. {
  4289. SET_SESSION_PROPERTY(FtpListAll);
  4290. }
  4291. //---------------------------------------------------------------------
  4292. void __fastcall TSessionData::SetFtpHost(TAutoSwitch value)
  4293. {
  4294. SET_SESSION_PROPERTY(FtpHost);
  4295. }
  4296. //---------------------------------------------------------------------
  4297. void __fastcall TSessionData::SetFtpWorkFromCwd(TAutoSwitch value)
  4298. {
  4299. SET_SESSION_PROPERTY(FtpWorkFromCwd);
  4300. }
  4301. //---------------------------------------------------------------------
  4302. void TSessionData::SetFtpAnyCodeForPwd(bool value)
  4303. {
  4304. SET_SESSION_PROPERTY(FtpAnyCodeForPwd);
  4305. }
  4306. //---------------------------------------------------------------------
  4307. void __fastcall TSessionData::SetSslSessionReuse(bool value)
  4308. {
  4309. SET_SESSION_PROPERTY(SslSessionReuse);
  4310. }
  4311. //---------------------------------------------------------------------
  4312. void __fastcall TSessionData::SetTlsCertificateFile(UnicodeString value)
  4313. {
  4314. SET_SESSION_PROPERTY(TlsCertificateFile);
  4315. }
  4316. //---------------------------------------------------------------------
  4317. void __fastcall TSessionData::SetNotUtf(TAutoSwitch value)
  4318. {
  4319. SET_SESSION_PROPERTY(NotUtf);
  4320. }
  4321. //---------------------------------------------------------------------
  4322. void __fastcall TSessionData::SetInternalEditorEncoding(int value)
  4323. {
  4324. SET_SESSION_PROPERTY(InternalEditorEncoding);
  4325. }
  4326. //---------------------------------------------------------------------
  4327. void __fastcall TSessionData::SetS3DefaultRegion(UnicodeString value)
  4328. {
  4329. SET_SESSION_PROPERTY(S3DefaultRegion);
  4330. }
  4331. //---------------------------------------------------------------------
  4332. void __fastcall TSessionData::SetS3SessionToken(UnicodeString value)
  4333. {
  4334. SET_SESSION_PROPERTY(S3SessionToken);
  4335. }
  4336. //---------------------------------------------------------------------
  4337. void __fastcall TSessionData::SetS3RoleArn(UnicodeString value)
  4338. {
  4339. SET_SESSION_PROPERTY(S3RoleArn);
  4340. }
  4341. //---------------------------------------------------------------------
  4342. void __fastcall TSessionData::SetS3RoleSessionName(UnicodeString value)
  4343. {
  4344. SET_SESSION_PROPERTY(S3RoleSessionName);
  4345. }
  4346. //---------------------------------------------------------------------
  4347. void __fastcall TSessionData::SetS3Profile(UnicodeString value)
  4348. {
  4349. SET_SESSION_PROPERTY(S3Profile);
  4350. }
  4351. //---------------------------------------------------------------------
  4352. void __fastcall TSessionData::SetS3UrlStyle(TS3UrlStyle value)
  4353. {
  4354. SET_SESSION_PROPERTY(S3UrlStyle);
  4355. }
  4356. //---------------------------------------------------------------------
  4357. void __fastcall TSessionData::SetS3MaxKeys(TAutoSwitch value)
  4358. {
  4359. SET_SESSION_PROPERTY(S3MaxKeys);
  4360. }
  4361. //---------------------------------------------------------------------
  4362. void __fastcall TSessionData::SetS3CredentialsEnv(bool value)
  4363. {
  4364. SET_SESSION_PROPERTY(S3CredentialsEnv);
  4365. }
  4366. //---------------------------------------------------------------------
  4367. void __fastcall TSessionData::SetS3RequesterPays(bool value)
  4368. {
  4369. SET_SESSION_PROPERTY(S3RequesterPays);
  4370. }
  4371. //---------------------------------------------------------------------
  4372. void __fastcall TSessionData::SetIsWorkspace(bool value)
  4373. {
  4374. SET_SESSION_PROPERTY(IsWorkspace);
  4375. }
  4376. //---------------------------------------------------------------------
  4377. void __fastcall TSessionData::SetLink(UnicodeString value)
  4378. {
  4379. SET_SESSION_PROPERTY(Link);
  4380. }
  4381. //---------------------------------------------------------------------
  4382. void __fastcall TSessionData::SetNameOverride(UnicodeString value)
  4383. {
  4384. SET_SESSION_PROPERTY(NameOverride);
  4385. }
  4386. //---------------------------------------------------------------------
  4387. void __fastcall TSessionData::SetHostKey(UnicodeString value)
  4388. {
  4389. SET_SESSION_PROPERTY(HostKey);
  4390. }
  4391. //---------------------------------------------------------------------
  4392. void __fastcall TSessionData::SetNote(UnicodeString value)
  4393. {
  4394. SET_SESSION_PROPERTY(Note);
  4395. }
  4396. //---------------------------------------------------------------------
  4397. void __fastcall TSessionData::SetWinTitle(UnicodeString value)
  4398. {
  4399. SET_SESSION_PROPERTY(WinTitle);
  4400. }
  4401. //---------------------------------------------------------------------
  4402. UnicodeString __fastcall TSessionData::GetEncryptKey() const
  4403. {
  4404. return DecryptPassword(FEncryptKey, GetSessionPasswordEncryptionKey());
  4405. }
  4406. //---------------------------------------------------------------------
  4407. void __fastcall TSessionData::SetEncryptKey(UnicodeString avalue)
  4408. {
  4409. RawByteString value = EncryptPassword(avalue, GetSessionPasswordEncryptionKey());
  4410. SET_SESSION_PROPERTY(EncryptKey);
  4411. }
  4412. //---------------------------------------------------------------------
  4413. void __fastcall TSessionData::SetWebDavLiberalEscaping(bool value)
  4414. {
  4415. SET_SESSION_PROPERTY(WebDavLiberalEscaping);
  4416. }
  4417. //---------------------------------------------------------------------
  4418. void __fastcall TSessionData::SetWebDavAuthLegacy(bool value)
  4419. {
  4420. SET_SESSION_PROPERTY(WebDavAuthLegacy);
  4421. }
  4422. //---------------------------------------------------------------------
  4423. UnicodeString __fastcall TSessionData::GetInfoTip()
  4424. {
  4425. if (UsesSsh)
  4426. {
  4427. return FMTLOAD(SESSION_INFO_TIP2,
  4428. (HostName, UserName,
  4429. (PublicKeyFile.IsEmpty() ? LoadStr(NO_STR) : LoadStr(YES_STR)),
  4430. FSProtocolStr));
  4431. }
  4432. else
  4433. {
  4434. return FMTLOAD(SESSION_INFO_TIP_NO_SSH,
  4435. (HostName, UserName, FSProtocolStr));
  4436. }
  4437. }
  4438. //---------------------------------------------------------------------
  4439. UnicodeString __fastcall TSessionData::ExtractLocalName(const UnicodeString & Name)
  4440. {
  4441. UnicodeString Result = Name;
  4442. int P = Result.LastDelimiter(L"/");
  4443. if (P > 0)
  4444. {
  4445. Result.Delete(1, P);
  4446. }
  4447. return Result;
  4448. }
  4449. //---------------------------------------------------------------------
  4450. UnicodeString __fastcall TSessionData::GetLocalName()
  4451. {
  4452. UnicodeString Result;
  4453. if (HasSessionName())
  4454. {
  4455. Result = ExtractLocalName(Name);
  4456. }
  4457. else
  4458. {
  4459. Result = DefaultSessionName;
  4460. }
  4461. return Result;
  4462. }
  4463. //---------------------------------------------------------------------
  4464. UnicodeString __fastcall TSessionData::ExtractFolderName(const UnicodeString & Name)
  4465. {
  4466. UnicodeString Result;
  4467. int P = Name.LastDelimiter(L"/");
  4468. if (P > 0)
  4469. {
  4470. Result = Name.SubString(1, P - 1);
  4471. }
  4472. return Result;
  4473. }
  4474. //---------------------------------------------------------------------
  4475. UnicodeString __fastcall TSessionData::GetFolderName()
  4476. {
  4477. UnicodeString Result;
  4478. if (HasSessionName() || IsWorkspace)
  4479. {
  4480. Result = ExtractFolderName(Name);
  4481. }
  4482. return Result;
  4483. }
  4484. //---------------------------------------------------------------------
  4485. UnicodeString __fastcall TSessionData::ComposePath(
  4486. const UnicodeString & Path, const UnicodeString & Name)
  4487. {
  4488. return UnixIncludeTrailingBackslash(Path) + Name;
  4489. }
  4490. //---------------------------------------------------------------------
  4491. void __fastcall TSessionData::DisableAuthentationsExceptPassword()
  4492. {
  4493. SshNoUserAuth = false;
  4494. AuthKI = false;
  4495. AuthKIPassword = false;
  4496. AuthGSSAPI = false;
  4497. AuthGSSAPIKEX = false;
  4498. PublicKeyFile = EmptyStr;
  4499. DetachedCertificate = EmptyStr;
  4500. TlsCertificateFile = EmptyStr;
  4501. Passphrase = EmptyStr;
  4502. TryAgent = false;
  4503. }
  4504. //---------------------------------------------------------------------
  4505. TStrings * TSessionData::GetAllOptionNames(bool PuttyExport)
  4506. {
  4507. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  4508. return FactoryDefaults->SaveToOptions(NULL, false, PuttyExport);
  4509. }
  4510. //---------------------------------------------------------------------
  4511. bool TSessionData::HasS3AutoCredentials()
  4512. {
  4513. return (FSProtocol == fsS3) && S3CredentialsEnv;
  4514. }
  4515. //---------------------------------------------------------------------
  4516. bool TSessionData::HasAutoCredentials()
  4517. {
  4518. return HasS3AutoCredentials();
  4519. }
  4520. //=== TStoredSessionList ----------------------------------------------
  4521. __fastcall TStoredSessionList::TStoredSessionList(bool aReadOnly):
  4522. TNamedObjectList(), FReadOnly(aReadOnly)
  4523. {
  4524. DebugAssert(Configuration);
  4525. FDefaultSettings = new TSessionData(DefaultName);
  4526. FPendingRemovals.reset(new TStringList());
  4527. }
  4528. //---------------------------------------------------------------------
  4529. __fastcall TStoredSessionList::~TStoredSessionList()
  4530. {
  4531. DebugAssert(Configuration);
  4532. delete FDefaultSettings;
  4533. }
  4534. //---------------------------------------------------------------------
  4535. void __fastcall TStoredSessionList::Load(THierarchicalStorage * Storage,
  4536. bool AsModified, bool UseDefaults, bool PuttyImport)
  4537. {
  4538. TStringList *SubKeys = new TStringList();
  4539. TList * Loaded = new TList;
  4540. try
  4541. {
  4542. DebugAssert(AutoSort);
  4543. AutoSort = false;
  4544. bool WasEmpty = (Count == 0);
  4545. Storage->GetSubKeyNames(SubKeys);
  4546. for (int Index = 0; Index < SubKeys->Count; Index++)
  4547. {
  4548. UnicodeString SessionName = SubKeys->Strings[Index];
  4549. bool ValidName = true;
  4550. try
  4551. {
  4552. TSessionData::ValidatePath(SessionName);
  4553. }
  4554. catch(...)
  4555. {
  4556. ValidName = false;
  4557. }
  4558. if (ValidName)
  4559. {
  4560. TSessionData * SessionData;
  4561. if (SessionName == FDefaultSettings->Name)
  4562. {
  4563. SessionData = FDefaultSettings;
  4564. }
  4565. else
  4566. {
  4567. // if the list was empty before loading, do not waste time trying to
  4568. // find existing sites to overwrite (we rely on underlying storage
  4569. // to secure uniqueness of the key names)
  4570. if (WasEmpty)
  4571. {
  4572. SessionData = NULL;
  4573. }
  4574. else
  4575. {
  4576. SessionData = (TSessionData*)FindByName(SessionName);
  4577. }
  4578. }
  4579. if ((SessionData != FDefaultSettings) || !UseDefaults)
  4580. {
  4581. if (SessionData == NULL)
  4582. {
  4583. SessionData = new TSessionData(L"");
  4584. if (UseDefaults)
  4585. {
  4586. SessionData->CopyData(DefaultSettings);
  4587. }
  4588. SessionData->Name = SessionName;
  4589. Add(SessionData);
  4590. }
  4591. Loaded->Add(SessionData);
  4592. SessionData->Load(Storage, PuttyImport);
  4593. if (AsModified)
  4594. {
  4595. SessionData->Modified = true;
  4596. }
  4597. }
  4598. }
  4599. }
  4600. if (!AsModified)
  4601. {
  4602. for (int Index = 0; Index < TObjectList::Count; Index++)
  4603. {
  4604. if (Loaded->IndexOf(Items[Index]) < 0)
  4605. {
  4606. Delete(Index);
  4607. Index--;
  4608. }
  4609. }
  4610. }
  4611. }
  4612. __finally
  4613. {
  4614. AutoSort = true;
  4615. AlphaSort();
  4616. delete SubKeys;
  4617. delete Loaded;
  4618. }
  4619. }
  4620. //---------------------------------------------------------------------
  4621. void __fastcall TStoredSessionList::Reload()
  4622. {
  4623. if (Count <= Configuration->DontReloadMoreThanSessions)
  4624. {
  4625. bool SessionList = true;
  4626. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));
  4627. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, False))
  4628. {
  4629. Load(Storage.get());
  4630. }
  4631. }
  4632. }
  4633. //---------------------------------------------------------------------
  4634. void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,
  4635. TSessionData * Data, bool All, bool RecryptPasswordOnly,
  4636. TSessionData * FactoryDefaults)
  4637. {
  4638. if (All || Data->Modified)
  4639. {
  4640. if (RecryptPasswordOnly)
  4641. {
  4642. Data->SaveRecryptedPasswords(Storage);
  4643. }
  4644. else
  4645. {
  4646. Data->Save(Storage, false, FactoryDefaults);
  4647. }
  4648. }
  4649. }
  4650. //---------------------------------------------------------------------
  4651. void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,
  4652. bool All, bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)
  4653. {
  4654. TSessionData * FactoryDefaults = new TSessionData(L"");
  4655. try
  4656. {
  4657. while (FPendingRemovals->Count > 0)
  4658. {
  4659. TSessionData::Remove(Storage, FPendingRemovals->Strings[0]);
  4660. FPendingRemovals->Delete(0);
  4661. }
  4662. DoSave(Storage, FDefaultSettings, All, RecryptPasswordOnly, FactoryDefaults);
  4663. for (int Index = 0; Index < CountIncludingHidden; Index++)
  4664. {
  4665. TSessionData * SessionData = (TSessionData *)Items[Index];
  4666. try
  4667. {
  4668. DoSave(Storage, SessionData, All, RecryptPasswordOnly, FactoryDefaults);
  4669. }
  4670. catch (Exception & E)
  4671. {
  4672. UnicodeString Message;
  4673. if (RecryptPasswordOnly && DebugAlwaysTrue(RecryptPasswordErrors != NULL) &&
  4674. ExceptionMessage(&E, Message))
  4675. {
  4676. RecryptPasswordErrors->Add(FORMAT("%s: %s", (SessionData->SessionName, Message)));
  4677. }
  4678. else
  4679. {
  4680. throw;
  4681. }
  4682. }
  4683. }
  4684. }
  4685. __finally
  4686. {
  4687. delete FactoryDefaults;
  4688. }
  4689. }
  4690. //---------------------------------------------------------------------
  4691. void __fastcall TStoredSessionList::Save(THierarchicalStorage * Storage, bool All)
  4692. {
  4693. DoSave(Storage, All, false, NULL);
  4694. }
  4695. //---------------------------------------------------------------------
  4696. void __fastcall TStoredSessionList::DoSave(bool All, bool Explicit,
  4697. bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)
  4698. {
  4699. bool SessionList = true;
  4700. THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);
  4701. try
  4702. {
  4703. Storage->AccessMode = smReadWrite;
  4704. Storage->Explicit = Explicit;
  4705. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))
  4706. {
  4707. DoSave(Storage, All, RecryptPasswordOnly, RecryptPasswordErrors);
  4708. }
  4709. }
  4710. __finally
  4711. {
  4712. delete Storage;
  4713. }
  4714. Saved();
  4715. }
  4716. //---------------------------------------------------------------------
  4717. void __fastcall TStoredSessionList::Save(bool All, bool Explicit)
  4718. {
  4719. DoSave(All, Explicit, false, NULL);
  4720. }
  4721. //---------------------------------------------------------------------
  4722. void __fastcall TStoredSessionList::RecryptPasswords(TStrings * RecryptPasswordErrors)
  4723. {
  4724. DoSave(true, true, true, RecryptPasswordErrors);
  4725. }
  4726. //---------------------------------------------------------------------
  4727. void __fastcall TStoredSessionList::Saved()
  4728. {
  4729. FDefaultSettings->Modified = false;
  4730. for (int Index = 0; Index < CountIncludingHidden; Index++)
  4731. {
  4732. ((TSessionData *)Items[Index])->Modified = false;
  4733. }
  4734. }
  4735. //---------------------------------------------------------------------
  4736. void __fastcall TStoredSessionList::ImportLevelFromFilezilla(
  4737. _di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode)
  4738. {
  4739. for (int Index = 0; Index < Node->ChildNodes->Count; Index++)
  4740. {
  4741. _di_IXMLNode ChildNode = Node->ChildNodes->Get(Index);
  4742. if (ChildNode->NodeName == L"Server")
  4743. {
  4744. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  4745. SessionData->CopyData(DefaultSettings);
  4746. SessionData->ImportFromFilezilla(ChildNode, Path, SettingsNode);
  4747. Add(SessionData.release());
  4748. }
  4749. else if (ChildNode->NodeName == L"Folder")
  4750. {
  4751. UnicodeString Name;
  4752. for (int Index = 0; Index < ChildNode->ChildNodes->Count; Index++)
  4753. {
  4754. _di_IXMLNode PossibleTextMode = ChildNode->ChildNodes->Get(Index);
  4755. if (PossibleTextMode->NodeType == ntText)
  4756. {
  4757. UnicodeString NodeValue = PossibleTextMode->NodeValue;
  4758. AddToList(Name, NodeValue.Trim(), L" ");
  4759. }
  4760. }
  4761. Name = TSessionData::MakeValidName(Name).Trim();
  4762. ImportLevelFromFilezilla(ChildNode, TSessionData::ComposePath(Path, Name), SettingsNode);
  4763. }
  4764. }
  4765. }
  4766. //---------------------------------------------------------------------
  4767. void __fastcall TStoredSessionList::ImportFromFilezilla(
  4768. const UnicodeString FileName, const UnicodeString ConfigurationFileName)
  4769. {
  4770. // not sure if the document must exists if we want to use its node
  4771. _di_IXMLDocument ConfigurationDocument;
  4772. _di_IXMLNode SettingsNode;
  4773. if (FileExists(ApiPath(ConfigurationFileName)))
  4774. {
  4775. ConfigurationDocument = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));
  4776. ConfigurationDocument->LoadFromFile(ConfigurationFileName);
  4777. _di_IXMLNode FileZilla3Node = ConfigurationDocument->ChildNodes->FindNode(L"FileZilla3");
  4778. if (FileZilla3Node != NULL)
  4779. {
  4780. SettingsNode = FileZilla3Node->ChildNodes->FindNode(L"Settings");
  4781. }
  4782. }
  4783. const _di_IXMLDocument Document = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));
  4784. Document->LoadFromFile(FileName);
  4785. _di_IXMLNode FileZilla3Node = Document->ChildNodes->FindNode(L"FileZilla3");
  4786. if (FileZilla3Node != NULL)
  4787. {
  4788. _di_IXMLNode ServersNode = FileZilla3Node->ChildNodes->FindNode(L"Servers");
  4789. if (ServersNode != NULL)
  4790. {
  4791. ImportLevelFromFilezilla(ServersNode, L"", SettingsNode);
  4792. }
  4793. }
  4794. }
  4795. //---------------------------------------------------------------------
  4796. UnicodeString FormatKnownHostName(const UnicodeString & HostName, int PortNumber)
  4797. {
  4798. return FORMAT(L"%s:%d", (HostName, PortNumber));
  4799. }
  4800. //---------------------------------------------------------------------
  4801. void __fastcall TStoredSessionList::ImportFromKnownHosts(TStrings * Lines)
  4802. {
  4803. bool SessionList = false;
  4804. std::unique_ptr<THierarchicalStorage> HostKeyStorage(Configuration->CreateScpStorage(SessionList));
  4805. std::unique_ptr<TStrings> KeyList(new TStringList());
  4806. if (OpenHostKeysSubKey(HostKeyStorage.get(), false))
  4807. {
  4808. HostKeyStorage->GetValueNames(KeyList.get());
  4809. }
  4810. HostKeyStorage.reset(NULL);
  4811. UnicodeString FirstError;
  4812. for (int Index = 0; Index < Lines->Count; Index++)
  4813. {
  4814. try
  4815. {
  4816. UnicodeString Line = Lines->Strings[Index];
  4817. Line = Trim(Line);
  4818. if (IsValidOpensshLine(Line))
  4819. {
  4820. int P = Pos(L' ', Line);
  4821. if (P > 0)
  4822. {
  4823. UnicodeString HostNameStr = Line.SubString(1, P - 1);
  4824. Line = Line.SubString(P + 1, Line.Length() - P);
  4825. P = Pos(L',', HostNameStr);
  4826. if (P > 0)
  4827. {
  4828. HostNameStr.SetLength(P - 1);
  4829. }
  4830. P = Pos(L':', HostNameStr);
  4831. int PortNumber = -1;
  4832. if (P > 0)
  4833. {
  4834. UnicodeString PortNumberStr = HostNameStr.SubString(P + 1, HostNameStr.Length() - P);
  4835. PortNumber = StrToInt(PortNumberStr);
  4836. HostNameStr.SetLength(P - 1);
  4837. }
  4838. if (HasIP6LiteralBrackets(HostNameStr))
  4839. {
  4840. HostNameStr = StripIP6LiteralBrackets(HostNameStr);
  4841. }
  4842. UnicodeString NameStr = HostNameStr;
  4843. if (PortNumber >= 0)
  4844. {
  4845. NameStr = FormatKnownHostName(NameStr, PortNumber);
  4846. }
  4847. std::unique_ptr<TSessionData> SessionDataOwner;
  4848. TSessionData * SessionData = dynamic_cast<TSessionData *>(FindByName(NameStr));
  4849. if (SessionData == NULL)
  4850. {
  4851. SessionData = new TSessionData(L"");
  4852. SessionDataOwner.reset(SessionData);
  4853. SessionData->CopyData(DefaultSettings);
  4854. SessionData->Name = NameStr;
  4855. SessionData->HostName = HostNameStr;
  4856. if (PortNumber >= 0)
  4857. {
  4858. SessionData->PortNumber = PortNumber;
  4859. }
  4860. }
  4861. const struct ssh_keyalg * Algorithm;
  4862. UnicodeString Key = ParseOpenSshPubLine(Line, Algorithm);
  4863. UnicodeString KeyKey =
  4864. FORMAT(L"%s@%d:%s", (Algorithm->cache_id, SessionData->PortNumber, HostNameStr));
  4865. UnicodeString HostKey =
  4866. FORMAT(L"%s:%s=%s", (Algorithm->ssh_id, KeyKey, Key));
  4867. UnicodeString HostKeyList = SessionData->HostKey;
  4868. AddToList(HostKeyList, HostKey, L";");
  4869. SessionData->HostKey = HostKeyList;
  4870. // If there's at least one unknown key type for this host, select it
  4871. if (KeyList->IndexOf(KeyKey) < 0)
  4872. {
  4873. SessionData->Selected = true;
  4874. }
  4875. if (SessionDataOwner.get() != NULL)
  4876. {
  4877. Add(SessionDataOwner.release());
  4878. }
  4879. }
  4880. }
  4881. }
  4882. catch (Exception & E)
  4883. {
  4884. if (FirstError.IsEmpty())
  4885. {
  4886. FirstError = E.Message;
  4887. }
  4888. }
  4889. }
  4890. if (Count == 0)
  4891. {
  4892. UnicodeString Message = LoadStr(KNOWN_HOSTS_NO_SITES);
  4893. if (!FirstError.IsEmpty())
  4894. {
  4895. Message = FORMAT(L"%s\n(%s)", (Message, FirstError));
  4896. }
  4897. throw Exception(Message);
  4898. }
  4899. }
  4900. //---------------------------------------------------------------------
  4901. void TStoredSessionList::ImportFromOpenssh(TStrings * Lines)
  4902. {
  4903. std::unique_ptr<TStrings> Hosts(CreateSortedStringList());
  4904. for (int Index = 0; Index < Lines->Count; Index++)
  4905. {
  4906. UnicodeString Line = Lines->Strings[Index];
  4907. UnicodeString Directive, Value;
  4908. if (ParseOpensshDirective(Line, Directive, Value))
  4909. {
  4910. if (SameText(Directive, OpensshHostDirective))
  4911. {
  4912. while (!Value.IsEmpty())
  4913. {
  4914. UnicodeString Name = CutOpensshToken(Value);
  4915. if ((Hosts->IndexOf(Name) < 0) && (Name.LastDelimiter(L"*?") == 0))
  4916. {
  4917. std::unique_ptr<TSessionData> Data(new TSessionData(EmptyStr));
  4918. Data->CopyData(DefaultSettings);
  4919. Data->Name = Name;
  4920. Data->HostName = Name;
  4921. Data->ImportFromOpenssh(Lines);
  4922. Add(Data.release());
  4923. Hosts->Add(Name);
  4924. }
  4925. }
  4926. }
  4927. }
  4928. }
  4929. }
  4930. //---------------------------------------------------------------------
  4931. void __fastcall TStoredSessionList::Export(const UnicodeString FileName)
  4932. {
  4933. THierarchicalStorage * Storage = TIniFileStorage::CreateFromPath(FileName);
  4934. try
  4935. {
  4936. Storage->AccessMode = smReadWrite;
  4937. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))
  4938. {
  4939. Save(Storage, true);
  4940. }
  4941. }
  4942. __finally
  4943. {
  4944. delete Storage;
  4945. }
  4946. }
  4947. //---------------------------------------------------------------------
  4948. void __fastcall TStoredSessionList::SelectAll(bool Select)
  4949. {
  4950. for (int Index = 0; Index < Count; Index++)
  4951. Sessions[Index]->Selected = Select;
  4952. }
  4953. //---------------------------------------------------------------------
  4954. bool TStoredSessionList::Import(TStoredSessionList * From,
  4955. bool OnlySelected, TList * Imported)
  4956. {
  4957. bool Result = false;
  4958. for (int Index = 0; Index < From->Count; Index++)
  4959. {
  4960. if (!OnlySelected || From->Sessions[Index]->Selected)
  4961. {
  4962. TSessionData *Session = new TSessionData(L"");
  4963. Session->Assign(From->Sessions[Index]);
  4964. Session->Modified = true;
  4965. Session->MakeUniqueIn(this);
  4966. Add(Session);
  4967. Result = true;
  4968. if (Imported != NULL)
  4969. {
  4970. Imported->Add(Session);
  4971. }
  4972. }
  4973. }
  4974. // only modified, explicit
  4975. Save(false, true);
  4976. return Result;
  4977. }
  4978. //---------------------------------------------------------------------
  4979. void __fastcall TStoredSessionList::SelectSessionsToImport
  4980. (TStoredSessionList * Dest, bool SSHOnly)
  4981. {
  4982. for (int Index = 0; Index < Count; Index++)
  4983. {
  4984. Sessions[Index]->Selected =
  4985. (!SSHOnly || (Sessions[Index]->GetNormalizedPuttyProtocol() == PuttySshProtocol)) &&
  4986. !Dest->FindByName(Sessions[Index]->Name);
  4987. }
  4988. }
  4989. //---------------------------------------------------------------------
  4990. void __fastcall TStoredSessionList::Cleanup()
  4991. {
  4992. try
  4993. {
  4994. if (Configuration->Storage == stRegistry) Clear();
  4995. TRegistryStorage * Storage = new TRegistryStorage(Configuration->RegistryStorageKey);
  4996. try
  4997. {
  4998. Storage->AccessMode = smReadWrite;
  4999. if (Storage->OpenRootKey(False))
  5000. Storage->RecursiveDeleteSubKey(Configuration->StoredSessionsSubKey);
  5001. }
  5002. __finally
  5003. {
  5004. delete Storage;
  5005. }
  5006. }
  5007. catch (Exception &E)
  5008. {
  5009. throw ExtException(&E, LoadStr(CLEANUP_SESSIONS_ERROR));
  5010. }
  5011. }
  5012. //---------------------------------------------------------------------------
  5013. void __fastcall TStoredSessionList::UpdateStaticUsage()
  5014. {
  5015. int SCP = 0;
  5016. int SFTP = 0;
  5017. int FTP = 0;
  5018. int FTPS = 0;
  5019. int WebDAV = 0;
  5020. int WebDAVS = 0;
  5021. int S3 = 0;
  5022. int Password = 0;
  5023. int Advanced = 0;
  5024. int Color = 0;
  5025. int Note = 0;
  5026. int Tunnel = 0;
  5027. bool Folders = false;
  5028. bool Workspaces = false;
  5029. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  5030. std::unique_ptr<TStringList> DifferentAdvancedProperties(CreateSortedStringList());
  5031. for (int Index = 0; Index < Count; Index++)
  5032. {
  5033. TSessionData * Data = Sessions[Index];
  5034. if (Data->IsWorkspace)
  5035. {
  5036. Workspaces = true;
  5037. }
  5038. else
  5039. {
  5040. switch (Data->FSProtocol)
  5041. {
  5042. case fsSCPonly:
  5043. SCP++;
  5044. break;
  5045. case fsSFTP:
  5046. case fsSFTPonly:
  5047. SFTP++;
  5048. break;
  5049. case fsFTP:
  5050. if (Data->Ftps == ftpsNone)
  5051. {
  5052. FTP++;
  5053. }
  5054. else
  5055. {
  5056. FTPS++;
  5057. }
  5058. break;
  5059. case fsWebDAV:
  5060. if (Data->Ftps == ftpsNone)
  5061. {
  5062. WebDAV++;
  5063. }
  5064. else
  5065. {
  5066. WebDAVS++;
  5067. }
  5068. break;
  5069. case fsS3:
  5070. S3++;
  5071. break;
  5072. }
  5073. if (Data->HasAnySessionPassword())
  5074. {
  5075. Password++;
  5076. }
  5077. if (Data->Color != 0)
  5078. {
  5079. Color++;
  5080. }
  5081. if (!Data->Note.IsEmpty())
  5082. {
  5083. Note++;
  5084. }
  5085. // This would not work for passwords, as they are compared in their encrypted form.
  5086. // But there are no passwords set in factory defaults anyway.
  5087. if (!Data->IsSame(FactoryDefaults.get(), true, DifferentAdvancedProperties.get(), false))
  5088. {
  5089. Advanced++;
  5090. }
  5091. if (Data->Tunnel)
  5092. {
  5093. Tunnel++;
  5094. }
  5095. if (!Data->FolderName.IsEmpty())
  5096. {
  5097. Folders = true;
  5098. }
  5099. }
  5100. }
  5101. Configuration->Usage->Set(L"StoredSessionsCountSCP", SCP);
  5102. Configuration->Usage->Set(L"StoredSessionsCountSFTP", SFTP);
  5103. Configuration->Usage->Set(L"StoredSessionsCountFTP", FTP);
  5104. Configuration->Usage->Set(L"StoredSessionsCountFTPS", FTPS);
  5105. Configuration->Usage->Set(L"StoredSessionsCountWebDAV", WebDAV);
  5106. Configuration->Usage->Set(L"StoredSessionsCountWebDAVS", WebDAVS);
  5107. Configuration->Usage->Set(L"StoredSessionsCountS3", S3);
  5108. Configuration->Usage->Set(L"StoredSessionsCountPassword", Password);
  5109. Configuration->Usage->Set(L"StoredSessionsCountColor", Color);
  5110. Configuration->Usage->Set(L"StoredSessionsCountNote", Note);
  5111. Configuration->Usage->Set(L"StoredSessionsCountAdvanced", Advanced);
  5112. DifferentAdvancedProperties->Delimiter = L',';
  5113. Configuration->Usage->Set(L"StoredSessionsAdvancedSettings", DifferentAdvancedProperties->DelimitedText);
  5114. Configuration->Usage->Set(L"StoredSessionsCountTunnel", Tunnel);
  5115. // actually default might be true, see below for when the default is actually used
  5116. bool CustomDefaultStoredSession = false;
  5117. try
  5118. {
  5119. // this can throw, when the default session settings have password set
  5120. // (and no other basic property, like hostname/username),
  5121. // and master password is enabled as we are called before master password
  5122. // handler is set
  5123. CustomDefaultStoredSession = !FDefaultSettings->IsSame(FactoryDefaults.get(), false);
  5124. }
  5125. catch (...)
  5126. {
  5127. }
  5128. Configuration->Usage->Set(L"UsingDefaultStoredSession", CustomDefaultStoredSession);
  5129. Configuration->Usage->Set(L"UsingStoredSessionsFolders", Folders);
  5130. Configuration->Usage->Set(L"UsingWorkspaces", Workspaces);
  5131. }
  5132. //---------------------------------------------------------------------------
  5133. TSessionData * __fastcall TStoredSessionList::FindSame(TSessionData * Data)
  5134. {
  5135. TSessionData * Result;
  5136. if (Data->Hidden || Data->Name.IsEmpty() || Data->IsWorkspace)
  5137. {
  5138. Result = NULL;
  5139. }
  5140. else
  5141. {
  5142. Result = dynamic_cast<TSessionData *>(FindByName(Data->Name));
  5143. }
  5144. return Result;
  5145. }
  5146. //---------------------------------------------------------------------------
  5147. int __fastcall TStoredSessionList::IndexOf(TSessionData * Data)
  5148. {
  5149. for (int Index = 0; Index < Count; Index++)
  5150. if (Data == Sessions[Index]) return Index;
  5151. return -1;
  5152. }
  5153. //---------------------------------------------------------------------------
  5154. TSessionData * __fastcall TStoredSessionList::NewSession(
  5155. UnicodeString SessionName, TSessionData * Session)
  5156. {
  5157. TSessionData * DuplicateSession = (TSessionData*)FindByName(SessionName);
  5158. if (!DuplicateSession)
  5159. {
  5160. DuplicateSession = new TSessionData(L"");
  5161. DuplicateSession->Assign(Session);
  5162. DuplicateSession->Name = SessionName;
  5163. // make sure, that new stored session is saved to registry
  5164. DuplicateSession->Modified = true;
  5165. Add(DuplicateSession);
  5166. }
  5167. else
  5168. {
  5169. DuplicateSession->Assign(Session);
  5170. DuplicateSession->Name = SessionName;
  5171. DuplicateSession->Modified = true;
  5172. }
  5173. // list was saved here before to default storage, but it would not allow
  5174. // to work with special lists (export/import) not using default storage
  5175. return DuplicateSession;
  5176. }
  5177. //---------------------------------------------------------------------------
  5178. void __fastcall TStoredSessionList::SetDefaultSettings(TSessionData * value)
  5179. {
  5180. DebugAssert(FDefaultSettings);
  5181. if (FDefaultSettings != value)
  5182. {
  5183. FDefaultSettings->Assign(value);
  5184. // make sure default settings are saved
  5185. FDefaultSettings->Modified = true;
  5186. FDefaultSettings->Name = DefaultName;
  5187. if (!FReadOnly)
  5188. {
  5189. // only modified, explicit
  5190. Save(false, true);
  5191. }
  5192. }
  5193. }
  5194. //---------------------------------------------------------------------------
  5195. bool __fastcall TStoredSessionList::OpenHostKeysSubKey(THierarchicalStorage * Storage, bool CanCreate)
  5196. {
  5197. return Storage->OpenSubKey(Configuration->SshHostKeysSubKey, CanCreate);
  5198. }
  5199. //---------------------------------------------------------------------------
  5200. THierarchicalStorage * __fastcall TStoredSessionList::CreateHostKeysStorageForWritting()
  5201. {
  5202. bool SessionList = false;
  5203. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));
  5204. Storage->Explicit = true;
  5205. Storage->AccessMode = smReadWrite;
  5206. return Storage.release();
  5207. }
  5208. //---------------------------------------------------------------------------
  5209. int TStoredSessionList::ImportHostKeys(
  5210. THierarchicalStorage * SourceStorage, THierarchicalStorage * TargetStorage, TStoredSessionList * Sessions, bool OnlySelected)
  5211. {
  5212. int Result = 0;
  5213. if (OpenHostKeysSubKey(SourceStorage, false) &&
  5214. OpenHostKeysSubKey(TargetStorage, true))
  5215. {
  5216. std::unique_ptr<TStringList> KeyList(new TStringList());
  5217. SourceStorage->GetValueNames(KeyList.get());
  5218. DebugAssert(Sessions != NULL);
  5219. for (int Index = 0; Index < Sessions->Count; Index++)
  5220. {
  5221. TSessionData * Session = Sessions->Sessions[Index];
  5222. if (!OnlySelected || Session->Selected)
  5223. {
  5224. UnicodeString HostKeyName = PuttyMungeStr(FORMAT(L"@%d:%s", (Session->PortNumber, Session->HostNameExpanded)));
  5225. for (int KeyIndex = 0; KeyIndex < KeyList->Count; KeyIndex++)
  5226. {
  5227. UnicodeString KeyName = KeyList->Strings[KeyIndex];
  5228. if (EndsText(HostKeyName, KeyName))
  5229. {
  5230. TargetStorage->WriteStringRaw(KeyName, SourceStorage->ReadStringRaw(KeyName, L""));
  5231. Result++;
  5232. }
  5233. }
  5234. }
  5235. }
  5236. }
  5237. return Result;
  5238. }
  5239. //---------------------------------------------------------------------------
  5240. void TStoredSessionList::ImportHostKeys(
  5241. THierarchicalStorage * SourceStorage, TStoredSessionList * Sessions, bool OnlySelected)
  5242. {
  5243. std::unique_ptr<THierarchicalStorage> TargetStorage(CreateHostKeysStorageForWritting());
  5244. ImportHostKeys(SourceStorage, TargetStorage.get(), Sessions, OnlySelected);
  5245. }
  5246. //---------------------------------------------------------------------------
  5247. void TStoredSessionList::ImportHostKeys(
  5248. const UnicodeString & SourceKey, TStoredSessionList * Sessions, bool OnlySelected)
  5249. {
  5250. std::unique_ptr<THierarchicalStorage> SourceStorage(new TRegistryStorage(SourceKey));
  5251. ImportHostKeys(SourceStorage.get(), Sessions, OnlySelected);
  5252. }
  5253. //---------------------------------------------------------------------------
  5254. void __fastcall TStoredSessionList::ImportSelectedKnownHosts(TStoredSessionList * Sessions)
  5255. {
  5256. std::unique_ptr<THierarchicalStorage> Storage(CreateHostKeysStorageForWritting());
  5257. if (OpenHostKeysSubKey(Storage.get(), true))
  5258. {
  5259. for (int Index = 0; Index < Sessions->Count; Index++)
  5260. {
  5261. TSessionData * Session = Sessions->Sessions[Index];
  5262. if (Session->Selected)
  5263. {
  5264. UnicodeString Algs;
  5265. UnicodeString HostKeys = Session->HostKey;
  5266. while (!HostKeys.IsEmpty())
  5267. {
  5268. UnicodeString HostKey = CutToChar(HostKeys, L';', true);
  5269. // skip alg
  5270. CutToChar(HostKey, L':', true);
  5271. UnicodeString Key = CutToChar(HostKey, L'=', true);
  5272. Storage->WriteStringRaw(Key, HostKey);
  5273. }
  5274. }
  5275. }
  5276. }
  5277. }
  5278. //---------------------------------------------------------------------------
  5279. void TStoredSessionList::SelectKnownHostsForSelectedSessions(
  5280. TStoredSessionList * KnownHosts, TStoredSessionList * Sessions)
  5281. {
  5282. for (int SessionIndex = 0; SessionIndex < Sessions->Count; SessionIndex++)
  5283. {
  5284. TSessionData * Session = Sessions->Sessions[SessionIndex];
  5285. if (Session->Selected)
  5286. {
  5287. UnicodeString Key = Session->HostName;
  5288. if (Session->PortNumber != Session->GetDefaultPort())
  5289. {
  5290. Key = FormatKnownHostName(Key, Session->PortNumber);
  5291. }
  5292. TSessionData * KnownHost = dynamic_cast<TSessionData *>(KnownHosts->FindByName(Key));
  5293. if (KnownHost != NULL)
  5294. {
  5295. KnownHost->Selected = true;
  5296. }
  5297. }
  5298. }
  5299. }
  5300. //---------------------------------------------------------------------------
  5301. TSessionData * TStoredSessionList::GetFirstFolderOrWorkspaceSession(const UnicodeString & Name)
  5302. {
  5303. TSessionData * Result = NULL;
  5304. if (!Name.IsEmpty())
  5305. {
  5306. UnicodeString NameWithSlash = UnixIncludeTrailingBackslash(Name); // optimization
  5307. for (int Index = 0; (Result == NULL) && (Index < Count); Index++)
  5308. {
  5309. if (Sessions[Index]->IsInFolderOrWorkspace(NameWithSlash))
  5310. {
  5311. Result = Sessions[Index];
  5312. }
  5313. }
  5314. }
  5315. return Result;
  5316. }
  5317. //---------------------------------------------------------------------------
  5318. bool __fastcall TStoredSessionList::IsFolderOrWorkspace(const UnicodeString & Name)
  5319. {
  5320. return (GetFirstFolderOrWorkspaceSession(Name) != NULL);
  5321. }
  5322. //---------------------------------------------------------------------------
  5323. bool __fastcall TStoredSessionList::IsFolder(const UnicodeString & Name)
  5324. {
  5325. TSessionData * SessionData = GetFirstFolderOrWorkspaceSession(Name);
  5326. return (SessionData != NULL) && !SessionData->IsWorkspace;
  5327. }
  5328. //---------------------------------------------------------------------------
  5329. bool __fastcall TStoredSessionList::IsWorkspace(const UnicodeString & Name)
  5330. {
  5331. TSessionData * SessionData = GetFirstFolderOrWorkspaceSession(Name);
  5332. return (SessionData != NULL) && SessionData->IsWorkspace;
  5333. }
  5334. //---------------------------------------------------------------------------
  5335. TSessionData * __fastcall TStoredSessionList::CheckIsInFolderOrWorkspaceAndResolve(
  5336. TSessionData * Data, const UnicodeString & Name)
  5337. {
  5338. if (Data->IsInFolderOrWorkspace(Name))
  5339. {
  5340. Data = ResolveWorkspaceData(Data);
  5341. if ((Data != NULL) && Data->CanOpen &&
  5342. DebugAlwaysTrue(Data->Link.IsEmpty()))
  5343. {
  5344. return Data;
  5345. }
  5346. }
  5347. return NULL;
  5348. }
  5349. //---------------------------------------------------------------------------
  5350. void __fastcall TStoredSessionList::GetFolderOrWorkspace(const UnicodeString & Name, TList * List)
  5351. {
  5352. DoGetFolderOrWorkspace(Name, List, false);
  5353. }
  5354. //---------------------------------------------------------------------------
  5355. void __fastcall TStoredSessionList::DoGetFolderOrWorkspace(const UnicodeString & Name, TList * List, bool NoRecrypt)
  5356. {
  5357. for (int Index = 0; (Index < Count); Index++)
  5358. {
  5359. TSessionData * RawData = Sessions[Index];
  5360. TSessionData * Data =
  5361. CheckIsInFolderOrWorkspaceAndResolve(RawData, Name);
  5362. if (Data != NULL)
  5363. {
  5364. TSessionData * Data2 = new TSessionData(L"");
  5365. if (NoRecrypt)
  5366. {
  5367. Data2->CopyDataNoRecrypt(Data);
  5368. }
  5369. else
  5370. {
  5371. Data2->Assign(Data);
  5372. }
  5373. if (!RawData->Link.IsEmpty() && (DebugAlwaysTrue(Data != RawData)) &&
  5374. // BACKWARD COMPATIBILITY
  5375. // When loading pre-5.6.4 workspace, that does not have state saved,
  5376. // do not overwrite the site "state" defaults
  5377. // with (empty) workspace state
  5378. RawData->HasStateData())
  5379. {
  5380. Data2->CopyStateData(RawData);
  5381. }
  5382. if (!RawData->NameOverride.IsEmpty())
  5383. {
  5384. Data2->Name = RawData->NameOverride;
  5385. }
  5386. else if (RawData->Link.IsEmpty() && RawData->IsWorkspace)
  5387. {
  5388. // Newly opened ad-hoc session has no name, so restore the workspace that way too.
  5389. // Otherwise we would persist the generated internal workspace name as a real name.
  5390. Data2->Name = UnicodeString();
  5391. }
  5392. List->Add(Data2);
  5393. }
  5394. }
  5395. }
  5396. //---------------------------------------------------------------------------
  5397. TStrings * __fastcall TStoredSessionList::GetFolderOrWorkspaceList(
  5398. const UnicodeString & Name)
  5399. {
  5400. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5401. DoGetFolderOrWorkspace(Name, DataList.get(), true);
  5402. std::unique_ptr<TStringList> Result(new TStringList());
  5403. for (int Index = 0; (Index < DataList->Count); Index++)
  5404. {
  5405. Result->Add(dynamic_cast<TSessionData *>(DataList->Items[Index])->SessionName);
  5406. }
  5407. return Result.release();
  5408. }
  5409. //---------------------------------------------------------------------------
  5410. TStrings * __fastcall TStoredSessionList::GetWorkspaces()
  5411. {
  5412. std::unique_ptr<TStringList> Result(CreateSortedStringList());
  5413. for (int Index = 0; (Index < Count); Index++)
  5414. {
  5415. TSessionData * Data = Sessions[Index];
  5416. if (Data->IsWorkspace)
  5417. {
  5418. Result->Add(Data->FolderName);
  5419. }
  5420. }
  5421. return Result.release();
  5422. }
  5423. //---------------------------------------------------------------------------
  5424. void __fastcall TStoredSessionList::NewWorkspace(
  5425. UnicodeString Name, TList * DataList)
  5426. {
  5427. for (int Index = 0; (Index < Count); Index++)
  5428. {
  5429. TSessionData * Data = Sessions[Index];
  5430. if (Data->IsInFolderOrWorkspace(Name))
  5431. {
  5432. FPendingRemovals->Add(Data->Name);
  5433. Remove(Data);
  5434. Index--;
  5435. }
  5436. }
  5437. for (int Index = 0; (Index < DataList->Count); Index++)
  5438. {
  5439. TSessionData * Data = static_cast<TSessionData *>(DataList->Items[Index]);
  5440. TSessionData * Data2 = new TSessionData(L"");
  5441. Data2->Assign(Data);
  5442. Data2->Name = TSessionData::ComposePath(Name, Data->Name);
  5443. // make sure, that new stored session is saved to registry
  5444. Data2->Modified = true;
  5445. Add(Data2);
  5446. }
  5447. }
  5448. //---------------------------------------------------------------------------
  5449. bool __fastcall TStoredSessionList::HasAnyWorkspace()
  5450. {
  5451. bool Result = false;
  5452. for (int Index = 0; !Result && (Index < Count); Index++)
  5453. {
  5454. TSessionData * Data = Sessions[Index];
  5455. Result = Data->IsWorkspace;
  5456. }
  5457. return Result;
  5458. }
  5459. //---------------------------------------------------------------------------
  5460. TSessionData * __fastcall TStoredSessionList::ParseUrl(UnicodeString Url,
  5461. TOptions * Options, bool & DefaultsOnly, UnicodeString * FileName,
  5462. bool * AProtocolDefined, UnicodeString * MaskedUrl, int Flags)
  5463. {
  5464. TSessionData * Data = new TSessionData(L"");
  5465. try
  5466. {
  5467. Data->ParseUrl(Url, Options, this, DefaultsOnly, FileName, AProtocolDefined, MaskedUrl, Flags);
  5468. }
  5469. catch(...)
  5470. {
  5471. delete Data;
  5472. throw;
  5473. }
  5474. return Data;
  5475. }
  5476. //---------------------------------------------------------------------
  5477. bool __fastcall TStoredSessionList::IsUrl(UnicodeString Url)
  5478. {
  5479. bool DefaultsOnly;
  5480. bool ProtocolDefined = false;
  5481. std::unique_ptr<TSessionData> ParsedData(ParseUrl(Url, NULL, DefaultsOnly, NULL, &ProtocolDefined));
  5482. bool Result = ProtocolDefined;
  5483. return Result;
  5484. }
  5485. //---------------------------------------------------------------------
  5486. TSessionData * __fastcall TStoredSessionList::ResolveWorkspaceData(TSessionData * Data)
  5487. {
  5488. if (!Data->Link.IsEmpty())
  5489. {
  5490. Data = dynamic_cast<TSessionData *>(FindByName(Data->Link));
  5491. if (Data != NULL)
  5492. {
  5493. Data = ResolveWorkspaceData(Data);
  5494. }
  5495. }
  5496. return Data;
  5497. }
  5498. //---------------------------------------------------------------------
  5499. TSessionData * __fastcall TStoredSessionList::SaveWorkspaceData(TSessionData * Data, int Index)
  5500. {
  5501. std::unique_ptr<TSessionData> Result(new TSessionData(L""));
  5502. TSessionData * SameData = StoredSessions->FindSame(Data);
  5503. if (SameData != NULL)
  5504. {
  5505. Result->CopyStateData(Data);
  5506. Result->Link = Data->Name;
  5507. }
  5508. else
  5509. {
  5510. Result->Assign(Data);
  5511. Result->NameOverride = Data->Name;
  5512. }
  5513. Result->IsWorkspace = true;
  5514. Result->Name = IntToHex(Index, 4); // See HasSessionName()
  5515. return Result.release();
  5516. }
  5517. //---------------------------------------------------------------------
  5518. bool __fastcall TStoredSessionList::CanOpen(TSessionData * Data)
  5519. {
  5520. Data = ResolveWorkspaceData(Data);
  5521. return (Data != NULL) && Data->CanOpen;
  5522. }
  5523. //---------------------------------------------------------------------
  5524. UnicodeString GetExpandedLogFileName(UnicodeString LogFileName, TDateTime Started, TSessionData * SessionData)
  5525. {
  5526. // StripPathQuotes should not be needed as we do not feed quotes anymore
  5527. UnicodeString ANewFileName = StripPathQuotes(ExpandEnvironmentVariables(LogFileName));
  5528. for (int Index = 1; Index < ANewFileName.Length(); Index++)
  5529. {
  5530. if (ANewFileName[Index] == L'!')
  5531. {
  5532. UnicodeString Replacement;
  5533. // keep consistent with TFileCustomCommand::PatternReplacement
  5534. switch (towlower(ANewFileName[Index + 1]))
  5535. {
  5536. case L'y':
  5537. Replacement = FormatDateTime(L"yyyy", Started);
  5538. break;
  5539. case L'm':
  5540. Replacement = FormatDateTime(L"mm", Started);
  5541. break;
  5542. case L'd':
  5543. Replacement = FormatDateTime(L"dd", Started);
  5544. break;
  5545. case L't':
  5546. Replacement = FormatDateTime(L"hhnnss", Started);
  5547. break;
  5548. case 'p':
  5549. Replacement = IntToStr(static_cast<int>(GetCurrentProcessId()));
  5550. break;
  5551. case L'@':
  5552. if (SessionData != NULL)
  5553. {
  5554. Replacement = MakeValidFileName(SessionData->HostNameExpanded);
  5555. }
  5556. else
  5557. {
  5558. Replacement = L"nohost";
  5559. }
  5560. break;
  5561. case L's':
  5562. if (SessionData != NULL)
  5563. {
  5564. Replacement = MakeValidFileName(SessionData->SessionName);
  5565. }
  5566. else
  5567. {
  5568. Replacement = L"nosession";
  5569. }
  5570. break;
  5571. case L'!':
  5572. Replacement = L"!";
  5573. break;
  5574. default:
  5575. Replacement = UnicodeString(L"!") + ANewFileName[Index + 1];
  5576. break;
  5577. }
  5578. ANewFileName.Delete(Index, 2);
  5579. ANewFileName.Insert(Replacement, Index);
  5580. Index += Replacement.Length() - 1;
  5581. }
  5582. }
  5583. return ANewFileName;
  5584. }
  5585. //---------------------------------------------------------------------
  5586. bool __fastcall IsSshProtocol(TFSProtocol FSProtocol)
  5587. {
  5588. return
  5589. (FSProtocol == fsSFTPonly) || (FSProtocol == fsSFTP) ||
  5590. (FSProtocol == fsSCPonly);
  5591. }
  5592. //---------------------------------------------------------------------------
  5593. int __fastcall DefaultPort(TFSProtocol FSProtocol, TFtps Ftps)
  5594. {
  5595. int Result;
  5596. switch (FSProtocol)
  5597. {
  5598. case fsFTP:
  5599. if (Ftps == ftpsImplicit)
  5600. {
  5601. Result = FtpsImplicitPortNumber;
  5602. }
  5603. else
  5604. {
  5605. Result = FtpPortNumber;
  5606. }
  5607. break;
  5608. case fsWebDAV:
  5609. case fsS3:
  5610. if (Ftps == ftpsNone)
  5611. {
  5612. Result = HTTPPortNumber;
  5613. }
  5614. else
  5615. {
  5616. Result = HTTPSPortNumber;
  5617. }
  5618. break;
  5619. default:
  5620. if (IsSshProtocol(FSProtocol))
  5621. {
  5622. Result = SshPortNumber;
  5623. }
  5624. else
  5625. {
  5626. DebugFail();
  5627. Result = -1;
  5628. }
  5629. break;
  5630. }
  5631. return Result;
  5632. }
  5633. //---------------------------------------------------------------------