SessionData.cpp 165 KB

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