SessionData.cpp 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336
  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 <Soap.EncdDecd.hpp>
  14. #include <StrUtils.hpp>
  15. #include <XMLDoc.hpp>
  16. #include <StrUtils.hpp>
  17. #include <algorithm>
  18. //---------------------------------------------------------------------------
  19. #pragma package(smart_init)
  20. //---------------------------------------------------------------------------
  21. const wchar_t * PingTypeNames = L"Off;Null;Dummy";
  22. const wchar_t * ProxyMethodNames = L"None;SOCKS4;SOCKS5;HTTP;Telnet;Cmd";
  23. const wchar_t * DefaultName = L"Default Settings";
  24. const UnicodeString CipherNames[CIPHER_COUNT] = {L"WARN", L"3des", L"blowfish", L"aes", L"des", L"arcfour", L"chacha20"};
  25. const UnicodeString KexNames[KEX_COUNT] = {L"WARN", L"dh-group1-sha1", L"dh-group14-sha1", L"dh-gex-sha1", L"rsa", L"ecdh"};
  26. const wchar_t SshProtList[][10] = {L"1 only", L"1", L"2", L"2 only"};
  27. const TCipher DefaultCipherList[CIPHER_COUNT] =
  28. { cipChaCha20, cipAES, cipBlowfish, cip3DES, cipWarn, cipArcfour, cipDES };
  29. const TKex DefaultKexList[KEX_COUNT] =
  30. { kexECDH, kexDHGEx, kexDHGroup14, kexDHGroup1, kexRSA, kexWarn };
  31. const wchar_t FSProtocolNames[FSPROTOCOL_COUNT][16] = { L"SCP", L"SFTP (SCP)", L"SFTP", L"", L"", L"FTP", L"WebDAV" };
  32. const int SshPortNumber = 22;
  33. const int FtpPortNumber = 21;
  34. const int FtpsImplicitPortNumber = 990;
  35. const int HTTPPortNumber = 80;
  36. const int HTTPSPortNumber = 443;
  37. const int TelnetPortNumber = 23;
  38. const int DefaultSendBuf = 262144;
  39. const int ProxyPortNumber = 80;
  40. const UnicodeString AnonymousUserName(L"anonymous");
  41. const UnicodeString AnonymousPassword(L"[email protected]");
  42. const UnicodeString PuttySshProtocol(L"ssh");
  43. const UnicodeString PuttyTelnetProtocol(L"telnet");
  44. const UnicodeString SftpProtocol(L"sftp");
  45. const UnicodeString ScpProtocol(L"scp");
  46. const UnicodeString FtpProtocol(L"ftp");
  47. const UnicodeString FtpsProtocol(L"ftps");
  48. const UnicodeString FtpesProtocol(L"ftpes");
  49. const UnicodeString WebDAVProtocol(L"http");
  50. const UnicodeString WebDAVSProtocol(L"https");
  51. const UnicodeString SshProtocol(L"ssh");
  52. const UnicodeString ProtocolSeparator(L"://");
  53. const UnicodeString WinSCPProtocolPrefix(L"winscp-");
  54. const wchar_t UrlParamSeparator = L';';
  55. const wchar_t UrlParamValueSeparator = L'=';
  56. const UnicodeString UrlHostKeyParamName(L"fingerprint");
  57. const UnicodeString UrlSaveParamName(L"save");
  58. const UnicodeString PassphraseOption(L"passphrase");
  59. //---------------------------------------------------------------------
  60. TDateTime __fastcall SecToDateTime(int Sec)
  61. {
  62. return TDateTime(double(Sec) / SecsPerDay);
  63. }
  64. //--- TSessionData ----------------------------------------------------
  65. __fastcall TSessionData::TSessionData(UnicodeString aName):
  66. TNamedObject(aName)
  67. {
  68. Default();
  69. FModified = true;
  70. }
  71. //---------------------------------------------------------------------
  72. _fastcall TSessionData::~TSessionData()
  73. {
  74. }
  75. //---------------------------------------------------------------------
  76. int __fastcall TSessionData::Compare(TNamedObject * Other)
  77. {
  78. int Result;
  79. // To avoid using CompareLogicalText on hex names of sessions in workspace.
  80. // The session 000A would be sorted before 0001.
  81. if (IsWorkspace && DebugNotNull(dynamic_cast<TSessionData *>(Other))->IsWorkspace)
  82. {
  83. Result = CompareText(Name, Other->Name);
  84. }
  85. else
  86. {
  87. Result = TNamedObject::Compare(Other);
  88. }
  89. return Result;
  90. }
  91. //---------------------------------------------------------------------
  92. TSessionData * __fastcall TSessionData::Clone()
  93. {
  94. std::unique_ptr<TSessionData> Data(new TSessionData(L""));
  95. Data->Assign(this);
  96. return Data.release();
  97. }
  98. //---------------------------------------------------------------------
  99. void __fastcall TSessionData::Default()
  100. {
  101. HostName = L"";
  102. PortNumber = SshPortNumber;
  103. UserName = L"";
  104. Password = L"";
  105. PingInterval = 30;
  106. PingType = ptOff;
  107. Timeout = 15;
  108. TryAgent = true;
  109. AgentFwd = false;
  110. AuthTIS = false;
  111. AuthKI = true;
  112. AuthKIPassword = true;
  113. AuthGSSAPI = false;
  114. GSSAPIFwdTGT = false;
  115. GSSAPIServerRealm = L"";
  116. ChangeUsername = false;
  117. Compression = false;
  118. SshProt = ssh2;
  119. Ssh2DES = false;
  120. SshNoUserAuth = false;
  121. for (int Index = 0; Index < CIPHER_COUNT; Index++)
  122. {
  123. Cipher[Index] = DefaultCipherList[Index];
  124. }
  125. for (int Index = 0; Index < KEX_COUNT; Index++)
  126. {
  127. Kex[Index] = DefaultKexList[Index];
  128. }
  129. PublicKeyFile = L"";
  130. Passphrase = L"";
  131. FPuttyProtocol = L"";
  132. TcpNoDelay = false;
  133. SendBuf = DefaultSendBuf;
  134. SshSimple = true;
  135. HostKey = L"";
  136. FOverrideCachedHostKey = true;
  137. Note = L"";
  138. ProxyMethod = ::pmNone;
  139. ProxyHost = L"proxy";
  140. ProxyPort = ProxyPortNumber;
  141. ProxyUsername = L"";
  142. ProxyPassword = L"";
  143. ProxyTelnetCommand = L"connect %host %port\\n";
  144. ProxyLocalCommand = L"";
  145. ProxyDNS = asAuto;
  146. ProxyLocalhost = false;
  147. for (unsigned int Index = 0; Index < LENOF(FBugs); Index++)
  148. {
  149. Bug[(TSshBug)Index] = asAuto;
  150. }
  151. Special = false;
  152. FSProtocol = fsSFTP;
  153. AddressFamily = afAuto;
  154. RekeyData = L"1G";
  155. RekeyTime = MinsPerHour;
  156. // FS common
  157. LocalDirectory = L"";
  158. RemoteDirectory = L"";
  159. SynchronizeBrowsing = false;
  160. UpdateDirectories = true;
  161. CacheDirectories = true;
  162. CacheDirectoryChanges = true;
  163. PreserveDirectoryChanges = true;
  164. LockInHome = false;
  165. ResolveSymlinks = true;
  166. DSTMode = dstmUnix;
  167. DeleteToRecycleBin = false;
  168. OverwrittenToRecycleBin = false;
  169. RecycleBinPath = L"";
  170. Color = 0;
  171. PostLoginCommands = L"";
  172. // SCP
  173. ReturnVar = L"";
  174. LookupUserGroups = asAuto;
  175. EOLType = eolLF;
  176. TrimVMSVersions = false;
  177. Shell = L""; //default shell
  178. ReturnVar = L"";
  179. ClearAliases = true;
  180. UnsetNationalVars = true;
  181. ListingCommand = L"ls -la";
  182. IgnoreLsWarnings = true;
  183. Scp1Compatibility = false;
  184. TimeDifference = 0;
  185. TimeDifferenceAuto = true;
  186. SCPLsFullTime = asAuto;
  187. NotUtf = asAuto;
  188. // SFTP
  189. SftpServer = L"";
  190. SFTPDownloadQueue = 32;
  191. SFTPUploadQueue = 32;
  192. SFTPListingQueue = 2;
  193. SFTPMaxVersion = ::SFTPMaxVersion;
  194. SFTPMaxPacketSize = 0;
  195. for (unsigned int Index = 0; Index < LENOF(FSFTPBugs); Index++)
  196. {
  197. SFTPBug[(TSftpBug)Index] = asAuto;
  198. }
  199. Tunnel = false;
  200. TunnelHostName = L"";
  201. TunnelPortNumber = SshPortNumber;
  202. TunnelUserName = L"";
  203. TunnelPassword = L"";
  204. TunnelPublicKeyFile = L"";
  205. TunnelLocalPortNumber = 0;
  206. TunnelPortFwd = L"";
  207. TunnelHostKey = L"";
  208. // FTP
  209. FtpPasvMode = true;
  210. FtpForcePasvIp = asAuto;
  211. FtpUseMlsd = asAuto;
  212. FtpAccount = L"";
  213. FtpPingInterval = 30;
  214. FtpPingType = ptDummyCommand;
  215. FtpTransferActiveImmediately = asAuto;
  216. Ftps = ftpsNone;
  217. MinTlsVersion = tls10;
  218. MaxTlsVersion = tls12;
  219. FtpListAll = asAuto;
  220. FtpHost = asAuto;
  221. SslSessionReuse = true;
  222. TlsCertificateFile = L"";
  223. FtpProxyLogonType = 0; // none
  224. CustomParam1 = L"";
  225. CustomParam2 = L"";
  226. IsWorkspace = false;
  227. Link = L"";
  228. Selected = false;
  229. FModified = false;
  230. FSource = ::ssNone;
  231. FSaveOnly = false;
  232. // add also to TSessionLog::AddStartupInfo()
  233. }
  234. //---------------------------------------------------------------------
  235. void __fastcall TSessionData::NonPersistant()
  236. {
  237. UpdateDirectories = false;
  238. PreserveDirectoryChanges = false;
  239. }
  240. //---------------------------------------------------------------------
  241. #define BASE_PROPERTIES \
  242. PROPERTY(HostName); \
  243. PROPERTY(PortNumber); \
  244. PROPERTY(UserName); \
  245. PROPERTY(Password); \
  246. PROPERTY(PublicKeyFile); \
  247. PROPERTY(Passphrase); \
  248. PROPERTY(FSProtocol); \
  249. PROPERTY(Ftps); \
  250. PROPERTY(LocalDirectory); \
  251. PROPERTY(RemoteDirectory); \
  252. PROPERTY(Color); \
  253. PROPERTY(SynchronizeBrowsing); \
  254. PROPERTY(Note);
  255. //---------------------------------------------------------------------
  256. #define ADVANCED_PROPERTIES \
  257. PROPERTY(PingInterval); \
  258. PROPERTY(PingType); \
  259. PROPERTY(Timeout); \
  260. PROPERTY(TryAgent); \
  261. PROPERTY(AgentFwd); \
  262. PROPERTY(AuthTIS); \
  263. PROPERTY(ChangeUsername); \
  264. PROPERTY(Compression); \
  265. PROPERTY(SshProt); \
  266. PROPERTY(Ssh2DES); \
  267. PROPERTY(SshNoUserAuth); \
  268. PROPERTY(CipherList); \
  269. PROPERTY(KexList); \
  270. PROPERTY(AddressFamily); \
  271. PROPERTY(RekeyData); \
  272. PROPERTY(RekeyTime); \
  273. PROPERTY(HostKey); \
  274. \
  275. PROPERTY(UpdateDirectories); \
  276. PROPERTY(CacheDirectories); \
  277. PROPERTY(CacheDirectoryChanges); \
  278. PROPERTY(PreserveDirectoryChanges); \
  279. \
  280. PROPERTY(ResolveSymlinks); \
  281. PROPERTY(DSTMode); \
  282. PROPERTY(LockInHome); \
  283. PROPERTY(Special); \
  284. PROPERTY(Selected); \
  285. PROPERTY(ReturnVar); \
  286. PROPERTY(LookupUserGroups); \
  287. PROPERTY(EOLType); \
  288. PROPERTY(TrimVMSVersions); \
  289. PROPERTY(Shell); \
  290. PROPERTY(ClearAliases); \
  291. PROPERTY(Scp1Compatibility); \
  292. PROPERTY(UnsetNationalVars); \
  293. PROPERTY(ListingCommand); \
  294. PROPERTY(IgnoreLsWarnings); \
  295. PROPERTY(SCPLsFullTime); \
  296. \
  297. PROPERTY(TimeDifference); \
  298. PROPERTY(TimeDifferenceAuto); \
  299. PROPERTY(TcpNoDelay); \
  300. PROPERTY(SendBuf); \
  301. PROPERTY(SshSimple); \
  302. PROPERTY(AuthKI); \
  303. PROPERTY(AuthKIPassword); \
  304. PROPERTY(AuthGSSAPI); \
  305. PROPERTY(GSSAPIFwdTGT); \
  306. PROPERTY(GSSAPIServerRealm); \
  307. PROPERTY(DeleteToRecycleBin); \
  308. PROPERTY(OverwrittenToRecycleBin); \
  309. PROPERTY(RecycleBinPath); \
  310. PROPERTY(NotUtf); \
  311. PROPERTY(PostLoginCommands); \
  312. \
  313. PROPERTY(ProxyMethod); \
  314. PROPERTY(ProxyHost); \
  315. PROPERTY(ProxyPort); \
  316. PROPERTY(ProxyUsername); \
  317. PROPERTY(ProxyPassword); \
  318. PROPERTY(ProxyTelnetCommand); \
  319. PROPERTY(ProxyLocalCommand); \
  320. PROPERTY(ProxyDNS); \
  321. PROPERTY(ProxyLocalhost); \
  322. \
  323. for (unsigned int Index = 0; Index < LENOF(FBugs); Index++) \
  324. { \
  325. PROPERTY(Bug[(TSshBug)Index]); \
  326. } \
  327. \
  328. PROPERTY(SftpServer); \
  329. PROPERTY(SFTPDownloadQueue); \
  330. PROPERTY(SFTPUploadQueue); \
  331. PROPERTY(SFTPListingQueue); \
  332. PROPERTY(SFTPMaxVersion); \
  333. PROPERTY(SFTPMaxPacketSize); \
  334. \
  335. for (unsigned int Index = 0; Index < LENOF(FSFTPBugs); Index++) \
  336. { \
  337. PROPERTY(SFTPBug[(TSftpBug)Index]); \
  338. } \
  339. \
  340. PROPERTY(Tunnel); \
  341. PROPERTY(TunnelHostName); \
  342. PROPERTY(TunnelPortNumber); \
  343. PROPERTY(TunnelUserName); \
  344. PROPERTY(TunnelPassword); \
  345. PROPERTY(TunnelPublicKeyFile); \
  346. PROPERTY(TunnelLocalPortNumber); \
  347. PROPERTY(TunnelPortFwd); \
  348. PROPERTY(TunnelHostKey); \
  349. \
  350. PROPERTY(FtpPasvMode); \
  351. PROPERTY(FtpForcePasvIp); \
  352. PROPERTY(FtpUseMlsd); \
  353. PROPERTY(FtpAccount); \
  354. PROPERTY(FtpPingInterval); \
  355. PROPERTY(FtpPingType); \
  356. PROPERTY(FtpTransferActiveImmediately); \
  357. PROPERTY(FtpListAll); \
  358. PROPERTY(FtpHost); \
  359. PROPERTY(SslSessionReuse); \
  360. PROPERTY(TlsCertificateFile); \
  361. \
  362. PROPERTY(FtpProxyLogonType); \
  363. \
  364. PROPERTY(MinTlsVersion); \
  365. PROPERTY(MaxTlsVersion); \
  366. \
  367. PROPERTY(CustomParam1); \
  368. PROPERTY(CustomParam2);
  369. #define META_PROPERTIES \
  370. PROPERTY(IsWorkspace); \
  371. PROPERTY(Link);
  372. //---------------------------------------------------------------------
  373. void __fastcall TSessionData::Assign(TPersistent * Source)
  374. {
  375. if (Source && Source->InheritsFrom(__classid(TSessionData)))
  376. {
  377. TSessionData * SourceData = (TSessionData *)Source;
  378. CopyData(SourceData);
  379. FSource = SourceData->FSource;
  380. }
  381. else
  382. {
  383. TNamedObject::Assign(Source);
  384. }
  385. }
  386. //---------------------------------------------------------------------
  387. void __fastcall TSessionData::CopyData(TSessionData * SourceData)
  388. {
  389. #define PROPERTY(P) P = SourceData->P
  390. PROPERTY(Name);
  391. BASE_PROPERTIES;
  392. ADVANCED_PROPERTIES;
  393. META_PROPERTIES;
  394. #undef PROPERTY
  395. FOverrideCachedHostKey = SourceData->FOverrideCachedHostKey;
  396. FModified = SourceData->Modified;
  397. FSaveOnly = SourceData->FSaveOnly;
  398. }
  399. //---------------------------------------------------------------------
  400. void __fastcall TSessionData::CopyDirectoriesStateData(TSessionData * SourceData)
  401. {
  402. RemoteDirectory = SourceData->RemoteDirectory;
  403. LocalDirectory = SourceData->LocalDirectory;
  404. SynchronizeBrowsing = SourceData->SynchronizeBrowsing;
  405. }
  406. //---------------------------------------------------------------------
  407. bool __fastcall TSessionData::HasStateData()
  408. {
  409. return
  410. !RemoteDirectory.IsEmpty() ||
  411. !LocalDirectory.IsEmpty() ||
  412. (Color != 0);
  413. }
  414. //---------------------------------------------------------------------
  415. void __fastcall TSessionData::CopyStateData(TSessionData * SourceData)
  416. {
  417. // Keep in sync with TCustomScpExplorerForm::UpdateSessionData.
  418. CopyDirectoriesStateData(SourceData);
  419. Color = SourceData->Color;
  420. }
  421. //---------------------------------------------------------------------
  422. void __fastcall TSessionData::CopyNonCoreData(TSessionData * SourceData)
  423. {
  424. CopyStateData(SourceData);
  425. UpdateDirectories = SourceData->UpdateDirectories;
  426. Note = SourceData->Note;
  427. }
  428. //---------------------------------------------------------------------
  429. bool __fastcall TSessionData::IsSame(const TSessionData * Default, bool AdvancedOnly, TStrings * DifferentProperties)
  430. {
  431. bool Result = true;
  432. #define PROPERTY(P) \
  433. if (P != Default->P) \
  434. { \
  435. if (DifferentProperties != NULL) \
  436. { \
  437. DifferentProperties->Add(#P); \
  438. } \
  439. Result = false; \
  440. }
  441. if (!AdvancedOnly)
  442. {
  443. BASE_PROPERTIES;
  444. META_PROPERTIES;
  445. }
  446. ADVANCED_PROPERTIES;
  447. #undef PROPERTY
  448. return Result;
  449. }
  450. //---------------------------------------------------------------------
  451. bool __fastcall TSessionData::IsSame(const TSessionData * Default, bool AdvancedOnly)
  452. {
  453. return IsSame(Default, AdvancedOnly, NULL);
  454. }
  455. //---------------------------------------------------------------------
  456. bool __fastcall TSessionData::IsSameSite(const TSessionData * Other)
  457. {
  458. return
  459. (FSProtocol == Other->FSProtocol) &&
  460. (HostName == Other->HostName) &&
  461. (PortNumber == Other->PortNumber) &&
  462. (UserName == Other->UserName);
  463. }
  464. //---------------------------------------------------------------------
  465. bool __fastcall TSessionData::IsInFolderOrWorkspace(UnicodeString AFolder)
  466. {
  467. return StartsText(UnixIncludeTrailingBackslash(AFolder), Name);
  468. }
  469. //---------------------------------------------------------------------
  470. void __fastcall TSessionData::DoLoad(THierarchicalStorage * Storage, bool & RewritePassword)
  471. {
  472. // Make sure we only ever use methods supported by TOptionsStorage
  473. // (implemented by TOptionsIniFile)
  474. PortNumber = Storage->ReadInteger(L"PortNumber", PortNumber);
  475. UserName = Storage->ReadString(L"UserName", UserName);
  476. // must be loaded after UserName, because HostName may be in format user@host
  477. HostName = Storage->ReadString(L"HostName", HostName);
  478. if (!Configuration->DisablePasswordStoring)
  479. {
  480. if (Storage->ValueExists(L"PasswordPlain"))
  481. {
  482. Password = Storage->ReadString(L"PasswordPlain", Password);
  483. RewritePassword = true;
  484. }
  485. else
  486. {
  487. FPassword = Storage->ReadStringAsBinaryData(L"Password", FPassword);
  488. }
  489. }
  490. HostKey = Storage->ReadString(L"HostKey", HostKey);
  491. Note = Storage->ReadString(L"Note", Note);
  492. // Putty uses PingIntervalSecs
  493. int PingIntervalSecs = Storage->ReadInteger(L"PingIntervalSecs", -1);
  494. if (PingIntervalSecs < 0)
  495. {
  496. PingIntervalSecs = Storage->ReadInteger(L"PingIntervalSec", PingInterval%SecsPerMin);
  497. }
  498. PingInterval =
  499. Storage->ReadInteger(L"PingInterval", PingInterval/SecsPerMin)*SecsPerMin +
  500. PingIntervalSecs;
  501. if (PingInterval == 0)
  502. {
  503. PingInterval = 30;
  504. }
  505. PingType = static_cast<TPingType>(Storage->ReadInteger(L"PingType", PingType));
  506. Timeout = Storage->ReadInteger(L"Timeout", Timeout);
  507. TryAgent = Storage->ReadBool(L"TryAgent", TryAgent);
  508. AgentFwd = Storage->ReadBool(L"AgentFwd", AgentFwd);
  509. AuthTIS = Storage->ReadBool(L"AuthTIS", AuthTIS);
  510. AuthKI = Storage->ReadBool(L"AuthKI", AuthKI);
  511. AuthKIPassword = Storage->ReadBool(L"AuthKIPassword", AuthKIPassword);
  512. // Continue to use setting keys of previous kerberos implementation (vaclav tomec),
  513. // but fallback to keys of other implementations (official putty and vintela quest putty),
  514. // to allow imports from all putty versions.
  515. // Both vaclav tomec and official putty use AuthGSSAPI
  516. AuthGSSAPI = Storage->ReadBool(L"AuthGSSAPI", Storage->ReadBool(L"AuthSSPI", AuthGSSAPI));
  517. GSSAPIFwdTGT = Storage->ReadBool(L"GSSAPIFwdTGT", Storage->ReadBool(L"GssapiFwd", Storage->ReadBool(L"SSPIFwdTGT", GSSAPIFwdTGT)));
  518. GSSAPIServerRealm = Storage->ReadString(L"GSSAPIServerRealm", Storage->ReadString(L"KerbPrincipal", GSSAPIServerRealm));
  519. ChangeUsername = Storage->ReadBool(L"ChangeUsername", ChangeUsername);
  520. Compression = Storage->ReadBool(L"Compression", Compression);
  521. SshProt = (TSshProt)Storage->ReadInteger(L"SshProt", SshProt);
  522. Ssh2DES = Storage->ReadBool(L"Ssh2DES", Ssh2DES);
  523. SshNoUserAuth = Storage->ReadBool(L"SshNoUserAuth", SshNoUserAuth);
  524. CipherList = Storage->ReadString(L"Cipher", CipherList);
  525. KexList = Storage->ReadString(L"KEX", KexList);
  526. PublicKeyFile = Storage->ReadString(L"PublicKeyFile", PublicKeyFile);
  527. AddressFamily = static_cast<TAddressFamily>
  528. (Storage->ReadInteger(L"AddressFamily", AddressFamily));
  529. RekeyData = Storage->ReadString(L"RekeyBytes", RekeyData);
  530. RekeyTime = Storage->ReadInteger(L"RekeyTime", RekeyTime);
  531. FSProtocol = (TFSProtocol)Storage->ReadInteger(L"FSProtocol", FSProtocol);
  532. LocalDirectory = Storage->ReadString(L"LocalDirectory", LocalDirectory);
  533. RemoteDirectory = Storage->ReadString(L"RemoteDirectory", RemoteDirectory);
  534. SynchronizeBrowsing = Storage->ReadBool(L"SynchronizeBrowsing", SynchronizeBrowsing);
  535. UpdateDirectories = Storage->ReadBool(L"UpdateDirectories", UpdateDirectories);
  536. CacheDirectories = Storage->ReadBool(L"CacheDirectories", CacheDirectories);
  537. CacheDirectoryChanges = Storage->ReadBool(L"CacheDirectoryChanges", CacheDirectoryChanges);
  538. PreserveDirectoryChanges = Storage->ReadBool(L"PreserveDirectoryChanges", PreserveDirectoryChanges);
  539. ResolveSymlinks = Storage->ReadBool(L"ResolveSymlinks", ResolveSymlinks);
  540. DSTMode = (TDSTMode)Storage->ReadInteger(L"ConsiderDST", DSTMode);
  541. LockInHome = Storage->ReadBool(L"LockInHome", LockInHome);
  542. Special = Storage->ReadBool(L"Special", Special);
  543. Shell = Storage->ReadString(L"Shell", Shell);
  544. ClearAliases = Storage->ReadBool(L"ClearAliases", ClearAliases);
  545. UnsetNationalVars = Storage->ReadBool(L"UnsetNationalVars", UnsetNationalVars);
  546. ListingCommand = Storage->ReadString(L"ListingCommand",
  547. Storage->ReadBool(L"AliasGroupList", false) ? UnicodeString(L"ls -gla") : ListingCommand);
  548. IgnoreLsWarnings = Storage->ReadBool(L"IgnoreLsWarnings", IgnoreLsWarnings);
  549. SCPLsFullTime = TAutoSwitch(Storage->ReadInteger(L"SCPLsFullTime", SCPLsFullTime));
  550. Scp1Compatibility = Storage->ReadBool(L"Scp1Compatibility", Scp1Compatibility);
  551. TimeDifference = Storage->ReadFloat(L"TimeDifference", TimeDifference);
  552. TimeDifferenceAuto = Storage->ReadBool(L"TimeDifferenceAuto", (TimeDifference == TDateTime()));
  553. DeleteToRecycleBin = Storage->ReadBool(L"DeleteToRecycleBin", DeleteToRecycleBin);
  554. OverwrittenToRecycleBin = Storage->ReadBool(L"OverwrittenToRecycleBin", OverwrittenToRecycleBin);
  555. RecycleBinPath = Storage->ReadString(L"RecycleBinPath", RecycleBinPath);
  556. PostLoginCommands = Storage->ReadString(L"PostLoginCommands", PostLoginCommands);
  557. ReturnVar = Storage->ReadString(L"ReturnVar", ReturnVar);
  558. LookupUserGroups = TAutoSwitch(Storage->ReadInteger(L"LookupUserGroups2", LookupUserGroups));
  559. EOLType = (TEOLType)Storage->ReadInteger(L"EOLType", EOLType);
  560. TrimVMSVersions = Storage->ReadBool(L"TrimVMSVersions", TrimVMSVersions);
  561. NotUtf = TAutoSwitch(Storage->ReadInteger(L"Utf", Storage->ReadInteger(L"SFTPUtfBug", NotUtf)));
  562. TcpNoDelay = Storage->ReadBool(L"TcpNoDelay", TcpNoDelay);
  563. SendBuf = Storage->ReadInteger(L"SendBuf", Storage->ReadInteger("SshSendBuf", SendBuf));
  564. SshSimple = Storage->ReadBool(L"SshSimple", SshSimple);
  565. ProxyMethod = (TProxyMethod)Storage->ReadInteger(L"ProxyMethod", ProxyMethod);
  566. ProxyHost = Storage->ReadString(L"ProxyHost", ProxyHost);
  567. ProxyPort = Storage->ReadInteger(L"ProxyPort", ProxyPort);
  568. ProxyUsername = Storage->ReadString(L"ProxyUsername", ProxyUsername);
  569. if (Storage->ValueExists(L"ProxyPassword"))
  570. {
  571. // encrypt unencrypted password
  572. ProxyPassword = Storage->ReadString(L"ProxyPassword", L"");
  573. }
  574. else
  575. {
  576. // load encrypted password
  577. FProxyPassword = Storage->ReadStringAsBinaryData(L"ProxyPasswordEnc", FProxyPassword);
  578. }
  579. if (ProxyMethod == pmCmd)
  580. {
  581. ProxyLocalCommand = Storage->ReadStringRaw(L"ProxyTelnetCommand", ProxyLocalCommand);
  582. }
  583. else
  584. {
  585. ProxyTelnetCommand = Storage->ReadStringRaw(L"ProxyTelnetCommand", ProxyTelnetCommand);
  586. }
  587. ProxyDNS = TAutoSwitch((Storage->ReadInteger(L"ProxyDNS", (ProxyDNS + 2) % 3) + 1) % 3);
  588. ProxyLocalhost = Storage->ReadBool(L"ProxyLocalhost", ProxyLocalhost);
  589. #define READ_BUG(BUG) \
  590. Bug[sb##BUG] = TAutoSwitch(2 - Storage->ReadInteger(L"Bug"#BUG, \
  591. 2 - Bug[sb##BUG]));
  592. READ_BUG(Ignore1);
  593. READ_BUG(PlainPW1);
  594. READ_BUG(RSA1);
  595. READ_BUG(HMAC2);
  596. READ_BUG(DeriveKey2);
  597. READ_BUG(RSAPad2);
  598. READ_BUG(PKSessID2);
  599. READ_BUG(Rekey2);
  600. READ_BUG(MaxPkt2);
  601. READ_BUG(Ignore2);
  602. READ_BUG(OldGex2);
  603. READ_BUG(WinAdj);
  604. #undef READ_BUG
  605. if ((Bug[sbHMAC2] == asAuto) &&
  606. Storage->ReadBool(L"BuggyMAC", false))
  607. {
  608. Bug[sbHMAC2] = asOn;
  609. }
  610. SftpServer = Storage->ReadString(L"SftpServer", SftpServer);
  611. #define READ_SFTP_BUG(BUG) \
  612. SFTPBug[sb##BUG] = TAutoSwitch(Storage->ReadInteger(L"SFTP" #BUG "Bug", SFTPBug[sb##BUG]));
  613. READ_SFTP_BUG(Symlink);
  614. READ_SFTP_BUG(SignedTS);
  615. #undef READ_SFTP_BUG
  616. SFTPMaxVersion = Storage->ReadInteger(L"SFTPMaxVersion", SFTPMaxVersion);
  617. SFTPMaxPacketSize = Storage->ReadInteger(L"SFTPMaxPacketSize", SFTPMaxPacketSize);
  618. SFTPDownloadQueue = Storage->ReadInteger(L"SFTPDownloadQueue", SFTPDownloadQueue);
  619. SFTPUploadQueue = Storage->ReadInteger(L"SFTPUploadQueue", SFTPUploadQueue);
  620. SFTPListingQueue = Storage->ReadInteger(L"SFTPListingQueue", SFTPListingQueue);
  621. Color = Storage->ReadInteger(L"Color", Color);
  622. PuttyProtocol = Storage->ReadString(L"Protocol", PuttyProtocol);
  623. Tunnel = Storage->ReadBool(L"Tunnel", Tunnel);
  624. TunnelPortNumber = Storage->ReadInteger(L"TunnelPortNumber", TunnelPortNumber);
  625. TunnelUserName = Storage->ReadString(L"TunnelUserName", TunnelUserName);
  626. // must be loaded after TunnelUserName,
  627. // because TunnelHostName may be in format user@host
  628. TunnelHostName = Storage->ReadString(L"TunnelHostName", TunnelHostName);
  629. if (!Configuration->DisablePasswordStoring)
  630. {
  631. if (Storage->ValueExists(L"TunnelPasswordPlain"))
  632. {
  633. TunnelPassword = Storage->ReadString(L"TunnelPasswordPlain", TunnelPassword);
  634. RewritePassword = true;
  635. }
  636. else
  637. {
  638. FTunnelPassword = Storage->ReadStringAsBinaryData(L"TunnelPassword", FTunnelPassword);
  639. }
  640. }
  641. TunnelPublicKeyFile = Storage->ReadString(L"TunnelPublicKeyFile", TunnelPublicKeyFile);
  642. TunnelLocalPortNumber = Storage->ReadInteger(L"TunnelLocalPortNumber", TunnelLocalPortNumber);
  643. TunnelHostKey = Storage->ReadString(L"TunnelHostKey", TunnelHostKey);
  644. // Ftp prefix
  645. FtpPasvMode = Storage->ReadBool(L"FtpPasvMode", FtpPasvMode);
  646. FtpForcePasvIp = TAutoSwitch(Storage->ReadInteger(L"FtpForcePasvIp2", FtpForcePasvIp));
  647. FtpUseMlsd = TAutoSwitch(Storage->ReadInteger(L"FtpUseMlsd", FtpUseMlsd));
  648. FtpAccount = Storage->ReadString(L"FtpAccount", FtpAccount);
  649. FtpPingInterval = Storage->ReadInteger(L"FtpPingInterval", FtpPingInterval);
  650. FtpPingType = static_cast<TPingType>(Storage->ReadInteger(L"FtpPingType", FtpPingType));
  651. FtpTransferActiveImmediately = static_cast<TAutoSwitch>(Storage->ReadInteger(L"FtpTransferActiveImmediately2", FtpTransferActiveImmediately));
  652. Ftps = static_cast<TFtps>(Storage->ReadInteger(L"Ftps", Ftps));
  653. FtpListAll = TAutoSwitch(Storage->ReadInteger(L"FtpListAll", FtpListAll));
  654. FtpHost = TAutoSwitch(Storage->ReadInteger(L"FtpHost", FtpHost));
  655. SslSessionReuse = Storage->ReadBool(L"SslSessionReuse", SslSessionReuse);
  656. TlsCertificateFile = Storage->ReadString(L"TlsCertificateFile", TlsCertificateFile);
  657. FtpProxyLogonType = Storage->ReadInteger(L"FtpProxyLogonType", FtpProxyLogonType);
  658. MinTlsVersion = static_cast<TTlsVersion>(Storage->ReadInteger(L"MinTlsVersion", MinTlsVersion));
  659. MaxTlsVersion = static_cast<TTlsVersion>(Storage->ReadInteger(L"MaxTlsVersion", MaxTlsVersion));
  660. IsWorkspace = Storage->ReadBool(L"IsWorkspace", IsWorkspace);
  661. Link = Storage->ReadString(L"Link", Link);
  662. CustomParam1 = Storage->ReadString(L"CustomParam1", CustomParam1);
  663. CustomParam2 = Storage->ReadString(L"CustomParam2", CustomParam2);
  664. }
  665. //---------------------------------------------------------------------
  666. void __fastcall TSessionData::Load(THierarchicalStorage * Storage)
  667. {
  668. bool RewritePassword = false;
  669. if (Storage->OpenSubKey(InternalStorageKey, False))
  670. {
  671. // In case we are re-loading, reset passwords, to avoid pointless
  672. // re-cryption, while loading username/hostname. And moreover, when
  673. // the password is wrongly encrypted (using a different master password),
  674. // this breaks sites reload and consequently an overal operation,
  675. // such as opening Sites menu
  676. ClearSessionPasswords();
  677. FProxyPassword = L"";
  678. DoLoad(Storage, RewritePassword);
  679. Storage->CloseSubKey();
  680. }
  681. if (RewritePassword)
  682. {
  683. TStorageAccessMode AccessMode = Storage->AccessMode;
  684. Storage->AccessMode = smReadWrite;
  685. try
  686. {
  687. if (Storage->OpenSubKey(InternalStorageKey, true))
  688. {
  689. Storage->DeleteValue(L"PasswordPlain");
  690. if (!Password.IsEmpty())
  691. {
  692. Storage->WriteBinaryDataAsString(L"Password", FPassword);
  693. }
  694. Storage->DeleteValue(L"TunnelPasswordPlain");
  695. if (!TunnelPassword.IsEmpty())
  696. {
  697. Storage->WriteBinaryDataAsString(L"TunnelPassword", FTunnelPassword);
  698. }
  699. Storage->CloseSubKey();
  700. }
  701. }
  702. catch(...)
  703. {
  704. // ignore errors (like read-only INI file)
  705. }
  706. Storage->AccessMode = AccessMode;
  707. }
  708. FModified = false;
  709. FSource = ssStored;
  710. }
  711. //---------------------------------------------------------------------
  712. void __fastcall TSessionData::DoSave(THierarchicalStorage * Storage,
  713. bool PuttyExport, const TSessionData * Default, bool DoNotEncryptPasswords)
  714. {
  715. #define WRITE_DATA_EX(TYPE, NAME, PROPERTY, CONV) \
  716. if ((Default != NULL) && (CONV(Default->PROPERTY) == CONV(PROPERTY))) \
  717. { \
  718. Storage->DeleteValue(NAME); \
  719. } \
  720. else \
  721. { \
  722. Storage->Write ## TYPE(NAME, CONV(PROPERTY)); \
  723. }
  724. #define WRITE_DATA_CONV(TYPE, NAME, PROPERTY) WRITE_DATA_EX(TYPE, NAME, PROPERTY, WRITE_DATA_CONV_FUNC)
  725. #define WRITE_DATA(TYPE, PROPERTY) WRITE_DATA_EX(TYPE, TEXT(#PROPERTY), PROPERTY, )
  726. WRITE_DATA(String, HostName);
  727. WRITE_DATA(Integer, PortNumber);
  728. WRITE_DATA_EX(Integer, L"PingInterval", PingInterval / SecsPerMin, );
  729. WRITE_DATA_EX(Integer, L"PingIntervalSecs", PingInterval % SecsPerMin, );
  730. Storage->DeleteValue(L"PingIntervalSec"); // obsolete
  731. WRITE_DATA(Integer, PingType);
  732. WRITE_DATA(Integer, Timeout);
  733. WRITE_DATA(Bool, TryAgent);
  734. WRITE_DATA(Bool, AgentFwd);
  735. WRITE_DATA(Bool, AuthTIS);
  736. WRITE_DATA(Bool, AuthKI);
  737. WRITE_DATA(Bool, AuthKIPassword);
  738. WRITE_DATA(String, Note);
  739. WRITE_DATA(Bool, AuthGSSAPI);
  740. WRITE_DATA(Bool, GSSAPIFwdTGT);
  741. WRITE_DATA(String, GSSAPIServerRealm);
  742. Storage->DeleteValue(L"TryGSSKEX");
  743. Storage->DeleteValue(L"UserNameFromEnvironment");
  744. Storage->DeleteValue("GSSAPIServerChoosesUserName");
  745. Storage->DeleteValue(L"GSSAPITrustDNS");
  746. if (PuttyExport)
  747. {
  748. // duplicate kerberos setting with keys of the vintela quest putty
  749. WRITE_DATA_EX(Bool, L"AuthSSPI", AuthGSSAPI, );
  750. WRITE_DATA_EX(Bool, L"SSPIFwdTGT", GSSAPIFwdTGT, );
  751. WRITE_DATA_EX(String, L"KerbPrincipal", GSSAPIServerRealm, );
  752. // duplicate kerberos setting with keys of the official putty
  753. WRITE_DATA_EX(Bool, L"GssapiFwd", GSSAPIFwdTGT, );
  754. }
  755. WRITE_DATA(Bool, ChangeUsername);
  756. WRITE_DATA(Bool, Compression);
  757. WRITE_DATA(Integer, SshProt);
  758. WRITE_DATA(Bool, Ssh2DES);
  759. WRITE_DATA(Bool, SshNoUserAuth);
  760. WRITE_DATA_EX(String, L"Cipher", CipherList, );
  761. WRITE_DATA_EX(String, L"KEX", KexList, );
  762. WRITE_DATA(Integer, AddressFamily);
  763. WRITE_DATA_EX(String, L"RekeyBytes", RekeyData, );
  764. WRITE_DATA(Integer, RekeyTime);
  765. WRITE_DATA(Bool, TcpNoDelay);
  766. if (PuttyExport)
  767. {
  768. WRITE_DATA(StringRaw, UserName);
  769. WRITE_DATA(StringRaw, PublicKeyFile);
  770. }
  771. else
  772. {
  773. WRITE_DATA(String, UserName);
  774. WRITE_DATA(String, PublicKeyFile);
  775. WRITE_DATA(Integer, FSProtocol);
  776. WRITE_DATA(String, LocalDirectory);
  777. WRITE_DATA(String, RemoteDirectory);
  778. WRITE_DATA(Bool, SynchronizeBrowsing);
  779. WRITE_DATA(Bool, UpdateDirectories);
  780. WRITE_DATA(Bool, CacheDirectories);
  781. WRITE_DATA(Bool, CacheDirectoryChanges);
  782. WRITE_DATA(Bool, PreserveDirectoryChanges);
  783. WRITE_DATA(Bool, ResolveSymlinks);
  784. WRITE_DATA_EX(Integer, L"ConsiderDST", DSTMode, );
  785. WRITE_DATA(Bool, LockInHome);
  786. // Special is never stored (if it would, login dialog must be modified not to
  787. // duplicate Special parameter when Special session is loaded and then stored
  788. // under different name)
  789. // WRITE_DATA(Bool, Special);
  790. WRITE_DATA(String, Shell);
  791. WRITE_DATA(Bool, ClearAliases);
  792. WRITE_DATA(Bool, UnsetNationalVars);
  793. WRITE_DATA(String, ListingCommand);
  794. WRITE_DATA(Bool, IgnoreLsWarnings);
  795. WRITE_DATA(Integer, SCPLsFullTime);
  796. WRITE_DATA(Bool, Scp1Compatibility);
  797. // TimeDifferenceAuto is valid for FTP protocol only.
  798. // For other protocols it's typically true (default value),
  799. // but ignored so TimeDifference is still taken into account (SCP only actually)
  800. if (TimeDifferenceAuto && (FSProtocol == fsFTP))
  801. {
  802. // Have to delete it as TimeDifferenceAuto is not saved when enabled,
  803. // but the default is derived from value of TimeDifference.
  804. Storage->DeleteValue(L"TimeDifference");
  805. }
  806. else
  807. {
  808. WRITE_DATA(Float, TimeDifference);
  809. }
  810. WRITE_DATA(Bool, TimeDifferenceAuto);
  811. WRITE_DATA(Bool, DeleteToRecycleBin);
  812. WRITE_DATA(Bool, OverwrittenToRecycleBin);
  813. WRITE_DATA(String, RecycleBinPath);
  814. WRITE_DATA(String, PostLoginCommands);
  815. WRITE_DATA(String, ReturnVar);
  816. WRITE_DATA_EX(Integer, L"LookupUserGroups2", LookupUserGroups, );
  817. WRITE_DATA(Integer, EOLType);
  818. WRITE_DATA(Bool, TrimVMSVersions);
  819. Storage->DeleteValue(L"SFTPUtfBug");
  820. WRITE_DATA_EX(Integer, L"Utf", NotUtf, );
  821. WRITE_DATA(Integer, SendBuf);
  822. WRITE_DATA(Bool, SshSimple);
  823. }
  824. WRITE_DATA(Integer, ProxyMethod);
  825. WRITE_DATA(String, ProxyHost);
  826. WRITE_DATA(Integer, ProxyPort);
  827. WRITE_DATA(String, ProxyUsername);
  828. if (ProxyMethod == pmCmd)
  829. {
  830. WRITE_DATA_EX(StringRaw, L"ProxyTelnetCommand", ProxyLocalCommand, );
  831. }
  832. else
  833. {
  834. WRITE_DATA(StringRaw, ProxyTelnetCommand);
  835. }
  836. #define WRITE_DATA_CONV_FUNC(X) (((X) + 2) % 3)
  837. WRITE_DATA_CONV(Integer, L"ProxyDNS", ProxyDNS);
  838. #undef WRITE_DATA_CONV_FUNC
  839. WRITE_DATA(Bool, ProxyLocalhost);
  840. #define WRITE_DATA_CONV_FUNC(X) (2 - (X))
  841. #define WRITE_BUG(BUG) WRITE_DATA_CONV(Integer, L"Bug" #BUG, Bug[sb##BUG]);
  842. WRITE_BUG(Ignore1);
  843. WRITE_BUG(PlainPW1);
  844. WRITE_BUG(RSA1);
  845. WRITE_BUG(HMAC2);
  846. WRITE_BUG(DeriveKey2);
  847. WRITE_BUG(RSAPad2);
  848. WRITE_BUG(PKSessID2);
  849. WRITE_BUG(Rekey2);
  850. WRITE_BUG(MaxPkt2);
  851. WRITE_BUG(Ignore2);
  852. WRITE_BUG(OldGex2);
  853. WRITE_BUG(WinAdj);
  854. #undef WRITE_BUG
  855. #undef WRITE_DATA_CONV_FUNC
  856. Storage->DeleteValue(L"BuggyMAC");
  857. Storage->DeleteValue(L"AliasGroupList");
  858. if (PuttyExport)
  859. {
  860. WRITE_DATA_EX(String, L"Protocol", GetNormalizedPuttyProtocol(), );
  861. }
  862. if (!PuttyExport)
  863. {
  864. WRITE_DATA(String, SftpServer);
  865. #define WRITE_SFTP_BUG(BUG) WRITE_DATA_EX(Integer, L"SFTP" #BUG "Bug", SFTPBug[sb##BUG], );
  866. WRITE_SFTP_BUG(Symlink);
  867. WRITE_SFTP_BUG(SignedTS);
  868. #undef WRITE_SFTP_BUG
  869. WRITE_DATA(Integer, SFTPMaxVersion);
  870. WRITE_DATA(Integer, SFTPMaxPacketSize);
  871. WRITE_DATA(Integer, SFTPDownloadQueue);
  872. WRITE_DATA(Integer, SFTPUploadQueue);
  873. WRITE_DATA(Integer, SFTPListingQueue);
  874. WRITE_DATA(Integer, Color);
  875. WRITE_DATA(Bool, Tunnel);
  876. WRITE_DATA(String, TunnelHostName);
  877. WRITE_DATA(Integer, TunnelPortNumber);
  878. WRITE_DATA(String, TunnelUserName);
  879. WRITE_DATA(String, TunnelPublicKeyFile);
  880. WRITE_DATA(Integer, TunnelLocalPortNumber);
  881. WRITE_DATA(Bool, FtpPasvMode);
  882. WRITE_DATA_EX(Integer, L"FtpForcePasvIp2", FtpForcePasvIp, );
  883. WRITE_DATA(Integer, FtpUseMlsd);
  884. WRITE_DATA(String, FtpAccount);
  885. WRITE_DATA(Integer, FtpPingInterval);
  886. WRITE_DATA(Integer, FtpPingType);
  887. WRITE_DATA_EX(Integer, L"FtpTransferActiveImmediately2", FtpTransferActiveImmediately, );
  888. WRITE_DATA(Integer, Ftps);
  889. WRITE_DATA(Integer, FtpListAll);
  890. WRITE_DATA(Integer, FtpHost);
  891. WRITE_DATA(Bool, SslSessionReuse);
  892. WRITE_DATA(String, TlsCertificateFile);
  893. WRITE_DATA(Integer, FtpProxyLogonType);
  894. WRITE_DATA(Integer, MinTlsVersion);
  895. WRITE_DATA(Integer, MaxTlsVersion);
  896. WRITE_DATA(Bool, IsWorkspace);
  897. WRITE_DATA(String, Link);
  898. WRITE_DATA(String, CustomParam1);
  899. WRITE_DATA(String, CustomParam2);
  900. }
  901. SavePasswords(Storage, PuttyExport, DoNotEncryptPasswords);
  902. }
  903. //---------------------------------------------------------------------
  904. TStrings * __fastcall TSessionData::SaveToOptions(const TSessionData * Default)
  905. {
  906. std::unique_ptr<TStringList> Options(new TStringList());
  907. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  908. DoSave(OptionsStorage.get(), false, Default, true);
  909. return Options.release();
  910. }
  911. //---------------------------------------------------------------------
  912. void __fastcall TSessionData::Save(THierarchicalStorage * Storage,
  913. bool PuttyExport, const TSessionData * Default)
  914. {
  915. if (Storage->OpenSubKey(InternalStorageKey, true))
  916. {
  917. DoSave(Storage, PuttyExport, Default, false);
  918. Storage->CloseSubKey();
  919. }
  920. }
  921. //---------------------------------------------------------------------
  922. UnicodeString __fastcall TSessionData::ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default)
  923. {
  924. _di_IXMLNode TheNode = Node->ChildNodes->FindNode(Name);
  925. UnicodeString Result;
  926. if (TheNode != NULL)
  927. {
  928. Result = TheNode->Text.Trim();
  929. }
  930. if (Result.IsEmpty())
  931. {
  932. Result = Default;
  933. }
  934. return Result;
  935. }
  936. //---------------------------------------------------------------------
  937. int __fastcall TSessionData::ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, int Default)
  938. {
  939. _di_IXMLNode TheNode = Node->ChildNodes->FindNode(Name);
  940. int Result;
  941. if (TheNode != NULL)
  942. {
  943. Result = StrToIntDef(TheNode->Text.Trim(), Default);
  944. }
  945. else
  946. {
  947. Result = Default;
  948. }
  949. return Result;
  950. }
  951. //---------------------------------------------------------------------
  952. void __fastcall TSessionData::ImportFromFilezilla(_di_IXMLNode Node, const UnicodeString & Path)
  953. {
  954. Name = UnixIncludeTrailingBackslash(Path) + MakeValidName(ReadXmlNode(Node, L"Name", Name));
  955. HostName = ReadXmlNode(Node, L"Host", HostName);
  956. PortNumber = ReadXmlNode(Node, L"Port", PortNumber);
  957. int AProtocol = ReadXmlNode(Node, L"Protocol", 0);
  958. // ServerProtocol enum
  959. switch (AProtocol)
  960. {
  961. case 0: // FTP
  962. default: // UNKNOWN, HTTP, HTTPS, INSECURE_FTP
  963. FSProtocol = fsFTP;
  964. break;
  965. case 1: // SFTP
  966. FSProtocol = fsSFTP;
  967. break;
  968. case 3: // FTPS
  969. FSProtocol = fsFTP;
  970. Ftps = ftpsImplicit;
  971. break;
  972. case 4: // FTPES
  973. FSProtocol = fsFTP;
  974. Ftps = ftpsExplicitTls;
  975. break;
  976. }
  977. // LogonType enum
  978. int LogonType = ReadXmlNode(Node, L"Logontype", 0);
  979. if (LogonType == 0) // ANONYMOUS
  980. {
  981. UserName = AnonymousUserName;
  982. Password = AnonymousPassword;
  983. }
  984. else
  985. {
  986. UserName = ReadXmlNode(Node, L"User", UserName);
  987. FtpAccount = ReadXmlNode(Node, L"Account", FtpAccount);
  988. _di_IXMLNode PassNode = Node->ChildNodes->FindNode(L"Pass");
  989. if (PassNode != NULL)
  990. {
  991. UnicodeString APassword = PassNode->Text.Trim();
  992. OleVariant EncodingValue = PassNode->GetAttribute(L"encoding");
  993. if (!EncodingValue.IsNull())
  994. {
  995. UnicodeString EncodingValueStr = EncodingValue;
  996. if (SameText(EncodingValueStr, L"base64"))
  997. {
  998. TBytes Bytes = DecodeBase64(APassword);
  999. APassword = TEncoding::UTF8->GetString(Bytes);
  1000. }
  1001. }
  1002. Password = APassword;
  1003. }
  1004. }
  1005. int DefaultTimeDifference = TimeToSeconds(TimeDifference);
  1006. TimeDifference =
  1007. (double(ReadXmlNode(Node, L"TimezoneOffset", DefaultTimeDifference) / SecsPerDay));
  1008. TimeDifferenceAuto = (TimeDifference == TDateTime());
  1009. UnicodeString PasvMode = ReadXmlNode(Node, L"PasvMode", L"");
  1010. if (SameText(PasvMode, L"MODE_PASSIVE"))
  1011. {
  1012. FtpPasvMode = true;
  1013. }
  1014. else if (SameText(PasvMode, L"MODE_ACTIVE"))
  1015. {
  1016. FtpPasvMode = false;
  1017. }
  1018. UnicodeString EncodingType = ReadXmlNode(Node, L"EncodingType", L"");
  1019. if (SameText(EncodingType, L"Auto"))
  1020. {
  1021. NotUtf = asAuto;
  1022. }
  1023. else if (SameText(EncodingType, L"UTF-8"))
  1024. {
  1025. NotUtf = asOff;
  1026. }
  1027. // todo PostLoginCommands
  1028. Note = ReadXmlNode(Node, L"Comments", Note);
  1029. LocalDirectory = ReadXmlNode(Node, L"LocalDir", LocalDirectory);
  1030. UnicodeString RemoteDir = ReadXmlNode(Node, L"RemoteDir", L"");
  1031. if (!RemoteDir.IsEmpty())
  1032. {
  1033. CutToChar(RemoteDir, L' ', false); // type
  1034. int PrefixSize = StrToIntDef(CutToChar(RemoteDir, L' ', false), 0); // prefix size
  1035. if (PrefixSize > 0)
  1036. {
  1037. RemoteDir.Delete(1, PrefixSize);
  1038. }
  1039. RemoteDirectory = L"/";
  1040. while (!RemoteDir.IsEmpty())
  1041. {
  1042. int SegmentSize = StrToIntDef(CutToChar(RemoteDir, L' ', false), 0);
  1043. UnicodeString Segment = RemoteDir.SubString(1, SegmentSize);
  1044. RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory) + Segment;
  1045. RemoteDir.Delete(1, SegmentSize + 1);
  1046. }
  1047. }
  1048. SynchronizeBrowsing = (ReadXmlNode(Node, L"SyncBrowsing", SynchronizeBrowsing ? 1 : 0) != 0);
  1049. }
  1050. //---------------------------------------------------------------------
  1051. void __fastcall TSessionData::SavePasswords(THierarchicalStorage * Storage, bool PuttyExport, bool DoNotEncryptPasswords)
  1052. {
  1053. if (!Configuration->DisablePasswordStoring && !PuttyExport && !FPassword.IsEmpty())
  1054. {
  1055. // DoNotEncryptPasswords is set when called from GenerateOpenCommandArgs only
  1056. // and it never saves session password
  1057. DebugAssert(!DoNotEncryptPasswords);
  1058. Storage->WriteBinaryDataAsString(L"Password", StronglyRecryptPassword(FPassword, UserName+HostName));
  1059. }
  1060. else
  1061. {
  1062. Storage->DeleteValue(L"Password");
  1063. }
  1064. Storage->DeleteValue(L"PasswordPlain");
  1065. if (PuttyExport)
  1066. {
  1067. // save password unencrypted
  1068. Storage->WriteString(L"ProxyPassword", ProxyPassword);
  1069. }
  1070. else
  1071. {
  1072. if (DoNotEncryptPasswords)
  1073. {
  1074. if (!FProxyPassword.IsEmpty())
  1075. {
  1076. Storage->WriteString(L"ProxyPassword", ProxyPassword);
  1077. }
  1078. else
  1079. {
  1080. Storage->DeleteValue(L"ProxyPassword");
  1081. }
  1082. Storage->DeleteValue(L"ProxyPasswordEnc");
  1083. }
  1084. else
  1085. {
  1086. // save password encrypted
  1087. if (!FProxyPassword.IsEmpty())
  1088. {
  1089. Storage->WriteBinaryDataAsString(L"ProxyPasswordEnc", StronglyRecryptPassword(FProxyPassword, ProxyUsername+ProxyHost));
  1090. }
  1091. else
  1092. {
  1093. Storage->DeleteValue(L"ProxyPasswordEnc");
  1094. }
  1095. Storage->DeleteValue(L"ProxyPassword");
  1096. }
  1097. if (DoNotEncryptPasswords)
  1098. {
  1099. if (!FTunnelPassword.IsEmpty())
  1100. {
  1101. Storage->WriteString(L"TunnelPasswordPlain", TunnelPassword);
  1102. }
  1103. else
  1104. {
  1105. Storage->DeleteValue(L"TunnelPasswordPlain");
  1106. }
  1107. }
  1108. else
  1109. {
  1110. if (!Configuration->DisablePasswordStoring && !FTunnelPassword.IsEmpty())
  1111. {
  1112. Storage->WriteBinaryDataAsString(L"TunnelPassword", StronglyRecryptPassword(FTunnelPassword, TunnelUserName+TunnelHostName));
  1113. }
  1114. else
  1115. {
  1116. Storage->DeleteValue(L"TunnelPassword");
  1117. }
  1118. }
  1119. }
  1120. }
  1121. //---------------------------------------------------------------------
  1122. void __fastcall TSessionData::RecryptPasswords()
  1123. {
  1124. Password = Password;
  1125. ProxyPassword = ProxyPassword;
  1126. TunnelPassword = TunnelPassword;
  1127. Passphrase = Passphrase;
  1128. }
  1129. //---------------------------------------------------------------------
  1130. bool __fastcall TSessionData::HasPassword()
  1131. {
  1132. return !FPassword.IsEmpty();
  1133. }
  1134. //---------------------------------------------------------------------
  1135. bool __fastcall TSessionData::HasAnySessionPassword()
  1136. {
  1137. return HasPassword() || !FTunnelPassword.IsEmpty();
  1138. }
  1139. //---------------------------------------------------------------------
  1140. bool __fastcall TSessionData::HasAnyPassword()
  1141. {
  1142. return HasAnySessionPassword() || !FProxyPassword.IsEmpty();
  1143. }
  1144. //---------------------------------------------------------------------
  1145. void __fastcall TSessionData::ClearSessionPasswords()
  1146. {
  1147. FPassword = L"";
  1148. FTunnelPassword = L"";
  1149. }
  1150. //---------------------------------------------------------------------
  1151. void __fastcall TSessionData::Modify()
  1152. {
  1153. FModified = true;
  1154. if (FSource == ssStored)
  1155. {
  1156. FSource = ssStoredModified;
  1157. }
  1158. }
  1159. //---------------------------------------------------------------------
  1160. UnicodeString __fastcall TSessionData::GetSource()
  1161. {
  1162. switch (FSource)
  1163. {
  1164. case ::ssNone:
  1165. return L"Ad-Hoc site";
  1166. case ssStored:
  1167. return L"Site";
  1168. case ssStoredModified:
  1169. return L"Modified site";
  1170. default:
  1171. DebugFail();
  1172. return L"";
  1173. }
  1174. }
  1175. //---------------------------------------------------------------------
  1176. void __fastcall TSessionData::SaveRecryptedPasswords(THierarchicalStorage * Storage)
  1177. {
  1178. if (Storage->OpenSubKey(InternalStorageKey, true))
  1179. {
  1180. try
  1181. {
  1182. RecryptPasswords();
  1183. SavePasswords(Storage, false, false);
  1184. }
  1185. __finally
  1186. {
  1187. Storage->CloseSubKey();
  1188. }
  1189. }
  1190. }
  1191. //---------------------------------------------------------------------
  1192. void __fastcall TSessionData::Remove()
  1193. {
  1194. bool SessionList = true;
  1195. THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);
  1196. try
  1197. {
  1198. Storage->Explicit = true;
  1199. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, false))
  1200. {
  1201. Storage->RecursiveDeleteSubKey(InternalStorageKey);
  1202. }
  1203. }
  1204. __finally
  1205. {
  1206. delete Storage;
  1207. }
  1208. }
  1209. //---------------------------------------------------------------------
  1210. void __fastcall TSessionData::CacheHostKeyIfNotCached()
  1211. {
  1212. UnicodeString KeyType = KeyTypeFromFingerprint(HostKey);
  1213. UnicodeString TargetKey = Configuration->RegistryStorageKey + L"\\" + Configuration->SshHostKeysSubKey;
  1214. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(TargetKey));
  1215. Storage->AccessMode = smReadWrite;
  1216. if (Storage->OpenRootKey(true))
  1217. {
  1218. UnicodeString HostKeyName = PuttyMungeStr(FORMAT(L"%s@%d:%s", (KeyType, PortNumber, HostName)));
  1219. if (!Storage->ValueExists(HostKeyName))
  1220. {
  1221. // fingerprint is MD5 of host key, so it cannot be translated back to host key,
  1222. // so we store fingerprint and TSecureShell::VerifyHostKey was
  1223. // modified to accept also fingerprint
  1224. Storage->WriteString(HostKeyName, HostKey);
  1225. }
  1226. }
  1227. }
  1228. //---------------------------------------------------------------------
  1229. inline void __fastcall MoveStr(UnicodeString & Source, UnicodeString * Dest, int Count)
  1230. {
  1231. if (Dest != NULL)
  1232. {
  1233. (*Dest) += Source.SubString(1, Count);
  1234. }
  1235. Source.Delete(1, Count);
  1236. }
  1237. //---------------------------------------------------------------------
  1238. bool __fastcall TSessionData::DoIsProtocolUrl(
  1239. const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen)
  1240. {
  1241. bool Result = SameText(Url.SubString(1, Protocol.Length() + 1), Protocol + L":");
  1242. if (Result)
  1243. {
  1244. ProtocolLen = Protocol.Length() + 1;
  1245. }
  1246. return Result;
  1247. }
  1248. //---------------------------------------------------------------------
  1249. bool __fastcall TSessionData::IsProtocolUrl(
  1250. const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen)
  1251. {
  1252. return
  1253. DoIsProtocolUrl(Url, Protocol, ProtocolLen) ||
  1254. DoIsProtocolUrl(Url, WinSCPProtocolPrefix + Protocol, ProtocolLen);
  1255. }
  1256. //---------------------------------------------------------------------
  1257. bool __fastcall TSessionData::IsSensitiveOption(const UnicodeString & Option)
  1258. {
  1259. return AnsiSameText(Option, PassphraseOption);
  1260. }
  1261. //---------------------------------------------------------------------
  1262. bool __fastcall TSessionData::ParseUrl(UnicodeString Url, TOptions * Options,
  1263. TStoredSessionList * StoredSessions, bool & DefaultsOnly, UnicodeString * FileName,
  1264. bool * AProtocolDefined, UnicodeString * MaskedUrl)
  1265. {
  1266. bool ProtocolDefined = false;
  1267. bool PortNumberDefined = false;
  1268. TFSProtocol AFSProtocol;
  1269. int APortNumber;
  1270. TFtps AFtps = ftpsNone;
  1271. int ProtocolLen = 0;
  1272. if (IsProtocolUrl(Url, ScpProtocol, ProtocolLen))
  1273. {
  1274. AFSProtocol = fsSCPonly;
  1275. APortNumber = SshPortNumber;
  1276. MoveStr(Url, MaskedUrl, ProtocolLen);
  1277. ProtocolDefined = true;
  1278. }
  1279. else if (IsProtocolUrl(Url, SftpProtocol, ProtocolLen))
  1280. {
  1281. AFSProtocol = fsSFTPonly;
  1282. APortNumber = SshPortNumber;
  1283. MoveStr(Url, MaskedUrl, ProtocolLen);
  1284. ProtocolDefined = true;
  1285. }
  1286. else if (IsProtocolUrl(Url, FtpProtocol, ProtocolLen))
  1287. {
  1288. AFSProtocol = fsFTP;
  1289. Ftps = ftpsNone;
  1290. APortNumber = FtpPortNumber;
  1291. MoveStr(Url, MaskedUrl, ProtocolLen);
  1292. ProtocolDefined = true;
  1293. }
  1294. else if (IsProtocolUrl(Url, FtpsProtocol, ProtocolLen))
  1295. {
  1296. AFSProtocol = fsFTP;
  1297. AFtps = ftpsImplicit;
  1298. APortNumber = FtpsImplicitPortNumber;
  1299. MoveStr(Url, MaskedUrl, ProtocolLen);
  1300. ProtocolDefined = true;
  1301. }
  1302. else if (IsProtocolUrl(Url, FtpesProtocol, ProtocolLen))
  1303. {
  1304. AFSProtocol = fsFTP;
  1305. AFtps = ftpsExplicitTls;
  1306. APortNumber = FtpPortNumber;
  1307. MoveStr(Url, MaskedUrl, ProtocolLen);
  1308. ProtocolDefined = true;
  1309. }
  1310. else if (IsProtocolUrl(Url, WebDAVProtocol, ProtocolLen))
  1311. {
  1312. AFSProtocol = fsWebDAV;
  1313. AFtps = ftpsNone;
  1314. APortNumber = HTTPPortNumber;
  1315. MoveStr(Url, MaskedUrl, ProtocolLen);
  1316. ProtocolDefined = true;
  1317. }
  1318. else if (IsProtocolUrl(Url, WebDAVSProtocol, ProtocolLen))
  1319. {
  1320. AFSProtocol = fsWebDAV;
  1321. AFtps = ftpsImplicit;
  1322. APortNumber = HTTPSPortNumber;
  1323. MoveStr(Url, MaskedUrl, ProtocolLen);
  1324. ProtocolDefined = true;
  1325. }
  1326. else if (IsProtocolUrl(Url, SshProtocol, ProtocolLen))
  1327. {
  1328. // For most uses, handling ssh:// the same way as sftp://
  1329. // The only place where a difference is made is GetLoginData() in WinMain.cpp
  1330. AFSProtocol = fsSFTPonly;
  1331. PuttyProtocol = PuttySshProtocol;
  1332. APortNumber = SshPortNumber;
  1333. MoveStr(Url, MaskedUrl, ProtocolLen);
  1334. ProtocolDefined = true;
  1335. }
  1336. if (ProtocolDefined && (Url.SubString(1, 2) == L"//"))
  1337. {
  1338. MoveStr(Url, MaskedUrl, 2);
  1339. }
  1340. if (AProtocolDefined != NULL)
  1341. {
  1342. *AProtocolDefined = ProtocolDefined;
  1343. }
  1344. if (!Url.IsEmpty())
  1345. {
  1346. UnicodeString DecodedUrl = DecodeUrlChars(Url);
  1347. // lookup stored session even if protocol was defined
  1348. // (this allows setting for example default username for host
  1349. // by creating stored session named by host)
  1350. TSessionData * Data = NULL;
  1351. // When using to paste URL on Login dialog, we do not want to lookup the stored sites
  1352. if (StoredSessions != NULL)
  1353. {
  1354. // this can be optimized as the list is sorted
  1355. for (Integer Index = 0; Index < StoredSessions->CountIncludingHidden; Index++)
  1356. {
  1357. TSessionData * AData = (TSessionData *)StoredSessions->Items[Index];
  1358. if (!AData->IsWorkspace)
  1359. {
  1360. bool Match = false;
  1361. // Comparison optimizations as this is called many times
  1362. // e.g. when updating jumplist
  1363. if ((AData->Name.Length() == DecodedUrl.Length()) &&
  1364. SameText(AData->Name, DecodedUrl))
  1365. {
  1366. Match = true;
  1367. }
  1368. else if ((AData->Name.Length() < DecodedUrl.Length()) &&
  1369. (DecodedUrl[AData->Name.Length() + 1] == L'/') &&
  1370. // StrLIComp is an equivalent of SameText
  1371. (StrLIComp(AData->Name.c_str(), DecodedUrl.c_str(), AData->Name.Length()) == 0))
  1372. {
  1373. Match = true;
  1374. }
  1375. if (Match)
  1376. {
  1377. Data = AData;
  1378. break;
  1379. }
  1380. }
  1381. }
  1382. }
  1383. UnicodeString ARemoteDirectory;
  1384. if (Data != NULL)
  1385. {
  1386. Assign(Data);
  1387. int P = 1;
  1388. while (!AnsiSameText(DecodeUrlChars(Url.SubString(1, P)), Data->Name))
  1389. {
  1390. P++;
  1391. DebugAssert(P <= Url.Length());
  1392. }
  1393. ARemoteDirectory = Url.SubString(P + 1, Url.Length() - P);
  1394. if (Data->Hidden)
  1395. {
  1396. Data->Remove();
  1397. StoredSessions->Remove(Data);
  1398. // only modified, implicit
  1399. StoredSessions->Save(false, false);
  1400. }
  1401. if (MaskedUrl != NULL)
  1402. {
  1403. (*MaskedUrl) += Url;
  1404. }
  1405. }
  1406. else
  1407. {
  1408. // This happens when pasting URL on Login dialog
  1409. if (StoredSessions != NULL)
  1410. {
  1411. CopyData(StoredSessions->DefaultSettings);
  1412. }
  1413. Name = L"";
  1414. int PSlash = Url.Pos(L"/");
  1415. if (PSlash == 0)
  1416. {
  1417. PSlash = Url.Length() + 1;
  1418. }
  1419. UnicodeString ConnectInfo = Url.SubString(1, PSlash - 1);
  1420. int P = ConnectInfo.LastDelimiter(L"@");
  1421. UnicodeString UserInfo;
  1422. UnicodeString HostInfo;
  1423. if (P > 0)
  1424. {
  1425. UserInfo = ConnectInfo.SubString(1, P - 1);
  1426. HostInfo = ConnectInfo.SubString(P + 1, ConnectInfo.Length() - P);
  1427. }
  1428. else
  1429. {
  1430. HostInfo = ConnectInfo;
  1431. }
  1432. UnicodeString OrigHostInfo = HostInfo;
  1433. if ((HostInfo.Length() >= 2) && (HostInfo[1] == L'[') && ((P = HostInfo.Pos(L"]")) > 0))
  1434. {
  1435. HostName = HostInfo.SubString(2, P - 2);
  1436. HostInfo.Delete(1, P);
  1437. if (!HostInfo.IsEmpty() && (HostInfo[1] == L':'))
  1438. {
  1439. HostInfo.Delete(1, 1);
  1440. }
  1441. }
  1442. else
  1443. {
  1444. HostName = DecodeUrlChars(CutToChar(HostInfo, L':', true));
  1445. }
  1446. // expanded from ?: operator, as it caused strange "access violation" errors
  1447. if (!HostInfo.IsEmpty())
  1448. {
  1449. PortNumber = StrToIntDef(DecodeUrlChars(HostInfo), -1);
  1450. PortNumberDefined = true;
  1451. }
  1452. else if (ProtocolDefined)
  1453. {
  1454. PortNumber = APortNumber;
  1455. }
  1456. if (ProtocolDefined)
  1457. {
  1458. Ftps = AFtps;
  1459. }
  1460. UnicodeString UserInfoWithoutConnectionParams = CutToChar(UserInfo, UrlParamSeparator, false);
  1461. UnicodeString ConnectionParams = UserInfo;
  1462. UserInfo = UserInfoWithoutConnectionParams;
  1463. while (!ConnectionParams.IsEmpty())
  1464. {
  1465. UnicodeString ConnectionParam = CutToChar(ConnectionParams, UrlParamSeparator, false);
  1466. UnicodeString ConnectionParamName = CutToChar(ConnectionParam, UrlParamValueSeparator, false);
  1467. if (AnsiSameText(ConnectionParamName, UrlHostKeyParamName))
  1468. {
  1469. HostKey = ConnectionParam;
  1470. FOverrideCachedHostKey = false;
  1471. }
  1472. }
  1473. UnicodeString RawUserName = CutToChar(UserInfo, L':', false);
  1474. UserName = DecodeUrlChars(RawUserName);
  1475. Password = DecodeUrlChars(UserInfo);
  1476. UnicodeString RemoteDirectoryWithSessionParams = Url.SubString(PSlash, Url.Length() - PSlash + 1);
  1477. ARemoteDirectory = CutToChar(RemoteDirectoryWithSessionParams, UrlParamSeparator, false);
  1478. UnicodeString SessionParams = RemoteDirectoryWithSessionParams;
  1479. // We should handle session params in "stored session" branch too.
  1480. // And particularly if there's a "save" param, we should actually not try to match the
  1481. // URL against site names
  1482. while (!SessionParams.IsEmpty())
  1483. {
  1484. UnicodeString SessionParam = CutToChar(SessionParams, UrlParamSeparator, false);
  1485. UnicodeString SessionParamName = CutToChar(SessionParam, UrlParamValueSeparator, false);
  1486. if (AnsiSameText(SessionParamName, UrlSaveParamName))
  1487. {
  1488. FSaveOnly = (StrToIntDef(SessionParam, 1) != 0);
  1489. }
  1490. }
  1491. if (MaskedUrl != NULL)
  1492. {
  1493. (*MaskedUrl) += RawUserName;
  1494. if (!UserInfo.IsEmpty())
  1495. {
  1496. (*MaskedUrl) += L":" + PasswordMask;
  1497. }
  1498. if (!RawUserName.IsEmpty() || !UserInfo.IsEmpty())
  1499. {
  1500. (*MaskedUrl) += L"@";
  1501. }
  1502. (*MaskedUrl) += OrigHostInfo + ARemoteDirectory;
  1503. }
  1504. }
  1505. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory != L"/"))
  1506. {
  1507. if ((ARemoteDirectory[ARemoteDirectory.Length()] != L'/') &&
  1508. (FileName != NULL))
  1509. {
  1510. *FileName = DecodeUrlChars(UnixExtractFileName(ARemoteDirectory));
  1511. ARemoteDirectory = UnixExtractFilePath(ARemoteDirectory);
  1512. }
  1513. RemoteDirectory = DecodeUrlChars(ARemoteDirectory);
  1514. }
  1515. DefaultsOnly = false;
  1516. }
  1517. else
  1518. {
  1519. // This happens when pasting URL on Login dialog
  1520. if (StoredSessions != NULL)
  1521. {
  1522. CopyData(StoredSessions->DefaultSettings);
  1523. }
  1524. DefaultsOnly = true;
  1525. }
  1526. if (ProtocolDefined)
  1527. {
  1528. FSProtocol = AFSProtocol;
  1529. }
  1530. if (Options != NULL)
  1531. {
  1532. // we deliberately do keep defaultonly to false, in presence of any option,
  1533. // as the option should not make session "connectable"
  1534. UnicodeString Value;
  1535. if (Options->FindSwitch(SESSIONNAME_SWICH, Value))
  1536. {
  1537. Name = Value;
  1538. }
  1539. if (Options->FindSwitch(L"privatekey", Value))
  1540. {
  1541. PublicKeyFile = Value;
  1542. }
  1543. if (Options->FindSwitch(L"clientcert", Value))
  1544. {
  1545. TlsCertificateFile = Value;
  1546. }
  1547. if (Options->FindSwitch(PassphraseOption, Value))
  1548. {
  1549. Passphrase = Value;
  1550. }
  1551. if (Options->FindSwitch(L"timeout", Value))
  1552. {
  1553. Timeout = StrToInt(Value);
  1554. }
  1555. if (Options->FindSwitch(L"hostkey", Value) ||
  1556. Options->FindSwitch(L"certificate", Value))
  1557. {
  1558. HostKey = Value;
  1559. FOverrideCachedHostKey = true;
  1560. }
  1561. FtpPasvMode = Options->SwitchValue(L"passive", FtpPasvMode);
  1562. if (Options->FindSwitch(L"implicit"))
  1563. {
  1564. bool Enabled = Options->SwitchValue(L"implicit", true);
  1565. Ftps = Enabled ? ftpsImplicit : ftpsNone;
  1566. if (!PortNumberDefined && Enabled)
  1567. {
  1568. PortNumber = FtpsImplicitPortNumber;
  1569. }
  1570. }
  1571. // BACKWARD COMPATIBILITY with 5.5.x
  1572. if (Options->FindSwitch(L"explicitssl"))
  1573. {
  1574. bool Enabled = Options->SwitchValue(L"explicitssl", true);
  1575. Ftps = Enabled ? ftpsExplicitSsl : ftpsNone;
  1576. if (!PortNumberDefined && Enabled)
  1577. {
  1578. PortNumber = FtpPortNumber;
  1579. }
  1580. }
  1581. if (Options->FindSwitch(L"explicit") ||
  1582. // BACKWARD COMPATIBILITY with 5.5.x
  1583. Options->FindSwitch(L"explicittls"))
  1584. {
  1585. UnicodeString SwitchName =
  1586. Options->FindSwitch(L"explicit") ? L"explicit" : L"explicittls";
  1587. bool Enabled = Options->SwitchValue(SwitchName, true);
  1588. Ftps = Enabled ? ftpsExplicitTls : ftpsNone;
  1589. if (!PortNumberDefined && Enabled)
  1590. {
  1591. PortNumber = FtpPortNumber;
  1592. }
  1593. }
  1594. if (Options->FindSwitch(L"rawsettings"))
  1595. {
  1596. TStrings * RawSettings = NULL;
  1597. TOptionsStorage * OptionsStorage = NULL;
  1598. try
  1599. {
  1600. RawSettings = new TStringList();
  1601. if (Options->FindSwitch(L"rawsettings", RawSettings))
  1602. {
  1603. OptionsStorage = new TOptionsStorage(RawSettings, false);
  1604. ApplyRawSettings(OptionsStorage);
  1605. }
  1606. }
  1607. __finally
  1608. {
  1609. delete RawSettings;
  1610. delete OptionsStorage;
  1611. }
  1612. }
  1613. }
  1614. return true;
  1615. }
  1616. //---------------------------------------------------------------------
  1617. void __fastcall TSessionData::ApplyRawSettings(THierarchicalStorage * Storage)
  1618. {
  1619. bool Dummy;
  1620. DoLoad(Storage, Dummy);
  1621. }
  1622. //---------------------------------------------------------------------
  1623. void __fastcall TSessionData::ConfigureTunnel(int APortNumber)
  1624. {
  1625. FOrigHostName = HostName;
  1626. FOrigPortNumber = PortNumber;
  1627. FOrigProxyMethod = ProxyMethod;
  1628. HostName = L"127.0.0.1";
  1629. PortNumber = APortNumber;
  1630. // proxy settings is used for tunnel
  1631. ProxyMethod = ::pmNone;
  1632. }
  1633. //---------------------------------------------------------------------
  1634. void __fastcall TSessionData::RollbackTunnel()
  1635. {
  1636. HostName = FOrigHostName;
  1637. PortNumber = FOrigPortNumber;
  1638. ProxyMethod = FOrigProxyMethod;
  1639. }
  1640. //---------------------------------------------------------------------
  1641. void __fastcall TSessionData::ExpandEnvironmentVariables()
  1642. {
  1643. HostName = HostNameExpanded;
  1644. UserName = UserNameExpanded;
  1645. PublicKeyFile = ::ExpandEnvironmentVariables(PublicKeyFile);
  1646. }
  1647. //---------------------------------------------------------------------
  1648. void __fastcall TSessionData::ValidatePath(const UnicodeString Path)
  1649. {
  1650. // noop
  1651. }
  1652. //---------------------------------------------------------------------
  1653. void __fastcall TSessionData::ValidateName(const UnicodeString Name)
  1654. {
  1655. // keep consistent with MakeValidName
  1656. if (Name.LastDelimiter(L"/") > 0)
  1657. {
  1658. throw Exception(FMTLOAD(ITEM_NAME_INVALID, (Name, L"/")));
  1659. }
  1660. }
  1661. //---------------------------------------------------------------------
  1662. UnicodeString __fastcall TSessionData::MakeValidName(const UnicodeString & Name)
  1663. {
  1664. // keep consistent with ValidateName
  1665. return ReplaceStr(Name, L"/", L"\\");
  1666. }
  1667. //---------------------------------------------------------------------
  1668. RawByteString __fastcall TSessionData::EncryptPassword(const UnicodeString & Password, UnicodeString Key)
  1669. {
  1670. return Configuration->EncryptPassword(Password, Key);
  1671. }
  1672. //---------------------------------------------------------------------
  1673. RawByteString __fastcall TSessionData::StronglyRecryptPassword(const RawByteString & Password, UnicodeString Key)
  1674. {
  1675. return Configuration->StronglyRecryptPassword(Password, Key);
  1676. }
  1677. //---------------------------------------------------------------------
  1678. UnicodeString __fastcall TSessionData::DecryptPassword(const RawByteString & Password, UnicodeString Key)
  1679. {
  1680. UnicodeString Result;
  1681. try
  1682. {
  1683. Result = Configuration->DecryptPassword(Password, Key);
  1684. }
  1685. catch(EAbort &)
  1686. {
  1687. // silently ignore aborted prompts for master password and return empty password
  1688. }
  1689. return Result;
  1690. }
  1691. //---------------------------------------------------------------------
  1692. bool __fastcall TSessionData::GetCanLogin()
  1693. {
  1694. return !FHostName.IsEmpty();
  1695. }
  1696. //---------------------------------------------------------------------------
  1697. UnicodeString __fastcall TSessionData::GetSessionKey()
  1698. {
  1699. return FORMAT(L"%s@%s", (UserName, HostName));
  1700. }
  1701. //---------------------------------------------------------------------
  1702. UnicodeString __fastcall TSessionData::GetInternalStorageKey()
  1703. {
  1704. if (Name.IsEmpty())
  1705. {
  1706. return SessionKey;
  1707. }
  1708. else
  1709. {
  1710. return Name;
  1711. }
  1712. }
  1713. //---------------------------------------------------------------------
  1714. UnicodeString __fastcall TSessionData::GetStorageKey()
  1715. {
  1716. return SessionName;
  1717. }
  1718. //---------------------------------------------------------------------
  1719. UnicodeString __fastcall TSessionData::FormatSiteKey(const UnicodeString & HostName, int PortNumber)
  1720. {
  1721. return FORMAT(L"%s:%d", (HostName, PortNumber));
  1722. }
  1723. //---------------------------------------------------------------------
  1724. UnicodeString __fastcall TSessionData::GetSiteKey()
  1725. {
  1726. return FormatSiteKey(HostNameExpanded, PortNumber);
  1727. }
  1728. //---------------------------------------------------------------------
  1729. void __fastcall TSessionData::SetHostName(UnicodeString value)
  1730. {
  1731. if (FHostName != value)
  1732. {
  1733. // HostName is key for password encryption
  1734. UnicodeString XPassword = Password;
  1735. // This is now hardly used as hostname is parsed directly on login dialog.
  1736. // But can be used when importing sites from PuTTY, as it allows same format too.
  1737. int P = value.LastDelimiter(L"@");
  1738. if (P > 0)
  1739. {
  1740. UserName = value.SubString(1, P - 1);
  1741. value = value.SubString(P + 1, value.Length() - P);
  1742. }
  1743. FHostName = value;
  1744. Modify();
  1745. Password = XPassword;
  1746. Shred(XPassword);
  1747. }
  1748. }
  1749. //---------------------------------------------------------------------
  1750. UnicodeString __fastcall TSessionData::GetHostNameExpanded()
  1751. {
  1752. return ::ExpandEnvironmentVariables(HostName);
  1753. }
  1754. //---------------------------------------------------------------------
  1755. void __fastcall TSessionData::SetPortNumber(int value)
  1756. {
  1757. SET_SESSION_PROPERTY(PortNumber);
  1758. }
  1759. //---------------------------------------------------------------------------
  1760. void __fastcall TSessionData::SetShell(UnicodeString value)
  1761. {
  1762. SET_SESSION_PROPERTY(Shell);
  1763. }
  1764. //---------------------------------------------------------------------------
  1765. void __fastcall TSessionData::SetSftpServer(UnicodeString value)
  1766. {
  1767. SET_SESSION_PROPERTY(SftpServer);
  1768. }
  1769. //---------------------------------------------------------------------------
  1770. void __fastcall TSessionData::SetClearAliases(bool value)
  1771. {
  1772. SET_SESSION_PROPERTY(ClearAliases);
  1773. }
  1774. //---------------------------------------------------------------------------
  1775. void __fastcall TSessionData::SetListingCommand(UnicodeString value)
  1776. {
  1777. SET_SESSION_PROPERTY(ListingCommand);
  1778. }
  1779. //---------------------------------------------------------------------------
  1780. void __fastcall TSessionData::SetIgnoreLsWarnings(bool value)
  1781. {
  1782. SET_SESSION_PROPERTY(IgnoreLsWarnings);
  1783. }
  1784. //---------------------------------------------------------------------------
  1785. void __fastcall TSessionData::SetUnsetNationalVars(bool value)
  1786. {
  1787. SET_SESSION_PROPERTY(UnsetNationalVars);
  1788. }
  1789. //---------------------------------------------------------------------
  1790. void __fastcall TSessionData::SetUserName(UnicodeString value)
  1791. {
  1792. // Avoid password recryption (what may popup master password prompt)
  1793. if (FUserName != value)
  1794. {
  1795. // UserName is key for password encryption
  1796. UnicodeString XPassword = Password;
  1797. SET_SESSION_PROPERTY(UserName);
  1798. Password = XPassword;
  1799. Shred(XPassword);
  1800. }
  1801. }
  1802. //---------------------------------------------------------------------
  1803. UnicodeString __fastcall TSessionData::GetUserNameExpanded()
  1804. {
  1805. return ::ExpandEnvironmentVariables(UserName);
  1806. }
  1807. //---------------------------------------------------------------------
  1808. void __fastcall TSessionData::SetPassword(UnicodeString avalue)
  1809. {
  1810. RawByteString value = EncryptPassword(avalue, UserName+HostName);
  1811. SET_SESSION_PROPERTY(Password);
  1812. }
  1813. //---------------------------------------------------------------------
  1814. UnicodeString __fastcall TSessionData::GetPassword() const
  1815. {
  1816. return DecryptPassword(FPassword, UserName+HostName);
  1817. }
  1818. //---------------------------------------------------------------------
  1819. void __fastcall TSessionData::SetPingInterval(int value)
  1820. {
  1821. SET_SESSION_PROPERTY(PingInterval);
  1822. }
  1823. //---------------------------------------------------------------------
  1824. void __fastcall TSessionData::SetTryAgent(bool value)
  1825. {
  1826. SET_SESSION_PROPERTY(TryAgent);
  1827. }
  1828. //---------------------------------------------------------------------
  1829. void __fastcall TSessionData::SetAgentFwd(bool value)
  1830. {
  1831. SET_SESSION_PROPERTY(AgentFwd);
  1832. }
  1833. //---------------------------------------------------------------------
  1834. void __fastcall TSessionData::SetAuthTIS(bool value)
  1835. {
  1836. SET_SESSION_PROPERTY(AuthTIS);
  1837. }
  1838. //---------------------------------------------------------------------
  1839. void __fastcall TSessionData::SetAuthKI(bool value)
  1840. {
  1841. SET_SESSION_PROPERTY(AuthKI);
  1842. }
  1843. //---------------------------------------------------------------------
  1844. void __fastcall TSessionData::SetAuthKIPassword(bool value)
  1845. {
  1846. SET_SESSION_PROPERTY(AuthKIPassword);
  1847. }
  1848. //---------------------------------------------------------------------
  1849. void __fastcall TSessionData::SetAuthGSSAPI(bool value)
  1850. {
  1851. SET_SESSION_PROPERTY(AuthGSSAPI);
  1852. }
  1853. //---------------------------------------------------------------------
  1854. void __fastcall TSessionData::SetGSSAPIFwdTGT(bool value)
  1855. {
  1856. SET_SESSION_PROPERTY(GSSAPIFwdTGT);
  1857. }
  1858. //---------------------------------------------------------------------
  1859. void __fastcall TSessionData::SetGSSAPIServerRealm(UnicodeString value)
  1860. {
  1861. SET_SESSION_PROPERTY(GSSAPIServerRealm);
  1862. }
  1863. //---------------------------------------------------------------------
  1864. void __fastcall TSessionData::SetChangeUsername(bool value)
  1865. {
  1866. SET_SESSION_PROPERTY(ChangeUsername);
  1867. }
  1868. //---------------------------------------------------------------------
  1869. void __fastcall TSessionData::SetCompression(bool value)
  1870. {
  1871. SET_SESSION_PROPERTY(Compression);
  1872. }
  1873. //---------------------------------------------------------------------
  1874. void __fastcall TSessionData::SetSshProt(TSshProt value)
  1875. {
  1876. SET_SESSION_PROPERTY(SshProt);
  1877. }
  1878. //---------------------------------------------------------------------
  1879. void __fastcall TSessionData::SetSsh2DES(bool value)
  1880. {
  1881. SET_SESSION_PROPERTY(Ssh2DES);
  1882. }
  1883. //---------------------------------------------------------------------
  1884. void __fastcall TSessionData::SetSshNoUserAuth(bool value)
  1885. {
  1886. SET_SESSION_PROPERTY(SshNoUserAuth);
  1887. }
  1888. //---------------------------------------------------------------------
  1889. UnicodeString __fastcall TSessionData::GetSshProtStr()
  1890. {
  1891. return SshProtList[FSshProt];
  1892. }
  1893. //---------------------------------------------------------------------
  1894. bool __fastcall TSessionData::GetUsesSsh()
  1895. {
  1896. return IsSshProtocol(FSProtocol);
  1897. }
  1898. //---------------------------------------------------------------------
  1899. void __fastcall TSessionData::SetCipher(int Index, TCipher value)
  1900. {
  1901. DebugAssert(Index >= 0 && Index < CIPHER_COUNT);
  1902. SET_SESSION_PROPERTY(Ciphers[Index]);
  1903. }
  1904. //---------------------------------------------------------------------
  1905. TCipher __fastcall TSessionData::GetCipher(int Index) const
  1906. {
  1907. DebugAssert(Index >= 0 && Index < CIPHER_COUNT);
  1908. return FCiphers[Index];
  1909. }
  1910. //---------------------------------------------------------------------
  1911. template<class AlgoT>
  1912. void __fastcall TSessionData::SetAlgoList(AlgoT * List, const AlgoT * DefaultList, const UnicodeString * Names, int Count, UnicodeString value)
  1913. {
  1914. std::vector<bool> Used(Count); // initialized to false
  1915. std::vector<AlgoT> NewList(Count);
  1916. int Index = 0;
  1917. while (!value.IsEmpty() && (Index < Count))
  1918. {
  1919. UnicodeString AlgoStr = CutToChar(value, L',', true);
  1920. for (int Algo = 0; Algo < Count; Algo++)
  1921. {
  1922. if (!AlgoStr.CompareIC(Names[Algo]))
  1923. {
  1924. NewList[Index] = (AlgoT)Algo;
  1925. Used[Algo] = true;
  1926. Index++;
  1927. break;
  1928. }
  1929. }
  1930. }
  1931. for (int Algo = 0; (Algo < Count) && (Index < Count); Algo++)
  1932. {
  1933. if (!Used[DefaultList[Algo]])
  1934. {
  1935. NewList[Index++] = DefaultList[Algo];
  1936. }
  1937. }
  1938. if (!std::equal(NewList.begin(), NewList.end(), List))
  1939. {
  1940. std::copy(NewList.begin(), NewList.end(), List);
  1941. Modify();
  1942. }
  1943. }
  1944. //---------------------------------------------------------------------
  1945. void __fastcall TSessionData::SetCipherList(UnicodeString value)
  1946. {
  1947. SetAlgoList(FCiphers, DefaultCipherList, CipherNames, CIPHER_COUNT, value);
  1948. }
  1949. //---------------------------------------------------------------------
  1950. UnicodeString __fastcall TSessionData::GetCipherList() const
  1951. {
  1952. UnicodeString Result;
  1953. for (int Index = 0; Index < CIPHER_COUNT; Index++)
  1954. {
  1955. Result += UnicodeString(Index ? L"," : L"") + CipherNames[Cipher[Index]];
  1956. }
  1957. return Result;
  1958. }
  1959. //---------------------------------------------------------------------
  1960. void __fastcall TSessionData::SetKex(int Index, TKex value)
  1961. {
  1962. DebugAssert(Index >= 0 && Index < KEX_COUNT);
  1963. SET_SESSION_PROPERTY(Kex[Index]);
  1964. }
  1965. //---------------------------------------------------------------------
  1966. TKex __fastcall TSessionData::GetKex(int Index) const
  1967. {
  1968. DebugAssert(Index >= 0 && Index < KEX_COUNT);
  1969. return FKex[Index];
  1970. }
  1971. //---------------------------------------------------------------------
  1972. void __fastcall TSessionData::SetKexList(UnicodeString value)
  1973. {
  1974. SetAlgoList(FKex, DefaultKexList, KexNames, KEX_COUNT, value);
  1975. }
  1976. //---------------------------------------------------------------------
  1977. UnicodeString __fastcall TSessionData::GetKexList() const
  1978. {
  1979. UnicodeString Result;
  1980. for (int Index = 0; Index < KEX_COUNT; Index++)
  1981. {
  1982. Result += UnicodeString(Index ? L"," : L"") + KexNames[Kex[Index]];
  1983. }
  1984. return Result;
  1985. }
  1986. //---------------------------------------------------------------------
  1987. void __fastcall TSessionData::SetPublicKeyFile(UnicodeString value)
  1988. {
  1989. if (FPublicKeyFile != value)
  1990. {
  1991. // PublicKeyFile is key for Passphrase encryption
  1992. UnicodeString XPassphrase = Passphrase;
  1993. // StripPathQuotes should not be needed as we do not feed quotes anymore
  1994. FPublicKeyFile = StripPathQuotes(value);
  1995. Modify();
  1996. Passphrase = XPassphrase;
  1997. Shred(XPassphrase);
  1998. }
  1999. }
  2000. //---------------------------------------------------------------------
  2001. void __fastcall TSessionData::SetPassphrase(UnicodeString avalue)
  2002. {
  2003. RawByteString value = EncryptPassword(avalue, PublicKeyFile);
  2004. SET_SESSION_PROPERTY(Passphrase);
  2005. }
  2006. //---------------------------------------------------------------------
  2007. UnicodeString __fastcall TSessionData::GetPassphrase() const
  2008. {
  2009. return DecryptPassword(FPassphrase, PublicKeyFile);
  2010. }
  2011. //---------------------------------------------------------------------
  2012. void __fastcall TSessionData::SetReturnVar(UnicodeString value)
  2013. {
  2014. SET_SESSION_PROPERTY(ReturnVar);
  2015. }
  2016. //---------------------------------------------------------------------------
  2017. void __fastcall TSessionData::SetLookupUserGroups(TAutoSwitch value)
  2018. {
  2019. SET_SESSION_PROPERTY(LookupUserGroups);
  2020. }
  2021. //---------------------------------------------------------------------------
  2022. void __fastcall TSessionData::SetEOLType(TEOLType value)
  2023. {
  2024. SET_SESSION_PROPERTY(EOLType);
  2025. }
  2026. //---------------------------------------------------------------------------
  2027. void __fastcall TSessionData::SetTrimVMSVersions(bool value)
  2028. {
  2029. SET_SESSION_PROPERTY(TrimVMSVersions);
  2030. }
  2031. //---------------------------------------------------------------------------
  2032. TDateTime __fastcall TSessionData::GetTimeoutDT()
  2033. {
  2034. return SecToDateTime(Timeout);
  2035. }
  2036. //---------------------------------------------------------------------------
  2037. void __fastcall TSessionData::SetTimeout(int value)
  2038. {
  2039. SET_SESSION_PROPERTY(Timeout);
  2040. }
  2041. //---------------------------------------------------------------------------
  2042. void __fastcall TSessionData::SetFSProtocol(TFSProtocol value)
  2043. {
  2044. SET_SESSION_PROPERTY(FSProtocol);
  2045. }
  2046. //---------------------------------------------------------------------
  2047. UnicodeString __fastcall TSessionData::GetFSProtocolStr()
  2048. {
  2049. DebugAssert(FSProtocol >= 0 && FSProtocol < FSPROTOCOL_COUNT);
  2050. return FSProtocolNames[FSProtocol];
  2051. }
  2052. //---------------------------------------------------------------------------
  2053. void __fastcall TSessionData::SetDetectReturnVar(bool value)
  2054. {
  2055. if (value != DetectReturnVar)
  2056. {
  2057. ReturnVar = value ? L"" : L"$?";
  2058. }
  2059. }
  2060. //---------------------------------------------------------------------------
  2061. bool __fastcall TSessionData::GetDetectReturnVar()
  2062. {
  2063. return ReturnVar.IsEmpty();
  2064. }
  2065. //---------------------------------------------------------------------------
  2066. void __fastcall TSessionData::SetDefaultShell(bool value)
  2067. {
  2068. if (value != DefaultShell)
  2069. {
  2070. Shell = value ? L"" : L"/bin/bash";
  2071. }
  2072. }
  2073. //---------------------------------------------------------------------------
  2074. bool __fastcall TSessionData::GetDefaultShell()
  2075. {
  2076. return Shell.IsEmpty();
  2077. }
  2078. //---------------------------------------------------------------------------
  2079. void __fastcall TSessionData::SetPuttyProtocol(UnicodeString value)
  2080. {
  2081. SET_SESSION_PROPERTY(PuttyProtocol);
  2082. }
  2083. //---------------------------------------------------------------------
  2084. UnicodeString __fastcall TSessionData::GetNormalizedPuttyProtocol() const
  2085. {
  2086. return DefaultStr(PuttyProtocol, PuttySshProtocol);
  2087. }
  2088. //---------------------------------------------------------------------
  2089. void __fastcall TSessionData::SetPingIntervalDT(TDateTime value)
  2090. {
  2091. unsigned short hour, min, sec, msec;
  2092. value.DecodeTime(&hour, &min, &sec, &msec);
  2093. PingInterval = ((int)hour)*SecsPerHour + ((int)min)*SecsPerMin + sec;
  2094. }
  2095. //---------------------------------------------------------------------------
  2096. TDateTime __fastcall TSessionData::GetPingIntervalDT()
  2097. {
  2098. return SecToDateTime(PingInterval);
  2099. }
  2100. //---------------------------------------------------------------------------
  2101. void __fastcall TSessionData::SetPingType(TPingType value)
  2102. {
  2103. SET_SESSION_PROPERTY(PingType);
  2104. }
  2105. //---------------------------------------------------------------------------
  2106. void __fastcall TSessionData::SetAddressFamily(TAddressFamily value)
  2107. {
  2108. SET_SESSION_PROPERTY(AddressFamily);
  2109. }
  2110. //---------------------------------------------------------------------------
  2111. void __fastcall TSessionData::SetRekeyData(UnicodeString value)
  2112. {
  2113. SET_SESSION_PROPERTY(RekeyData);
  2114. }
  2115. //---------------------------------------------------------------------------
  2116. void __fastcall TSessionData::SetRekeyTime(unsigned int value)
  2117. {
  2118. SET_SESSION_PROPERTY(RekeyTime);
  2119. }
  2120. //---------------------------------------------------------------------
  2121. UnicodeString __fastcall TSessionData::GetDefaultSessionName()
  2122. {
  2123. if (!HostName.IsEmpty() && !UserName.IsEmpty())
  2124. {
  2125. // If we ever choose to include port number,
  2126. // we have to escape IPv6 literals in HostName
  2127. return FORMAT(L"%s@%s", (UserName, HostName));
  2128. }
  2129. else if (!HostName.IsEmpty())
  2130. {
  2131. return HostName;
  2132. }
  2133. else
  2134. {
  2135. return L"session";
  2136. }
  2137. }
  2138. //---------------------------------------------------------------------
  2139. UnicodeString __fastcall TSessionData::GetNameWithoutHiddenPrefix()
  2140. {
  2141. UnicodeString Result = Name;
  2142. if (Hidden)
  2143. {
  2144. Result = Result.SubString(TNamedObjectList::HiddenPrefix.Length() + 1, Result.Length() - TNamedObjectList::HiddenPrefix.Length());
  2145. }
  2146. return Result;
  2147. }
  2148. //---------------------------------------------------------------------
  2149. bool __fastcall TSessionData::HasSessionName()
  2150. {
  2151. return (!GetNameWithoutHiddenPrefix().IsEmpty() && (Name != DefaultName) && !IsWorkspace);
  2152. }
  2153. //---------------------------------------------------------------------
  2154. UnicodeString __fastcall TSessionData::GetSessionName()
  2155. {
  2156. UnicodeString Result;
  2157. if (HasSessionName())
  2158. {
  2159. Result = GetNameWithoutHiddenPrefix();
  2160. }
  2161. else
  2162. {
  2163. Result = DefaultSessionName;
  2164. }
  2165. return Result;
  2166. }
  2167. //---------------------------------------------------------------------
  2168. bool __fastcall TSessionData::IsSecure()
  2169. {
  2170. bool Result;
  2171. switch (FSProtocol)
  2172. {
  2173. case fsSCPonly:
  2174. case fsSFTP:
  2175. case fsSFTPonly:
  2176. Result = true;
  2177. break;
  2178. case fsFTP:
  2179. case fsWebDAV:
  2180. Result = (Ftps != ftpsNone);
  2181. break;
  2182. default:
  2183. DebugFail();
  2184. break;
  2185. }
  2186. return Result;
  2187. }
  2188. //---------------------------------------------------------------------
  2189. UnicodeString __fastcall TSessionData::GetProtocolUrl()
  2190. {
  2191. UnicodeString Url;
  2192. switch (FSProtocol)
  2193. {
  2194. case fsSCPonly:
  2195. Url = ScpProtocol;
  2196. break;
  2197. default:
  2198. DebugFail();
  2199. // fallback
  2200. case fsSFTP:
  2201. case fsSFTPonly:
  2202. Url = SftpProtocol;
  2203. break;
  2204. case fsFTP:
  2205. if (Ftps == ftpsImplicit)
  2206. {
  2207. Url = FtpsProtocol;
  2208. }
  2209. else if ((Ftps == ftpsExplicitTls) || (Ftps == ftpsExplicitSsl))
  2210. {
  2211. Url = FtpesProtocol;
  2212. }
  2213. else
  2214. {
  2215. Url = FtpProtocol;
  2216. }
  2217. break;
  2218. case fsWebDAV:
  2219. if (Ftps == ftpsImplicit)
  2220. {
  2221. Url = WebDAVSProtocol;
  2222. }
  2223. else
  2224. {
  2225. Url = WebDAVProtocol;
  2226. }
  2227. break;
  2228. }
  2229. Url += ProtocolSeparator;
  2230. return Url;
  2231. }
  2232. //---------------------------------------------------------------------
  2233. static bool __fastcall IsIPv6Literal(const UnicodeString & HostName)
  2234. {
  2235. bool Result = (HostName.Pos(L":") > 0);
  2236. if (Result)
  2237. {
  2238. for (int Index = 1; Result && (Index <= HostName.Length()); Index++)
  2239. {
  2240. wchar_t C = HostName[Index];
  2241. Result = IsHex(C) || (C == L':');
  2242. }
  2243. }
  2244. return Result;
  2245. }
  2246. //---------------------------------------------------------------------
  2247. UnicodeString __fastcall TSessionData::GenerateSessionUrl(unsigned int Flags)
  2248. {
  2249. UnicodeString Url;
  2250. if (FLAGSET(Flags, sufSpecific))
  2251. {
  2252. Url += WinSCPProtocolPrefix;
  2253. }
  2254. Url += GetProtocolUrl();
  2255. if (FLAGSET(Flags, sufUserName) && !UserNameExpanded.IsEmpty())
  2256. {
  2257. Url += EncodeUrlString(UserNameExpanded);
  2258. if (FLAGSET(Flags, sufPassword) && !Password.IsEmpty())
  2259. {
  2260. Url += L":" + EncodeUrlString(Password);
  2261. }
  2262. if (FLAGSET(Flags, sufHostKey) && !HostKey.IsEmpty())
  2263. {
  2264. Url +=
  2265. UnicodeString(UrlParamSeparator) + UrlHostKeyParamName +
  2266. UnicodeString(UrlParamValueSeparator) + NormalizeFingerprint(HostKey);
  2267. }
  2268. Url += L"@";
  2269. }
  2270. DebugAssert(!HostNameExpanded.IsEmpty());
  2271. if (IsIPv6Literal(HostNameExpanded))
  2272. {
  2273. Url += L"[" + HostNameExpanded + L"]";
  2274. }
  2275. else
  2276. {
  2277. Url += EncodeUrlString(HostNameExpanded);
  2278. }
  2279. if (PortNumber != DefaultPort(FSProtocol, Ftps))
  2280. {
  2281. Url += L":" + IntToStr(PortNumber);
  2282. }
  2283. Url += L"/";
  2284. return Url;
  2285. }
  2286. //---------------------------------------------------------------------
  2287. void __fastcall TSessionData::AddSwitch(UnicodeString & Result, const UnicodeString & Switch)
  2288. {
  2289. Result += FORMAT(L" -%s", (Switch));
  2290. }
  2291. //---------------------------------------------------------------------
  2292. void __fastcall TSessionData::AddSwitchValue(UnicodeString & Result, const UnicodeString & Name, const UnicodeString & Value)
  2293. {
  2294. AddSwitch(Result, FORMAT(L"%s=%s", (Name, Value)));
  2295. }
  2296. //---------------------------------------------------------------------
  2297. void __fastcall TSessionData::AddSwitch(UnicodeString & Result, const UnicodeString & Name, const UnicodeString & Value)
  2298. {
  2299. AddSwitchValue(Result, Name, FORMAT("\"%s\"", (EscapeParam(Value))));
  2300. }
  2301. //---------------------------------------------------------------------
  2302. void __fastcall TSessionData::AddSwitch(UnicodeString & Result, const UnicodeString & Name, int Value)
  2303. {
  2304. AddSwitchValue(Result, Name, IntToStr(Value));
  2305. }
  2306. //---------------------------------------------------------------------
  2307. void __fastcall TSessionData::LookupLastFingerprint()
  2308. {
  2309. UnicodeString FingerprintType;
  2310. if (IsSshProtocol(FSProtocol))
  2311. {
  2312. FingerprintType = SshFingerprintType;
  2313. }
  2314. else if (Ftps != ftpsNone)
  2315. {
  2316. FingerprintType = TlsFingerprintType;
  2317. }
  2318. if (!FingerprintType.IsEmpty())
  2319. {
  2320. HostKey = Configuration->LastFingerprint(SiteKey, FingerprintType);
  2321. }
  2322. }
  2323. //---------------------------------------------------------------------
  2324. UnicodeString __fastcall TSessionData::GenerateOpenCommandArgs()
  2325. {
  2326. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  2327. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  2328. SessionData->Assign(this);
  2329. UnicodeString Result = SessionData->GenerateSessionUrl(sufOpen);
  2330. // Before we reset the FSProtocol
  2331. bool AUsesSsh = SessionData->UsesSsh;
  2332. // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that
  2333. if (SessionData->FSProtocol != fsSFTPonly)
  2334. {
  2335. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  2336. }
  2337. SessionData->HostName = FactoryDefaults->HostName;
  2338. SessionData->PortNumber = FactoryDefaults->PortNumber;
  2339. SessionData->UserName = FactoryDefaults->UserName;
  2340. SessionData->Password = FactoryDefaults->Password;
  2341. SessionData->CopyNonCoreData(FactoryDefaults.get());
  2342. SessionData->Ftps = FactoryDefaults->Ftps;
  2343. if (SessionData->HostKey != FactoryDefaults->HostKey)
  2344. {
  2345. UnicodeString SwitchName = AUsesSsh ? L"hostkey" : L"certificate";
  2346. AddSwitch(Result, SwitchName, SessionData->HostKey);
  2347. SessionData->HostKey = FactoryDefaults->HostKey;
  2348. }
  2349. if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)
  2350. {
  2351. AddSwitch(Result, L"privatekey", SessionData->PublicKeyFile);
  2352. SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;
  2353. }
  2354. if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)
  2355. {
  2356. AddSwitch(Result, L"clientcert", SessionData->TlsCertificateFile);
  2357. SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;
  2358. }
  2359. if (SessionData->Passphrase != FactoryDefaults->Passphrase)
  2360. {
  2361. AddSwitch(Result, PassphraseOption, SessionData->Passphrase);
  2362. SessionData->Passphrase = FactoryDefaults->Passphrase;
  2363. }
  2364. if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)
  2365. {
  2366. AddSwitch(Result, L"passive", SessionData->FtpPasvMode ? 1 : 0);
  2367. SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;
  2368. }
  2369. if (SessionData->Timeout != FactoryDefaults->Timeout)
  2370. {
  2371. AddSwitch(Result, L"timeout", SessionData->Timeout);
  2372. SessionData->Timeout = FactoryDefaults->Timeout;
  2373. }
  2374. std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get()));
  2375. if (RawSettings->Count > 0)
  2376. {
  2377. AddSwitch(Result, L"rawsettings");
  2378. for (int Index = 0; Index < RawSettings->Count; Index++)
  2379. {
  2380. UnicodeString Name = RawSettings->Names[Index];
  2381. UnicodeString Value = RawSettings->ValueFromIndex[Index];
  2382. // Do not quote if it is all-numeric
  2383. if (IntToStr(StrToIntDef(Value, -1)) != Value)
  2384. {
  2385. Value = FORMAT(L"\"%s\"", (EscapeParam(Value)));
  2386. }
  2387. Result += FORMAT(L" %s=%s", (Name, Value));
  2388. }
  2389. }
  2390. return Result;
  2391. }
  2392. //---------------------------------------------------------------------
  2393. void __fastcall TSessionData::AddAssemblyProperty(
  2394. UnicodeString & Result, TAssemblyLanguage Language,
  2395. const UnicodeString & Name, const UnicodeString & Type,
  2396. const UnicodeString & Member)
  2397. {
  2398. UnicodeString PropertyCode;
  2399. switch (Language)
  2400. {
  2401. case alCSharp:
  2402. PropertyCode = L" %s = %s.%s,\n";
  2403. break;
  2404. case alVBNET:
  2405. PropertyCode = L" .%s = %s.%s\n";
  2406. break;
  2407. case alPowerShell:
  2408. PropertyCode = L"$sessionOptions.%s = [WinSCP.%s]::%s\n";
  2409. break;
  2410. }
  2411. Result += FORMAT(PropertyCode, (Name, Type, Member));
  2412. }
  2413. //---------------------------------------------------------------------
  2414. UnicodeString __fastcall TSessionData::AssemblyString(TAssemblyLanguage Language, UnicodeString S)
  2415. {
  2416. switch (Language)
  2417. {
  2418. case alCSharp:
  2419. if (S.Pos(L"\\") > 0)
  2420. {
  2421. S = FORMAT(L"@\"%s\"", (ReplaceStr(S, L"\"", L"\"\"")));
  2422. }
  2423. else
  2424. {
  2425. S = FORMAT(L"\"%s\"", (ReplaceStr(S, L"\"", L"\\\"")));
  2426. }
  2427. break;
  2428. case alVBNET:
  2429. S = FORMAT(L"\"%s\"", (ReplaceStr(S, L"\"", L"\"\"")));
  2430. break;
  2431. case alPowerShell:
  2432. S = FORMAT(L"\"%s\"", (ReplaceStr(S, L"\"", L"`\"")));
  2433. break;
  2434. default:
  2435. DebugFail();
  2436. break;
  2437. }
  2438. return S;
  2439. }
  2440. //---------------------------------------------------------------------
  2441. void __fastcall TSessionData::AddAssemblyPropertyRaw(
  2442. UnicodeString & Result, TAssemblyLanguage Language,
  2443. const UnicodeString & Name, const UnicodeString & Value)
  2444. {
  2445. UnicodeString PropertyCode;
  2446. switch (Language)
  2447. {
  2448. case alCSharp:
  2449. PropertyCode = L" %s = %s,\n";
  2450. break;
  2451. case alVBNET:
  2452. PropertyCode = L" .%s = %s\n";
  2453. break;
  2454. case alPowerShell:
  2455. PropertyCode = L"$sessionOptions.%s = %s\n";
  2456. break;
  2457. }
  2458. Result += FORMAT(PropertyCode, (Name, Value));
  2459. }
  2460. //---------------------------------------------------------------------
  2461. void __fastcall TSessionData::AddAssemblyProperty(
  2462. UnicodeString & Result, TAssemblyLanguage Language,
  2463. const UnicodeString & Name, UnicodeString Value)
  2464. {
  2465. AddAssemblyPropertyRaw(Result, Language, Name, AssemblyString(Language, Value));
  2466. }
  2467. //---------------------------------------------------------------------
  2468. void __fastcall TSessionData::AddAssemblyProperty(
  2469. UnicodeString & Result, TAssemblyLanguage Language,
  2470. const UnicodeString & Name, int Value)
  2471. {
  2472. AddAssemblyPropertyRaw(Result, Language, Name, IntToStr(Value));
  2473. }
  2474. //---------------------------------------------------------------------
  2475. void __fastcall TSessionData::AddAssemblyProperty(
  2476. UnicodeString & Result, TAssemblyLanguage Language,
  2477. const UnicodeString & Name, bool Value)
  2478. {
  2479. UnicodeString PropertyValue;
  2480. switch (Language)
  2481. {
  2482. case alCSharp:
  2483. PropertyValue = (Value ? L"true" : L"false");
  2484. break;
  2485. case alVBNET:
  2486. PropertyValue = (Value ? L"True" : L"False");
  2487. break;
  2488. case alPowerShell:
  2489. PropertyValue = (Value ? L"$True" : L"$False");
  2490. break;
  2491. }
  2492. AddAssemblyPropertyRaw(Result, Language, Name, PropertyValue);
  2493. }
  2494. //---------------------------------------------------------------------
  2495. UnicodeString __fastcall TSessionData::GenerateAssemblyCode(
  2496. TAssemblyLanguage Language)
  2497. {
  2498. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  2499. std::unique_ptr<TSessionData> SessionData(Clone());
  2500. UnicodeString Result;
  2501. UnicodeString SessionOptionsPreamble;
  2502. switch (Language)
  2503. {
  2504. case alCSharp:
  2505. SessionOptionsPreamble =
  2506. L"// %s\n"
  2507. "SessionOptions sessionOptions = new SessionOptions\n"
  2508. "{\n";
  2509. break;
  2510. case alVBNET:
  2511. SessionOptionsPreamble =
  2512. L"' %s\n"
  2513. "Dim mySessionOptions As New SessionOptions\n"
  2514. "With mySessionOptions\n";
  2515. break;
  2516. case alPowerShell:
  2517. SessionOptionsPreamble =
  2518. FORMAT(L"# %s\n", (LoadStr(CODE_PS_ADD_TYPE))) +
  2519. L"Add-Type -Path \"WinSCPnet.dll\"\n"
  2520. "\n"
  2521. "# %s\n"
  2522. "$sessionOptions = New-Object WinSCP.SessionOptions\n";
  2523. break;
  2524. default:
  2525. DebugFail();
  2526. break;
  2527. }
  2528. Result = FORMAT(SessionOptionsPreamble, (LoadStr(CODE_SESSION_OPTIONS)));
  2529. UnicodeString ProtocolMember;
  2530. switch (SessionData->FSProtocol)
  2531. {
  2532. case fsSCPonly:
  2533. ProtocolMember = "Scp";
  2534. break;
  2535. default:
  2536. DebugFail();
  2537. // fallback
  2538. case fsSFTP:
  2539. case fsSFTPonly:
  2540. ProtocolMember = "Sftp";
  2541. break;
  2542. case fsFTP:
  2543. ProtocolMember = "Ftp";
  2544. break;
  2545. case fsWebDAV:
  2546. ProtocolMember = "Webdav";
  2547. break;
  2548. }
  2549. // Before we reset the FSProtocol
  2550. bool AUsesSsh = SessionData->UsesSsh;
  2551. // Protocol is set unconditionally, we want even the default SFTP
  2552. AddAssemblyProperty(Result, Language, L"Protocol", L"Protocol", ProtocolMember);
  2553. // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that
  2554. if (SessionData->FSProtocol != fsSFTPonly)
  2555. {
  2556. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  2557. }
  2558. if (SessionData->HostName != FactoryDefaults->HostName)
  2559. {
  2560. AddAssemblyProperty(Result, Language, L"HostName", HostName);
  2561. SessionData->HostName = FactoryDefaults->HostName;
  2562. }
  2563. if (SessionData->PortNumber != FactoryDefaults->PortNumber)
  2564. {
  2565. AddAssemblyProperty(Result, Language, L"PortNumber", PortNumber);
  2566. SessionData->PortNumber = FactoryDefaults->PortNumber;
  2567. }
  2568. if (SessionData->UserName != FactoryDefaults->UserName)
  2569. {
  2570. AddAssemblyProperty(Result, Language, L"UserName", UserName);
  2571. SessionData->UserName = FactoryDefaults->UserName;
  2572. }
  2573. if (SessionData->Password != FactoryDefaults->Password)
  2574. {
  2575. AddAssemblyProperty(Result, Language, L"Password", Password);
  2576. SessionData->Password = FactoryDefaults->Password;
  2577. }
  2578. SessionData->CopyNonCoreData(FactoryDefaults.get());
  2579. if (SessionData->Ftps != FactoryDefaults->Ftps)
  2580. {
  2581. // SessionData->FSProtocol is reset already
  2582. switch (FSProtocol)
  2583. {
  2584. case fsFTP:
  2585. {
  2586. UnicodeString FtpSecureMember;
  2587. switch (SessionData->Ftps)
  2588. {
  2589. case ftpsNone:
  2590. // noop
  2591. break;
  2592. case ftpsImplicit:
  2593. FtpSecureMember = L"Implicit";
  2594. break;
  2595. case ftpsExplicitTls:
  2596. case ftpsExplicitSsl:
  2597. FtpSecureMember = L"Explicit";
  2598. break;
  2599. default:
  2600. DebugFail();
  2601. break;
  2602. }
  2603. AddAssemblyProperty(Result, Language, L"FtpSecure", L"FtpSecure", FtpSecureMember);
  2604. }
  2605. break;
  2606. case fsWebDAV:
  2607. AddAssemblyProperty(Result, Language, L"WebdavSecure", (SessionData->Ftps != ftpsNone));
  2608. break;
  2609. default:
  2610. DebugFail();
  2611. break;
  2612. }
  2613. SessionData->Ftps = FactoryDefaults->Ftps;
  2614. }
  2615. if (SessionData->HostKey != FactoryDefaults->HostKey)
  2616. {
  2617. UnicodeString PropertyName = AUsesSsh ? L"SshHostKeyFingerprint" : L"TlsHostCertificateFingerprint";
  2618. AddAssemblyProperty(Result, Language, PropertyName, SessionData->HostKey);
  2619. SessionData->HostKey = FactoryDefaults->HostKey;
  2620. }
  2621. if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)
  2622. {
  2623. AddAssemblyProperty(Result, Language, L"SshPrivateKeyPath", SessionData->PublicKeyFile);
  2624. SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;
  2625. }
  2626. if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)
  2627. {
  2628. AddAssemblyProperty(Result, Language, L"TlsClientCertificatePath", SessionData->TlsCertificateFile);
  2629. SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;
  2630. }
  2631. if (SessionData->Passphrase != FactoryDefaults->Passphrase)
  2632. {
  2633. AddAssemblyProperty(Result, Language, L"PrivateKeyPassphrase", SessionData->Passphrase);
  2634. SessionData->Passphrase = FactoryDefaults->Passphrase;
  2635. }
  2636. if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)
  2637. {
  2638. AddAssemblyProperty(Result, Language, L"FtpMode", L"FtpMode", (SessionData->FtpPasvMode ? L"Passive" : L"Active"));
  2639. SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;
  2640. }
  2641. if (SessionData->Timeout != FactoryDefaults->Timeout)
  2642. {
  2643. AddAssemblyProperty(Result, Language, L"TimeoutInMilliseconds", SessionData->Timeout);
  2644. SessionData->Timeout = FactoryDefaults->Timeout;
  2645. }
  2646. switch (Language)
  2647. {
  2648. case alCSharp:
  2649. Result += L"};\n";
  2650. break;
  2651. case alVBNET:
  2652. // noop
  2653. // Ending With only after AddRawSettings
  2654. break;
  2655. }
  2656. std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get()));
  2657. if (RawSettings->Count > 0)
  2658. {
  2659. Result += L"\n";
  2660. for (int Index = 0; Index < RawSettings->Count; Index++)
  2661. {
  2662. UnicodeString Name = RawSettings->Names[Index];
  2663. UnicodeString Value = RawSettings->ValueFromIndex[Index];
  2664. UnicodeString SettingsCode;
  2665. switch (Language)
  2666. {
  2667. case alCSharp:
  2668. SettingsCode = L"sessionOptions.AddRawSettings(\"%s\", %s);\n";
  2669. break;
  2670. case alVBNET:
  2671. SettingsCode = L" .AddRawSettings(\"%s\", %s)\n";
  2672. break;
  2673. case alPowerShell:
  2674. SettingsCode = L"$sessionOptions.AddRawSettings(\"%s\", %s)\n";
  2675. break;
  2676. }
  2677. Result += FORMAT(SettingsCode, (Name, AssemblyString(Language, Value)));
  2678. }
  2679. }
  2680. UnicodeString SessionCode;
  2681. switch (Language)
  2682. {
  2683. case alCSharp:
  2684. SessionCode =
  2685. L"\n"
  2686. "using (Session session = new Session())\n"
  2687. "{\n"
  2688. " // %s\n"
  2689. " session.Open(sessionOptions);\n"
  2690. "\n"
  2691. " // %s\n"
  2692. "}\n";
  2693. break;
  2694. case alVBNET:
  2695. SessionCode =
  2696. L"End With\n"
  2697. "\n"
  2698. "Using mySession As Session = New Session\n"
  2699. " ' %s\n"
  2700. " mySession.Open(mySessionOptions)\n"
  2701. "\n"
  2702. " ' %s\n"
  2703. "End Using\n";
  2704. break;
  2705. case alPowerShell:
  2706. SessionCode =
  2707. L"\n"
  2708. "$session = New-Object WinSCP.Session\n"
  2709. "\n"
  2710. "try\n"
  2711. "{\n"
  2712. " # %s\n"
  2713. " $session.Open($sessionOptions)\n"
  2714. "\n"
  2715. " # %s\n"
  2716. "}\n"
  2717. "finally\n"
  2718. "{\n"
  2719. " $session.Dispose()\n"
  2720. "}\n";
  2721. break;
  2722. }
  2723. Result += FORMAT(SessionCode, (LoadStr(CODE_CONNECT), LoadStr(CODE_YOUR_CODE)));
  2724. return Result;
  2725. }
  2726. //---------------------------------------------------------------------
  2727. void __fastcall TSessionData::SetTimeDifference(TDateTime value)
  2728. {
  2729. SET_SESSION_PROPERTY(TimeDifference);
  2730. }
  2731. //---------------------------------------------------------------------
  2732. void __fastcall TSessionData::SetTimeDifferenceAuto(bool value)
  2733. {
  2734. SET_SESSION_PROPERTY(TimeDifferenceAuto);
  2735. }
  2736. //---------------------------------------------------------------------
  2737. void __fastcall TSessionData::SetLocalDirectory(UnicodeString value)
  2738. {
  2739. SET_SESSION_PROPERTY(LocalDirectory);
  2740. }
  2741. //---------------------------------------------------------------------
  2742. void __fastcall TSessionData::SetRemoteDirectory(UnicodeString value)
  2743. {
  2744. SET_SESSION_PROPERTY(RemoteDirectory);
  2745. }
  2746. //---------------------------------------------------------------------
  2747. void __fastcall TSessionData::SetSynchronizeBrowsing(bool value)
  2748. {
  2749. SET_SESSION_PROPERTY(SynchronizeBrowsing);
  2750. }
  2751. //---------------------------------------------------------------------
  2752. void __fastcall TSessionData::SetUpdateDirectories(bool value)
  2753. {
  2754. SET_SESSION_PROPERTY(UpdateDirectories);
  2755. }
  2756. //---------------------------------------------------------------------
  2757. void __fastcall TSessionData::SetCacheDirectories(bool value)
  2758. {
  2759. SET_SESSION_PROPERTY(CacheDirectories);
  2760. }
  2761. //---------------------------------------------------------------------
  2762. void __fastcall TSessionData::SetCacheDirectoryChanges(bool value)
  2763. {
  2764. SET_SESSION_PROPERTY(CacheDirectoryChanges);
  2765. }
  2766. //---------------------------------------------------------------------
  2767. void __fastcall TSessionData::SetPreserveDirectoryChanges(bool value)
  2768. {
  2769. SET_SESSION_PROPERTY(PreserveDirectoryChanges);
  2770. }
  2771. //---------------------------------------------------------------------
  2772. void __fastcall TSessionData::SetResolveSymlinks(bool value)
  2773. {
  2774. SET_SESSION_PROPERTY(ResolveSymlinks);
  2775. }
  2776. //---------------------------------------------------------------------------
  2777. void __fastcall TSessionData::SetDSTMode(TDSTMode value)
  2778. {
  2779. SET_SESSION_PROPERTY(DSTMode);
  2780. }
  2781. //---------------------------------------------------------------------------
  2782. void __fastcall TSessionData::SetDeleteToRecycleBin(bool value)
  2783. {
  2784. SET_SESSION_PROPERTY(DeleteToRecycleBin);
  2785. }
  2786. //---------------------------------------------------------------------------
  2787. void __fastcall TSessionData::SetOverwrittenToRecycleBin(bool value)
  2788. {
  2789. SET_SESSION_PROPERTY(OverwrittenToRecycleBin);
  2790. }
  2791. //---------------------------------------------------------------------------
  2792. void __fastcall TSessionData::SetRecycleBinPath(UnicodeString value)
  2793. {
  2794. SET_SESSION_PROPERTY(RecycleBinPath);
  2795. }
  2796. //---------------------------------------------------------------------------
  2797. void __fastcall TSessionData::SetPostLoginCommands(UnicodeString value)
  2798. {
  2799. SET_SESSION_PROPERTY(PostLoginCommands);
  2800. }
  2801. //---------------------------------------------------------------------
  2802. void __fastcall TSessionData::SetLockInHome(bool value)
  2803. {
  2804. SET_SESSION_PROPERTY(LockInHome);
  2805. }
  2806. //---------------------------------------------------------------------
  2807. void __fastcall TSessionData::SetSpecial(bool value)
  2808. {
  2809. SET_SESSION_PROPERTY(Special);
  2810. }
  2811. //---------------------------------------------------------------------------
  2812. void __fastcall TSessionData::SetScp1Compatibility(bool value)
  2813. {
  2814. SET_SESSION_PROPERTY(Scp1Compatibility);
  2815. }
  2816. //---------------------------------------------------------------------
  2817. void __fastcall TSessionData::SetTcpNoDelay(bool value)
  2818. {
  2819. SET_SESSION_PROPERTY(TcpNoDelay);
  2820. }
  2821. //---------------------------------------------------------------------
  2822. void __fastcall TSessionData::SetSendBuf(int value)
  2823. {
  2824. SET_SESSION_PROPERTY(SendBuf);
  2825. }
  2826. //---------------------------------------------------------------------
  2827. void __fastcall TSessionData::SetSshSimple(bool value)
  2828. {
  2829. SET_SESSION_PROPERTY(SshSimple);
  2830. }
  2831. //---------------------------------------------------------------------
  2832. void __fastcall TSessionData::SetProxyMethod(TProxyMethod value)
  2833. {
  2834. SET_SESSION_PROPERTY(ProxyMethod);
  2835. }
  2836. //---------------------------------------------------------------------
  2837. void __fastcall TSessionData::SetProxyHost(UnicodeString value)
  2838. {
  2839. SET_SESSION_PROPERTY(ProxyHost);
  2840. }
  2841. //---------------------------------------------------------------------
  2842. void __fastcall TSessionData::SetProxyPort(int value)
  2843. {
  2844. SET_SESSION_PROPERTY(ProxyPort);
  2845. }
  2846. //---------------------------------------------------------------------
  2847. void __fastcall TSessionData::SetProxyUsername(UnicodeString value)
  2848. {
  2849. SET_SESSION_PROPERTY(ProxyUsername);
  2850. }
  2851. //---------------------------------------------------------------------
  2852. void __fastcall TSessionData::SetProxyPassword(UnicodeString avalue)
  2853. {
  2854. RawByteString value = EncryptPassword(avalue, ProxyUsername+ProxyHost);
  2855. SET_SESSION_PROPERTY(ProxyPassword);
  2856. }
  2857. //---------------------------------------------------------------------
  2858. UnicodeString __fastcall TSessionData::GetProxyPassword() const
  2859. {
  2860. return DecryptPassword(FProxyPassword, ProxyUsername+ProxyHost);
  2861. }
  2862. //---------------------------------------------------------------------
  2863. void __fastcall TSessionData::SetProxyTelnetCommand(UnicodeString value)
  2864. {
  2865. SET_SESSION_PROPERTY(ProxyTelnetCommand);
  2866. }
  2867. //---------------------------------------------------------------------
  2868. void __fastcall TSessionData::SetProxyLocalCommand(UnicodeString value)
  2869. {
  2870. SET_SESSION_PROPERTY(ProxyLocalCommand);
  2871. }
  2872. //---------------------------------------------------------------------
  2873. void __fastcall TSessionData::SetProxyDNS(TAutoSwitch value)
  2874. {
  2875. SET_SESSION_PROPERTY(ProxyDNS);
  2876. }
  2877. //---------------------------------------------------------------------
  2878. void __fastcall TSessionData::SetProxyLocalhost(bool value)
  2879. {
  2880. SET_SESSION_PROPERTY(ProxyLocalhost);
  2881. }
  2882. //---------------------------------------------------------------------
  2883. void __fastcall TSessionData::SetFtpProxyLogonType(int value)
  2884. {
  2885. SET_SESSION_PROPERTY(FtpProxyLogonType);
  2886. }
  2887. //---------------------------------------------------------------------
  2888. void __fastcall TSessionData::SetBug(TSshBug Bug, TAutoSwitch value)
  2889. {
  2890. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));
  2891. SET_SESSION_PROPERTY(Bugs[Bug]);
  2892. }
  2893. //---------------------------------------------------------------------
  2894. TAutoSwitch __fastcall TSessionData::GetBug(TSshBug Bug) const
  2895. {
  2896. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));
  2897. return FBugs[Bug];
  2898. }
  2899. //---------------------------------------------------------------------
  2900. void __fastcall TSessionData::SetCustomParam1(UnicodeString value)
  2901. {
  2902. SET_SESSION_PROPERTY(CustomParam1);
  2903. }
  2904. //---------------------------------------------------------------------
  2905. void __fastcall TSessionData::SetCustomParam2(UnicodeString value)
  2906. {
  2907. SET_SESSION_PROPERTY(CustomParam2);
  2908. }
  2909. //---------------------------------------------------------------------
  2910. void __fastcall TSessionData::SetSFTPDownloadQueue(int value)
  2911. {
  2912. SET_SESSION_PROPERTY(SFTPDownloadQueue);
  2913. }
  2914. //---------------------------------------------------------------------
  2915. void __fastcall TSessionData::SetSFTPUploadQueue(int value)
  2916. {
  2917. SET_SESSION_PROPERTY(SFTPUploadQueue);
  2918. }
  2919. //---------------------------------------------------------------------
  2920. void __fastcall TSessionData::SetSFTPListingQueue(int value)
  2921. {
  2922. SET_SESSION_PROPERTY(SFTPListingQueue);
  2923. }
  2924. //---------------------------------------------------------------------
  2925. void __fastcall TSessionData::SetSFTPMaxVersion(int value)
  2926. {
  2927. SET_SESSION_PROPERTY(SFTPMaxVersion);
  2928. }
  2929. //---------------------------------------------------------------------
  2930. void __fastcall TSessionData::SetSFTPMaxPacketSize(unsigned long value)
  2931. {
  2932. SET_SESSION_PROPERTY(SFTPMaxPacketSize);
  2933. }
  2934. //---------------------------------------------------------------------
  2935. void __fastcall TSessionData::SetSFTPBug(TSftpBug Bug, TAutoSwitch value)
  2936. {
  2937. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));
  2938. SET_SESSION_PROPERTY(SFTPBugs[Bug]);
  2939. }
  2940. //---------------------------------------------------------------------
  2941. TAutoSwitch __fastcall TSessionData::GetSFTPBug(TSftpBug Bug) const
  2942. {
  2943. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));
  2944. return FSFTPBugs[Bug];
  2945. }
  2946. //---------------------------------------------------------------------
  2947. void __fastcall TSessionData::SetSCPLsFullTime(TAutoSwitch value)
  2948. {
  2949. SET_SESSION_PROPERTY(SCPLsFullTime);
  2950. }
  2951. //---------------------------------------------------------------------------
  2952. void __fastcall TSessionData::SetColor(int value)
  2953. {
  2954. SET_SESSION_PROPERTY(Color);
  2955. }
  2956. //---------------------------------------------------------------------------
  2957. void __fastcall TSessionData::SetTunnel(bool value)
  2958. {
  2959. SET_SESSION_PROPERTY(Tunnel);
  2960. }
  2961. //---------------------------------------------------------------------
  2962. void __fastcall TSessionData::SetTunnelHostName(UnicodeString value)
  2963. {
  2964. if (FTunnelHostName != value)
  2965. {
  2966. // HostName is key for password encryption
  2967. UnicodeString XTunnelPassword = TunnelPassword;
  2968. int P = value.LastDelimiter(L"@");
  2969. if (P > 0)
  2970. {
  2971. TunnelUserName = value.SubString(1, P - 1);
  2972. value = value.SubString(P + 1, value.Length() - P);
  2973. }
  2974. FTunnelHostName = value;
  2975. Modify();
  2976. TunnelPassword = XTunnelPassword;
  2977. Shred(XTunnelPassword);
  2978. }
  2979. }
  2980. //---------------------------------------------------------------------
  2981. void __fastcall TSessionData::SetTunnelPortNumber(int value)
  2982. {
  2983. SET_SESSION_PROPERTY(TunnelPortNumber);
  2984. }
  2985. //---------------------------------------------------------------------
  2986. void __fastcall TSessionData::SetTunnelUserName(UnicodeString value)
  2987. {
  2988. // Avoid password recryption (what may popup master password prompt)
  2989. if (FTunnelUserName != value)
  2990. {
  2991. // TunnelUserName is key for password encryption
  2992. UnicodeString XTunnelPassword = TunnelPassword;
  2993. SET_SESSION_PROPERTY(TunnelUserName);
  2994. TunnelPassword = XTunnelPassword;
  2995. Shred(XTunnelPassword);
  2996. }
  2997. }
  2998. //---------------------------------------------------------------------
  2999. void __fastcall TSessionData::SetTunnelPassword(UnicodeString avalue)
  3000. {
  3001. RawByteString value = EncryptPassword(avalue, TunnelUserName+TunnelHostName);
  3002. SET_SESSION_PROPERTY(TunnelPassword);
  3003. }
  3004. //---------------------------------------------------------------------
  3005. UnicodeString __fastcall TSessionData::GetTunnelPassword() const
  3006. {
  3007. return DecryptPassword(FTunnelPassword, TunnelUserName+TunnelHostName);
  3008. }
  3009. //---------------------------------------------------------------------
  3010. void __fastcall TSessionData::SetTunnelPublicKeyFile(UnicodeString value)
  3011. {
  3012. if (FTunnelPublicKeyFile != value)
  3013. {
  3014. // StripPathQuotes should not be needed as we do not feed quotes anymore
  3015. FTunnelPublicKeyFile = StripPathQuotes(value);
  3016. Modify();
  3017. }
  3018. }
  3019. //---------------------------------------------------------------------
  3020. void __fastcall TSessionData::SetTunnelLocalPortNumber(int value)
  3021. {
  3022. SET_SESSION_PROPERTY(TunnelLocalPortNumber);
  3023. }
  3024. //---------------------------------------------------------------------
  3025. bool __fastcall TSessionData::GetTunnelAutoassignLocalPortNumber()
  3026. {
  3027. return (FTunnelLocalPortNumber <= 0);
  3028. }
  3029. //---------------------------------------------------------------------
  3030. void __fastcall TSessionData::SetTunnelPortFwd(UnicodeString value)
  3031. {
  3032. SET_SESSION_PROPERTY(TunnelPortFwd);
  3033. }
  3034. //---------------------------------------------------------------------
  3035. void __fastcall TSessionData::SetTunnelHostKey(UnicodeString value)
  3036. {
  3037. SET_SESSION_PROPERTY(TunnelHostKey);
  3038. }
  3039. //---------------------------------------------------------------------
  3040. void __fastcall TSessionData::SetFtpPasvMode(bool value)
  3041. {
  3042. SET_SESSION_PROPERTY(FtpPasvMode);
  3043. }
  3044. //---------------------------------------------------------------------
  3045. void __fastcall TSessionData::SetFtpForcePasvIp(TAutoSwitch value)
  3046. {
  3047. SET_SESSION_PROPERTY(FtpForcePasvIp);
  3048. }
  3049. //---------------------------------------------------------------------
  3050. void __fastcall TSessionData::SetFtpUseMlsd(TAutoSwitch value)
  3051. {
  3052. SET_SESSION_PROPERTY(FtpUseMlsd);
  3053. }
  3054. //---------------------------------------------------------------------
  3055. void __fastcall TSessionData::SetFtpAccount(UnicodeString value)
  3056. {
  3057. SET_SESSION_PROPERTY(FtpAccount);
  3058. }
  3059. //---------------------------------------------------------------------
  3060. void __fastcall TSessionData::SetFtpPingInterval(int value)
  3061. {
  3062. SET_SESSION_PROPERTY(FtpPingInterval);
  3063. }
  3064. //---------------------------------------------------------------------------
  3065. TDateTime __fastcall TSessionData::GetFtpPingIntervalDT()
  3066. {
  3067. return SecToDateTime(FtpPingInterval);
  3068. }
  3069. //---------------------------------------------------------------------------
  3070. void __fastcall TSessionData::SetFtpPingType(TPingType value)
  3071. {
  3072. SET_SESSION_PROPERTY(FtpPingType);
  3073. }
  3074. //---------------------------------------------------------------------------
  3075. void __fastcall TSessionData::SetFtpTransferActiveImmediately(TAutoSwitch value)
  3076. {
  3077. SET_SESSION_PROPERTY(FtpTransferActiveImmediately);
  3078. }
  3079. //---------------------------------------------------------------------------
  3080. void __fastcall TSessionData::SetFtps(TFtps value)
  3081. {
  3082. SET_SESSION_PROPERTY(Ftps);
  3083. }
  3084. //---------------------------------------------------------------------------
  3085. void __fastcall TSessionData::SetMinTlsVersion(TTlsVersion value)
  3086. {
  3087. SET_SESSION_PROPERTY(MinTlsVersion);
  3088. }
  3089. //---------------------------------------------------------------------------
  3090. void __fastcall TSessionData::SetMaxTlsVersion(TTlsVersion value)
  3091. {
  3092. SET_SESSION_PROPERTY(MaxTlsVersion);
  3093. }
  3094. //---------------------------------------------------------------------
  3095. void __fastcall TSessionData::SetFtpListAll(TAutoSwitch value)
  3096. {
  3097. SET_SESSION_PROPERTY(FtpListAll);
  3098. }
  3099. //---------------------------------------------------------------------
  3100. void __fastcall TSessionData::SetFtpHost(TAutoSwitch value)
  3101. {
  3102. SET_SESSION_PROPERTY(FtpHost);
  3103. }
  3104. //---------------------------------------------------------------------
  3105. void __fastcall TSessionData::SetSslSessionReuse(bool value)
  3106. {
  3107. SET_SESSION_PROPERTY(SslSessionReuse);
  3108. }
  3109. //---------------------------------------------------------------------
  3110. void __fastcall TSessionData::SetTlsCertificateFile(UnicodeString value)
  3111. {
  3112. SET_SESSION_PROPERTY(TlsCertificateFile);
  3113. }
  3114. //---------------------------------------------------------------------
  3115. void __fastcall TSessionData::SetNotUtf(TAutoSwitch value)
  3116. {
  3117. SET_SESSION_PROPERTY(NotUtf);
  3118. }
  3119. //---------------------------------------------------------------------
  3120. void __fastcall TSessionData::SetIsWorkspace(bool value)
  3121. {
  3122. SET_SESSION_PROPERTY(IsWorkspace);
  3123. }
  3124. //---------------------------------------------------------------------
  3125. void __fastcall TSessionData::SetLink(UnicodeString value)
  3126. {
  3127. SET_SESSION_PROPERTY(Link);
  3128. }
  3129. //---------------------------------------------------------------------
  3130. void __fastcall TSessionData::SetHostKey(UnicodeString value)
  3131. {
  3132. SET_SESSION_PROPERTY(HostKey);
  3133. }
  3134. //---------------------------------------------------------------------
  3135. void __fastcall TSessionData::SetNote(UnicodeString value)
  3136. {
  3137. SET_SESSION_PROPERTY(Note);
  3138. }
  3139. //---------------------------------------------------------------------
  3140. UnicodeString __fastcall TSessionData::GetInfoTip()
  3141. {
  3142. if (UsesSsh)
  3143. {
  3144. return FMTLOAD(SESSION_INFO_TIP2,
  3145. (HostName, UserName,
  3146. (PublicKeyFile.IsEmpty() ? LoadStr(NO_STR) : LoadStr(YES_STR)),
  3147. FSProtocolStr));
  3148. }
  3149. else
  3150. {
  3151. return FMTLOAD(SESSION_INFO_TIP_NO_SSH,
  3152. (HostName, UserName, FSProtocolStr));
  3153. }
  3154. }
  3155. //---------------------------------------------------------------------
  3156. UnicodeString __fastcall TSessionData::ExtractLocalName(const UnicodeString & Name)
  3157. {
  3158. UnicodeString Result = Name;
  3159. int P = Result.LastDelimiter(L"/");
  3160. if (P > 0)
  3161. {
  3162. Result.Delete(1, P);
  3163. }
  3164. return Result;
  3165. }
  3166. //---------------------------------------------------------------------
  3167. UnicodeString __fastcall TSessionData::GetLocalName()
  3168. {
  3169. UnicodeString Result;
  3170. if (HasSessionName())
  3171. {
  3172. Result = ExtractLocalName(Name);
  3173. }
  3174. else
  3175. {
  3176. Result = DefaultSessionName;
  3177. }
  3178. return Result;
  3179. }
  3180. //---------------------------------------------------------------------
  3181. UnicodeString __fastcall TSessionData::ExtractFolderName(const UnicodeString & Name)
  3182. {
  3183. UnicodeString Result;
  3184. int P = Name.LastDelimiter(L"/");
  3185. if (P > 0)
  3186. {
  3187. Result = Name.SubString(1, P - 1);
  3188. }
  3189. return Result;
  3190. }
  3191. //---------------------------------------------------------------------
  3192. UnicodeString __fastcall TSessionData::GetFolderName()
  3193. {
  3194. UnicodeString Result;
  3195. if (HasSessionName() || IsWorkspace)
  3196. {
  3197. Result = ExtractFolderName(Name);
  3198. }
  3199. return Result;
  3200. }
  3201. //---------------------------------------------------------------------
  3202. UnicodeString __fastcall TSessionData::ComposePath(
  3203. const UnicodeString & Path, const UnicodeString & Name)
  3204. {
  3205. return UnixIncludeTrailingBackslash(Path) + Name;
  3206. }
  3207. //=== TStoredSessionList ----------------------------------------------
  3208. __fastcall TStoredSessionList::TStoredSessionList(bool aReadOnly):
  3209. TNamedObjectList(), FReadOnly(aReadOnly)
  3210. {
  3211. DebugAssert(Configuration);
  3212. FDefaultSettings = new TSessionData(DefaultName);
  3213. }
  3214. //---------------------------------------------------------------------
  3215. __fastcall TStoredSessionList::~TStoredSessionList()
  3216. {
  3217. DebugAssert(Configuration);
  3218. delete FDefaultSettings;
  3219. }
  3220. //---------------------------------------------------------------------
  3221. void __fastcall TStoredSessionList::Load(THierarchicalStorage * Storage,
  3222. bool AsModified, bool UseDefaults)
  3223. {
  3224. TStringList *SubKeys = new TStringList();
  3225. TList * Loaded = new TList;
  3226. try
  3227. {
  3228. DebugAssert(AutoSort);
  3229. AutoSort = false;
  3230. bool WasEmpty = (Count == 0);
  3231. Storage->GetSubKeyNames(SubKeys);
  3232. for (int Index = 0; Index < SubKeys->Count; Index++)
  3233. {
  3234. UnicodeString SessionName = SubKeys->Strings[Index];
  3235. bool ValidName = true;
  3236. try
  3237. {
  3238. TSessionData::ValidatePath(SessionName);
  3239. }
  3240. catch(...)
  3241. {
  3242. ValidName = false;
  3243. }
  3244. if (ValidName)
  3245. {
  3246. TSessionData * SessionData;
  3247. if (SessionName == FDefaultSettings->Name)
  3248. {
  3249. SessionData = FDefaultSettings;
  3250. }
  3251. else
  3252. {
  3253. // if the list was empty before loading, do not waste time trying to
  3254. // find existing sites to overwrite (we rely on underlying storage
  3255. // to secure uniqueness of the key names)
  3256. if (WasEmpty)
  3257. {
  3258. SessionData = NULL;
  3259. }
  3260. else
  3261. {
  3262. SessionData = (TSessionData*)FindByName(SessionName);
  3263. }
  3264. }
  3265. if ((SessionData != FDefaultSettings) || !UseDefaults)
  3266. {
  3267. if (SessionData == NULL)
  3268. {
  3269. SessionData = new TSessionData(L"");
  3270. if (UseDefaults)
  3271. {
  3272. SessionData->CopyData(DefaultSettings);
  3273. }
  3274. SessionData->Name = SessionName;
  3275. Add(SessionData);
  3276. }
  3277. Loaded->Add(SessionData);
  3278. SessionData->Load(Storage);
  3279. if (AsModified)
  3280. {
  3281. SessionData->Modified = true;
  3282. }
  3283. }
  3284. }
  3285. }
  3286. if (!AsModified)
  3287. {
  3288. for (int Index = 0; Index < TObjectList::Count; Index++)
  3289. {
  3290. if (Loaded->IndexOf(Items[Index]) < 0)
  3291. {
  3292. Delete(Index);
  3293. Index--;
  3294. }
  3295. }
  3296. }
  3297. }
  3298. __finally
  3299. {
  3300. AutoSort = true;
  3301. AlphaSort();
  3302. delete SubKeys;
  3303. delete Loaded;
  3304. }
  3305. }
  3306. //---------------------------------------------------------------------
  3307. void __fastcall TStoredSessionList::Load()
  3308. {
  3309. bool SessionList = true;
  3310. THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);
  3311. try
  3312. {
  3313. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, False))
  3314. Load(Storage);
  3315. }
  3316. __finally
  3317. {
  3318. delete Storage;
  3319. }
  3320. }
  3321. //---------------------------------------------------------------------
  3322. void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,
  3323. TSessionData * Data, bool All, bool RecryptPasswordOnly,
  3324. TSessionData * FactoryDefaults)
  3325. {
  3326. if (All || Data->Modified)
  3327. {
  3328. if (RecryptPasswordOnly)
  3329. {
  3330. Data->SaveRecryptedPasswords(Storage);
  3331. }
  3332. else
  3333. {
  3334. Data->Save(Storage, false, FactoryDefaults);
  3335. }
  3336. }
  3337. }
  3338. //---------------------------------------------------------------------
  3339. void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,
  3340. bool All, bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)
  3341. {
  3342. TSessionData * FactoryDefaults = new TSessionData(L"");
  3343. try
  3344. {
  3345. DoSave(Storage, FDefaultSettings, All, RecryptPasswordOnly, FactoryDefaults);
  3346. for (int Index = 0; Index < CountIncludingHidden; Index++)
  3347. {
  3348. TSessionData * SessionData = (TSessionData *)Items[Index];
  3349. try
  3350. {
  3351. DoSave(Storage, SessionData, All, RecryptPasswordOnly, FactoryDefaults);
  3352. }
  3353. catch (Exception & E)
  3354. {
  3355. UnicodeString Message;
  3356. if (RecryptPasswordOnly && DebugAlwaysTrue(RecryptPasswordErrors != NULL) &&
  3357. ExceptionMessage(&E, Message))
  3358. {
  3359. RecryptPasswordErrors->Add(FORMAT("%s: %s", (SessionData->SessionName, Message)));
  3360. }
  3361. else
  3362. {
  3363. throw;
  3364. }
  3365. }
  3366. }
  3367. }
  3368. __finally
  3369. {
  3370. delete FactoryDefaults;
  3371. }
  3372. }
  3373. //---------------------------------------------------------------------
  3374. void __fastcall TStoredSessionList::Save(THierarchicalStorage * Storage, bool All)
  3375. {
  3376. DoSave(Storage, All, false, NULL);
  3377. }
  3378. //---------------------------------------------------------------------
  3379. void __fastcall TStoredSessionList::DoSave(bool All, bool Explicit,
  3380. bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)
  3381. {
  3382. bool SessionList = true;
  3383. THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);
  3384. try
  3385. {
  3386. Storage->AccessMode = smReadWrite;
  3387. Storage->Explicit = Explicit;
  3388. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))
  3389. {
  3390. DoSave(Storage, All, RecryptPasswordOnly, RecryptPasswordErrors);
  3391. }
  3392. }
  3393. __finally
  3394. {
  3395. delete Storage;
  3396. }
  3397. Saved();
  3398. }
  3399. //---------------------------------------------------------------------
  3400. void __fastcall TStoredSessionList::Save(bool All, bool Explicit)
  3401. {
  3402. DoSave(All, Explicit, false, NULL);
  3403. }
  3404. //---------------------------------------------------------------------
  3405. void __fastcall TStoredSessionList::RecryptPasswords(TStrings * RecryptPasswordErrors)
  3406. {
  3407. DoSave(true, true, true, RecryptPasswordErrors);
  3408. }
  3409. //---------------------------------------------------------------------
  3410. void __fastcall TStoredSessionList::Saved()
  3411. {
  3412. FDefaultSettings->Modified = false;
  3413. for (int Index = 0; Index < CountIncludingHidden; Index++)
  3414. {
  3415. ((TSessionData *)Items[Index])->Modified = false;
  3416. }
  3417. }
  3418. //---------------------------------------------------------------------
  3419. void __fastcall TStoredSessionList::ImportLevelFromFilezilla(_di_IXMLNode Node, const UnicodeString & Path)
  3420. {
  3421. for (int Index = 0; Index < Node->ChildNodes->Count; Index++)
  3422. {
  3423. _di_IXMLNode ChildNode = Node->ChildNodes->Get(Index);
  3424. if (ChildNode->NodeName == L"Server")
  3425. {
  3426. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  3427. SessionData->CopyData(DefaultSettings);
  3428. SessionData->ImportFromFilezilla(ChildNode, Path);
  3429. Add(SessionData.release());
  3430. }
  3431. else if (ChildNode->NodeName == L"Folder")
  3432. {
  3433. UnicodeString Name;
  3434. for (int Index = 0; Index < ChildNode->ChildNodes->Count; Index++)
  3435. {
  3436. _di_IXMLNode PossibleTextMode = ChildNode->ChildNodes->Get(Index);
  3437. if (PossibleTextMode->NodeType == ntText)
  3438. {
  3439. UnicodeString NodeValue = PossibleTextMode->NodeValue;
  3440. AddToList(Name, NodeValue.Trim(), L" ");
  3441. }
  3442. }
  3443. Name = TSessionData::MakeValidName(Name).Trim();
  3444. ImportLevelFromFilezilla(ChildNode, TSessionData::ComposePath(Path, Name));
  3445. }
  3446. }
  3447. }
  3448. //---------------------------------------------------------------------
  3449. void __fastcall TStoredSessionList::ImportFromFilezilla(const UnicodeString FileName)
  3450. {
  3451. const _di_IXMLDocument Document = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));
  3452. Document->LoadFromFile(FileName);
  3453. _di_IXMLNode FileZilla3Node = Document->ChildNodes->FindNode(L"FileZilla3");
  3454. if (FileZilla3Node != NULL)
  3455. {
  3456. _di_IXMLNode ServersNode = FileZilla3Node->ChildNodes->FindNode(L"Servers");
  3457. if (ServersNode != NULL)
  3458. {
  3459. ImportLevelFromFilezilla(ServersNode, L"");
  3460. }
  3461. }
  3462. }
  3463. //---------------------------------------------------------------------
  3464. void __fastcall TStoredSessionList::Export(const UnicodeString FileName)
  3465. {
  3466. THierarchicalStorage * Storage = new TIniFileStorage(FileName);
  3467. try
  3468. {
  3469. Storage->AccessMode = smReadWrite;
  3470. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))
  3471. {
  3472. Save(Storage, true);
  3473. }
  3474. }
  3475. __finally
  3476. {
  3477. delete Storage;
  3478. }
  3479. }
  3480. //---------------------------------------------------------------------
  3481. void __fastcall TStoredSessionList::SelectAll(bool Select)
  3482. {
  3483. for (int Index = 0; Index < Count; Index++)
  3484. Sessions[Index]->Selected = Select;
  3485. }
  3486. //---------------------------------------------------------------------
  3487. void __fastcall TStoredSessionList::Import(TStoredSessionList * From,
  3488. bool OnlySelected, TList * Imported)
  3489. {
  3490. for (int Index = 0; Index < From->Count; Index++)
  3491. {
  3492. if (!OnlySelected || From->Sessions[Index]->Selected)
  3493. {
  3494. TSessionData *Session = new TSessionData(L"");
  3495. Session->Assign(From->Sessions[Index]);
  3496. Session->Modified = true;
  3497. Session->MakeUniqueIn(this);
  3498. Add(Session);
  3499. if (Imported != NULL)
  3500. {
  3501. Imported->Add(Session);
  3502. }
  3503. }
  3504. }
  3505. // only modified, explicit
  3506. Save(false, true);
  3507. }
  3508. //---------------------------------------------------------------------
  3509. void __fastcall TStoredSessionList::SelectSessionsToImport
  3510. (TStoredSessionList * Dest, bool SSHOnly)
  3511. {
  3512. for (int Index = 0; Index < Count; Index++)
  3513. {
  3514. Sessions[Index]->Selected =
  3515. (!SSHOnly || (Sessions[Index]->GetNormalizedPuttyProtocol() == PuttySshProtocol)) &&
  3516. !Dest->FindByName(Sessions[Index]->Name);
  3517. }
  3518. }
  3519. //---------------------------------------------------------------------
  3520. void __fastcall TStoredSessionList::Cleanup()
  3521. {
  3522. try
  3523. {
  3524. if (Configuration->Storage == stRegistry) Clear();
  3525. TRegistryStorage * Storage = new TRegistryStorage(Configuration->RegistryStorageKey);
  3526. try
  3527. {
  3528. Storage->AccessMode = smReadWrite;
  3529. if (Storage->OpenRootKey(False))
  3530. Storage->RecursiveDeleteSubKey(Configuration->StoredSessionsSubKey);
  3531. }
  3532. __finally
  3533. {
  3534. delete Storage;
  3535. }
  3536. }
  3537. catch (Exception &E)
  3538. {
  3539. throw ExtException(&E, LoadStr(CLEANUP_SESSIONS_ERROR));
  3540. }
  3541. }
  3542. //---------------------------------------------------------------------------
  3543. void __fastcall TStoredSessionList::UpdateStaticUsage()
  3544. {
  3545. int SCP = 0;
  3546. int SFTP = 0;
  3547. int FTP = 0;
  3548. int FTPS = 0;
  3549. int WebDAV = 0;
  3550. int WebDAVS = 0;
  3551. int Password = 0;
  3552. int Advanced = 0;
  3553. int Color = 0;
  3554. int Note = 0;
  3555. int Tunnel = 0;
  3556. bool Folders = false;
  3557. bool Workspaces = false;
  3558. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3559. std::unique_ptr<TStringList> DifferentAdvancedProperties(CreateSortedStringList());
  3560. for (int Index = 0; Index < Count; Index++)
  3561. {
  3562. TSessionData * Data = Sessions[Index];
  3563. if (Data->IsWorkspace)
  3564. {
  3565. Workspaces = true;
  3566. }
  3567. else
  3568. {
  3569. switch (Data->FSProtocol)
  3570. {
  3571. case fsSCPonly:
  3572. SCP++;
  3573. break;
  3574. case fsSFTP:
  3575. case fsSFTPonly:
  3576. SFTP++;
  3577. break;
  3578. case fsFTP:
  3579. if (Data->Ftps == ftpsNone)
  3580. {
  3581. FTP++;
  3582. }
  3583. else
  3584. {
  3585. FTPS++;
  3586. }
  3587. break;
  3588. case fsWebDAV:
  3589. if (Data->Ftps == ftpsNone)
  3590. {
  3591. WebDAV++;
  3592. }
  3593. else
  3594. {
  3595. WebDAVS++;
  3596. }
  3597. break;
  3598. }
  3599. if (Data->HasAnySessionPassword())
  3600. {
  3601. Password++;
  3602. }
  3603. if (Data->Color != 0)
  3604. {
  3605. Color++;
  3606. }
  3607. if (!Data->Note.IsEmpty())
  3608. {
  3609. Note++;
  3610. }
  3611. // this effectively does not take passwords (proxy + tunnel) into account,
  3612. // when master password is set, as master password handler in not set up yet
  3613. if (!Data->IsSame(FactoryDefaults.get(), true, DifferentAdvancedProperties.get()))
  3614. {
  3615. Advanced++;
  3616. }
  3617. if (Data->Tunnel)
  3618. {
  3619. Tunnel++;
  3620. }
  3621. if (!Data->FolderName.IsEmpty())
  3622. {
  3623. Folders = true;
  3624. }
  3625. }
  3626. }
  3627. Configuration->Usage->Set(L"StoredSessionsCountSCP", SCP);
  3628. Configuration->Usage->Set(L"StoredSessionsCountSFTP", SFTP);
  3629. Configuration->Usage->Set(L"StoredSessionsCountFTP", FTP);
  3630. Configuration->Usage->Set(L"StoredSessionsCountFTPS", FTPS);
  3631. Configuration->Usage->Set(L"StoredSessionsCountWebDAV", WebDAV);
  3632. Configuration->Usage->Set(L"StoredSessionsCountWebDAVS", WebDAVS);
  3633. Configuration->Usage->Set(L"StoredSessionsCountPassword", Password);
  3634. Configuration->Usage->Set(L"StoredSessionsCountColor", Color);
  3635. Configuration->Usage->Set(L"StoredSessionsCountNote", Note);
  3636. Configuration->Usage->Set(L"StoredSessionsCountAdvanced", Advanced);
  3637. DifferentAdvancedProperties->Delimiter = L',';
  3638. Configuration->Usage->Set(L"StoredSessionsAdvancedSettings", DifferentAdvancedProperties->DelimitedText);
  3639. Configuration->Usage->Set(L"StoredSessionsCountTunnel", Tunnel);
  3640. // actually default might be true, see below for when the default is actually used
  3641. bool CustomDefaultStoredSession = false;
  3642. try
  3643. {
  3644. // this can throw, when the default session settings have password set
  3645. // (and no other basic property, like hostname/username),
  3646. // and master password is enabled as we are called before master password
  3647. // handler is set
  3648. CustomDefaultStoredSession = !FDefaultSettings->IsSame(FactoryDefaults.get(), false);
  3649. }
  3650. catch (...)
  3651. {
  3652. }
  3653. Configuration->Usage->Set(L"UsingDefaultStoredSession", CustomDefaultStoredSession);
  3654. Configuration->Usage->Set(L"UsingStoredSessionsFolders", Folders);
  3655. Configuration->Usage->Set(L"UsingWorkspaces", Workspaces);
  3656. }
  3657. //---------------------------------------------------------------------------
  3658. TSessionData * __fastcall TStoredSessionList::FindSame(TSessionData * Data)
  3659. {
  3660. TSessionData * Result;
  3661. if (Data->Hidden || Data->Name.IsEmpty() || Data->IsWorkspace)
  3662. {
  3663. Result = NULL;
  3664. }
  3665. else
  3666. {
  3667. Result = dynamic_cast<TSessionData *>(FindByName(Data->Name));
  3668. }
  3669. return Result;
  3670. }
  3671. //---------------------------------------------------------------------------
  3672. int __fastcall TStoredSessionList::IndexOf(TSessionData * Data)
  3673. {
  3674. for (int Index = 0; Index < Count; Index++)
  3675. if (Data == Sessions[Index]) return Index;
  3676. return -1;
  3677. }
  3678. //---------------------------------------------------------------------------
  3679. TSessionData * __fastcall TStoredSessionList::NewSession(
  3680. UnicodeString SessionName, TSessionData * Session)
  3681. {
  3682. TSessionData * DuplicateSession = (TSessionData*)FindByName(SessionName);
  3683. if (!DuplicateSession)
  3684. {
  3685. DuplicateSession = new TSessionData(L"");
  3686. DuplicateSession->Assign(Session);
  3687. DuplicateSession->Name = SessionName;
  3688. // make sure, that new stored session is saved to registry
  3689. DuplicateSession->Modified = true;
  3690. Add(DuplicateSession);
  3691. }
  3692. else
  3693. {
  3694. DuplicateSession->Assign(Session);
  3695. DuplicateSession->Name = SessionName;
  3696. DuplicateSession->Modified = true;
  3697. }
  3698. // list was saved here before to default storage, but it would not allow
  3699. // to work with special lists (export/import) not using default storage
  3700. return DuplicateSession;
  3701. }
  3702. //---------------------------------------------------------------------------
  3703. void __fastcall TStoredSessionList::SetDefaultSettings(TSessionData * value)
  3704. {
  3705. DebugAssert(FDefaultSettings);
  3706. if (FDefaultSettings != value)
  3707. {
  3708. FDefaultSettings->Assign(value);
  3709. // make sure default settings are saved
  3710. FDefaultSettings->Modified = true;
  3711. FDefaultSettings->Name = DefaultName;
  3712. if (!FReadOnly)
  3713. {
  3714. // only modified, explicit
  3715. Save(false, true);
  3716. }
  3717. }
  3718. }
  3719. //---------------------------------------------------------------------------
  3720. void __fastcall TStoredSessionList::ImportHostKeys(const UnicodeString TargetKey,
  3721. const UnicodeString SourceKey, TStoredSessionList * Sessions,
  3722. bool OnlySelected)
  3723. {
  3724. TRegistryStorage * SourceStorage = NULL;
  3725. TRegistryStorage * TargetStorage = NULL;
  3726. TStringList * KeyList = NULL;
  3727. try
  3728. {
  3729. SourceStorage = new TRegistryStorage(SourceKey);
  3730. TargetStorage = new TRegistryStorage(TargetKey);
  3731. TargetStorage->AccessMode = smReadWrite;
  3732. KeyList = new TStringList();
  3733. if (SourceStorage->OpenRootKey(false) &&
  3734. TargetStorage->OpenRootKey(true))
  3735. {
  3736. SourceStorage->GetValueNames(KeyList);
  3737. TSessionData * Session;
  3738. UnicodeString HostKeyName;
  3739. DebugAssert(Sessions != NULL);
  3740. for (int Index = 0; Index < Sessions->Count; Index++)
  3741. {
  3742. Session = Sessions->Sessions[Index];
  3743. if (!OnlySelected || Session->Selected)
  3744. {
  3745. HostKeyName = PuttyMungeStr(FORMAT(L"@%d:%s", (Session->PortNumber, Session->HostNameExpanded)));
  3746. UnicodeString KeyName;
  3747. for (int KeyIndex = 0; KeyIndex < KeyList->Count; KeyIndex++)
  3748. {
  3749. KeyName = KeyList->Strings[KeyIndex];
  3750. int P = KeyName.Pos(HostKeyName);
  3751. if ((P > 0) && (P == KeyName.Length() - HostKeyName.Length() + 1))
  3752. {
  3753. TargetStorage->WriteStringRaw(KeyName,
  3754. SourceStorage->ReadStringRaw(KeyName, L""));
  3755. }
  3756. }
  3757. }
  3758. }
  3759. }
  3760. }
  3761. __finally
  3762. {
  3763. delete SourceStorage;
  3764. delete TargetStorage;
  3765. delete KeyList;
  3766. }
  3767. }
  3768. //---------------------------------------------------------------------------
  3769. bool __fastcall TStoredSessionList::IsFolderOrWorkspace(
  3770. const UnicodeString & Name, bool Workspace)
  3771. {
  3772. bool Result = false;
  3773. TSessionData * FirstData = NULL;
  3774. if (!Name.IsEmpty())
  3775. {
  3776. for (int Index = 0; !Result && (Index < Count); Index++)
  3777. {
  3778. Result = Sessions[Index]->IsInFolderOrWorkspace(Name);
  3779. if (Result)
  3780. {
  3781. FirstData = Sessions[Index];
  3782. }
  3783. }
  3784. }
  3785. return
  3786. Result &&
  3787. DebugAlwaysTrue(FirstData != NULL) &&
  3788. (FirstData->IsWorkspace == Workspace);
  3789. }
  3790. //---------------------------------------------------------------------------
  3791. bool __fastcall TStoredSessionList::IsFolder(const UnicodeString & Name)
  3792. {
  3793. return IsFolderOrWorkspace(Name, false);
  3794. }
  3795. //---------------------------------------------------------------------------
  3796. bool __fastcall TStoredSessionList::IsWorkspace(const UnicodeString & Name)
  3797. {
  3798. return IsFolderOrWorkspace(Name, true);
  3799. }
  3800. //---------------------------------------------------------------------------
  3801. TSessionData * __fastcall TStoredSessionList::CheckIsInFolderOrWorkspaceAndResolve(
  3802. TSessionData * Data, const UnicodeString & Name)
  3803. {
  3804. if (Data->IsInFolderOrWorkspace(Name))
  3805. {
  3806. Data = ResolveWorkspaceData(Data);
  3807. if ((Data != NULL) && Data->CanLogin &&
  3808. DebugAlwaysTrue(Data->Link.IsEmpty()))
  3809. {
  3810. return Data;
  3811. }
  3812. }
  3813. return NULL;
  3814. }
  3815. //---------------------------------------------------------------------------
  3816. void __fastcall TStoredSessionList::GetFolderOrWorkspace(const UnicodeString & Name, TList * List)
  3817. {
  3818. for (int Index = 0; (Index < Count); Index++)
  3819. {
  3820. TSessionData * RawData = Sessions[Index];
  3821. TSessionData * Data =
  3822. CheckIsInFolderOrWorkspaceAndResolve(RawData, Name);
  3823. if (Data != NULL)
  3824. {
  3825. TSessionData * Data2 = new TSessionData(L"");
  3826. Data2->Assign(Data);
  3827. if (!RawData->Link.IsEmpty() && (DebugAlwaysTrue(Data != RawData)) &&
  3828. // BACKWARD COMPATIBILITY
  3829. // When loading pre-5.6.4 workspace, that does not have state saved,
  3830. // do not overwrite the site "state" defaults
  3831. // with (empty) workspace state
  3832. RawData->HasStateData())
  3833. {
  3834. Data2->CopyStateData(RawData);
  3835. }
  3836. List->Add(Data2);
  3837. }
  3838. }
  3839. }
  3840. //---------------------------------------------------------------------------
  3841. TStrings * __fastcall TStoredSessionList::GetFolderOrWorkspaceList(
  3842. const UnicodeString & Name)
  3843. {
  3844. std::unique_ptr<TStringList> Result(new TStringList());
  3845. for (int Index = 0; (Index < Count); Index++)
  3846. {
  3847. TSessionData * Data =
  3848. CheckIsInFolderOrWorkspaceAndResolve(Sessions[Index], Name);
  3849. if (Data != NULL)
  3850. {
  3851. Result->Add(Data->SessionName);
  3852. }
  3853. }
  3854. return Result.release();
  3855. }
  3856. //---------------------------------------------------------------------------
  3857. TStrings * __fastcall TStoredSessionList::GetWorkspaces()
  3858. {
  3859. std::unique_ptr<TStringList> Result(CreateSortedStringList());
  3860. for (int Index = 0; (Index < Count); Index++)
  3861. {
  3862. TSessionData * Data = Sessions[Index];
  3863. if (Data->IsWorkspace)
  3864. {
  3865. Result->Add(Data->FolderName);
  3866. }
  3867. }
  3868. return Result.release();
  3869. }
  3870. //---------------------------------------------------------------------------
  3871. void __fastcall TStoredSessionList::NewWorkspace(
  3872. UnicodeString Name, TList * DataList)
  3873. {
  3874. for (int Index = 0; (Index < Count); Index++)
  3875. {
  3876. TSessionData * Data = Sessions[Index];
  3877. if (Data->IsInFolderOrWorkspace(Name))
  3878. {
  3879. Data->Remove();
  3880. Remove(Data);
  3881. Index--;
  3882. }
  3883. }
  3884. for (int Index = 0; (Index < DataList->Count); Index++)
  3885. {
  3886. TSessionData * Data = static_cast<TSessionData *>(DataList->Items[Index]);
  3887. TSessionData * Data2 = new TSessionData(L"");
  3888. Data2->Assign(Data);
  3889. Data2->Name = TSessionData::ComposePath(Name, Data->Name);
  3890. // make sure, that new stored session is saved to registry
  3891. Data2->Modified = true;
  3892. Add(Data2);
  3893. }
  3894. }
  3895. //---------------------------------------------------------------------------
  3896. bool __fastcall TStoredSessionList::HasAnyWorkspace()
  3897. {
  3898. bool Result = false;
  3899. for (int Index = 0; !Result && (Index < Count); Index++)
  3900. {
  3901. TSessionData * Data = Sessions[Index];
  3902. Result = Data->IsWorkspace;
  3903. }
  3904. return Result;
  3905. }
  3906. //---------------------------------------------------------------------------
  3907. TSessionData * __fastcall TStoredSessionList::ParseUrl(UnicodeString Url,
  3908. TOptions * Options, bool & DefaultsOnly, UnicodeString * FileName,
  3909. bool * AProtocolDefined, UnicodeString * MaskedUrl)
  3910. {
  3911. TSessionData * Data = new TSessionData(L"");
  3912. try
  3913. {
  3914. Data->ParseUrl(Url, Options, this, DefaultsOnly, FileName, AProtocolDefined, MaskedUrl);
  3915. }
  3916. catch(...)
  3917. {
  3918. delete Data;
  3919. throw;
  3920. }
  3921. return Data;
  3922. }
  3923. //---------------------------------------------------------------------
  3924. bool __fastcall TStoredSessionList::IsUrl(UnicodeString Url)
  3925. {
  3926. bool DefaultsOnly;
  3927. bool ProtocolDefined = false;
  3928. std::unique_ptr<TSessionData> ParsedData(ParseUrl(Url, NULL, DefaultsOnly, NULL, &ProtocolDefined));
  3929. bool Result = ProtocolDefined;
  3930. return Result;
  3931. }
  3932. //---------------------------------------------------------------------
  3933. TSessionData * __fastcall TStoredSessionList::ResolveWorkspaceData(TSessionData * Data)
  3934. {
  3935. if (!Data->Link.IsEmpty())
  3936. {
  3937. Data = dynamic_cast<TSessionData *>(FindByName(Data->Link));
  3938. if (Data != NULL)
  3939. {
  3940. Data = ResolveWorkspaceData(Data);
  3941. }
  3942. }
  3943. return Data;
  3944. }
  3945. //---------------------------------------------------------------------
  3946. TSessionData * __fastcall TStoredSessionList::SaveWorkspaceData(TSessionData * Data)
  3947. {
  3948. std::unique_ptr<TSessionData> Result(new TSessionData(L""));
  3949. TSessionData * SameData = StoredSessions->FindSame(Data);
  3950. if (SameData != NULL)
  3951. {
  3952. Result->CopyStateData(Data);
  3953. Result->Link = Data->Name;
  3954. }
  3955. else
  3956. {
  3957. Result->Assign(Data);
  3958. }
  3959. Result->IsWorkspace = true;
  3960. return Result.release();
  3961. }
  3962. //---------------------------------------------------------------------
  3963. bool __fastcall TStoredSessionList::CanLogin(TSessionData * Data)
  3964. {
  3965. Data = ResolveWorkspaceData(Data);
  3966. return (Data != NULL) && Data->CanLogin;
  3967. }
  3968. //---------------------------------------------------------------------
  3969. UnicodeString GetExpandedLogFileName(UnicodeString LogFileName, TSessionData * SessionData)
  3970. {
  3971. // StripPathQuotes should not be needed as we do not feed quotes anymore
  3972. UnicodeString ANewFileName = StripPathQuotes(ExpandEnvironmentVariables(LogFileName));
  3973. TDateTime N = Now();
  3974. for (int Index = 1; Index < ANewFileName.Length(); Index++)
  3975. {
  3976. if (ANewFileName[Index] == L'!')
  3977. {
  3978. UnicodeString Replacement;
  3979. // keep consistent with TFileCustomCommand::PatternReplacement
  3980. switch (tolower(ANewFileName[Index + 1]))
  3981. {
  3982. case L'y':
  3983. Replacement = FormatDateTime(L"yyyy", N);
  3984. break;
  3985. case L'm':
  3986. Replacement = FormatDateTime(L"mm", N);
  3987. break;
  3988. case L'd':
  3989. Replacement = FormatDateTime(L"dd", N);
  3990. break;
  3991. case L't':
  3992. Replacement = FormatDateTime(L"hhnnss", N);
  3993. break;
  3994. case 'p':
  3995. Replacement = IntToStr(static_cast<int>(GetCurrentProcessId()));
  3996. break;
  3997. case L'@':
  3998. if (SessionData != NULL)
  3999. {
  4000. Replacement = MakeValidFileName(SessionData->HostNameExpanded);
  4001. }
  4002. else
  4003. {
  4004. Replacement = L"nohost";
  4005. }
  4006. break;
  4007. case L's':
  4008. if (SessionData != NULL)
  4009. {
  4010. Replacement = MakeValidFileName(SessionData->SessionName);
  4011. }
  4012. else
  4013. {
  4014. Replacement = L"nosession";
  4015. }
  4016. break;
  4017. case L'!':
  4018. Replacement = L"!";
  4019. break;
  4020. default:
  4021. Replacement = UnicodeString(L"!") + ANewFileName[Index + 1];
  4022. break;
  4023. }
  4024. ANewFileName.Delete(Index, 2);
  4025. ANewFileName.Insert(Replacement, Index);
  4026. Index += Replacement.Length() - 1;
  4027. }
  4028. }
  4029. return ANewFileName;
  4030. }
  4031. //---------------------------------------------------------------------
  4032. bool __fastcall IsSshProtocol(TFSProtocol FSProtocol)
  4033. {
  4034. return
  4035. (FSProtocol == fsSFTPonly) || (FSProtocol == fsSFTP) ||
  4036. (FSProtocol == fsSCPonly);
  4037. }
  4038. //---------------------------------------------------------------------------
  4039. int __fastcall DefaultPort(TFSProtocol FSProtocol, TFtps Ftps)
  4040. {
  4041. int Result;
  4042. switch (FSProtocol)
  4043. {
  4044. case fsFTP:
  4045. if (Ftps == ftpsImplicit)
  4046. {
  4047. Result = FtpsImplicitPortNumber;
  4048. }
  4049. else
  4050. {
  4051. Result = FtpPortNumber;
  4052. }
  4053. break;
  4054. case fsWebDAV:
  4055. if (Ftps == ftpsNone)
  4056. {
  4057. Result = HTTPPortNumber;
  4058. }
  4059. else
  4060. {
  4061. Result = HTTPSPortNumber;
  4062. }
  4063. break;
  4064. default:
  4065. if (IsSshProtocol(FSProtocol))
  4066. {
  4067. Result = SshPortNumber;
  4068. }
  4069. else
  4070. {
  4071. DebugFail();
  4072. Result = -1;
  4073. }
  4074. break;
  4075. }
  4076. return Result;
  4077. }
  4078. //---------------------------------------------------------------------