SessionData.cpp 173 KB

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