SessionData.cpp 190 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797
  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 UnicodeString ReadPasswordFromFile(const UnicodeString & FileName)
  1699. {
  1700. UnicodeString Result = FileName;
  1701. if (!Result.IsEmpty())
  1702. {
  1703. std::unique_ptr<TStrings> Lines(new TStringList());
  1704. LoadScriptFromFile(Result, Lines.get());
  1705. if (Lines->Count > 0)
  1706. {
  1707. Result = Lines->Strings[0];
  1708. }
  1709. }
  1710. return Result;
  1711. }
  1712. //---------------------------------------------------------------------
  1713. void TSessionData::ReadPasswordsFromFiles()
  1714. {
  1715. Password = ReadPasswordFromFile(Password);
  1716. NewPassword = ReadPasswordFromFile(NewPassword);
  1717. ProxyPassword = ReadPasswordFromFile(ProxyPassword);
  1718. TunnelPassword = ReadPasswordFromFile(TunnelPassword);
  1719. TunnelPassphrase = ReadPasswordFromFile(TunnelPassphrase);
  1720. Passphrase = ReadPasswordFromFile(Passphrase);
  1721. EncryptKey = ReadPasswordFromFile(EncryptKey);
  1722. }
  1723. //---------------------------------------------------------------------
  1724. bool __fastcall TSessionData::HasPassword()
  1725. {
  1726. return !FPassword.IsEmpty();
  1727. }
  1728. //---------------------------------------------------------------------
  1729. bool __fastcall TSessionData::HasAnySessionPassword()
  1730. {
  1731. // Keep in sync with ClearSessionPasswords
  1732. return
  1733. HasPassword() ||
  1734. !FTunnelPassword.IsEmpty() ||
  1735. // will probably be never used
  1736. !FNewPassword.IsEmpty();
  1737. }
  1738. //---------------------------------------------------------------------
  1739. bool __fastcall TSessionData::HasAnyPassword()
  1740. {
  1741. // Keep in sync with MaskPasswords
  1742. return
  1743. HasAnySessionPassword() ||
  1744. !FProxyPassword.IsEmpty() ||
  1745. !FEncryptKey.IsEmpty() ||
  1746. !FPassphrase.IsEmpty() ||
  1747. !FTunnelPassphrase.IsEmpty();
  1748. }
  1749. //---------------------------------------------------------------------
  1750. void __fastcall TSessionData::ClearSessionPasswords()
  1751. {
  1752. // Keep in sync with HasAnySessionPassword
  1753. FPassword = L"";
  1754. FNewPassword = L"";
  1755. FTunnelPassword = L"";
  1756. }
  1757. //---------------------------------------------------------------------
  1758. void __fastcall TSessionData::Modify()
  1759. {
  1760. FModified = true;
  1761. if (FSource == ssStored)
  1762. {
  1763. FSource = ssStoredModified;
  1764. }
  1765. }
  1766. //---------------------------------------------------------------------
  1767. UnicodeString __fastcall TSessionData::GetSource()
  1768. {
  1769. switch (FSource)
  1770. {
  1771. case ::ssNone:
  1772. return L"Ad-Hoc site";
  1773. case ssStored:
  1774. return L"Site";
  1775. case ssStoredModified:
  1776. return L"Modified site";
  1777. default:
  1778. DebugFail();
  1779. return L"";
  1780. }
  1781. }
  1782. //---------------------------------------------------------------------
  1783. void __fastcall TSessionData::SaveRecryptedPasswords(THierarchicalStorage * Storage)
  1784. {
  1785. if (Storage->OpenSubKey(InternalStorageKey, true))
  1786. {
  1787. try
  1788. {
  1789. RecryptPasswords();
  1790. SavePasswords(Storage, false, false, false);
  1791. }
  1792. __finally
  1793. {
  1794. Storage->CloseSubKey();
  1795. }
  1796. }
  1797. }
  1798. //---------------------------------------------------------------------
  1799. void __fastcall TSessionData::Remove(THierarchicalStorage * Storage, const UnicodeString & Name)
  1800. {
  1801. Storage->RecursiveDeleteSubKey(Name);
  1802. }
  1803. //---------------------------------------------------------------------
  1804. void __fastcall TSessionData::Remove()
  1805. {
  1806. bool SessionList = true;
  1807. THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);
  1808. try
  1809. {
  1810. Storage->Explicit = true;
  1811. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, false))
  1812. {
  1813. Remove(Storage, InternalStorageKey);
  1814. }
  1815. }
  1816. __finally
  1817. {
  1818. delete Storage;
  1819. }
  1820. }
  1821. //---------------------------------------------------------------------
  1822. void __fastcall TSessionData::CacheHostKeyIfNotCached()
  1823. {
  1824. UnicodeString KeyType = KeyTypeFromFingerprint(HostKey);
  1825. // Should allow importing to INI file as ImportHostKeys
  1826. UnicodeString TargetKey = Configuration->RegistryStorageKey + L"\\" + Configuration->SshHostKeysSubKey;
  1827. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(TargetKey));
  1828. Storage->AccessMode = smReadWrite;
  1829. if (Storage->OpenRootKey(true))
  1830. {
  1831. UnicodeString HostKeyName = PuttyMungeStr(FORMAT(L"%s@%d:%s", (KeyType, PortNumber, HostName)));
  1832. if (!Storage->ValueExists(HostKeyName))
  1833. {
  1834. // fingerprint is a checksum of a host key, so it cannot be translated back to host key,
  1835. // so we store fingerprint and TSecureShell::VerifyHostKey was
  1836. // modified to accept also fingerprint
  1837. Storage->WriteString(HostKeyName, HostKey);
  1838. }
  1839. }
  1840. }
  1841. //---------------------------------------------------------------------
  1842. inline void __fastcall MoveStr(UnicodeString & Source, UnicodeString * Dest, int Count)
  1843. {
  1844. if (Dest != NULL)
  1845. {
  1846. (*Dest) += Source.SubString(1, Count);
  1847. }
  1848. Source.Delete(1, Count);
  1849. }
  1850. //---------------------------------------------------------------------
  1851. bool __fastcall TSessionData::DoIsProtocolUrl(
  1852. const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen)
  1853. {
  1854. bool Result = SameText(Url.SubString(1, Protocol.Length() + 1), Protocol + L":");
  1855. if (Result)
  1856. {
  1857. ProtocolLen = Protocol.Length() + 1;
  1858. }
  1859. return Result;
  1860. }
  1861. //---------------------------------------------------------------------
  1862. bool __fastcall TSessionData::IsProtocolUrl(
  1863. const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen)
  1864. {
  1865. return
  1866. DoIsProtocolUrl(Url, Protocol, ProtocolLen) ||
  1867. DoIsProtocolUrl(Url, WinSCPProtocolPrefix + Protocol, ProtocolLen);
  1868. }
  1869. //---------------------------------------------------------------------
  1870. bool __fastcall TSessionData::IsSensitiveOption(const UnicodeString & Option, const UnicodeString & Value)
  1871. {
  1872. bool Result;
  1873. if (SameText(Option, PassphraseOption) ||
  1874. SameText(Option, PASSWORD_SWITCH) ||
  1875. SameText(Option, NEWPASSWORD_SWITCH))
  1876. {
  1877. Result = true;
  1878. }
  1879. else if (SameText(Option, PRIVATEKEY_SWITCH))
  1880. {
  1881. Filename * AFilename = filename_from_str(UTF8String(Value).c_str());
  1882. Result = (in_memory_key_data(AFilename) != NULL);
  1883. filename_free(AFilename);
  1884. }
  1885. else
  1886. {
  1887. Result = false;
  1888. }
  1889. return Result;
  1890. }
  1891. //---------------------------------------------------------------------
  1892. bool __fastcall TSessionData::IsOptionWithParameters(const UnicodeString & Option)
  1893. {
  1894. return SameText(Option, RawSettingsOption);
  1895. }
  1896. //---------------------------------------------------------------------
  1897. bool __fastcall TSessionData::MaskPasswordInOptionParameter(const UnicodeString & Option, UnicodeString & Param)
  1898. {
  1899. bool Result = false;
  1900. if (SameText(Option, RawSettingsOption))
  1901. {
  1902. int P = Param.Pos(L"=");
  1903. if (P > 0)
  1904. {
  1905. // TStrings.IndexOfName does not trim
  1906. UnicodeString Key = Param.SubString(1, P - 1);
  1907. if (SameText(Key, L"ProxyPassword") ||
  1908. SameText(Key, L"ProxyPasswordEnc") ||
  1909. SameText(Key, L"TunnelPassword") ||
  1910. SameText(Key, L"TunnelPasswordPlain") ||
  1911. SameText(Key, L"TunnelPassphrase") ||
  1912. SameText(Key, L"TunnelPassphrasePlain") ||
  1913. SameText(Key, L"EncryptKey") ||
  1914. SameText(Key, L"EncryptKeyPlain"))
  1915. {
  1916. Param = Key + L"=" + PasswordMask;
  1917. Result = true;
  1918. }
  1919. }
  1920. }
  1921. return Result;
  1922. }
  1923. //---------------------------------------------------------------------
  1924. void __fastcall TSessionData::MaskPasswords()
  1925. {
  1926. // Keep in sync with HasAnyPassword
  1927. if (!Password.IsEmpty())
  1928. {
  1929. Password = PasswordMask;
  1930. }
  1931. if (!NewPassword.IsEmpty())
  1932. {
  1933. NewPassword = PasswordMask;
  1934. }
  1935. if (!ProxyPassword.IsEmpty())
  1936. {
  1937. ProxyPassword = PasswordMask;
  1938. }
  1939. if (!TunnelPassword.IsEmpty())
  1940. {
  1941. TunnelPassword = PasswordMask;
  1942. }
  1943. if (!TunnelPassphrase.IsEmpty())
  1944. {
  1945. TunnelPassphrase = PasswordMask;
  1946. }
  1947. if (!EncryptKey.IsEmpty())
  1948. {
  1949. EncryptKey = PasswordMask;
  1950. }
  1951. if (!Passphrase.IsEmpty())
  1952. {
  1953. Passphrase = PasswordMask;
  1954. }
  1955. }
  1956. //---------------------------------------------------------------------
  1957. static bool IsDomainOrSubdomain(const UnicodeString & FullDomain, const UnicodeString & Domain)
  1958. {
  1959. return
  1960. SameText(FullDomain, Domain) ||
  1961. EndsText(L"." + Domain, FullDomain);
  1962. }
  1963. //---------------------------------------------------------------------
  1964. bool __fastcall TSessionData::ParseUrl(UnicodeString Url, TOptions * Options,
  1965. TStoredSessionList * StoredSessions, bool & DefaultsOnly, UnicodeString * FileName,
  1966. bool * AProtocolDefined, UnicodeString * MaskedUrl, int Flags)
  1967. {
  1968. bool ProtocolDefined = true;
  1969. bool PortNumberDefined = false;
  1970. TFSProtocol AFSProtocol;
  1971. int DefaultProtocolPortNumber;
  1972. TFtps AFtps = ftpsNone;
  1973. int ProtocolLen = 0;
  1974. bool HttpForWebdav = FLAGCLEAR(Flags, pufPreferProtocol) || (FSProtocol != fsS3);
  1975. if (IsProtocolUrl(Url, ScpProtocol, ProtocolLen))
  1976. {
  1977. AFSProtocol = fsSCPonly;
  1978. DefaultProtocolPortNumber = SshPortNumber;
  1979. }
  1980. else if (IsProtocolUrl(Url, SftpProtocol, ProtocolLen))
  1981. {
  1982. AFSProtocol = fsSFTPonly;
  1983. DefaultProtocolPortNumber = SshPortNumber;
  1984. }
  1985. else if (IsProtocolUrl(Url, FtpProtocol, ProtocolLen))
  1986. {
  1987. AFSProtocol = fsFTP;
  1988. Ftps = ftpsNone;
  1989. DefaultProtocolPortNumber = FtpPortNumber;
  1990. }
  1991. else if (IsProtocolUrl(Url, FtpsProtocol, ProtocolLen))
  1992. {
  1993. AFSProtocol = fsFTP;
  1994. AFtps = ftpsImplicit;
  1995. DefaultProtocolPortNumber = FtpsImplicitPortNumber;
  1996. }
  1997. else if (IsProtocolUrl(Url, FtpesProtocol, ProtocolLen))
  1998. {
  1999. AFSProtocol = fsFTP;
  2000. AFtps = ftpsExplicitTls;
  2001. DefaultProtocolPortNumber = FtpPortNumber;
  2002. }
  2003. else if (IsProtocolUrl(Url, WebDAVProtocol, ProtocolLen) ||
  2004. (HttpForWebdav && IsProtocolUrl(Url, HttpProtocol, ProtocolLen)))
  2005. {
  2006. AFSProtocol = fsWebDAV;
  2007. AFtps = ftpsNone;
  2008. DefaultProtocolPortNumber = HTTPPortNumber;
  2009. }
  2010. else if (IsProtocolUrl(Url, WebDAVSProtocol, ProtocolLen) ||
  2011. (HttpForWebdav && IsProtocolUrl(Url, HttpsProtocol, ProtocolLen)))
  2012. {
  2013. AFSProtocol = fsWebDAV;
  2014. AFtps = ftpsImplicit;
  2015. DefaultProtocolPortNumber = HTTPSPortNumber;
  2016. }
  2017. else if (IsProtocolUrl(Url, S3PlainProtocol, ProtocolLen) ||
  2018. IsProtocolUrl(Url, HttpProtocol, ProtocolLen))
  2019. {
  2020. AFSProtocol = fsS3;
  2021. AFtps = ftpsNone;
  2022. DefaultProtocolPortNumber = HTTPPortNumber;
  2023. }
  2024. else if (IsProtocolUrl(Url, S3Protocol, ProtocolLen) ||
  2025. IsProtocolUrl(Url, HttpsProtocol, ProtocolLen))
  2026. {
  2027. AFSProtocol = fsS3;
  2028. AFtps = ftpsImplicit;
  2029. DefaultProtocolPortNumber = HTTPSPortNumber;
  2030. }
  2031. else if (IsProtocolUrl(Url, SshProtocol, ProtocolLen))
  2032. {
  2033. // For most uses, handling ssh:// the same way as sftp://
  2034. // The only place where a difference is made is GetLoginData() in WinMain.cpp
  2035. AFSProtocol = fsSFTPonly;
  2036. PuttyProtocol = PuttySshProtocol;
  2037. DefaultProtocolPortNumber = SshPortNumber;
  2038. }
  2039. else
  2040. {
  2041. ProtocolDefined = false;
  2042. }
  2043. if (ProtocolDefined)
  2044. {
  2045. MoveStr(Url, MaskedUrl, ProtocolLen);
  2046. }
  2047. if (ProtocolDefined && (Url.SubString(1, 2) == L"//"))
  2048. {
  2049. MoveStr(Url, MaskedUrl, 2);
  2050. }
  2051. if (AProtocolDefined != NULL)
  2052. {
  2053. *AProtocolDefined = ProtocolDefined;
  2054. }
  2055. bool Unsafe = FLAGSET(Flags, pufUnsafe);
  2056. if (!Url.IsEmpty())
  2057. {
  2058. UnicodeString DecodedUrl = DecodeUrlChars(Url);
  2059. // lookup stored session even if protocol was defined
  2060. // (this allows setting for example default username for host
  2061. // by creating stored session named by host)
  2062. TSessionData * Data = NULL;
  2063. // When using to paste URL on Login dialog, we do not want to lookup the stored sites
  2064. if ((StoredSessions != NULL) &&
  2065. (!ProtocolDefined || FLAGSET(Flags, pufAllowStoredSiteWithProtocol)))
  2066. {
  2067. // this can be optimized as the list is sorted
  2068. for (Integer Index = 0; Index < StoredSessions->CountIncludingHidden; Index++)
  2069. {
  2070. TSessionData * AData = (TSessionData *)StoredSessions->Items[Index];
  2071. if (!AData->IsWorkspace)
  2072. {
  2073. bool Match = false;
  2074. // Comparison optimizations as this is called many times
  2075. // e.g. when updating jumplist
  2076. if ((AData->Name.Length() == DecodedUrl.Length()) &&
  2077. SameText(AData->Name, DecodedUrl))
  2078. {
  2079. Match = true;
  2080. }
  2081. else if ((AData->Name.Length() < DecodedUrl.Length()) &&
  2082. (DecodedUrl[AData->Name.Length() + 1] == L'/') &&
  2083. // StrLIComp is an equivalent of SameText
  2084. (StrLIComp(AData->Name.c_str(), DecodedUrl.c_str(), AData->Name.Length()) == 0))
  2085. {
  2086. Match = true;
  2087. }
  2088. if (Match)
  2089. {
  2090. Data = AData;
  2091. break;
  2092. }
  2093. }
  2094. }
  2095. }
  2096. UnicodeString ARemoteDirectory;
  2097. if (Data != NULL)
  2098. {
  2099. Assign(Data);
  2100. int P = 1;
  2101. while (!AnsiSameText(DecodeUrlChars(Url.SubString(1, P)), Data->Name))
  2102. {
  2103. P++;
  2104. DebugAssert(P <= Url.Length());
  2105. }
  2106. ARemoteDirectory = Url.SubString(P + 1, Url.Length() - P);
  2107. if (Data->Hidden)
  2108. {
  2109. Data->Remove();
  2110. StoredSessions->Remove(Data);
  2111. // only modified, implicit
  2112. StoredSessions->Save(false, false);
  2113. }
  2114. if (MaskedUrl != NULL)
  2115. {
  2116. (*MaskedUrl) += Url;
  2117. }
  2118. }
  2119. else
  2120. {
  2121. // When ad-hoc URL is used, always display error when the directories are not valid,
  2122. // no matter if they are part of the URL or raw settings.
  2123. RequireDirectories = true;
  2124. // This happens when pasting URL on Login dialog
  2125. if (StoredSessions != NULL)
  2126. {
  2127. CopyData(StoredSessions->DefaultSettings);
  2128. }
  2129. Name = L"";
  2130. int PSlash = Url.Pos(L"/");
  2131. if (PSlash == 0)
  2132. {
  2133. PSlash = Url.Length() + 1;
  2134. }
  2135. UnicodeString ConnectInfo = Url.SubString(1, PSlash - 1);
  2136. int P = ConnectInfo.LastDelimiter(L"@");
  2137. UnicodeString UserInfo;
  2138. UnicodeString HostInfo;
  2139. if (P > 0)
  2140. {
  2141. UserInfo = ConnectInfo.SubString(1, P - 1);
  2142. HostInfo = ConnectInfo.SubString(P + 1, ConnectInfo.Length() - P);
  2143. }
  2144. else
  2145. {
  2146. HostInfo = ConnectInfo;
  2147. }
  2148. UnicodeString OrigHostInfo = HostInfo;
  2149. if ((HostInfo.Length() >= 2) && (HostInfo[1] == L'[') && ((P = HostInfo.Pos(L"]")) > 0))
  2150. {
  2151. HostName = HostInfo.SubString(2, P - 2);
  2152. HostInfo.Delete(1, P);
  2153. if (!HostInfo.IsEmpty() && (HostInfo[1] == L':'))
  2154. {
  2155. HostInfo.Delete(1, 1);
  2156. }
  2157. }
  2158. else
  2159. {
  2160. HostName = DecodeUrlChars(CutToChar(HostInfo, L':', true));
  2161. }
  2162. // expanded from ?: operator, as it caused strange "access violation" errors
  2163. if (!HostInfo.IsEmpty())
  2164. {
  2165. int APortNumber = StrToIntDef(DecodeUrlChars(HostInfo), -1);
  2166. if ((APortNumber > 0) && (APortNumber <= 65535))
  2167. {
  2168. PortNumber = APortNumber;
  2169. PortNumberDefined = true;
  2170. }
  2171. }
  2172. else if (ProtocolDefined)
  2173. {
  2174. if ((AFSProtocol == fsWebDAV) &&
  2175. (IsDomainOrSubdomain(HostName, S3LibDefaultHostName()) ||
  2176. IsDomainOrSubdomain(HostName, L"digitaloceanspaces.com") ||
  2177. IsDomainOrSubdomain(HostName, L"storage.googleapis.com")))
  2178. {
  2179. AFSProtocol = fsS3;
  2180. }
  2181. PortNumber = DefaultProtocolPortNumber;
  2182. }
  2183. if (ProtocolDefined)
  2184. {
  2185. Ftps = AFtps;
  2186. }
  2187. UnicodeString UserInfoWithoutConnectionParams = CutToChar(UserInfo, UrlParamSeparator, false);
  2188. UnicodeString ConnectionParams = UserInfo;
  2189. UserInfo = UserInfoWithoutConnectionParams;
  2190. std::unique_ptr<TStrings> RawSettings(new TStringList());
  2191. while (!ConnectionParams.IsEmpty())
  2192. {
  2193. UnicodeString ConnectionParam = CutToChar(ConnectionParams, UrlParamSeparator, false);
  2194. UnicodeString ConnectionParamName = CutToChar(ConnectionParam, UrlParamValueSeparator, false);
  2195. if (SameText(ConnectionParamName, UrlHostKeyParamName))
  2196. {
  2197. HostKey = DecodeUrlChars(ConnectionParam);
  2198. FOverrideCachedHostKey = false;
  2199. }
  2200. else if (StartsText(UrlRawSettingsParamNamePrefix, ConnectionParamName))
  2201. {
  2202. UnicodeString AName = RightStr(ConnectionParamName, ConnectionParamName.Length() - UrlRawSettingsParamNamePrefix.Length());
  2203. AName = DecodeUrlChars(AName);
  2204. UnicodeString Value = DecodeUrlChars(ConnectionParam);
  2205. if (SameText(AName, L"Name"))
  2206. {
  2207. Name = Value;
  2208. }
  2209. else
  2210. {
  2211. RawSettings->Values[AName] = Value;
  2212. }
  2213. }
  2214. }
  2215. if (RawSettings->Count > 0) // optimization
  2216. {
  2217. ApplyRawSettings(RawSettings.get(), Unsafe);
  2218. }
  2219. bool HasPassword = (UserInfo.Pos(L':') > 0);
  2220. UnicodeString RawUserName = CutToChar(UserInfo, L':', false);
  2221. UserName = DecodeUrlChars(RawUserName);
  2222. Password = DecodeUrlChars(UserInfo);
  2223. if (HasPassword && Password.IsEmpty())
  2224. {
  2225. Password = EmptyString;
  2226. }
  2227. UnicodeString RemoteDirectoryWithSessionParams = Url.SubString(PSlash, Url.Length() - PSlash + 1);
  2228. ARemoteDirectory = CutToChar(RemoteDirectoryWithSessionParams, UrlParamSeparator, false);
  2229. UnicodeString SessionParams = RemoteDirectoryWithSessionParams;
  2230. // We should handle session params in "stored session" branch too.
  2231. // And particularly if there's a "save" param, we should actually not try to match the
  2232. // URL against site names
  2233. while (!SessionParams.IsEmpty())
  2234. {
  2235. UnicodeString SessionParam = CutToChar(SessionParams, UrlParamSeparator, false);
  2236. UnicodeString SessionParamName = CutToChar(SessionParam, UrlParamValueSeparator, false);
  2237. if (SameText(SessionParamName, UrlSaveParamName))
  2238. {
  2239. FSaveOnly = (StrToIntDef(SessionParam, 1) != 0);
  2240. }
  2241. }
  2242. if (MaskedUrl != NULL)
  2243. {
  2244. (*MaskedUrl) += RawUserName;
  2245. if (HasPassword)
  2246. {
  2247. (*MaskedUrl) += L":" + PasswordMask;
  2248. }
  2249. if (!RawUserName.IsEmpty() || HasPassword)
  2250. {
  2251. (*MaskedUrl) += L"@";
  2252. }
  2253. (*MaskedUrl) += OrigHostInfo + ARemoteDirectory;
  2254. }
  2255. }
  2256. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory != L"/"))
  2257. {
  2258. if ((ARemoteDirectory[ARemoteDirectory.Length()] != L'/') &&
  2259. (FileName != NULL))
  2260. {
  2261. *FileName = DecodeUrlChars(UnixExtractFileName(ARemoteDirectory));
  2262. ARemoteDirectory = UnixExtractFilePath(ARemoteDirectory);
  2263. }
  2264. RemoteDirectory = DecodeUrlChars(ARemoteDirectory);
  2265. // Is already true for ad-hoc URL, but we want to error even for "storedsite/path/"-style URL.
  2266. RequireDirectories = true;
  2267. }
  2268. DefaultsOnly = false;
  2269. }
  2270. else
  2271. {
  2272. // This happens when pasting URL on Login dialog
  2273. if (StoredSessions != NULL)
  2274. {
  2275. CopyData(StoredSessions->DefaultSettings);
  2276. }
  2277. DefaultsOnly = true;
  2278. }
  2279. if (ProtocolDefined)
  2280. {
  2281. FSProtocol = AFSProtocol;
  2282. }
  2283. if (Options != NULL)
  2284. {
  2285. // we deliberately do keep defaultonly to false, in presence of any option,
  2286. // as the option should not make session "connectable"
  2287. UnicodeString Value;
  2288. if (Options->FindSwitch(USERNAME_SWITCH, Value))
  2289. {
  2290. UserName = Value;
  2291. }
  2292. if (Options->FindSwitch(PASSWORD_SWITCH, Value))
  2293. {
  2294. Password = Value;
  2295. }
  2296. if (Options->FindSwitch(SESSIONNAME_SWICH, Value))
  2297. {
  2298. Name = Value;
  2299. }
  2300. if (Options->FindSwitch(NEWPASSWORD_SWITCH, Value))
  2301. {
  2302. ChangePassword = true;
  2303. NewPassword = Value;
  2304. }
  2305. if (Options->FindSwitch(PRIVATEKEY_SWITCH, Value))
  2306. {
  2307. PublicKeyFile = Value;
  2308. }
  2309. if (Options->FindSwitch(L"clientcert", Value))
  2310. {
  2311. TlsCertificateFile = Value;
  2312. }
  2313. if (Options->FindSwitch(PassphraseOption, Value))
  2314. {
  2315. Passphrase = Value;
  2316. }
  2317. if (Options->FindSwitch(L"timeout", Value))
  2318. {
  2319. Timeout = StrToInt(Value);
  2320. }
  2321. if (Options->FindSwitch(L"hostkey", Value) ||
  2322. Options->FindSwitch(L"certificate", Value))
  2323. {
  2324. HostKey = Value;
  2325. FOverrideCachedHostKey = true;
  2326. }
  2327. FtpPasvMode = Options->SwitchValue(L"passive", FtpPasvMode);
  2328. if (Options->FindSwitch(L"implicit"))
  2329. {
  2330. bool Enabled = Options->SwitchValue(L"implicit", true);
  2331. Ftps = Enabled ? ftpsImplicit : ftpsNone;
  2332. if (!PortNumberDefined && Enabled)
  2333. {
  2334. PortNumber = FtpsImplicitPortNumber;
  2335. }
  2336. }
  2337. // BACKWARD COMPATIBILITY with 5.5.x
  2338. if (Options->FindSwitch(L"explicitssl"))
  2339. {
  2340. bool Enabled = Options->SwitchValue(L"explicitssl", true);
  2341. Ftps = Enabled ? ftpsExplicitSsl : ftpsNone;
  2342. if (!PortNumberDefined && Enabled)
  2343. {
  2344. PortNumber = FtpPortNumber;
  2345. }
  2346. }
  2347. if (Options->FindSwitch(L"explicit") ||
  2348. // BACKWARD COMPATIBILITY with 5.5.x
  2349. Options->FindSwitch(L"explicittls"))
  2350. {
  2351. UnicodeString SwitchName =
  2352. Options->FindSwitch(L"explicit") ? L"explicit" : L"explicittls";
  2353. bool Enabled = Options->SwitchValue(SwitchName, true);
  2354. Ftps = Enabled ? ftpsExplicitTls : ftpsNone;
  2355. if (!PortNumberDefined && Enabled)
  2356. {
  2357. PortNumber = FtpPortNumber;
  2358. }
  2359. }
  2360. if (Options->FindSwitch(RawSettingsOption))
  2361. {
  2362. std::unique_ptr<TStrings> RawSettings(new TStringList());
  2363. if (Options->FindSwitch(RawSettingsOption, RawSettings.get()))
  2364. {
  2365. ApplyRawSettings(RawSettings.get(), Unsafe);
  2366. }
  2367. }
  2368. }
  2369. return true;
  2370. }
  2371. //---------------------------------------------------------------------
  2372. void __fastcall TSessionData::ApplyRawSettings(TStrings * RawSettings, bool Unsafe)
  2373. {
  2374. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings, false));
  2375. ApplyRawSettings(OptionsStorage.get(), Unsafe);
  2376. }
  2377. //---------------------------------------------------------------------
  2378. void __fastcall TSessionData::ApplyRawSettings(THierarchicalStorage * Storage, bool Unsafe)
  2379. {
  2380. bool Dummy;
  2381. DoLoad(Storage, false, Dummy, Unsafe);
  2382. }
  2383. //---------------------------------------------------------------------
  2384. void __fastcall TSessionData::ConfigureTunnel(int APortNumber)
  2385. {
  2386. FOrigHostName = HostName;
  2387. FOrigPortNumber = PortNumber;
  2388. FOrigProxyMethod = ProxyMethod;
  2389. HostName = L"127.0.0.1";
  2390. PortNumber = APortNumber;
  2391. // proxy settings is used for tunnel
  2392. ProxyMethod = ::pmNone;
  2393. FLogicalHostName = FOrigHostName;
  2394. }
  2395. //---------------------------------------------------------------------
  2396. void __fastcall TSessionData::RollbackTunnel()
  2397. {
  2398. HostName = FOrigHostName;
  2399. PortNumber = FOrigPortNumber;
  2400. ProxyMethod = FOrigProxyMethod;
  2401. FLogicalHostName = L"";
  2402. }
  2403. //---------------------------------------------------------------------
  2404. TSessionData * TSessionData::CreateTunnelData(int TunnelLocalPortNumber)
  2405. {
  2406. std::unique_ptr<TSessionData> TunnelData(new TSessionData(EmptyStr));
  2407. TunnelData->Assign(StoredSessions->DefaultSettings);
  2408. TunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (SessionName));
  2409. TunnelData->Tunnel = false;
  2410. TunnelData->HostName = TunnelHostName;
  2411. TunnelData->PortNumber = TunnelPortNumber;
  2412. TunnelData->UserName = TunnelUserName;
  2413. TunnelData->Password = TunnelPassword;
  2414. TunnelData->PublicKeyFile = TunnelPublicKeyFile;
  2415. TunnelData->Passphrase = TunnelPassphrase;
  2416. UnicodeString AHostName = HostNameExpanded;
  2417. if (IsIPv6Literal(AHostName))
  2418. {
  2419. AHostName = EscapeIPv6Literal(AHostName);
  2420. }
  2421. TunnelData->TunnelPortFwd = FORMAT(L"L%d\t%s:%d",
  2422. (TunnelLocalPortNumber, AHostName, PortNumber));
  2423. TunnelData->HostKey = TunnelHostKey;
  2424. // inherit proxy options on the main session
  2425. TunnelData->ProxyMethod = ProxyMethod;
  2426. TunnelData->ProxyHost = ProxyHost;
  2427. TunnelData->ProxyPort = ProxyPort;
  2428. TunnelData->ProxyUsername = ProxyUsername;
  2429. TunnelData->ProxyPassword = ProxyPassword;
  2430. TunnelData->ProxyTelnetCommand = ProxyTelnetCommand;
  2431. TunnelData->ProxyLocalCommand = ProxyLocalCommand;
  2432. TunnelData->ProxyDNS = ProxyDNS;
  2433. TunnelData->ProxyLocalhost = ProxyLocalhost;
  2434. // inherit most SSH options of the main session (except for private key and bugs)
  2435. TunnelData->Compression = Compression;
  2436. TunnelData->CipherList = CipherList;
  2437. TunnelData->Ssh2DES = Ssh2DES;
  2438. TunnelData->KexList = KexList;
  2439. TunnelData->RekeyData = RekeyData;
  2440. TunnelData->RekeyTime = RekeyTime;
  2441. TunnelData->SshNoUserAuth = SshNoUserAuth;
  2442. TunnelData->AuthGSSAPI = AuthGSSAPI;
  2443. TunnelData->AuthGSSAPIKEX = AuthGSSAPIKEX;
  2444. TunnelData->GSSAPIFwdTGT = GSSAPIFwdTGT;
  2445. TunnelData->TryAgent = TryAgent;
  2446. TunnelData->AgentFwd = AgentFwd;
  2447. TunnelData->AuthKI = AuthKI;
  2448. TunnelData->AuthKIPassword = AuthKIPassword;
  2449. return TunnelData.release();
  2450. }
  2451. //---------------------------------------------------------------------
  2452. void __fastcall TSessionData::ExpandEnvironmentVariables()
  2453. {
  2454. HostName = HostNameExpanded;
  2455. UserName = UserNameExpanded;
  2456. PublicKeyFile = ::ExpandEnvironmentVariables(PublicKeyFile);
  2457. }
  2458. //---------------------------------------------------------------------
  2459. void __fastcall TSessionData::ValidatePath(const UnicodeString Path)
  2460. {
  2461. // noop
  2462. }
  2463. //---------------------------------------------------------------------
  2464. void __fastcall TSessionData::ValidateName(const UnicodeString Name)
  2465. {
  2466. // keep consistent with MakeValidName
  2467. if (Name.LastDelimiter(L"/") > 0)
  2468. {
  2469. throw Exception(FMTLOAD(ITEM_NAME_INVALID, (Name, L"/")));
  2470. }
  2471. }
  2472. //---------------------------------------------------------------------
  2473. UnicodeString __fastcall TSessionData::MakeValidName(const UnicodeString & Name)
  2474. {
  2475. // keep consistent with ValidateName
  2476. return ReplaceStr(Name, L"/", L"\\");
  2477. }
  2478. //---------------------------------------------------------------------
  2479. RawByteString __fastcall TSessionData::EncryptPassword(const UnicodeString & Password, UnicodeString Key)
  2480. {
  2481. return Configuration->EncryptPassword(Password, Key);
  2482. }
  2483. //---------------------------------------------------------------------
  2484. RawByteString __fastcall TSessionData::StronglyRecryptPassword(const RawByteString & Password, UnicodeString Key)
  2485. {
  2486. return Configuration->StronglyRecryptPassword(Password, Key);
  2487. }
  2488. //---------------------------------------------------------------------
  2489. UnicodeString __fastcall TSessionData::DecryptPassword(const RawByteString & Password, UnicodeString Key)
  2490. {
  2491. UnicodeString Result;
  2492. try
  2493. {
  2494. Result = Configuration->DecryptPassword(Password, Key);
  2495. }
  2496. catch(EAbort &)
  2497. {
  2498. // silently ignore aborted prompts for master password and return empty password
  2499. }
  2500. return Result;
  2501. }
  2502. //---------------------------------------------------------------------
  2503. bool __fastcall TSessionData::GetCanLogin()
  2504. {
  2505. return !FHostName.IsEmpty();
  2506. }
  2507. //---------------------------------------------------------------------
  2508. bool __fastcall TSessionData::GetIsLocalBrowser()
  2509. {
  2510. return !LocalDirectory.IsEmpty() && !OtherLocalDirectory.IsEmpty();
  2511. }
  2512. //---------------------------------------------------------------------
  2513. bool __fastcall TSessionData::GetCanOpen()
  2514. {
  2515. return CanLogin || IsLocalBrowser;
  2516. }
  2517. //---------------------------------------------------------------------------
  2518. int TSessionData::GetDefaultPort()
  2519. {
  2520. return DefaultPort(FSProtocol, Ftps);
  2521. }
  2522. //---------------------------------------------------------------------------
  2523. UnicodeString __fastcall TSessionData::GetSessionKey()
  2524. {
  2525. UnicodeString Result = FORMAT(L"%s@%s", (UserName, HostName));
  2526. if (PortNumber != GetDefaultPort())
  2527. {
  2528. Result += FORMAT(L":%d", (PortNumber));
  2529. }
  2530. return Result;
  2531. }
  2532. //---------------------------------------------------------------------
  2533. UnicodeString __fastcall TSessionData::GetInternalStorageKey()
  2534. {
  2535. // This is probably useless remnant of previous use of this method from OpenSessionInPutty
  2536. // that needs the method to return something even for ad-hoc sessions
  2537. if (Name.IsEmpty())
  2538. {
  2539. return SessionKey;
  2540. }
  2541. else
  2542. {
  2543. return Name;
  2544. }
  2545. }
  2546. //---------------------------------------------------------------------
  2547. UnicodeString __fastcall TSessionData::GetStorageKey()
  2548. {
  2549. return SessionName;
  2550. }
  2551. //---------------------------------------------------------------------
  2552. UnicodeString __fastcall TSessionData::FormatSiteKey(const UnicodeString & HostName, int PortNumber)
  2553. {
  2554. return FORMAT(L"%s:%d", (HostName, PortNumber));
  2555. }
  2556. //---------------------------------------------------------------------
  2557. UnicodeString __fastcall TSessionData::GetSiteKey()
  2558. {
  2559. return FormatSiteKey(HostNameExpanded, PortNumber);
  2560. }
  2561. //---------------------------------------------------------------------
  2562. void __fastcall TSessionData::SetHostName(UnicodeString value)
  2563. {
  2564. if (FHostName != value)
  2565. {
  2566. // HostName is key for password encryption
  2567. UnicodeString XPassword = Password;
  2568. UnicodeString XNewPassword = NewPassword;
  2569. UnicodeString XEncryptKey = EncryptKey;
  2570. // This is now hardly used as hostname is parsed directly on login dialog.
  2571. // But can be used when importing sites from PuTTY, as it allows same format too.
  2572. int P = value.LastDelimiter(L"@");
  2573. if (P > 0)
  2574. {
  2575. UserName = value.SubString(1, P - 1);
  2576. value = value.SubString(P + 1, value.Length() - P);
  2577. }
  2578. FHostName = value;
  2579. Modify();
  2580. Password = XPassword;
  2581. NewPassword = XNewPassword;
  2582. EncryptKey = XEncryptKey;
  2583. Shred(XPassword);
  2584. Shred(XNewPassword);
  2585. Shred(XEncryptKey);
  2586. }
  2587. }
  2588. //---------------------------------------------------------------------
  2589. UnicodeString __fastcall TSessionData::GetHostNameExpanded()
  2590. {
  2591. return ::ExpandEnvironmentVariables(HostName);
  2592. }
  2593. //---------------------------------------------------------------------
  2594. UnicodeString TSessionData::GetHostNameSource()
  2595. {
  2596. UnicodeString Result;
  2597. if (HostName != HostNameExpanded)
  2598. {
  2599. Result = HostName;
  2600. }
  2601. return Result;
  2602. }
  2603. //---------------------------------------------------------------------
  2604. void __fastcall TSessionData::SetPortNumber(int value)
  2605. {
  2606. SET_SESSION_PROPERTY(PortNumber);
  2607. }
  2608. //---------------------------------------------------------------------------
  2609. void __fastcall TSessionData::SetShell(UnicodeString value)
  2610. {
  2611. SET_SESSION_PROPERTY(Shell);
  2612. }
  2613. //---------------------------------------------------------------------------
  2614. void __fastcall TSessionData::SetSftpServer(UnicodeString value)
  2615. {
  2616. SET_SESSION_PROPERTY(SftpServer);
  2617. }
  2618. //---------------------------------------------------------------------------
  2619. void __fastcall TSessionData::SetClearAliases(bool value)
  2620. {
  2621. SET_SESSION_PROPERTY(ClearAliases);
  2622. }
  2623. //---------------------------------------------------------------------------
  2624. void __fastcall TSessionData::SetListingCommand(UnicodeString value)
  2625. {
  2626. SET_SESSION_PROPERTY(ListingCommand);
  2627. }
  2628. //---------------------------------------------------------------------------
  2629. void __fastcall TSessionData::SetIgnoreLsWarnings(bool value)
  2630. {
  2631. SET_SESSION_PROPERTY(IgnoreLsWarnings);
  2632. }
  2633. //---------------------------------------------------------------------------
  2634. void __fastcall TSessionData::SetUnsetNationalVars(bool value)
  2635. {
  2636. SET_SESSION_PROPERTY(UnsetNationalVars);
  2637. }
  2638. //---------------------------------------------------------------------
  2639. void __fastcall TSessionData::SetUserName(UnicodeString value)
  2640. {
  2641. // Avoid password recryption (what may popup master password prompt)
  2642. if (FUserName != value)
  2643. {
  2644. // UserName is key for password encryption
  2645. UnicodeString XPassword = Password;
  2646. UnicodeString XNewPassword = NewPassword;
  2647. UnicodeString XEncryptKey = EncryptKey;
  2648. SET_SESSION_PROPERTY(UserName);
  2649. Password = XPassword;
  2650. NewPassword = XNewPassword;
  2651. EncryptKey = XEncryptKey;
  2652. Shred(XPassword);
  2653. Shred(XNewPassword);
  2654. Shred(XEncryptKey);
  2655. }
  2656. }
  2657. //---------------------------------------------------------------------
  2658. UnicodeString __fastcall TSessionData::GetUserNameExpanded()
  2659. {
  2660. UnicodeString Result = ::ExpandEnvironmentVariables(UserName);
  2661. if (Result.IsEmpty() && HasS3AutoCredentials())
  2662. {
  2663. Result = S3EnvUserName();
  2664. }
  2665. return Result;
  2666. }
  2667. //---------------------------------------------------------------------
  2668. UnicodeString TSessionData::GetUserNameSource()
  2669. {
  2670. UnicodeString Result;
  2671. if (UserName.IsEmpty() && HasS3AutoCredentials())
  2672. {
  2673. S3EnvUserName(&Result);
  2674. }
  2675. if (Result.IsEmpty() && (UserName != UserNameExpanded))
  2676. {
  2677. Result = UserName;
  2678. }
  2679. return Result;
  2680. }
  2681. //---------------------------------------------------------------------
  2682. void __fastcall TSessionData::SetPassword(UnicodeString avalue)
  2683. {
  2684. RawByteString value = EncryptPassword(avalue, UserName+HostName);
  2685. SET_SESSION_PROPERTY(Password);
  2686. }
  2687. //---------------------------------------------------------------------
  2688. UnicodeString __fastcall TSessionData::GetPassword() const
  2689. {
  2690. return DecryptPassword(FPassword, UserName+HostName);
  2691. }
  2692. //---------------------------------------------------------------------
  2693. void __fastcall TSessionData::SetNewPassword(UnicodeString avalue)
  2694. {
  2695. RawByteString value = EncryptPassword(avalue, UserName+HostName);
  2696. SET_SESSION_PROPERTY(NewPassword);
  2697. }
  2698. //---------------------------------------------------------------------
  2699. UnicodeString __fastcall TSessionData::GetNewPassword() const
  2700. {
  2701. return DecryptPassword(FNewPassword, UserName+HostName);
  2702. }
  2703. //---------------------------------------------------------------------
  2704. void __fastcall TSessionData::SetChangePassword(bool value)
  2705. {
  2706. SET_SESSION_PROPERTY(ChangePassword);
  2707. }
  2708. //---------------------------------------------------------------------
  2709. void __fastcall TSessionData::SetPingInterval(int value)
  2710. {
  2711. SET_SESSION_PROPERTY(PingInterval);
  2712. }
  2713. //---------------------------------------------------------------------
  2714. void __fastcall TSessionData::SetTryAgent(bool value)
  2715. {
  2716. SET_SESSION_PROPERTY(TryAgent);
  2717. }
  2718. //---------------------------------------------------------------------
  2719. void __fastcall TSessionData::SetAgentFwd(bool value)
  2720. {
  2721. SET_SESSION_PROPERTY(AgentFwd);
  2722. }
  2723. //---------------------------------------------------------------------
  2724. void __fastcall TSessionData::SetAuthKI(bool value)
  2725. {
  2726. SET_SESSION_PROPERTY(AuthKI);
  2727. }
  2728. //---------------------------------------------------------------------
  2729. void __fastcall TSessionData::SetAuthKIPassword(bool value)
  2730. {
  2731. SET_SESSION_PROPERTY(AuthKIPassword);
  2732. }
  2733. //---------------------------------------------------------------------
  2734. void __fastcall TSessionData::SetAuthGSSAPI(bool value)
  2735. {
  2736. SET_SESSION_PROPERTY(AuthGSSAPI);
  2737. }
  2738. //---------------------------------------------------------------------
  2739. void __fastcall TSessionData::SetAuthGSSAPIKEX(bool value)
  2740. {
  2741. SET_SESSION_PROPERTY(AuthGSSAPIKEX);
  2742. }
  2743. //---------------------------------------------------------------------
  2744. void __fastcall TSessionData::SetGSSAPIFwdTGT(bool value)
  2745. {
  2746. SET_SESSION_PROPERTY(GSSAPIFwdTGT);
  2747. }
  2748. //---------------------------------------------------------------------
  2749. void __fastcall TSessionData::SetChangeUsername(bool value)
  2750. {
  2751. SET_SESSION_PROPERTY(ChangeUsername);
  2752. }
  2753. //---------------------------------------------------------------------
  2754. void __fastcall TSessionData::SetCompression(bool value)
  2755. {
  2756. SET_SESSION_PROPERTY(Compression);
  2757. }
  2758. //---------------------------------------------------------------------
  2759. void __fastcall TSessionData::SetSsh2DES(bool value)
  2760. {
  2761. SET_SESSION_PROPERTY(Ssh2DES);
  2762. }
  2763. //---------------------------------------------------------------------
  2764. void __fastcall TSessionData::SetSshNoUserAuth(bool value)
  2765. {
  2766. SET_SESSION_PROPERTY(SshNoUserAuth);
  2767. }
  2768. //---------------------------------------------------------------------
  2769. bool __fastcall TSessionData::GetUsesSsh()
  2770. {
  2771. return IsSshProtocol(FSProtocol);
  2772. }
  2773. //---------------------------------------------------------------------
  2774. void __fastcall TSessionData::SetCipher(int Index, TCipher value)
  2775. {
  2776. DebugAssert(Index >= 0 && Index < CIPHER_COUNT);
  2777. SET_SESSION_PROPERTY(Ciphers[Index]);
  2778. }
  2779. //---------------------------------------------------------------------
  2780. TCipher __fastcall TSessionData::GetCipher(int Index) const
  2781. {
  2782. DebugAssert(Index >= 0 && Index < CIPHER_COUNT);
  2783. return FCiphers[Index];
  2784. }
  2785. //---------------------------------------------------------------------
  2786. template<class AlgoT>
  2787. void __fastcall TSessionData::SetAlgoList(AlgoT * List, const AlgoT * DefaultList, const UnicodeString * Names,
  2788. int Count, AlgoT WarnAlgo, UnicodeString value)
  2789. {
  2790. std::vector<bool> Used(Count); // initialized to false
  2791. std::vector<AlgoT> NewList(Count);
  2792. bool HasWarnAlgo = (WarnAlgo >= AlgoT());
  2793. const AlgoT * WarnPtr;
  2794. int WarnDefaultIndex;
  2795. if (!HasWarnAlgo)
  2796. {
  2797. WarnPtr = NULL;
  2798. WarnDefaultIndex = -1;
  2799. }
  2800. else
  2801. {
  2802. WarnPtr = std::find(DefaultList, DefaultList + Count, WarnAlgo);
  2803. DebugAssert(WarnPtr != NULL);
  2804. WarnDefaultIndex = (WarnPtr - DefaultList);
  2805. }
  2806. int Index = 0;
  2807. while (!value.IsEmpty())
  2808. {
  2809. UnicodeString AlgoStr = CutToChar(value, L',', true);
  2810. for (int Algo = 0; Algo < Count; Algo++)
  2811. {
  2812. if (!AlgoStr.CompareIC(Names[Algo]) &&
  2813. !Used[Algo] && DebugAlwaysTrue(Index < Count))
  2814. {
  2815. NewList[Index] = (AlgoT)Algo;
  2816. Used[Algo] = true;
  2817. Index++;
  2818. break;
  2819. }
  2820. }
  2821. }
  2822. if (HasWarnAlgo && !Used[WarnAlgo] && DebugAlwaysTrue(Index < Count))
  2823. {
  2824. NewList[Index] = WarnAlgo;
  2825. Used[WarnAlgo] = true;
  2826. Index++;
  2827. }
  2828. int WarnIndex = -1;
  2829. if (HasWarnAlgo)
  2830. {
  2831. WarnIndex = std::find(NewList.begin(), NewList.end(), WarnAlgo) - NewList.begin();
  2832. }
  2833. bool Priority = true;
  2834. for (int DefaultIndex = 0; (DefaultIndex < Count); DefaultIndex++)
  2835. {
  2836. AlgoT DefaultAlgo = DefaultList[DefaultIndex];
  2837. if (!Used[DefaultAlgo] && DebugAlwaysTrue(Index < Count))
  2838. {
  2839. int TargetIndex;
  2840. // Unused algs that are prioritized in the default list,
  2841. // should be merged before the existing custom list
  2842. if (Priority)
  2843. {
  2844. TargetIndex = DefaultIndex;
  2845. }
  2846. else
  2847. {
  2848. if (HasWarnAlgo && (DefaultIndex < WarnDefaultIndex))
  2849. {
  2850. TargetIndex = WarnIndex;
  2851. }
  2852. else
  2853. {
  2854. TargetIndex = Index;
  2855. }
  2856. }
  2857. NewList.insert(NewList.begin() + TargetIndex, DefaultAlgo);
  2858. DebugAssert(NewList.back() == AlgoT());
  2859. NewList.pop_back();
  2860. if (HasWarnAlgo && (TargetIndex <= WarnIndex))
  2861. {
  2862. WarnIndex++;
  2863. }
  2864. Index++;
  2865. }
  2866. else
  2867. {
  2868. Priority = false;
  2869. }
  2870. }
  2871. if (!std::equal(NewList.begin(), NewList.end(), List))
  2872. {
  2873. std::copy(NewList.begin(), NewList.end(), List);
  2874. Modify();
  2875. }
  2876. }
  2877. //---------------------------------------------------------------------
  2878. void __fastcall TSessionData::SetCipherList(UnicodeString value)
  2879. {
  2880. SetAlgoList(FCiphers, DefaultCipherList, CipherNames, CIPHER_COUNT, cipWarn, value);
  2881. }
  2882. //---------------------------------------------------------------------
  2883. UnicodeString __fastcall TSessionData::GetCipherList() const
  2884. {
  2885. UnicodeString Result;
  2886. for (int Index = 0; Index < CIPHER_COUNT; Index++)
  2887. {
  2888. Result += UnicodeString(Index ? L"," : L"") + CipherNames[Cipher[Index]];
  2889. }
  2890. return Result;
  2891. }
  2892. //---------------------------------------------------------------------
  2893. void __fastcall TSessionData::SetKex(int Index, TKex value)
  2894. {
  2895. DebugAssert(Index >= 0 && Index < KEX_COUNT);
  2896. SET_SESSION_PROPERTY(Kex[Index]);
  2897. }
  2898. //---------------------------------------------------------------------
  2899. TKex __fastcall TSessionData::GetKex(int Index) const
  2900. {
  2901. DebugAssert(Index >= 0 && Index < KEX_COUNT);
  2902. return FKex[Index];
  2903. }
  2904. //---------------------------------------------------------------------
  2905. void __fastcall TSessionData::SetKexList(UnicodeString value)
  2906. {
  2907. SetAlgoList(FKex, DefaultKexList, KexNames, KEX_COUNT, kexWarn, value);
  2908. }
  2909. //---------------------------------------------------------------------
  2910. UnicodeString __fastcall TSessionData::GetKexList() const
  2911. {
  2912. UnicodeString Result;
  2913. for (int Index = 0; Index < KEX_COUNT; Index++)
  2914. {
  2915. Result += UnicodeString(Index ? L"," : L"") + KexNames[Kex[Index]];
  2916. }
  2917. return Result;
  2918. }
  2919. //---------------------------------------------------------------------
  2920. void __fastcall TSessionData::SetHostKeys(int Index, THostKey value)
  2921. {
  2922. DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);
  2923. SET_SESSION_PROPERTY(HostKeys[Index]);
  2924. }
  2925. //---------------------------------------------------------------------
  2926. THostKey __fastcall TSessionData::GetHostKeys(int Index) const
  2927. {
  2928. DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);
  2929. return FHostKeys[Index];
  2930. }
  2931. //---------------------------------------------------------------------
  2932. void __fastcall TSessionData::SetHostKeyList(UnicodeString value)
  2933. {
  2934. SetAlgoList(FHostKeys, DefaultHostKeyList, HostKeyNames, HOSTKEY_COUNT, hkWarn, value);
  2935. }
  2936. //---------------------------------------------------------------------
  2937. UnicodeString __fastcall TSessionData::GetHostKeyList() const
  2938. {
  2939. UnicodeString Result;
  2940. for (int Index = 0; Index < HOSTKEY_COUNT; Index++)
  2941. {
  2942. Result += UnicodeString(Index ? L"," : L"") + HostKeyNames[HostKeys[Index]];
  2943. }
  2944. return Result;
  2945. }
  2946. //---------------------------------------------------------------------
  2947. void __fastcall TSessionData::SetGssLib(int Index, TGssLib value)
  2948. {
  2949. DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);
  2950. SET_SESSION_PROPERTY(GssLib[Index]);
  2951. }
  2952. //---------------------------------------------------------------------
  2953. TGssLib __fastcall TSessionData::GetGssLib(int Index) const
  2954. {
  2955. DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);
  2956. return FGssLib[Index];
  2957. }
  2958. //---------------------------------------------------------------------
  2959. void __fastcall TSessionData::SetGssLibList(UnicodeString value)
  2960. {
  2961. SetAlgoList(FGssLib, DefaultGssLibList, GssLibNames, GSSLIB_COUNT, TGssLib(-1), value);
  2962. }
  2963. //---------------------------------------------------------------------
  2964. UnicodeString __fastcall TSessionData::GetGssLibList() const
  2965. {
  2966. UnicodeString Result;
  2967. for (int Index = 0; Index < GSSLIB_COUNT; Index++)
  2968. {
  2969. Result += UnicodeString(Index ? L"," : L"") + GssLibNames[GssLib[Index]];
  2970. }
  2971. return Result;
  2972. }
  2973. //---------------------------------------------------------------------
  2974. void __fastcall TSessionData::SetGssLibCustom(UnicodeString value)
  2975. {
  2976. SET_SESSION_PROPERTY(GssLibCustom);
  2977. }
  2978. //---------------------------------------------------------------------
  2979. void __fastcall TSessionData::SetPublicKeyFile(UnicodeString value)
  2980. {
  2981. if (FPublicKeyFile != value)
  2982. {
  2983. // PublicKeyFile is key for Passphrase encryption
  2984. UnicodeString XPassphrase = Passphrase;
  2985. // StripPathQuotes should not be needed as we do not feed quotes anymore
  2986. FPublicKeyFile = StripPathQuotes(value);
  2987. Modify();
  2988. Passphrase = XPassphrase;
  2989. Shred(XPassphrase);
  2990. }
  2991. }
  2992. //---------------------------------------------------------------------
  2993. UnicodeString TSessionData::ResolvePublicKeyFile()
  2994. {
  2995. UnicodeString Result = PublicKeyFile;
  2996. if (Result.IsEmpty())
  2997. {
  2998. Result = Configuration->DefaultKeyFile;
  2999. }
  3000. // StripPathQuotes should not be needed as we do not feed quotes anymore
  3001. Result = StripPathQuotes(::ExpandEnvironmentVariables(Result));
  3002. return Result;
  3003. }
  3004. //---------------------------------------------------------------------
  3005. void __fastcall TSessionData::SetPassphrase(UnicodeString avalue)
  3006. {
  3007. RawByteString value = EncryptPassword(avalue, PublicKeyFile);
  3008. SET_SESSION_PROPERTY(Passphrase);
  3009. }
  3010. //---------------------------------------------------------------------
  3011. UnicodeString __fastcall TSessionData::GetPassphrase() const
  3012. {
  3013. return DecryptPassword(FPassphrase, PublicKeyFile);
  3014. }
  3015. //---------------------------------------------------------------------
  3016. void __fastcall TSessionData::SetReturnVar(UnicodeString value)
  3017. {
  3018. SET_SESSION_PROPERTY(ReturnVar);
  3019. }
  3020. //---------------------------------------------------------------------
  3021. void __fastcall TSessionData::SetExitCode1IsError(bool value)
  3022. {
  3023. SET_SESSION_PROPERTY(ExitCode1IsError);
  3024. }
  3025. //---------------------------------------------------------------------------
  3026. void __fastcall TSessionData::SetLookupUserGroups(TAutoSwitch value)
  3027. {
  3028. SET_SESSION_PROPERTY(LookupUserGroups);
  3029. }
  3030. //---------------------------------------------------------------------------
  3031. void __fastcall TSessionData::SetEOLType(TEOLType value)
  3032. {
  3033. SET_SESSION_PROPERTY(EOLType);
  3034. }
  3035. //---------------------------------------------------------------------------
  3036. void __fastcall TSessionData::SetTrimVMSVersions(bool value)
  3037. {
  3038. SET_SESSION_PROPERTY(TrimVMSVersions);
  3039. }
  3040. //---------------------------------------------------------------------------
  3041. void __fastcall TSessionData::SetVMSAllRevisions(bool value)
  3042. {
  3043. SET_SESSION_PROPERTY(VMSAllRevisions);
  3044. }
  3045. //---------------------------------------------------------------------------
  3046. TDateTime __fastcall TSessionData::GetTimeoutDT()
  3047. {
  3048. return SecToDateTime(Timeout);
  3049. }
  3050. //---------------------------------------------------------------------------
  3051. void __fastcall TSessionData::SetTimeout(int value)
  3052. {
  3053. SET_SESSION_PROPERTY(Timeout);
  3054. }
  3055. //---------------------------------------------------------------------------
  3056. void __fastcall TSessionData::SetFSProtocol(TFSProtocol value)
  3057. {
  3058. SET_SESSION_PROPERTY(FSProtocol);
  3059. }
  3060. //---------------------------------------------------------------------
  3061. UnicodeString __fastcall TSessionData::GetFSProtocolStr()
  3062. {
  3063. DebugAssert(FSProtocol >= 0 && FSProtocol < FSPROTOCOL_COUNT);
  3064. return FSProtocolNames[FSProtocol];
  3065. }
  3066. //---------------------------------------------------------------------------
  3067. void __fastcall TSessionData::SetDetectReturnVar(bool value)
  3068. {
  3069. if (value != DetectReturnVar)
  3070. {
  3071. ReturnVar = value ? L"" : L"$?";
  3072. }
  3073. }
  3074. //---------------------------------------------------------------------------
  3075. bool __fastcall TSessionData::GetDetectReturnVar()
  3076. {
  3077. return ReturnVar.IsEmpty();
  3078. }
  3079. //---------------------------------------------------------------------------
  3080. void __fastcall TSessionData::SetDefaultShell(bool value)
  3081. {
  3082. if (value != DefaultShell)
  3083. {
  3084. Shell = value ? L"" : L"/bin/bash";
  3085. }
  3086. }
  3087. //---------------------------------------------------------------------------
  3088. bool __fastcall TSessionData::GetDefaultShell()
  3089. {
  3090. return Shell.IsEmpty();
  3091. }
  3092. //---------------------------------------------------------------------------
  3093. void __fastcall TSessionData::SetPuttyProtocol(UnicodeString value)
  3094. {
  3095. SET_SESSION_PROPERTY(PuttyProtocol);
  3096. }
  3097. //---------------------------------------------------------------------
  3098. UnicodeString __fastcall TSessionData::GetNormalizedPuttyProtocol() const
  3099. {
  3100. return DefaultStr(PuttyProtocol, PuttySshProtocol);
  3101. }
  3102. //---------------------------------------------------------------------
  3103. void __fastcall TSessionData::SetPingIntervalDT(TDateTime value)
  3104. {
  3105. unsigned short hour, min, sec, msec;
  3106. value.DecodeTime(&hour, &min, &sec, &msec);
  3107. PingInterval = ((int)hour)*SecsPerHour + ((int)min)*SecsPerMin + sec;
  3108. }
  3109. //---------------------------------------------------------------------------
  3110. TDateTime __fastcall TSessionData::GetPingIntervalDT()
  3111. {
  3112. return SecToDateTime(PingInterval);
  3113. }
  3114. //---------------------------------------------------------------------------
  3115. void __fastcall TSessionData::SetPingType(TPingType value)
  3116. {
  3117. SET_SESSION_PROPERTY(PingType);
  3118. }
  3119. //---------------------------------------------------------------------------
  3120. void __fastcall TSessionData::SetAddressFamily(TAddressFamily value)
  3121. {
  3122. SET_SESSION_PROPERTY(AddressFamily);
  3123. }
  3124. //---------------------------------------------------------------------------
  3125. void __fastcall TSessionData::SetRekeyData(UnicodeString value)
  3126. {
  3127. SET_SESSION_PROPERTY(RekeyData);
  3128. }
  3129. //---------------------------------------------------------------------------
  3130. void __fastcall TSessionData::SetRekeyTime(unsigned int value)
  3131. {
  3132. SET_SESSION_PROPERTY(RekeyTime);
  3133. }
  3134. //---------------------------------------------------------------------
  3135. UnicodeString __fastcall TSessionData::GetDefaultSessionName()
  3136. {
  3137. UnicodeString Result;
  3138. if (IsLocalBrowser)
  3139. {
  3140. // See also TScpCommanderForm::GetLocalBrowserSessionTitle
  3141. UnicodeString Path1 = ExtractShortName(LocalDirectory, false);
  3142. UnicodeString Path2 = ExtractShortName(OtherLocalDirectory, false);
  3143. Result = Path1 + TitleSeparator + Path2;
  3144. }
  3145. else if (!HostName.IsEmpty() && !UserName.IsEmpty())
  3146. {
  3147. // If we ever choose to include port number,
  3148. // we have to escape IPv6 literals in HostName
  3149. Result = FORMAT(L"%s@%s", (UserName, HostName));
  3150. }
  3151. else if (!HostName.IsEmpty())
  3152. {
  3153. Result = HostName;
  3154. }
  3155. else
  3156. {
  3157. Result = L"session";
  3158. }
  3159. Result = MakeValidName(Result);
  3160. return Result;
  3161. }
  3162. //---------------------------------------------------------------------
  3163. UnicodeString __fastcall TSessionData::GetNameWithoutHiddenPrefix()
  3164. {
  3165. UnicodeString Result = Name;
  3166. if (Hidden)
  3167. {
  3168. Result = Result.SubString(TNamedObjectList::HiddenPrefix.Length() + 1, Result.Length() - TNamedObjectList::HiddenPrefix.Length());
  3169. }
  3170. return Result;
  3171. }
  3172. //---------------------------------------------------------------------
  3173. bool __fastcall TSessionData::HasSessionName()
  3174. {
  3175. return (!GetNameWithoutHiddenPrefix().IsEmpty() && (Name != DefaultName));
  3176. }
  3177. //---------------------------------------------------------------------
  3178. UnicodeString __fastcall TSessionData::GetSessionName()
  3179. {
  3180. UnicodeString Result;
  3181. if (HasSessionName())
  3182. {
  3183. Result = GetNameWithoutHiddenPrefix();
  3184. }
  3185. else
  3186. {
  3187. Result = DefaultSessionName;
  3188. }
  3189. return Result;
  3190. }
  3191. //---------------------------------------------------------------------
  3192. bool __fastcall TSessionData::IsSecure()
  3193. {
  3194. bool Result;
  3195. switch (FSProtocol)
  3196. {
  3197. case fsSCPonly:
  3198. case fsSFTP:
  3199. case fsSFTPonly:
  3200. Result = true;
  3201. break;
  3202. case fsFTP:
  3203. case fsWebDAV:
  3204. case fsS3:
  3205. Result = (Ftps != ftpsNone);
  3206. break;
  3207. default:
  3208. DebugFail();
  3209. break;
  3210. }
  3211. return Result;
  3212. }
  3213. //---------------------------------------------------------------------
  3214. UnicodeString __fastcall TSessionData::GetProtocolUrl(bool HttpForWebDAV)
  3215. {
  3216. UnicodeString Url;
  3217. switch (FSProtocol)
  3218. {
  3219. case fsSCPonly:
  3220. Url = ScpProtocol;
  3221. break;
  3222. default:
  3223. DebugFail();
  3224. // fallback
  3225. case fsSFTP:
  3226. case fsSFTPonly:
  3227. Url = SftpProtocol;
  3228. break;
  3229. case fsFTP:
  3230. if (Ftps == ftpsImplicit)
  3231. {
  3232. Url = FtpsProtocol;
  3233. }
  3234. else if ((Ftps == ftpsExplicitTls) || (Ftps == ftpsExplicitSsl))
  3235. {
  3236. Url = FtpesProtocol;
  3237. }
  3238. else
  3239. {
  3240. Url = FtpProtocol;
  3241. }
  3242. break;
  3243. case fsWebDAV:
  3244. if (HttpForWebDAV)
  3245. {
  3246. if (Ftps == ftpsImplicit)
  3247. {
  3248. Url = HttpsProtocol;
  3249. }
  3250. else
  3251. {
  3252. Url = HttpProtocol;
  3253. }
  3254. }
  3255. else
  3256. {
  3257. if (Ftps == ftpsImplicit)
  3258. {
  3259. Url = WebDAVSProtocol;
  3260. }
  3261. else
  3262. {
  3263. Url = WebDAVProtocol;
  3264. }
  3265. }
  3266. break;
  3267. case fsS3:
  3268. if (Ftps == ftpsImplicit)
  3269. {
  3270. Url = S3Protocol;
  3271. }
  3272. else
  3273. {
  3274. Url = S3PlainProtocol;
  3275. }
  3276. break;
  3277. }
  3278. Url += ProtocolSeparator;
  3279. return Url;
  3280. }
  3281. //---------------------------------------------------------------------
  3282. static bool HasIP6LiteralBrackets(const UnicodeString & HostName)
  3283. {
  3284. return
  3285. (HostName.Length() >= 2) &&
  3286. (HostName[1] == L'[') &&
  3287. (HostName[HostName.Length()] == L']');
  3288. }
  3289. //---------------------------------------------------------------------
  3290. static UnicodeString StripIP6LiteralBrackets(const UnicodeString & HostName)
  3291. {
  3292. UnicodeString Result = HostName;
  3293. if (DebugAlwaysTrue(HasIP6LiteralBrackets(Result)))
  3294. {
  3295. Result = Result.SubString(2, Result.Length() - 2);
  3296. }
  3297. return Result;
  3298. }
  3299. //---------------------------------------------------------------------
  3300. bool __fastcall IsIPv6Literal(const UnicodeString & HostName)
  3301. {
  3302. UnicodeString Buf = HostName;
  3303. if (HasIP6LiteralBrackets(Buf))
  3304. {
  3305. Buf = StripIP6LiteralBrackets(Buf);
  3306. }
  3307. int Colons = 0;
  3308. bool Result = true;
  3309. for (int Index = 1; Result && (Index <= Buf.Length()); Index++)
  3310. {
  3311. wchar_t C = Buf[Index];
  3312. if (C == L'%')
  3313. {
  3314. break;
  3315. }
  3316. else if (C == L':')
  3317. {
  3318. Colons++;
  3319. }
  3320. else
  3321. {
  3322. Result = IsHex(C);
  3323. }
  3324. }
  3325. Result = Result && (Colons >= 2);
  3326. return Result;
  3327. }
  3328. //---------------------------------------------------------------------
  3329. UnicodeString __fastcall EscapeIPv6Literal(const UnicodeString & IP)
  3330. {
  3331. UnicodeString Result = IP;
  3332. if (!HasIP6LiteralBrackets(Result))
  3333. {
  3334. Result = L"[" + IP + L"]";
  3335. }
  3336. return Result;
  3337. }
  3338. //---------------------------------------------------------------------
  3339. TStrings * __fastcall TSessionData::GetRawSettingsForUrl()
  3340. {
  3341. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3342. std::unique_ptr<TSessionData> SessionData(Clone());
  3343. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3344. SessionData->HostName = FactoryDefaults->HostName;
  3345. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3346. SessionData->UserName = FactoryDefaults->UserName;
  3347. SessionData->Password = FactoryDefaults->Password;
  3348. SessionData->Ftps = FactoryDefaults->Ftps;
  3349. SessionData->HostKey = FactoryDefaults->HostKey;
  3350. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3351. // Cannot be decided in SaveToOptions as it does not have HostName and UserName, so it cannot calculate DefaultSessionName.
  3352. bool SaveName = HasSessionName() && (Name != DefaultSessionName);
  3353. return SessionData->SaveToOptions(FactoryDefaults.get(), SaveName, false);
  3354. }
  3355. //---------------------------------------------------------------------
  3356. bool __fastcall TSessionData::HasRawSettingsForUrl()
  3357. {
  3358. std::unique_ptr<TStrings> RawSettings(GetRawSettingsForUrl());
  3359. return (RawSettings->Count > 0);
  3360. }
  3361. //---------------------------------------------------------------------
  3362. UnicodeString __fastcall TSessionData::GenerateSessionUrl(unsigned int Flags)
  3363. {
  3364. UnicodeString Url;
  3365. if (FLAGSET(Flags, sufSpecific))
  3366. {
  3367. Url += WinSCPProtocolPrefix;
  3368. }
  3369. Url += GetProtocolUrl(FLAGSET(Flags, sufHttpForWebDAV));
  3370. // Add username only if it was somehow explicitly specified (so not with S3CredentialsEnv), but if it was, add it in the expanded form.
  3371. // For scripting, we might use unexpanded form (keeping the environment variables),
  3372. // but for consistency with code generation (where explicit expansion code would need to be added), we do not.
  3373. if (FLAGSET(Flags, sufUserName) && !UserName.IsEmpty())
  3374. {
  3375. Url += EncodeUrlString(UserNameExpanded);
  3376. if (FLAGSET(Flags, sufPassword) && !Password.IsEmpty())
  3377. {
  3378. Url += L":" + EncodeUrlString(NormalizeString(Password));
  3379. }
  3380. if (FLAGSET(Flags, sufHostKey) && !HostKey.IsEmpty())
  3381. {
  3382. UnicodeString KeyName;
  3383. UnicodeString Fingerprint = HostKey;
  3384. NormalizeFingerprint(Fingerprint, KeyName);
  3385. UnicodeString S = Fingerprint;
  3386. if (!KeyName.IsEmpty())
  3387. {
  3388. S = KeyName + NormalizedFingerprintSeparator + S;
  3389. }
  3390. S = Base64ToUrlSafe(S); // Noop for MD5 (both in SSH host keys and TLS/SSL)
  3391. S = MD5ToUrlSafe(S); // TLS/SSL fingerprints
  3392. UnicodeString S2 = EncodeUrlString(S);
  3393. DebugAssert(S2 == S2); // There should be nothing left for encoding
  3394. Url +=
  3395. UnicodeString(UrlParamSeparator) + UrlHostKeyParamName +
  3396. UnicodeString(UrlParamValueSeparator) + S2;
  3397. }
  3398. if (FLAGSET(Flags, sufRawSettings))
  3399. {
  3400. std::unique_ptr<TStrings> RawSettings(GetRawSettingsForUrl());
  3401. for (int Index = 0; Index < RawSettings->Count; Index++)
  3402. {
  3403. Url +=
  3404. UnicodeString(UrlParamSeparator) +
  3405. UrlRawSettingsParamNamePrefix + EncodeUrlString(LowerCase(RawSettings->Names[Index])) +
  3406. UnicodeString(UrlParamValueSeparator) + EncodeUrlString(RawSettings->ValueFromIndex[Index]);
  3407. }
  3408. }
  3409. Url += L"@";
  3410. }
  3411. DebugAssert(!HostNameExpanded.IsEmpty());
  3412. if (IsIPv6Literal(HostNameExpanded))
  3413. {
  3414. Url += EscapeIPv6Literal(HostNameExpanded);
  3415. }
  3416. else
  3417. {
  3418. Url += EncodeUrlString(HostNameExpanded);
  3419. }
  3420. if (PortNumber != GetDefaultPort())
  3421. {
  3422. Url += L":" + IntToStr(PortNumber);
  3423. }
  3424. Url += L"/";
  3425. return Url;
  3426. }
  3427. //---------------------------------------------------------------------
  3428. UnicodeString ScriptCommandOpenLink(TraceInitStr(ScriptCommandLink(L"open")));
  3429. //---------------------------------------------------------------------
  3430. void __fastcall TSessionData::AddSwitch(
  3431. UnicodeString & Result, const UnicodeString & Name, bool Rtf)
  3432. {
  3433. Result += RtfSwitch(Name, ScriptCommandOpenLink, Rtf);
  3434. }
  3435. //---------------------------------------------------------------------
  3436. void __fastcall TSessionData::AddSwitch(
  3437. UnicodeString & Result, const UnicodeString & Name, const UnicodeString & Value, bool Rtf)
  3438. {
  3439. Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);
  3440. }
  3441. //---------------------------------------------------------------------
  3442. void __fastcall TSessionData::AddSwitch(
  3443. UnicodeString & Result, const UnicodeString & Name, int Value, bool Rtf)
  3444. {
  3445. Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);
  3446. }
  3447. //---------------------------------------------------------------------
  3448. void __fastcall TSessionData::LookupLastFingerprint()
  3449. {
  3450. UnicodeString FingerprintType;
  3451. if (IsSshProtocol(FSProtocol))
  3452. {
  3453. FingerprintType = SshFingerprintType;
  3454. }
  3455. else if (Ftps != ftpsNone)
  3456. {
  3457. FingerprintType = TlsFingerprintType;
  3458. }
  3459. if (!FingerprintType.IsEmpty())
  3460. {
  3461. HostKey = Configuration->LastFingerprint(SiteKey, FingerprintType);
  3462. }
  3463. if (Tunnel)
  3464. {
  3465. // not used anyway
  3466. int TunnelPortNumber = std::max(TunnelLocalPortNumber, Configuration->TunnelLocalPortNumberLow);
  3467. std::unique_ptr<TSessionData> TunnelData(CreateTunnelData(TunnelPortNumber));
  3468. TunnelHostKey = Configuration->LastFingerprint(TunnelData->SiteKey, SshFingerprintType);
  3469. }
  3470. }
  3471. //---------------------------------------------------------------------
  3472. UnicodeString __fastcall TSessionData::GenerateOpenCommandArgs(bool Rtf)
  3473. {
  3474. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3475. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  3476. SessionData->Assign(this);
  3477. UnicodeString Result = SessionData->GenerateSessionUrl(sufOpen);
  3478. // Before we reset the FSProtocol
  3479. bool AUsesSsh = SessionData->UsesSsh;
  3480. // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that
  3481. if (SessionData->FSProtocol != fsSFTPonly)
  3482. {
  3483. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3484. }
  3485. SessionData->HostName = FactoryDefaults->HostName;
  3486. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3487. SessionData->UserName = FactoryDefaults->UserName;
  3488. SessionData->Password = FactoryDefaults->Password;
  3489. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3490. SessionData->Ftps = FactoryDefaults->Ftps;
  3491. if (SessionData->HostKey != FactoryDefaults->HostKey)
  3492. {
  3493. UnicodeString SwitchName = AUsesSsh ? L"hostkey" : L"certificate";
  3494. AddSwitch(Result, SwitchName, SessionData->HostKey, Rtf);
  3495. SessionData->HostKey = FactoryDefaults->HostKey;
  3496. }
  3497. if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)
  3498. {
  3499. AddSwitch(Result, PRIVATEKEY_SWITCH, SessionData->PublicKeyFile, Rtf);
  3500. SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;
  3501. }
  3502. if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)
  3503. {
  3504. AddSwitch(Result, L"clientcert", SessionData->TlsCertificateFile, Rtf);
  3505. SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;
  3506. }
  3507. if (SessionData->Passphrase != FactoryDefaults->Passphrase)
  3508. {
  3509. AddSwitch(Result, PassphraseOption, SessionData->Passphrase, Rtf);
  3510. SessionData->Passphrase = FactoryDefaults->Passphrase;
  3511. }
  3512. if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)
  3513. {
  3514. AddSwitch(Result, L"passive", SessionData->FtpPasvMode ? 1 : 0, Rtf);
  3515. SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;
  3516. }
  3517. if (SessionData->Timeout != FactoryDefaults->Timeout)
  3518. {
  3519. AddSwitch(Result, L"timeout", SessionData->Timeout, Rtf);
  3520. SessionData->Timeout = FactoryDefaults->Timeout;
  3521. }
  3522. std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get(), false, false));
  3523. if (RawSettings->Count > 0)
  3524. {
  3525. AddSwitch(Result, RawSettingsOption, Rtf);
  3526. Result += StringsToParams(RawSettings.get());
  3527. }
  3528. return Result;
  3529. }
  3530. //---------------------------------------------------------------------
  3531. UnicodeString SessionOptionsClassName(L"SessionOptions");
  3532. //---------------------------------------------------------------------
  3533. void __fastcall TSessionData::AddAssemblyProperty(
  3534. UnicodeString & Result, TAssemblyLanguage Language,
  3535. const UnicodeString & Name, const UnicodeString & Type,
  3536. const UnicodeString & Member)
  3537. {
  3538. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Type, Member, false);
  3539. }
  3540. //---------------------------------------------------------------------
  3541. void __fastcall TSessionData::AddAssemblyProperty(
  3542. UnicodeString & Result, TAssemblyLanguage Language,
  3543. const UnicodeString & Name, const UnicodeString & Value)
  3544. {
  3545. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3546. }
  3547. //---------------------------------------------------------------------
  3548. void __fastcall TSessionData::AddAssemblyProperty(
  3549. UnicodeString & Result, TAssemblyLanguage Language,
  3550. const UnicodeString & Name, int Value)
  3551. {
  3552. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3553. }
  3554. //---------------------------------------------------------------------
  3555. void __fastcall TSessionData::AddAssemblyProperty(
  3556. UnicodeString & Result, TAssemblyLanguage Language,
  3557. const UnicodeString & Name, bool Value)
  3558. {
  3559. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3560. }
  3561. //---------------------------------------------------------------------
  3562. void __fastcall TSessionData::GenerateAssemblyCode(
  3563. TAssemblyLanguage Language, UnicodeString & Head, UnicodeString & Tail, int & Indent)
  3564. {
  3565. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3566. std::unique_ptr<TSessionData> SessionData(Clone());
  3567. switch (Language)
  3568. {
  3569. case alCSharp:
  3570. case alVBNET:
  3571. // noop
  3572. break;
  3573. case alPowerShell:
  3574. Head +=
  3575. AssemblyCommentLine(Language, LoadStr(CODE_PS_ADD_TYPE)) +
  3576. RtfKeyword(L"Add-Type") + RtfText(" -Path ") + AssemblyString(Language, "WinSCPnet.dll") + RtfPara +
  3577. RtfPara;
  3578. break;
  3579. default:
  3580. DebugFail();
  3581. break;
  3582. }
  3583. Head +=
  3584. AssemblyCommentLine(Language, LoadStr(CODE_SESSION_OPTIONS)) +
  3585. AssemblyNewClassInstanceStart(Language, SessionOptionsClassName, false);
  3586. UnicodeString ProtocolMember;
  3587. switch (SessionData->FSProtocol)
  3588. {
  3589. case fsSCPonly:
  3590. ProtocolMember = "Scp";
  3591. break;
  3592. default:
  3593. DebugFail();
  3594. // fallback
  3595. case fsSFTP:
  3596. case fsSFTPonly:
  3597. ProtocolMember = "Sftp";
  3598. break;
  3599. case fsFTP:
  3600. ProtocolMember = "Ftp";
  3601. break;
  3602. case fsWebDAV:
  3603. ProtocolMember = "Webdav";
  3604. break;
  3605. case fsS3:
  3606. ProtocolMember = "S3";
  3607. break;
  3608. }
  3609. // Before we reset the FSProtocol
  3610. bool AUsesSsh = SessionData->UsesSsh;
  3611. // Protocol is set unconditionally, we want even the default SFTP
  3612. AddAssemblyProperty(Head, Language, L"Protocol", L"Protocol", ProtocolMember);
  3613. // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that
  3614. if (SessionData->FSProtocol != fsSFTPonly)
  3615. {
  3616. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3617. }
  3618. if (SessionData->HostName != FactoryDefaults->HostName)
  3619. {
  3620. AddAssemblyProperty(Head, Language, L"HostName", HostName);
  3621. SessionData->HostName = FactoryDefaults->HostName;
  3622. }
  3623. int ADefaultPort = GetDefaultPort();
  3624. if (SessionData->PortNumber != ADefaultPort)
  3625. {
  3626. AddAssemblyProperty(Head, Language, L"PortNumber", PortNumber);
  3627. }
  3628. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3629. if (SessionData->UserName != FactoryDefaults->UserName)
  3630. {
  3631. AddAssemblyProperty(Head, Language, L"UserName", UserName);
  3632. SessionData->UserName = FactoryDefaults->UserName;
  3633. }
  3634. if (SessionData->Password != FactoryDefaults->Password)
  3635. {
  3636. AddAssemblyProperty(Head, Language, L"Password", NormalizeString(Password));
  3637. SessionData->Password = FactoryDefaults->Password;
  3638. }
  3639. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3640. if (SessionData->Ftps != FactoryDefaults->Ftps)
  3641. {
  3642. // SessionData->FSProtocol is reset already
  3643. switch (FSProtocol)
  3644. {
  3645. case fsFTP:
  3646. {
  3647. UnicodeString FtpSecureMember;
  3648. switch (SessionData->Ftps)
  3649. {
  3650. case ftpsNone:
  3651. // noop
  3652. break;
  3653. case ftpsImplicit:
  3654. FtpSecureMember = L"Implicit";
  3655. break;
  3656. case ftpsExplicitTls:
  3657. case ftpsExplicitSsl:
  3658. FtpSecureMember = L"Explicit";
  3659. break;
  3660. default:
  3661. DebugFail();
  3662. break;
  3663. }
  3664. AddAssemblyProperty(Head, Language, L"FtpSecure", L"FtpSecure", FtpSecureMember);
  3665. }
  3666. break;
  3667. case fsWebDAV:
  3668. AddAssemblyProperty(Head, Language, L"WebdavSecure", (SessionData->Ftps != ftpsNone));
  3669. break;
  3670. case fsS3:
  3671. // implicit
  3672. break;
  3673. default:
  3674. DebugFail();
  3675. break;
  3676. }
  3677. SessionData->Ftps = FactoryDefaults->Ftps;
  3678. }
  3679. if (SessionData->HostKey != FactoryDefaults->HostKey)
  3680. {
  3681. UnicodeString PropertyName = AUsesSsh ? L"SshHostKeyFingerprint" : L"TlsHostCertificateFingerprint";
  3682. AddAssemblyProperty(Head, Language, PropertyName, SessionData->HostKey);
  3683. SessionData->HostKey = FactoryDefaults->HostKey;
  3684. }
  3685. if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)
  3686. {
  3687. AddAssemblyProperty(Head, Language, L"SshPrivateKeyPath", SessionData->PublicKeyFile);
  3688. SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;
  3689. }
  3690. if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)
  3691. {
  3692. AddAssemblyProperty(Head, Language, L"TlsClientCertificatePath", SessionData->TlsCertificateFile);
  3693. SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;
  3694. }
  3695. if (SessionData->Passphrase != FactoryDefaults->Passphrase)
  3696. {
  3697. AddAssemblyProperty(Head, Language, L"PrivateKeyPassphrase", SessionData->Passphrase);
  3698. SessionData->Passphrase = FactoryDefaults->Passphrase;
  3699. }
  3700. if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)
  3701. {
  3702. AddAssemblyProperty(Head, Language, L"FtpMode", L"FtpMode", (SessionData->FtpPasvMode ? L"Passive" : L"Active"));
  3703. SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;
  3704. }
  3705. if (SessionData->Timeout != FactoryDefaults->Timeout)
  3706. {
  3707. AddAssemblyProperty(Head, Language, L"TimeoutInMilliseconds", SessionData->Timeout * 1000);
  3708. SessionData->Timeout = FactoryDefaults->Timeout;
  3709. }
  3710. Head += AssemblyNewClassInstanceEnd(Language, false);
  3711. std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get(), false, false));
  3712. UnicodeString SessionOptionsVariableName = AssemblyVariableName(Language, SessionOptionsClassName);
  3713. if (RawSettings->Count > 0)
  3714. {
  3715. Head +=
  3716. RtfPara +
  3717. AssemblyAddRawSettings(Language, RawSettings.get(), SessionOptionsClassName, L"AddRawSettings");
  3718. }
  3719. Head += RtfPara;
  3720. UnicodeString Indentation = L" ";
  3721. UnicodeString SessionVariableName = AssemblyVariableName(Language, SessionClassName);
  3722. UnicodeString RtfSessionClass = RtfLibraryClass(SessionClassName);
  3723. UnicodeString RtfSessionOpenMethod = RtfLibraryMethod(SessionClassName, L"Open", false);
  3724. UnicodeString NewSessionInstance = AssemblyNewClassInstance(Language, SessionClassName, false);
  3725. UnicodeString OpenCall =
  3726. Indentation + AssemblyCommentLine(Language, LoadStr(CODE_CONNECT)) +
  3727. Indentation + RtfText(SessionVariableName + L".") + RtfSessionOpenMethod + RtfText(L"(" + SessionOptionsVariableName + L")") +
  3728. AssemblyStatementSeparator(Language) + RtfPara;
  3729. switch (Language)
  3730. {
  3731. case alCSharp:
  3732. Head +=
  3733. RtfKeyword(L"using") + RtfText(" (") + NewSessionInstance + RtfText(L"())") + RtfPara +
  3734. RtfText(L"{") + RtfPara +
  3735. OpenCall;
  3736. Tail =
  3737. RtfText(L"}") + RtfPara;
  3738. break;
  3739. case alVBNET:
  3740. Head +=
  3741. RtfKeyword(L"Using") + RtfText(L" ") + NewSessionInstance + RtfPara +
  3742. OpenCall;
  3743. Tail =
  3744. RtfKeyword(L"End Using") + RtfPara;
  3745. break;
  3746. case alPowerShell:
  3747. Head +=
  3748. NewSessionInstance + RtfPara +
  3749. RtfPara +
  3750. RtfKeyword(L"try") + RtfPara +
  3751. RtfText(L"{") + RtfPara +
  3752. OpenCall;
  3753. Tail =
  3754. RtfText(L"}") + RtfPara +
  3755. RtfKeyword(L"finally") + RtfPara +
  3756. RtfText(L"{") + RtfPara +
  3757. RtfText(Indentation + SessionVariableName + L".") +
  3758. RtfLibraryMethod(SessionClassName, L"Dispose", false) + RtfText(L"()") + RtfPara +
  3759. RtfText(L"}") + RtfPara;
  3760. break;
  3761. }
  3762. Head += RtfPara;
  3763. Indent = 4; // the same for all languages so far
  3764. }
  3765. //---------------------------------------------------------------------
  3766. void __fastcall TSessionData::SetTimeDifference(TDateTime value)
  3767. {
  3768. SET_SESSION_PROPERTY(TimeDifference);
  3769. }
  3770. //---------------------------------------------------------------------
  3771. void __fastcall TSessionData::SetTimeDifferenceAuto(bool value)
  3772. {
  3773. SET_SESSION_PROPERTY(TimeDifferenceAuto);
  3774. }
  3775. //---------------------------------------------------------------------
  3776. void __fastcall TSessionData::SetLocalDirectory(UnicodeString value)
  3777. {
  3778. SET_SESSION_PROPERTY(LocalDirectory);
  3779. }
  3780. //---------------------------------------------------------------------
  3781. void __fastcall TSessionData::SetOtherLocalDirectory(const UnicodeString & value)
  3782. {
  3783. SET_SESSION_PROPERTY(OtherLocalDirectory);
  3784. }
  3785. //---------------------------------------------------------------------
  3786. UnicodeString __fastcall TSessionData::GetLocalDirectoryExpanded()
  3787. {
  3788. return ExpandFileName(::ExpandEnvironmentVariables(LocalDirectory));
  3789. }
  3790. //---------------------------------------------------------------------
  3791. void __fastcall TSessionData::SetRemoteDirectory(UnicodeString value)
  3792. {
  3793. SET_SESSION_PROPERTY(RemoteDirectory);
  3794. }
  3795. //---------------------------------------------------------------------
  3796. void __fastcall TSessionData::SetSynchronizeBrowsing(bool value)
  3797. {
  3798. SET_SESSION_PROPERTY(SynchronizeBrowsing);
  3799. }
  3800. //---------------------------------------------------------------------
  3801. void __fastcall TSessionData::SetUpdateDirectories(bool value)
  3802. {
  3803. SET_SESSION_PROPERTY(UpdateDirectories);
  3804. }
  3805. //---------------------------------------------------------------------
  3806. void __fastcall TSessionData::SetCacheDirectories(bool value)
  3807. {
  3808. SET_SESSION_PROPERTY(CacheDirectories);
  3809. }
  3810. //---------------------------------------------------------------------
  3811. void __fastcall TSessionData::SetCacheDirectoryChanges(bool value)
  3812. {
  3813. SET_SESSION_PROPERTY(CacheDirectoryChanges);
  3814. }
  3815. //---------------------------------------------------------------------
  3816. void __fastcall TSessionData::SetPreserveDirectoryChanges(bool value)
  3817. {
  3818. SET_SESSION_PROPERTY(PreserveDirectoryChanges);
  3819. }
  3820. //---------------------------------------------------------------------
  3821. void __fastcall TSessionData::SetResolveSymlinks(bool value)
  3822. {
  3823. SET_SESSION_PROPERTY(ResolveSymlinks);
  3824. }
  3825. //---------------------------------------------------------------------
  3826. void __fastcall TSessionData::SetFollowDirectorySymlinks(bool value)
  3827. {
  3828. SET_SESSION_PROPERTY(FollowDirectorySymlinks);
  3829. }
  3830. //---------------------------------------------------------------------------
  3831. void __fastcall TSessionData::SetDSTMode(TDSTMode value)
  3832. {
  3833. SET_SESSION_PROPERTY(DSTMode);
  3834. }
  3835. //---------------------------------------------------------------------------
  3836. void __fastcall TSessionData::SetDeleteToRecycleBin(bool value)
  3837. {
  3838. SET_SESSION_PROPERTY(DeleteToRecycleBin);
  3839. }
  3840. //---------------------------------------------------------------------------
  3841. void __fastcall TSessionData::SetOverwrittenToRecycleBin(bool value)
  3842. {
  3843. SET_SESSION_PROPERTY(OverwrittenToRecycleBin);
  3844. }
  3845. //---------------------------------------------------------------------------
  3846. void __fastcall TSessionData::SetRecycleBinPath(UnicodeString value)
  3847. {
  3848. SET_SESSION_PROPERTY(RecycleBinPath);
  3849. }
  3850. //---------------------------------------------------------------------------
  3851. void __fastcall TSessionData::SetPostLoginCommands(UnicodeString value)
  3852. {
  3853. SET_SESSION_PROPERTY(PostLoginCommands);
  3854. }
  3855. //---------------------------------------------------------------------
  3856. void __fastcall TSessionData::SetSpecial(bool value)
  3857. {
  3858. SET_SESSION_PROPERTY(Special);
  3859. }
  3860. //---------------------------------------------------------------------------
  3861. void __fastcall TSessionData::SetScp1Compatibility(bool value)
  3862. {
  3863. SET_SESSION_PROPERTY(Scp1Compatibility);
  3864. }
  3865. //---------------------------------------------------------------------
  3866. void __fastcall TSessionData::SetTcpNoDelay(bool value)
  3867. {
  3868. SET_SESSION_PROPERTY(TcpNoDelay);
  3869. }
  3870. //---------------------------------------------------------------------
  3871. void __fastcall TSessionData::SetSendBuf(int value)
  3872. {
  3873. SET_SESSION_PROPERTY(SendBuf);
  3874. }
  3875. //---------------------------------------------------------------------
  3876. void __fastcall TSessionData::SetSourceAddress(const UnicodeString & value)
  3877. {
  3878. SET_SESSION_PROPERTY(SourceAddress);
  3879. }
  3880. //---------------------------------------------------------------------
  3881. void __fastcall TSessionData::SetProtocolFeatures(const UnicodeString & value)
  3882. {
  3883. SET_SESSION_PROPERTY(ProtocolFeatures);
  3884. }
  3885. //---------------------------------------------------------------------
  3886. void __fastcall TSessionData::SetSshSimple(bool value)
  3887. {
  3888. SET_SESSION_PROPERTY(SshSimple);
  3889. }
  3890. //---------------------------------------------------------------------
  3891. void __fastcall TSessionData::SetProxyMethod(TProxyMethod value)
  3892. {
  3893. SET_SESSION_PROPERTY(ProxyMethod);
  3894. }
  3895. //---------------------------------------------------------------------
  3896. void __fastcall TSessionData::SetProxyHost(UnicodeString value)
  3897. {
  3898. SET_SESSION_PROPERTY(ProxyHost);
  3899. }
  3900. //---------------------------------------------------------------------
  3901. void __fastcall TSessionData::SetProxyPort(int value)
  3902. {
  3903. SET_SESSION_PROPERTY(ProxyPort);
  3904. }
  3905. //---------------------------------------------------------------------
  3906. void __fastcall TSessionData::SetProxyUsername(UnicodeString value)
  3907. {
  3908. SET_SESSION_PROPERTY(ProxyUsername);
  3909. }
  3910. //---------------------------------------------------------------------
  3911. void __fastcall TSessionData::SetProxyPassword(UnicodeString avalue)
  3912. {
  3913. RawByteString value = EncryptPassword(avalue, ProxyUsername+ProxyHost);
  3914. SET_SESSION_PROPERTY(ProxyPassword);
  3915. }
  3916. //---------------------------------------------------------------------
  3917. UnicodeString __fastcall TSessionData::GetProxyPassword() const
  3918. {
  3919. return DecryptPassword(FProxyPassword, ProxyUsername+ProxyHost);
  3920. }
  3921. //---------------------------------------------------------------------
  3922. void __fastcall TSessionData::SetProxyTelnetCommand(UnicodeString value)
  3923. {
  3924. SET_SESSION_PROPERTY(ProxyTelnetCommand);
  3925. }
  3926. //---------------------------------------------------------------------
  3927. void __fastcall TSessionData::SetProxyLocalCommand(UnicodeString value)
  3928. {
  3929. SET_SESSION_PROPERTY(ProxyLocalCommand);
  3930. }
  3931. //---------------------------------------------------------------------
  3932. void __fastcall TSessionData::SetProxyDNS(TAutoSwitch value)
  3933. {
  3934. SET_SESSION_PROPERTY(ProxyDNS);
  3935. }
  3936. //---------------------------------------------------------------------
  3937. void __fastcall TSessionData::SetProxyLocalhost(bool value)
  3938. {
  3939. SET_SESSION_PROPERTY(ProxyLocalhost);
  3940. }
  3941. //---------------------------------------------------------------------
  3942. void __fastcall TSessionData::SetFtpProxyLogonType(int value)
  3943. {
  3944. SET_SESSION_PROPERTY(FtpProxyLogonType);
  3945. }
  3946. //---------------------------------------------------------------------
  3947. void __fastcall TSessionData::SetBug(TSshBug Bug, TAutoSwitch value)
  3948. {
  3949. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));
  3950. SET_SESSION_PROPERTY(Bugs[Bug]);
  3951. }
  3952. //---------------------------------------------------------------------
  3953. TAutoSwitch __fastcall TSessionData::GetBug(TSshBug Bug) const
  3954. {
  3955. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));
  3956. return FBugs[Bug];
  3957. }
  3958. //---------------------------------------------------------------------
  3959. void __fastcall TSessionData::SetPuttySettings(UnicodeString value)
  3960. {
  3961. SET_SESSION_PROPERTY(PuttySettings);
  3962. }
  3963. //---------------------------------------------------------------------
  3964. void __fastcall TSessionData::SetCustomParam1(UnicodeString value)
  3965. {
  3966. SET_SESSION_PROPERTY(CustomParam1);
  3967. }
  3968. //---------------------------------------------------------------------
  3969. void __fastcall TSessionData::SetCustomParam2(UnicodeString value)
  3970. {
  3971. SET_SESSION_PROPERTY(CustomParam2);
  3972. }
  3973. //---------------------------------------------------------------------
  3974. void __fastcall TSessionData::SetSFTPDownloadQueue(int value)
  3975. {
  3976. SET_SESSION_PROPERTY(SFTPDownloadQueue);
  3977. }
  3978. //---------------------------------------------------------------------
  3979. void __fastcall TSessionData::SetSFTPUploadQueue(int value)
  3980. {
  3981. SET_SESSION_PROPERTY(SFTPUploadQueue);
  3982. }
  3983. //---------------------------------------------------------------------
  3984. void __fastcall TSessionData::SetSFTPListingQueue(int value)
  3985. {
  3986. SET_SESSION_PROPERTY(SFTPListingQueue);
  3987. }
  3988. //---------------------------------------------------------------------
  3989. void __fastcall TSessionData::SetSFTPMaxVersion(int value)
  3990. {
  3991. SET_SESSION_PROPERTY(SFTPMaxVersion);
  3992. }
  3993. //---------------------------------------------------------------------
  3994. void __fastcall TSessionData::SetSFTPMaxPacketSize(unsigned long value)
  3995. {
  3996. SET_SESSION_PROPERTY(SFTPMaxPacketSize);
  3997. }
  3998. //---------------------------------------------------------------------
  3999. void __fastcall TSessionData::SetSFTPRealPath(TAutoSwitch value)
  4000. {
  4001. SET_SESSION_PROPERTY(SFTPRealPath);
  4002. }
  4003. //---------------------------------------------------------------------
  4004. void __fastcall TSessionData::SetSFTPBug(TSftpBug Bug, TAutoSwitch value)
  4005. {
  4006. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));
  4007. SET_SESSION_PROPERTY(SFTPBugs[Bug]);
  4008. }
  4009. //---------------------------------------------------------------------
  4010. TAutoSwitch __fastcall TSessionData::GetSFTPBug(TSftpBug Bug) const
  4011. {
  4012. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));
  4013. return FSFTPBugs[Bug];
  4014. }
  4015. //---------------------------------------------------------------------
  4016. void __fastcall TSessionData::SetSCPLsFullTime(TAutoSwitch value)
  4017. {
  4018. SET_SESSION_PROPERTY(SCPLsFullTime);
  4019. }
  4020. //---------------------------------------------------------------------------
  4021. void __fastcall TSessionData::SetColor(int value)
  4022. {
  4023. SET_SESSION_PROPERTY(Color);
  4024. }
  4025. //---------------------------------------------------------------------------
  4026. void __fastcall TSessionData::SetTunnel(bool value)
  4027. {
  4028. SET_SESSION_PROPERTY(Tunnel);
  4029. }
  4030. //---------------------------------------------------------------------
  4031. void __fastcall TSessionData::SetTunnelHostName(UnicodeString value)
  4032. {
  4033. if (FTunnelHostName != value)
  4034. {
  4035. // HostName is key for password encryption
  4036. UnicodeString XTunnelPassword = TunnelPassword;
  4037. int P = value.LastDelimiter(L"@");
  4038. if (P > 0)
  4039. {
  4040. TunnelUserName = value.SubString(1, P - 1);
  4041. value = value.SubString(P + 1, value.Length() - P);
  4042. }
  4043. FTunnelHostName = value;
  4044. Modify();
  4045. TunnelPassword = XTunnelPassword;
  4046. Shred(XTunnelPassword);
  4047. }
  4048. }
  4049. //---------------------------------------------------------------------
  4050. void __fastcall TSessionData::SetTunnelPortNumber(int value)
  4051. {
  4052. SET_SESSION_PROPERTY(TunnelPortNumber);
  4053. }
  4054. //---------------------------------------------------------------------
  4055. void __fastcall TSessionData::SetTunnelUserName(UnicodeString value)
  4056. {
  4057. // Avoid password recryption (what may popup master password prompt)
  4058. if (FTunnelUserName != value)
  4059. {
  4060. // TunnelUserName is key for password encryption
  4061. UnicodeString XTunnelPassword = TunnelPassword;
  4062. SET_SESSION_PROPERTY(TunnelUserName);
  4063. TunnelPassword = XTunnelPassword;
  4064. Shred(XTunnelPassword);
  4065. }
  4066. }
  4067. //---------------------------------------------------------------------
  4068. void __fastcall TSessionData::SetTunnelPassword(UnicodeString avalue)
  4069. {
  4070. RawByteString value = EncryptPassword(avalue, TunnelUserName+TunnelHostName);
  4071. SET_SESSION_PROPERTY(TunnelPassword);
  4072. }
  4073. //---------------------------------------------------------------------
  4074. UnicodeString __fastcall TSessionData::GetTunnelPassword() const
  4075. {
  4076. return DecryptPassword(FTunnelPassword, TunnelUserName+TunnelHostName);
  4077. }
  4078. //---------------------------------------------------------------------
  4079. void __fastcall TSessionData::SetTunnelPassphrase(UnicodeString avalue)
  4080. {
  4081. RawByteString value = EncryptPassword(avalue, TunnelPublicKeyFile);
  4082. SET_SESSION_PROPERTY(TunnelPassphrase);
  4083. }
  4084. //---------------------------------------------------------------------
  4085. UnicodeString __fastcall TSessionData::GetTunnelPassphrase() const
  4086. {
  4087. return DecryptPassword(FTunnelPassphrase, TunnelPublicKeyFile);
  4088. }
  4089. //---------------------------------------------------------------------
  4090. void __fastcall TSessionData::SetTunnelPublicKeyFile(UnicodeString value)
  4091. {
  4092. if (FTunnelPublicKeyFile != value)
  4093. {
  4094. // TunnelPublicKeyFile is key for TunnelPassphrase encryption
  4095. UnicodeString XTunnelPassphrase = TunnelPassphrase;
  4096. // StripPathQuotes should not be needed as we do not feed quotes anymore
  4097. FTunnelPublicKeyFile = StripPathQuotes(value);
  4098. Modify();
  4099. TunnelPassphrase = XTunnelPassphrase;
  4100. Shred(XTunnelPassphrase);
  4101. }
  4102. }
  4103. //---------------------------------------------------------------------
  4104. void __fastcall TSessionData::SetTunnelLocalPortNumber(int value)
  4105. {
  4106. SET_SESSION_PROPERTY(TunnelLocalPortNumber);
  4107. }
  4108. //---------------------------------------------------------------------
  4109. bool __fastcall TSessionData::GetTunnelAutoassignLocalPortNumber()
  4110. {
  4111. return (FTunnelLocalPortNumber <= 0);
  4112. }
  4113. //---------------------------------------------------------------------
  4114. void __fastcall TSessionData::SetTunnelPortFwd(UnicodeString value)
  4115. {
  4116. SET_SESSION_PROPERTY(TunnelPortFwd);
  4117. }
  4118. //---------------------------------------------------------------------
  4119. void __fastcall TSessionData::SetTunnelHostKey(UnicodeString value)
  4120. {
  4121. SET_SESSION_PROPERTY(TunnelHostKey);
  4122. }
  4123. //---------------------------------------------------------------------
  4124. void __fastcall TSessionData::SetFtpPasvMode(bool value)
  4125. {
  4126. SET_SESSION_PROPERTY(FtpPasvMode);
  4127. }
  4128. //---------------------------------------------------------------------
  4129. void __fastcall TSessionData::SetFtpForcePasvIp(TAutoSwitch value)
  4130. {
  4131. SET_SESSION_PROPERTY(FtpForcePasvIp);
  4132. }
  4133. //---------------------------------------------------------------------
  4134. void __fastcall TSessionData::SetFtpUseMlsd(TAutoSwitch value)
  4135. {
  4136. SET_SESSION_PROPERTY(FtpUseMlsd);
  4137. }
  4138. //---------------------------------------------------------------------
  4139. void __fastcall TSessionData::SetFtpAccount(UnicodeString value)
  4140. {
  4141. SET_SESSION_PROPERTY(FtpAccount);
  4142. }
  4143. //---------------------------------------------------------------------
  4144. void __fastcall TSessionData::SetFtpPingInterval(int value)
  4145. {
  4146. SET_SESSION_PROPERTY(FtpPingInterval);
  4147. }
  4148. //---------------------------------------------------------------------------
  4149. TDateTime __fastcall TSessionData::GetFtpPingIntervalDT()
  4150. {
  4151. return SecToDateTime(FtpPingInterval);
  4152. }
  4153. //---------------------------------------------------------------------------
  4154. void __fastcall TSessionData::SetFtpPingType(TPingType value)
  4155. {
  4156. SET_SESSION_PROPERTY(FtpPingType);
  4157. }
  4158. //---------------------------------------------------------------------------
  4159. void __fastcall TSessionData::SetFtpTransferActiveImmediately(TAutoSwitch value)
  4160. {
  4161. SET_SESSION_PROPERTY(FtpTransferActiveImmediately);
  4162. }
  4163. //---------------------------------------------------------------------------
  4164. void __fastcall TSessionData::SetFtps(TFtps value)
  4165. {
  4166. SET_SESSION_PROPERTY(Ftps);
  4167. }
  4168. //---------------------------------------------------------------------------
  4169. void __fastcall TSessionData::SetMinTlsVersion(TTlsVersion value)
  4170. {
  4171. SET_SESSION_PROPERTY(MinTlsVersion);
  4172. }
  4173. //---------------------------------------------------------------------------
  4174. void __fastcall TSessionData::SetMaxTlsVersion(TTlsVersion value)
  4175. {
  4176. SET_SESSION_PROPERTY(MaxTlsVersion);
  4177. }
  4178. //---------------------------------------------------------------------------
  4179. void __fastcall TSessionData::SetLogicalHostName(UnicodeString value)
  4180. {
  4181. SET_SESSION_PROPERTY(LogicalHostName);
  4182. }
  4183. //---------------------------------------------------------------------
  4184. void __fastcall TSessionData::SetFtpListAll(TAutoSwitch value)
  4185. {
  4186. SET_SESSION_PROPERTY(FtpListAll);
  4187. }
  4188. //---------------------------------------------------------------------
  4189. void __fastcall TSessionData::SetFtpHost(TAutoSwitch value)
  4190. {
  4191. SET_SESSION_PROPERTY(FtpHost);
  4192. }
  4193. //---------------------------------------------------------------------
  4194. void __fastcall TSessionData::SetFtpWorkFromCwd(TAutoSwitch value)
  4195. {
  4196. SET_SESSION_PROPERTY(FtpWorkFromCwd);
  4197. }
  4198. //---------------------------------------------------------------------
  4199. void TSessionData::SetFtpAnyCodeForPwd(bool value)
  4200. {
  4201. SET_SESSION_PROPERTY(FtpAnyCodeForPwd);
  4202. }
  4203. //---------------------------------------------------------------------
  4204. void __fastcall TSessionData::SetSslSessionReuse(bool value)
  4205. {
  4206. SET_SESSION_PROPERTY(SslSessionReuse);
  4207. }
  4208. //---------------------------------------------------------------------
  4209. void __fastcall TSessionData::SetTlsCertificateFile(UnicodeString value)
  4210. {
  4211. SET_SESSION_PROPERTY(TlsCertificateFile);
  4212. }
  4213. //---------------------------------------------------------------------
  4214. void __fastcall TSessionData::SetNotUtf(TAutoSwitch value)
  4215. {
  4216. SET_SESSION_PROPERTY(NotUtf);
  4217. }
  4218. //---------------------------------------------------------------------
  4219. void __fastcall TSessionData::SetInternalEditorEncoding(int value)
  4220. {
  4221. SET_SESSION_PROPERTY(InternalEditorEncoding);
  4222. }
  4223. //---------------------------------------------------------------------
  4224. void __fastcall TSessionData::SetS3DefaultRegion(UnicodeString value)
  4225. {
  4226. SET_SESSION_PROPERTY(S3DefaultRegion);
  4227. }
  4228. //---------------------------------------------------------------------
  4229. void __fastcall TSessionData::SetS3SessionToken(UnicodeString value)
  4230. {
  4231. SET_SESSION_PROPERTY(S3SessionToken);
  4232. }
  4233. //---------------------------------------------------------------------
  4234. void __fastcall TSessionData::SetS3UrlStyle(TS3UrlStyle value)
  4235. {
  4236. SET_SESSION_PROPERTY(S3UrlStyle);
  4237. }
  4238. //---------------------------------------------------------------------
  4239. void __fastcall TSessionData::SetS3MaxKeys(TAutoSwitch value)
  4240. {
  4241. SET_SESSION_PROPERTY(S3MaxKeys);
  4242. }
  4243. //---------------------------------------------------------------------
  4244. void __fastcall TSessionData::SetS3CredentialsEnv(bool value)
  4245. {
  4246. SET_SESSION_PROPERTY(S3CredentialsEnv);
  4247. }
  4248. //---------------------------------------------------------------------
  4249. void __fastcall TSessionData::SetIsWorkspace(bool value)
  4250. {
  4251. SET_SESSION_PROPERTY(IsWorkspace);
  4252. }
  4253. //---------------------------------------------------------------------
  4254. void __fastcall TSessionData::SetLink(UnicodeString value)
  4255. {
  4256. SET_SESSION_PROPERTY(Link);
  4257. }
  4258. //---------------------------------------------------------------------
  4259. void __fastcall TSessionData::SetNameOverride(UnicodeString value)
  4260. {
  4261. SET_SESSION_PROPERTY(NameOverride);
  4262. }
  4263. //---------------------------------------------------------------------
  4264. void __fastcall TSessionData::SetHostKey(UnicodeString value)
  4265. {
  4266. SET_SESSION_PROPERTY(HostKey);
  4267. }
  4268. //---------------------------------------------------------------------
  4269. void __fastcall TSessionData::SetNote(UnicodeString value)
  4270. {
  4271. SET_SESSION_PROPERTY(Note);
  4272. }
  4273. //---------------------------------------------------------------------
  4274. void __fastcall TSessionData::SetWinTitle(UnicodeString value)
  4275. {
  4276. SET_SESSION_PROPERTY(WinTitle);
  4277. }
  4278. //---------------------------------------------------------------------
  4279. UnicodeString __fastcall TSessionData::GetEncryptKey() const
  4280. {
  4281. return DecryptPassword(FEncryptKey, UserName+HostName);
  4282. }
  4283. //---------------------------------------------------------------------
  4284. void __fastcall TSessionData::SetEncryptKey(UnicodeString avalue)
  4285. {
  4286. RawByteString value = EncryptPassword(avalue, UserName+HostName);
  4287. SET_SESSION_PROPERTY(EncryptKey);
  4288. }
  4289. //---------------------------------------------------------------------
  4290. void __fastcall TSessionData::SetWebDavLiberalEscaping(bool value)
  4291. {
  4292. SET_SESSION_PROPERTY(WebDavLiberalEscaping);
  4293. }
  4294. //---------------------------------------------------------------------
  4295. UnicodeString __fastcall TSessionData::GetInfoTip()
  4296. {
  4297. if (UsesSsh)
  4298. {
  4299. return FMTLOAD(SESSION_INFO_TIP2,
  4300. (HostName, UserName,
  4301. (PublicKeyFile.IsEmpty() ? LoadStr(NO_STR) : LoadStr(YES_STR)),
  4302. FSProtocolStr));
  4303. }
  4304. else
  4305. {
  4306. return FMTLOAD(SESSION_INFO_TIP_NO_SSH,
  4307. (HostName, UserName, FSProtocolStr));
  4308. }
  4309. }
  4310. //---------------------------------------------------------------------
  4311. UnicodeString __fastcall TSessionData::ExtractLocalName(const UnicodeString & Name)
  4312. {
  4313. UnicodeString Result = Name;
  4314. int P = Result.LastDelimiter(L"/");
  4315. if (P > 0)
  4316. {
  4317. Result.Delete(1, P);
  4318. }
  4319. return Result;
  4320. }
  4321. //---------------------------------------------------------------------
  4322. UnicodeString __fastcall TSessionData::GetLocalName()
  4323. {
  4324. UnicodeString Result;
  4325. if (HasSessionName())
  4326. {
  4327. Result = ExtractLocalName(Name);
  4328. }
  4329. else
  4330. {
  4331. Result = DefaultSessionName;
  4332. }
  4333. return Result;
  4334. }
  4335. //---------------------------------------------------------------------
  4336. UnicodeString __fastcall TSessionData::ExtractFolderName(const UnicodeString & Name)
  4337. {
  4338. UnicodeString Result;
  4339. int P = Name.LastDelimiter(L"/");
  4340. if (P > 0)
  4341. {
  4342. Result = Name.SubString(1, P - 1);
  4343. }
  4344. return Result;
  4345. }
  4346. //---------------------------------------------------------------------
  4347. UnicodeString __fastcall TSessionData::GetFolderName()
  4348. {
  4349. UnicodeString Result;
  4350. if (HasSessionName() || IsWorkspace)
  4351. {
  4352. Result = ExtractFolderName(Name);
  4353. }
  4354. return Result;
  4355. }
  4356. //---------------------------------------------------------------------
  4357. UnicodeString __fastcall TSessionData::ComposePath(
  4358. const UnicodeString & Path, const UnicodeString & Name)
  4359. {
  4360. return UnixIncludeTrailingBackslash(Path) + Name;
  4361. }
  4362. //---------------------------------------------------------------------
  4363. void __fastcall TSessionData::DisableAuthentationsExceptPassword()
  4364. {
  4365. SshNoUserAuth = false;
  4366. AuthKI = false;
  4367. AuthKIPassword = false;
  4368. AuthGSSAPI = false;
  4369. AuthGSSAPIKEX = false;
  4370. PublicKeyFile = L"";
  4371. TlsCertificateFile = L"";
  4372. Passphrase = L"";
  4373. TryAgent = false;
  4374. }
  4375. //---------------------------------------------------------------------
  4376. TStrings * TSessionData::GetAllOptionNames(bool PuttyExport)
  4377. {
  4378. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  4379. return FactoryDefaults->SaveToOptions(NULL, false, PuttyExport);
  4380. }
  4381. //---------------------------------------------------------------------
  4382. bool TSessionData::HasS3AutoCredentials()
  4383. {
  4384. return (FSProtocol == fsS3) && S3CredentialsEnv;
  4385. }
  4386. //---------------------------------------------------------------------
  4387. bool TSessionData::HasAutoCredentials()
  4388. {
  4389. return HasS3AutoCredentials();
  4390. }
  4391. //=== TStoredSessionList ----------------------------------------------
  4392. __fastcall TStoredSessionList::TStoredSessionList(bool aReadOnly):
  4393. TNamedObjectList(), FReadOnly(aReadOnly)
  4394. {
  4395. DebugAssert(Configuration);
  4396. FDefaultSettings = new TSessionData(DefaultName);
  4397. FPendingRemovals.reset(new TStringList());
  4398. }
  4399. //---------------------------------------------------------------------
  4400. __fastcall TStoredSessionList::~TStoredSessionList()
  4401. {
  4402. DebugAssert(Configuration);
  4403. delete FDefaultSettings;
  4404. }
  4405. //---------------------------------------------------------------------
  4406. void __fastcall TStoredSessionList::Load(THierarchicalStorage * Storage,
  4407. bool AsModified, bool UseDefaults, bool PuttyImport)
  4408. {
  4409. TStringList *SubKeys = new TStringList();
  4410. TList * Loaded = new TList;
  4411. try
  4412. {
  4413. DebugAssert(AutoSort);
  4414. AutoSort = false;
  4415. bool WasEmpty = (Count == 0);
  4416. Storage->GetSubKeyNames(SubKeys);
  4417. for (int Index = 0; Index < SubKeys->Count; Index++)
  4418. {
  4419. UnicodeString SessionName = SubKeys->Strings[Index];
  4420. bool ValidName = true;
  4421. try
  4422. {
  4423. TSessionData::ValidatePath(SessionName);
  4424. }
  4425. catch(...)
  4426. {
  4427. ValidName = false;
  4428. }
  4429. if (ValidName)
  4430. {
  4431. TSessionData * SessionData;
  4432. if (SessionName == FDefaultSettings->Name)
  4433. {
  4434. SessionData = FDefaultSettings;
  4435. }
  4436. else
  4437. {
  4438. // if the list was empty before loading, do not waste time trying to
  4439. // find existing sites to overwrite (we rely on underlying storage
  4440. // to secure uniqueness of the key names)
  4441. if (WasEmpty)
  4442. {
  4443. SessionData = NULL;
  4444. }
  4445. else
  4446. {
  4447. SessionData = (TSessionData*)FindByName(SessionName);
  4448. }
  4449. }
  4450. if ((SessionData != FDefaultSettings) || !UseDefaults)
  4451. {
  4452. if (SessionData == NULL)
  4453. {
  4454. SessionData = new TSessionData(L"");
  4455. if (UseDefaults)
  4456. {
  4457. SessionData->CopyData(DefaultSettings);
  4458. }
  4459. SessionData->Name = SessionName;
  4460. Add(SessionData);
  4461. }
  4462. Loaded->Add(SessionData);
  4463. SessionData->Load(Storage, PuttyImport);
  4464. if (AsModified)
  4465. {
  4466. SessionData->Modified = true;
  4467. }
  4468. }
  4469. }
  4470. }
  4471. if (!AsModified)
  4472. {
  4473. for (int Index = 0; Index < TObjectList::Count; Index++)
  4474. {
  4475. if (Loaded->IndexOf(Items[Index]) < 0)
  4476. {
  4477. Delete(Index);
  4478. Index--;
  4479. }
  4480. }
  4481. }
  4482. }
  4483. __finally
  4484. {
  4485. AutoSort = true;
  4486. AlphaSort();
  4487. delete SubKeys;
  4488. delete Loaded;
  4489. }
  4490. }
  4491. //---------------------------------------------------------------------
  4492. void __fastcall TStoredSessionList::Reload()
  4493. {
  4494. if (Count <= Configuration->DontReloadMoreThanSessions)
  4495. {
  4496. bool SessionList = true;
  4497. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));
  4498. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, False))
  4499. {
  4500. Load(Storage.get());
  4501. }
  4502. }
  4503. }
  4504. //---------------------------------------------------------------------
  4505. void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,
  4506. TSessionData * Data, bool All, bool RecryptPasswordOnly,
  4507. TSessionData * FactoryDefaults)
  4508. {
  4509. if (All || Data->Modified)
  4510. {
  4511. if (RecryptPasswordOnly)
  4512. {
  4513. Data->SaveRecryptedPasswords(Storage);
  4514. }
  4515. else
  4516. {
  4517. Data->Save(Storage, false, FactoryDefaults);
  4518. }
  4519. }
  4520. }
  4521. //---------------------------------------------------------------------
  4522. void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,
  4523. bool All, bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)
  4524. {
  4525. TSessionData * FactoryDefaults = new TSessionData(L"");
  4526. try
  4527. {
  4528. while (FPendingRemovals->Count > 0)
  4529. {
  4530. TSessionData::Remove(Storage, FPendingRemovals->Strings[0]);
  4531. FPendingRemovals->Delete(0);
  4532. }
  4533. DoSave(Storage, FDefaultSettings, All, RecryptPasswordOnly, FactoryDefaults);
  4534. for (int Index = 0; Index < CountIncludingHidden; Index++)
  4535. {
  4536. TSessionData * SessionData = (TSessionData *)Items[Index];
  4537. try
  4538. {
  4539. DoSave(Storage, SessionData, All, RecryptPasswordOnly, FactoryDefaults);
  4540. }
  4541. catch (Exception & E)
  4542. {
  4543. UnicodeString Message;
  4544. if (RecryptPasswordOnly && DebugAlwaysTrue(RecryptPasswordErrors != NULL) &&
  4545. ExceptionMessage(&E, Message))
  4546. {
  4547. RecryptPasswordErrors->Add(FORMAT("%s: %s", (SessionData->SessionName, Message)));
  4548. }
  4549. else
  4550. {
  4551. throw;
  4552. }
  4553. }
  4554. }
  4555. }
  4556. __finally
  4557. {
  4558. delete FactoryDefaults;
  4559. }
  4560. }
  4561. //---------------------------------------------------------------------
  4562. void __fastcall TStoredSessionList::Save(THierarchicalStorage * Storage, bool All)
  4563. {
  4564. DoSave(Storage, All, false, NULL);
  4565. }
  4566. //---------------------------------------------------------------------
  4567. void __fastcall TStoredSessionList::DoSave(bool All, bool Explicit,
  4568. bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)
  4569. {
  4570. bool SessionList = true;
  4571. THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);
  4572. try
  4573. {
  4574. Storage->AccessMode = smReadWrite;
  4575. Storage->Explicit = Explicit;
  4576. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))
  4577. {
  4578. DoSave(Storage, All, RecryptPasswordOnly, RecryptPasswordErrors);
  4579. }
  4580. }
  4581. __finally
  4582. {
  4583. delete Storage;
  4584. }
  4585. Saved();
  4586. }
  4587. //---------------------------------------------------------------------
  4588. void __fastcall TStoredSessionList::Save(bool All, bool Explicit)
  4589. {
  4590. DoSave(All, Explicit, false, NULL);
  4591. }
  4592. //---------------------------------------------------------------------
  4593. void __fastcall TStoredSessionList::RecryptPasswords(TStrings * RecryptPasswordErrors)
  4594. {
  4595. DoSave(true, true, true, RecryptPasswordErrors);
  4596. }
  4597. //---------------------------------------------------------------------
  4598. void __fastcall TStoredSessionList::Saved()
  4599. {
  4600. FDefaultSettings->Modified = false;
  4601. for (int Index = 0; Index < CountIncludingHidden; Index++)
  4602. {
  4603. ((TSessionData *)Items[Index])->Modified = false;
  4604. }
  4605. }
  4606. //---------------------------------------------------------------------
  4607. void __fastcall TStoredSessionList::ImportLevelFromFilezilla(
  4608. _di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode)
  4609. {
  4610. for (int Index = 0; Index < Node->ChildNodes->Count; Index++)
  4611. {
  4612. _di_IXMLNode ChildNode = Node->ChildNodes->Get(Index);
  4613. if (ChildNode->NodeName == L"Server")
  4614. {
  4615. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  4616. SessionData->CopyData(DefaultSettings);
  4617. SessionData->ImportFromFilezilla(ChildNode, Path, SettingsNode);
  4618. Add(SessionData.release());
  4619. }
  4620. else if (ChildNode->NodeName == L"Folder")
  4621. {
  4622. UnicodeString Name;
  4623. for (int Index = 0; Index < ChildNode->ChildNodes->Count; Index++)
  4624. {
  4625. _di_IXMLNode PossibleTextMode = ChildNode->ChildNodes->Get(Index);
  4626. if (PossibleTextMode->NodeType == ntText)
  4627. {
  4628. UnicodeString NodeValue = PossibleTextMode->NodeValue;
  4629. AddToList(Name, NodeValue.Trim(), L" ");
  4630. }
  4631. }
  4632. Name = TSessionData::MakeValidName(Name).Trim();
  4633. ImportLevelFromFilezilla(ChildNode, TSessionData::ComposePath(Path, Name), SettingsNode);
  4634. }
  4635. }
  4636. }
  4637. //---------------------------------------------------------------------
  4638. void __fastcall TStoredSessionList::ImportFromFilezilla(
  4639. const UnicodeString FileName, const UnicodeString ConfigurationFileName)
  4640. {
  4641. // not sure if the document must exists if we want to use its node
  4642. _di_IXMLDocument ConfigurationDocument;
  4643. _di_IXMLNode SettingsNode;
  4644. if (FileExists(ApiPath(ConfigurationFileName)))
  4645. {
  4646. ConfigurationDocument = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));
  4647. ConfigurationDocument->LoadFromFile(ConfigurationFileName);
  4648. _di_IXMLNode FileZilla3Node = ConfigurationDocument->ChildNodes->FindNode(L"FileZilla3");
  4649. if (FileZilla3Node != NULL)
  4650. {
  4651. SettingsNode = FileZilla3Node->ChildNodes->FindNode(L"Settings");
  4652. }
  4653. }
  4654. const _di_IXMLDocument Document = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));
  4655. Document->LoadFromFile(FileName);
  4656. _di_IXMLNode FileZilla3Node = Document->ChildNodes->FindNode(L"FileZilla3");
  4657. if (FileZilla3Node != NULL)
  4658. {
  4659. _di_IXMLNode ServersNode = FileZilla3Node->ChildNodes->FindNode(L"Servers");
  4660. if (ServersNode != NULL)
  4661. {
  4662. ImportLevelFromFilezilla(ServersNode, L"", SettingsNode);
  4663. }
  4664. }
  4665. }
  4666. //---------------------------------------------------------------------
  4667. UnicodeString FormatKnownHostName(const UnicodeString & HostName, int PortNumber)
  4668. {
  4669. return FORMAT(L"%s:%d", (HostName, PortNumber));
  4670. }
  4671. //---------------------------------------------------------------------
  4672. void __fastcall TStoredSessionList::ImportFromKnownHosts(TStrings * Lines)
  4673. {
  4674. bool SessionList = false;
  4675. std::unique_ptr<THierarchicalStorage> HostKeyStorage(Configuration->CreateScpStorage(SessionList));
  4676. std::unique_ptr<TStrings> KeyList(new TStringList());
  4677. if (OpenHostKeysSubKey(HostKeyStorage.get(), false))
  4678. {
  4679. HostKeyStorage->GetValueNames(KeyList.get());
  4680. }
  4681. HostKeyStorage.reset(NULL);
  4682. UnicodeString FirstError;
  4683. for (int Index = 0; Index < Lines->Count; Index++)
  4684. {
  4685. try
  4686. {
  4687. UnicodeString Line = Lines->Strings[Index];
  4688. Line = Trim(Line);
  4689. if (IsValidOpensshLine(Line))
  4690. {
  4691. int P = Pos(L' ', Line);
  4692. if (P > 0)
  4693. {
  4694. UnicodeString HostNameStr = Line.SubString(1, P - 1);
  4695. Line = Line.SubString(P + 1, Line.Length() - P);
  4696. P = Pos(L',', HostNameStr);
  4697. if (P > 0)
  4698. {
  4699. HostNameStr.SetLength(P - 1);
  4700. }
  4701. P = Pos(L':', HostNameStr);
  4702. int PortNumber = -1;
  4703. if (P > 0)
  4704. {
  4705. UnicodeString PortNumberStr = HostNameStr.SubString(P + 1, HostNameStr.Length() - P);
  4706. PortNumber = StrToInt(PortNumberStr);
  4707. HostNameStr.SetLength(P - 1);
  4708. }
  4709. if (HasIP6LiteralBrackets(HostNameStr))
  4710. {
  4711. HostNameStr = StripIP6LiteralBrackets(HostNameStr);
  4712. }
  4713. UnicodeString NameStr = HostNameStr;
  4714. if (PortNumber >= 0)
  4715. {
  4716. NameStr = FormatKnownHostName(NameStr, PortNumber);
  4717. }
  4718. std::unique_ptr<TSessionData> SessionDataOwner;
  4719. TSessionData * SessionData = dynamic_cast<TSessionData *>(FindByName(NameStr));
  4720. if (SessionData == NULL)
  4721. {
  4722. SessionData = new TSessionData(L"");
  4723. SessionDataOwner.reset(SessionData);
  4724. SessionData->CopyData(DefaultSettings);
  4725. SessionData->Name = NameStr;
  4726. SessionData->HostName = HostNameStr;
  4727. if (PortNumber >= 0)
  4728. {
  4729. SessionData->PortNumber = PortNumber;
  4730. }
  4731. }
  4732. const struct ssh_keyalg * Algorithm;
  4733. UnicodeString Key = ParseOpenSshPubLine(Line, Algorithm);
  4734. UnicodeString KeyKey =
  4735. FORMAT(L"%s@%d:%s", (Algorithm->cache_id, SessionData->PortNumber, HostNameStr));
  4736. UnicodeString HostKey =
  4737. FORMAT(L"%s:%s=%s", (Algorithm->ssh_id, KeyKey, Key));
  4738. UnicodeString HostKeyList = SessionData->HostKey;
  4739. AddToList(HostKeyList, HostKey, L";");
  4740. SessionData->HostKey = HostKeyList;
  4741. // If there's at least one unknown key type for this host, select it
  4742. if (KeyList->IndexOf(KeyKey) < 0)
  4743. {
  4744. SessionData->Selected = true;
  4745. }
  4746. if (SessionDataOwner.get() != NULL)
  4747. {
  4748. Add(SessionDataOwner.release());
  4749. }
  4750. }
  4751. }
  4752. }
  4753. catch (Exception & E)
  4754. {
  4755. if (FirstError.IsEmpty())
  4756. {
  4757. FirstError = E.Message;
  4758. }
  4759. }
  4760. }
  4761. if (Count == 0)
  4762. {
  4763. UnicodeString Message = LoadStr(KNOWN_HOSTS_NO_SITES);
  4764. if (!FirstError.IsEmpty())
  4765. {
  4766. Message = FORMAT(L"%s\n(%s)", (Message, FirstError));
  4767. }
  4768. throw Exception(Message);
  4769. }
  4770. }
  4771. //---------------------------------------------------------------------
  4772. void TStoredSessionList::ImportFromOpenssh(TStrings * Lines)
  4773. {
  4774. std::unique_ptr<TStrings> Hosts(CreateSortedStringList());
  4775. for (int Index = 0; Index < Lines->Count; Index++)
  4776. {
  4777. UnicodeString Line = Lines->Strings[Index];
  4778. UnicodeString Directive, Value;
  4779. if (ParseOpensshDirective(Line, Directive, Value) &&
  4780. SameText(Directive, OpensshHostDirective))
  4781. {
  4782. while (!Value.IsEmpty())
  4783. {
  4784. UnicodeString Name = CutOpensshToken(Value);
  4785. if ((Hosts->IndexOf(Name) < 0) && (Name.LastDelimiter(L"*?") == 0))
  4786. {
  4787. std::unique_ptr<TSessionData> Data(new TSessionData(EmptyStr));
  4788. Data->CopyData(DefaultSettings);
  4789. Data->Name = Name;
  4790. Data->HostName = Name;
  4791. Data->ImportFromOpenssh(Lines);
  4792. Add(Data.release());
  4793. Hosts->Add(Name);
  4794. }
  4795. }
  4796. }
  4797. }
  4798. }
  4799. //---------------------------------------------------------------------
  4800. void __fastcall TStoredSessionList::Export(const UnicodeString FileName)
  4801. {
  4802. THierarchicalStorage * Storage = TIniFileStorage::CreateFromPath(FileName);
  4803. try
  4804. {
  4805. Storage->AccessMode = smReadWrite;
  4806. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))
  4807. {
  4808. Save(Storage, true);
  4809. }
  4810. }
  4811. __finally
  4812. {
  4813. delete Storage;
  4814. }
  4815. }
  4816. //---------------------------------------------------------------------
  4817. void __fastcall TStoredSessionList::SelectAll(bool Select)
  4818. {
  4819. for (int Index = 0; Index < Count; Index++)
  4820. Sessions[Index]->Selected = Select;
  4821. }
  4822. //---------------------------------------------------------------------
  4823. void __fastcall TStoredSessionList::Import(TStoredSessionList * From,
  4824. bool OnlySelected, TList * Imported)
  4825. {
  4826. for (int Index = 0; Index < From->Count; Index++)
  4827. {
  4828. if (!OnlySelected || From->Sessions[Index]->Selected)
  4829. {
  4830. TSessionData *Session = new TSessionData(L"");
  4831. Session->Assign(From->Sessions[Index]);
  4832. Session->Modified = true;
  4833. Session->MakeUniqueIn(this);
  4834. Add(Session);
  4835. if (Imported != NULL)
  4836. {
  4837. Imported->Add(Session);
  4838. }
  4839. }
  4840. }
  4841. // only modified, explicit
  4842. Save(false, true);
  4843. }
  4844. //---------------------------------------------------------------------
  4845. void __fastcall TStoredSessionList::SelectSessionsToImport
  4846. (TStoredSessionList * Dest, bool SSHOnly)
  4847. {
  4848. for (int Index = 0; Index < Count; Index++)
  4849. {
  4850. Sessions[Index]->Selected =
  4851. (!SSHOnly || (Sessions[Index]->GetNormalizedPuttyProtocol() == PuttySshProtocol)) &&
  4852. !Dest->FindByName(Sessions[Index]->Name);
  4853. }
  4854. }
  4855. //---------------------------------------------------------------------
  4856. void __fastcall TStoredSessionList::Cleanup()
  4857. {
  4858. try
  4859. {
  4860. if (Configuration->Storage == stRegistry) Clear();
  4861. TRegistryStorage * Storage = new TRegistryStorage(Configuration->RegistryStorageKey);
  4862. try
  4863. {
  4864. Storage->AccessMode = smReadWrite;
  4865. if (Storage->OpenRootKey(False))
  4866. Storage->RecursiveDeleteSubKey(Configuration->StoredSessionsSubKey);
  4867. }
  4868. __finally
  4869. {
  4870. delete Storage;
  4871. }
  4872. }
  4873. catch (Exception &E)
  4874. {
  4875. throw ExtException(&E, LoadStr(CLEANUP_SESSIONS_ERROR));
  4876. }
  4877. }
  4878. //---------------------------------------------------------------------------
  4879. void __fastcall TStoredSessionList::UpdateStaticUsage()
  4880. {
  4881. int SCP = 0;
  4882. int SFTP = 0;
  4883. int FTP = 0;
  4884. int FTPS = 0;
  4885. int WebDAV = 0;
  4886. int WebDAVS = 0;
  4887. int S3 = 0;
  4888. int Password = 0;
  4889. int Advanced = 0;
  4890. int Color = 0;
  4891. int Note = 0;
  4892. int Tunnel = 0;
  4893. bool Folders = false;
  4894. bool Workspaces = false;
  4895. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  4896. std::unique_ptr<TStringList> DifferentAdvancedProperties(CreateSortedStringList());
  4897. for (int Index = 0; Index < Count; Index++)
  4898. {
  4899. TSessionData * Data = Sessions[Index];
  4900. if (Data->IsWorkspace)
  4901. {
  4902. Workspaces = true;
  4903. }
  4904. else
  4905. {
  4906. switch (Data->FSProtocol)
  4907. {
  4908. case fsSCPonly:
  4909. SCP++;
  4910. break;
  4911. case fsSFTP:
  4912. case fsSFTPonly:
  4913. SFTP++;
  4914. break;
  4915. case fsFTP:
  4916. if (Data->Ftps == ftpsNone)
  4917. {
  4918. FTP++;
  4919. }
  4920. else
  4921. {
  4922. FTPS++;
  4923. }
  4924. break;
  4925. case fsWebDAV:
  4926. if (Data->Ftps == ftpsNone)
  4927. {
  4928. WebDAV++;
  4929. }
  4930. else
  4931. {
  4932. WebDAVS++;
  4933. }
  4934. break;
  4935. case fsS3:
  4936. S3++;
  4937. break;
  4938. }
  4939. if (Data->HasAnySessionPassword())
  4940. {
  4941. Password++;
  4942. }
  4943. if (Data->Color != 0)
  4944. {
  4945. Color++;
  4946. }
  4947. if (!Data->Note.IsEmpty())
  4948. {
  4949. Note++;
  4950. }
  4951. // This would not work for passwords, as they are compared in their encrypted form.
  4952. // But there are no passwords set in factory defaults anyway.
  4953. if (!Data->IsSame(FactoryDefaults.get(), true, DifferentAdvancedProperties.get(), false))
  4954. {
  4955. Advanced++;
  4956. }
  4957. if (Data->Tunnel)
  4958. {
  4959. Tunnel++;
  4960. }
  4961. if (!Data->FolderName.IsEmpty())
  4962. {
  4963. Folders = true;
  4964. }
  4965. }
  4966. }
  4967. Configuration->Usage->Set(L"StoredSessionsCountSCP", SCP);
  4968. Configuration->Usage->Set(L"StoredSessionsCountSFTP", SFTP);
  4969. Configuration->Usage->Set(L"StoredSessionsCountFTP", FTP);
  4970. Configuration->Usage->Set(L"StoredSessionsCountFTPS", FTPS);
  4971. Configuration->Usage->Set(L"StoredSessionsCountWebDAV", WebDAV);
  4972. Configuration->Usage->Set(L"StoredSessionsCountWebDAVS", WebDAVS);
  4973. Configuration->Usage->Set(L"StoredSessionsCountS3", S3);
  4974. Configuration->Usage->Set(L"StoredSessionsCountPassword", Password);
  4975. Configuration->Usage->Set(L"StoredSessionsCountColor", Color);
  4976. Configuration->Usage->Set(L"StoredSessionsCountNote", Note);
  4977. Configuration->Usage->Set(L"StoredSessionsCountAdvanced", Advanced);
  4978. DifferentAdvancedProperties->Delimiter = L',';
  4979. Configuration->Usage->Set(L"StoredSessionsAdvancedSettings", DifferentAdvancedProperties->DelimitedText);
  4980. Configuration->Usage->Set(L"StoredSessionsCountTunnel", Tunnel);
  4981. // actually default might be true, see below for when the default is actually used
  4982. bool CustomDefaultStoredSession = false;
  4983. try
  4984. {
  4985. // this can throw, when the default session settings have password set
  4986. // (and no other basic property, like hostname/username),
  4987. // and master password is enabled as we are called before master password
  4988. // handler is set
  4989. CustomDefaultStoredSession = !FDefaultSettings->IsSame(FactoryDefaults.get(), false);
  4990. }
  4991. catch (...)
  4992. {
  4993. }
  4994. Configuration->Usage->Set(L"UsingDefaultStoredSession", CustomDefaultStoredSession);
  4995. Configuration->Usage->Set(L"UsingStoredSessionsFolders", Folders);
  4996. Configuration->Usage->Set(L"UsingWorkspaces", Workspaces);
  4997. }
  4998. //---------------------------------------------------------------------------
  4999. TSessionData * __fastcall TStoredSessionList::FindSame(TSessionData * Data)
  5000. {
  5001. TSessionData * Result;
  5002. if (Data->Hidden || Data->Name.IsEmpty() || Data->IsWorkspace)
  5003. {
  5004. Result = NULL;
  5005. }
  5006. else
  5007. {
  5008. Result = dynamic_cast<TSessionData *>(FindByName(Data->Name));
  5009. }
  5010. return Result;
  5011. }
  5012. //---------------------------------------------------------------------------
  5013. int __fastcall TStoredSessionList::IndexOf(TSessionData * Data)
  5014. {
  5015. for (int Index = 0; Index < Count; Index++)
  5016. if (Data == Sessions[Index]) return Index;
  5017. return -1;
  5018. }
  5019. //---------------------------------------------------------------------------
  5020. TSessionData * __fastcall TStoredSessionList::NewSession(
  5021. UnicodeString SessionName, TSessionData * Session)
  5022. {
  5023. TSessionData * DuplicateSession = (TSessionData*)FindByName(SessionName);
  5024. if (!DuplicateSession)
  5025. {
  5026. DuplicateSession = new TSessionData(L"");
  5027. DuplicateSession->Assign(Session);
  5028. DuplicateSession->Name = SessionName;
  5029. // make sure, that new stored session is saved to registry
  5030. DuplicateSession->Modified = true;
  5031. Add(DuplicateSession);
  5032. }
  5033. else
  5034. {
  5035. DuplicateSession->Assign(Session);
  5036. DuplicateSession->Name = SessionName;
  5037. DuplicateSession->Modified = true;
  5038. }
  5039. // list was saved here before to default storage, but it would not allow
  5040. // to work with special lists (export/import) not using default storage
  5041. return DuplicateSession;
  5042. }
  5043. //---------------------------------------------------------------------------
  5044. void __fastcall TStoredSessionList::SetDefaultSettings(TSessionData * value)
  5045. {
  5046. DebugAssert(FDefaultSettings);
  5047. if (FDefaultSettings != value)
  5048. {
  5049. FDefaultSettings->Assign(value);
  5050. // make sure default settings are saved
  5051. FDefaultSettings->Modified = true;
  5052. FDefaultSettings->Name = DefaultName;
  5053. if (!FReadOnly)
  5054. {
  5055. // only modified, explicit
  5056. Save(false, true);
  5057. }
  5058. }
  5059. }
  5060. //---------------------------------------------------------------------------
  5061. bool __fastcall TStoredSessionList::OpenHostKeysSubKey(THierarchicalStorage * Storage, bool CanCreate)
  5062. {
  5063. return
  5064. Storage->OpenRootKey(CanCreate) &&
  5065. Storage->OpenSubKey(Configuration->SshHostKeysSubKey, CanCreate);
  5066. }
  5067. //---------------------------------------------------------------------------
  5068. THierarchicalStorage * __fastcall TStoredSessionList::CreateHostKeysStorageForWritting()
  5069. {
  5070. bool SessionList = false;
  5071. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));
  5072. Storage->Explicit = true;
  5073. Storage->AccessMode = smReadWrite;
  5074. return Storage.release();
  5075. }
  5076. //---------------------------------------------------------------------------
  5077. void __fastcall TStoredSessionList::ImportHostKeys(
  5078. THierarchicalStorage * SourceStorage, THierarchicalStorage * TargetStorage, TStoredSessionList * Sessions, bool OnlySelected)
  5079. {
  5080. if (OpenHostKeysSubKey(SourceStorage, false) &&
  5081. OpenHostKeysSubKey(TargetStorage, true))
  5082. {
  5083. std::auto_ptr<TStringList> KeyList(new TStringList());
  5084. SourceStorage->GetValueNames(KeyList.get());
  5085. DebugAssert(Sessions != NULL);
  5086. for (int Index = 0; Index < Sessions->Count; Index++)
  5087. {
  5088. TSessionData * Session = Sessions->Sessions[Index];
  5089. if (!OnlySelected || Session->Selected)
  5090. {
  5091. UnicodeString HostKeyName = PuttyMungeStr(FORMAT(L"@%d:%s", (Session->PortNumber, Session->HostNameExpanded)));
  5092. for (int KeyIndex = 0; KeyIndex < KeyList->Count; KeyIndex++)
  5093. {
  5094. UnicodeString KeyName = KeyList->Strings[KeyIndex];
  5095. if (EndsText(HostKeyName, KeyName))
  5096. {
  5097. TargetStorage->WriteStringRaw(KeyName, SourceStorage->ReadStringRaw(KeyName, L""));
  5098. }
  5099. }
  5100. }
  5101. }
  5102. }
  5103. }
  5104. //---------------------------------------------------------------------------
  5105. void __fastcall TStoredSessionList::ImportHostKeys(
  5106. const UnicodeString & SourceKey, TStoredSessionList * Sessions, bool OnlySelected)
  5107. {
  5108. std::auto_ptr<THierarchicalStorage> TargetStorage(CreateHostKeysStorageForWritting());
  5109. std::auto_ptr<THierarchicalStorage> SourceStorage(new TRegistryStorage(SourceKey));
  5110. ImportHostKeys(SourceStorage.get(), TargetStorage.get(), Sessions, OnlySelected);
  5111. }
  5112. //---------------------------------------------------------------------------
  5113. void __fastcall TStoredSessionList::ImportSelectedKnownHosts(TStoredSessionList * Sessions)
  5114. {
  5115. std::unique_ptr<THierarchicalStorage> Storage(CreateHostKeysStorageForWritting());
  5116. if (OpenHostKeysSubKey(Storage.get(), true))
  5117. {
  5118. for (int Index = 0; Index < Sessions->Count; Index++)
  5119. {
  5120. TSessionData * Session = Sessions->Sessions[Index];
  5121. if (Session->Selected)
  5122. {
  5123. UnicodeString Algs;
  5124. UnicodeString HostKeys = Session->HostKey;
  5125. while (!HostKeys.IsEmpty())
  5126. {
  5127. UnicodeString HostKey = CutToChar(HostKeys, L';', true);
  5128. // skip alg
  5129. CutToChar(HostKey, L':', true);
  5130. UnicodeString Key = CutToChar(HostKey, L'=', true);
  5131. Storage->WriteStringRaw(Key, HostKey);
  5132. }
  5133. }
  5134. }
  5135. }
  5136. }
  5137. //---------------------------------------------------------------------------
  5138. void TStoredSessionList::SelectKnownHostsForSelectedSessions(
  5139. TStoredSessionList * KnownHosts, TStoredSessionList * Sessions)
  5140. {
  5141. for (int SessionIndex = 0; SessionIndex < Sessions->Count; SessionIndex++)
  5142. {
  5143. TSessionData * Session = Sessions->Sessions[SessionIndex];
  5144. if (Session->Selected)
  5145. {
  5146. UnicodeString Key = Session->HostName;
  5147. if (Session->PortNumber != Session->GetDefaultPort())
  5148. {
  5149. Key = FormatKnownHostName(Key, Session->PortNumber);
  5150. }
  5151. TSessionData * KnownHost = dynamic_cast<TSessionData *>(KnownHosts->FindByName(Key));
  5152. if (KnownHost != NULL)
  5153. {
  5154. KnownHost->Selected = true;
  5155. }
  5156. }
  5157. }
  5158. }
  5159. //---------------------------------------------------------------------------
  5160. bool __fastcall TStoredSessionList::IsFolderOrWorkspace(
  5161. const UnicodeString & Name, bool Workspace)
  5162. {
  5163. bool Result = false;
  5164. TSessionData * FirstData = NULL;
  5165. if (!Name.IsEmpty())
  5166. {
  5167. for (int Index = 0; !Result && (Index < Count); Index++)
  5168. {
  5169. Result = Sessions[Index]->IsInFolderOrWorkspace(Name);
  5170. if (Result)
  5171. {
  5172. FirstData = Sessions[Index];
  5173. }
  5174. }
  5175. }
  5176. return
  5177. Result &&
  5178. DebugAlwaysTrue(FirstData != NULL) &&
  5179. (FirstData->IsWorkspace == Workspace);
  5180. }
  5181. //---------------------------------------------------------------------------
  5182. bool __fastcall TStoredSessionList::IsFolder(const UnicodeString & Name)
  5183. {
  5184. return IsFolderOrWorkspace(Name, false);
  5185. }
  5186. //---------------------------------------------------------------------------
  5187. bool __fastcall TStoredSessionList::IsWorkspace(const UnicodeString & Name)
  5188. {
  5189. return IsFolderOrWorkspace(Name, true);
  5190. }
  5191. //---------------------------------------------------------------------------
  5192. TSessionData * __fastcall TStoredSessionList::CheckIsInFolderOrWorkspaceAndResolve(
  5193. TSessionData * Data, const UnicodeString & Name)
  5194. {
  5195. if (Data->IsInFolderOrWorkspace(Name))
  5196. {
  5197. Data = ResolveWorkspaceData(Data);
  5198. if ((Data != NULL) && Data->CanOpen &&
  5199. DebugAlwaysTrue(Data->Link.IsEmpty()))
  5200. {
  5201. return Data;
  5202. }
  5203. }
  5204. return NULL;
  5205. }
  5206. //---------------------------------------------------------------------------
  5207. void __fastcall TStoredSessionList::GetFolderOrWorkspace(const UnicodeString & Name, TList * List)
  5208. {
  5209. DoGetFolderOrWorkspace(Name, List, false);
  5210. }
  5211. //---------------------------------------------------------------------------
  5212. void __fastcall TStoredSessionList::DoGetFolderOrWorkspace(const UnicodeString & Name, TList * List, bool NoRecrypt)
  5213. {
  5214. for (int Index = 0; (Index < Count); Index++)
  5215. {
  5216. TSessionData * RawData = Sessions[Index];
  5217. TSessionData * Data =
  5218. CheckIsInFolderOrWorkspaceAndResolve(RawData, Name);
  5219. if (Data != NULL)
  5220. {
  5221. TSessionData * Data2 = new TSessionData(L"");
  5222. if (NoRecrypt)
  5223. {
  5224. Data2->CopyDataNoRecrypt(Data);
  5225. }
  5226. else
  5227. {
  5228. Data2->Assign(Data);
  5229. }
  5230. if (!RawData->Link.IsEmpty() && (DebugAlwaysTrue(Data != RawData)) &&
  5231. // BACKWARD COMPATIBILITY
  5232. // When loading pre-5.6.4 workspace, that does not have state saved,
  5233. // do not overwrite the site "state" defaults
  5234. // with (empty) workspace state
  5235. RawData->HasStateData())
  5236. {
  5237. Data2->CopyStateData(RawData);
  5238. }
  5239. if (!RawData->NameOverride.IsEmpty())
  5240. {
  5241. Data2->Name = RawData->NameOverride;
  5242. }
  5243. else if (RawData->Link.IsEmpty() && RawData->IsWorkspace)
  5244. {
  5245. // Newly opened ad-hoc session has no name, so restore the workspace that way too.
  5246. // Otherwise we would persist the generated internal workspace name as a real name.
  5247. Data2->Name = UnicodeString();
  5248. }
  5249. List->Add(Data2);
  5250. }
  5251. }
  5252. }
  5253. //---------------------------------------------------------------------------
  5254. TStrings * __fastcall TStoredSessionList::GetFolderOrWorkspaceList(
  5255. const UnicodeString & Name)
  5256. {
  5257. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5258. DoGetFolderOrWorkspace(Name, DataList.get(), true);
  5259. std::unique_ptr<TStringList> Result(new TStringList());
  5260. for (int Index = 0; (Index < DataList->Count); Index++)
  5261. {
  5262. Result->Add(dynamic_cast<TSessionData *>(DataList->Items[Index])->SessionName);
  5263. }
  5264. return Result.release();
  5265. }
  5266. //---------------------------------------------------------------------------
  5267. TStrings * __fastcall TStoredSessionList::GetWorkspaces()
  5268. {
  5269. std::unique_ptr<TStringList> Result(CreateSortedStringList());
  5270. for (int Index = 0; (Index < Count); Index++)
  5271. {
  5272. TSessionData * Data = Sessions[Index];
  5273. if (Data->IsWorkspace)
  5274. {
  5275. Result->Add(Data->FolderName);
  5276. }
  5277. }
  5278. return Result.release();
  5279. }
  5280. //---------------------------------------------------------------------------
  5281. void __fastcall TStoredSessionList::NewWorkspace(
  5282. UnicodeString Name, TList * DataList)
  5283. {
  5284. for (int Index = 0; (Index < Count); Index++)
  5285. {
  5286. TSessionData * Data = Sessions[Index];
  5287. if (Data->IsInFolderOrWorkspace(Name))
  5288. {
  5289. FPendingRemovals->Add(Data->Name);
  5290. Remove(Data);
  5291. Index--;
  5292. }
  5293. }
  5294. for (int Index = 0; (Index < DataList->Count); Index++)
  5295. {
  5296. TSessionData * Data = static_cast<TSessionData *>(DataList->Items[Index]);
  5297. TSessionData * Data2 = new TSessionData(L"");
  5298. Data2->Assign(Data);
  5299. Data2->Name = TSessionData::ComposePath(Name, Data->Name);
  5300. // make sure, that new stored session is saved to registry
  5301. Data2->Modified = true;
  5302. Add(Data2);
  5303. }
  5304. }
  5305. //---------------------------------------------------------------------------
  5306. bool __fastcall TStoredSessionList::HasAnyWorkspace()
  5307. {
  5308. bool Result = false;
  5309. for (int Index = 0; !Result && (Index < Count); Index++)
  5310. {
  5311. TSessionData * Data = Sessions[Index];
  5312. Result = Data->IsWorkspace;
  5313. }
  5314. return Result;
  5315. }
  5316. //---------------------------------------------------------------------------
  5317. TSessionData * __fastcall TStoredSessionList::ParseUrl(UnicodeString Url,
  5318. TOptions * Options, bool & DefaultsOnly, UnicodeString * FileName,
  5319. bool * AProtocolDefined, UnicodeString * MaskedUrl, int Flags)
  5320. {
  5321. TSessionData * Data = new TSessionData(L"");
  5322. try
  5323. {
  5324. Data->ParseUrl(Url, Options, this, DefaultsOnly, FileName, AProtocolDefined, MaskedUrl, Flags);
  5325. }
  5326. catch(...)
  5327. {
  5328. delete Data;
  5329. throw;
  5330. }
  5331. return Data;
  5332. }
  5333. //---------------------------------------------------------------------
  5334. bool __fastcall TStoredSessionList::IsUrl(UnicodeString Url)
  5335. {
  5336. bool DefaultsOnly;
  5337. bool ProtocolDefined = false;
  5338. std::unique_ptr<TSessionData> ParsedData(ParseUrl(Url, NULL, DefaultsOnly, NULL, &ProtocolDefined));
  5339. bool Result = ProtocolDefined;
  5340. return Result;
  5341. }
  5342. //---------------------------------------------------------------------
  5343. TSessionData * __fastcall TStoredSessionList::ResolveWorkspaceData(TSessionData * Data)
  5344. {
  5345. if (!Data->Link.IsEmpty())
  5346. {
  5347. Data = dynamic_cast<TSessionData *>(FindByName(Data->Link));
  5348. if (Data != NULL)
  5349. {
  5350. Data = ResolveWorkspaceData(Data);
  5351. }
  5352. }
  5353. return Data;
  5354. }
  5355. //---------------------------------------------------------------------
  5356. TSessionData * __fastcall TStoredSessionList::SaveWorkspaceData(TSessionData * Data, int Index)
  5357. {
  5358. std::unique_ptr<TSessionData> Result(new TSessionData(L""));
  5359. TSessionData * SameData = StoredSessions->FindSame(Data);
  5360. if (SameData != NULL)
  5361. {
  5362. Result->CopyStateData(Data);
  5363. Result->Link = Data->Name;
  5364. }
  5365. else
  5366. {
  5367. Result->Assign(Data);
  5368. Result->NameOverride = Data->Name;
  5369. }
  5370. Result->IsWorkspace = true;
  5371. Result->Name = IntToHex(Index, 4); // See HasSessionName()
  5372. return Result.release();
  5373. }
  5374. //---------------------------------------------------------------------
  5375. bool __fastcall TStoredSessionList::CanOpen(TSessionData * Data)
  5376. {
  5377. Data = ResolveWorkspaceData(Data);
  5378. return (Data != NULL) && Data->CanOpen;
  5379. }
  5380. //---------------------------------------------------------------------
  5381. UnicodeString GetExpandedLogFileName(UnicodeString LogFileName, TDateTime Started, TSessionData * SessionData)
  5382. {
  5383. // StripPathQuotes should not be needed as we do not feed quotes anymore
  5384. UnicodeString ANewFileName = StripPathQuotes(ExpandEnvironmentVariables(LogFileName));
  5385. for (int Index = 1; Index < ANewFileName.Length(); Index++)
  5386. {
  5387. if (ANewFileName[Index] == L'!')
  5388. {
  5389. UnicodeString Replacement;
  5390. // keep consistent with TFileCustomCommand::PatternReplacement
  5391. switch (tolower(ANewFileName[Index + 1]))
  5392. {
  5393. case L'y':
  5394. Replacement = FormatDateTime(L"yyyy", Started);
  5395. break;
  5396. case L'm':
  5397. Replacement = FormatDateTime(L"mm", Started);
  5398. break;
  5399. case L'd':
  5400. Replacement = FormatDateTime(L"dd", Started);
  5401. break;
  5402. case L't':
  5403. Replacement = FormatDateTime(L"hhnnss", Started);
  5404. break;
  5405. case 'p':
  5406. Replacement = IntToStr(static_cast<int>(GetCurrentProcessId()));
  5407. break;
  5408. case L'@':
  5409. if (SessionData != NULL)
  5410. {
  5411. Replacement = MakeValidFileName(SessionData->HostNameExpanded);
  5412. }
  5413. else
  5414. {
  5415. Replacement = L"nohost";
  5416. }
  5417. break;
  5418. case L's':
  5419. if (SessionData != NULL)
  5420. {
  5421. Replacement = MakeValidFileName(SessionData->SessionName);
  5422. }
  5423. else
  5424. {
  5425. Replacement = L"nosession";
  5426. }
  5427. break;
  5428. case L'!':
  5429. Replacement = L"!";
  5430. break;
  5431. default:
  5432. Replacement = UnicodeString(L"!") + ANewFileName[Index + 1];
  5433. break;
  5434. }
  5435. ANewFileName.Delete(Index, 2);
  5436. ANewFileName.Insert(Replacement, Index);
  5437. Index += Replacement.Length() - 1;
  5438. }
  5439. }
  5440. return ANewFileName;
  5441. }
  5442. //---------------------------------------------------------------------
  5443. bool __fastcall IsSshProtocol(TFSProtocol FSProtocol)
  5444. {
  5445. return
  5446. (FSProtocol == fsSFTPonly) || (FSProtocol == fsSFTP) ||
  5447. (FSProtocol == fsSCPonly);
  5448. }
  5449. //---------------------------------------------------------------------------
  5450. int __fastcall DefaultPort(TFSProtocol FSProtocol, TFtps Ftps)
  5451. {
  5452. int Result;
  5453. switch (FSProtocol)
  5454. {
  5455. case fsFTP:
  5456. if (Ftps == ftpsImplicit)
  5457. {
  5458. Result = FtpsImplicitPortNumber;
  5459. }
  5460. else
  5461. {
  5462. Result = FtpPortNumber;
  5463. }
  5464. break;
  5465. case fsWebDAV:
  5466. case fsS3:
  5467. if (Ftps == ftpsNone)
  5468. {
  5469. Result = HTTPPortNumber;
  5470. }
  5471. else
  5472. {
  5473. Result = HTTPSPortNumber;
  5474. }
  5475. break;
  5476. default:
  5477. if (IsSshProtocol(FSProtocol))
  5478. {
  5479. Result = SshPortNumber;
  5480. }
  5481. else
  5482. {
  5483. DebugFail();
  5484. Result = -1;
  5485. }
  5486. break;
  5487. }
  5488. return Result;
  5489. }
  5490. //---------------------------------------------------------------------