SessionData.cpp 165 KB

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