SessionData.cpp 168 KB

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