SessionData.cpp 191 KB

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