SessionData.cpp 160 KB

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