SessionData.cpp 187 KB

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