SessionData.cpp 184 KB

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