SessionData.cpp 177 KB

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