SessionData.cpp 165 KB

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