SessionData.cpp 191 KB

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