SessionData.cpp 177 KB

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