SessionData.cpp 167 KB

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