SessionData.cpp 171 KB

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