SessionData.cpp 168 KB

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