SessionData.cpp 190 KB

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