SessionData.cpp 173 KB

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