SessionData.cpp 166 KB

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