SessionData.cpp 166 KB

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