SessionData.cpp 184 KB

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