SessionData.cpp 190 KB

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