SessionData.cpp 195 KB

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