SessionData.cpp 191 KB

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