SessionData.cpp 186 KB

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