SessionData.cpp 187 KB

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