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