SessionData.cpp 190 KB

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