SessionData.cpp 164 KB

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