SessionData.cpp 165 KB

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