SessionData.cpp 193 KB

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