SessionData.cpp 187 KB

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