SessionData.cpp 172 KB

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