SessionData.cpp 167 KB

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