SessionData.cpp 170 KB

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