SessionData.cpp 191 KB

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