SessionData.cpp 160 KB

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