1
0

Common.cpp 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include "Common.h"
  6. #include "Exceptions.h"
  7. #include "TextsCore.h"
  8. #include "Interface.h"
  9. #include <StrUtils.hpp>
  10. #include <DateUtils.hpp>
  11. #include <System.IOUtils.hpp>
  12. #include <math.h>
  13. #include <shlobj.h>
  14. #include <limits>
  15. #include <algorithm>
  16. #include <shlwapi.h>
  17. #include <tlhelp32.h>
  18. #include <psapi.h>
  19. #include <CoreMain.h>
  20. #include <SessionInfo.h>
  21. #include <Soap.EncdDecd.hpp>
  22. #include <openssl/pkcs12.h>
  23. #include <openssl/pem.h>
  24. #include <openssl/err.h>
  25. #include <openssl/ssl.h>
  26. //---------------------------------------------------------------------------
  27. #pragma package(smart_init)
  28. //---------------------------------------------------------------------------
  29. const wchar_t * DSTModeNames = L"Win;Unix;Keep";
  30. //---------------------------------------------------------------------------
  31. //---------------------------------------------------------------------------
  32. const UnicodeString AnyMask = L"*.*";
  33. const wchar_t EngShortMonthNames[12][4] =
  34. {L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun",
  35. L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec"};
  36. const char Bom[4] = "\xEF\xBB\xBF";
  37. const UnicodeString XmlDeclaration(TraceInitStr(L"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
  38. const wchar_t TokenPrefix = L'%';
  39. const wchar_t NoReplacement = wchar_t(false);
  40. const wchar_t TokenReplacement = wchar_t(true);
  41. // Note similar list in MakeValidFileName
  42. const UnicodeString LocalInvalidChars(TraceInitStr(L"/\\:*?\"<>|"));
  43. const UnicodeString PasswordMask(TraceInitStr(L"***"));
  44. const UnicodeString Ellipsis(TraceInitStr(L"..."));
  45. const UnicodeString TitleSeparator(TraceInitStr(L" \u2013 ")); // En-Dash
  46. const UnicodeString OfficialPackage(TraceInitStr(L"MartinPikryl.WinSCP_tvv458r3h9r5m"));
  47. //---------------------------------------------------------------------------
  48. UnicodeString ReplaceChar(UnicodeString Str, wchar_t A, wchar_t B)
  49. {
  50. for (Integer Index = 0; Index < Str.Length(); Index++)
  51. if (Str[Index+1] == A) Str[Index+1] = B;
  52. return Str;
  53. }
  54. //---------------------------------------------------------------------------
  55. UnicodeString DeleteChar(UnicodeString Str, wchar_t C)
  56. {
  57. int P;
  58. while ((P = Str.Pos(C)) > 0)
  59. {
  60. Str.Delete(P, 1);
  61. }
  62. return Str;
  63. }
  64. //---------------------------------------------------------------------------
  65. template<typename T>
  66. void DoPackStr(T & Str)
  67. {
  68. // Following will free unnecessary bytes
  69. Str = Str.c_str();
  70. }
  71. //---------------------------------------------------------------------------
  72. void PackStr(UnicodeString & Str)
  73. {
  74. DoPackStr(Str);
  75. }
  76. //---------------------------------------------------------------------------
  77. void PackStr(RawByteString & Str)
  78. {
  79. DoPackStr(Str);
  80. }
  81. //---------------------------------------------------------------------------
  82. void PackStr(AnsiString & Str)
  83. {
  84. DoPackStr(Str);
  85. }
  86. //---------------------------------------------------------------------------
  87. template<typename T>
  88. void __fastcall DoShred(T & Str)
  89. {
  90. if (!Str.IsEmpty())
  91. {
  92. // Should instead test for (StringRefCount(Str) == 1) to prevent Unique making yet another copy
  93. Str.Unique();
  94. memset(Str.c_str(), 0, Str.Length() * sizeof(*Str.c_str()));
  95. Str = L"";
  96. }
  97. }
  98. //---------------------------------------------------------------------------
  99. void __fastcall Shred(UnicodeString & Str)
  100. {
  101. DoShred(Str);
  102. }
  103. //---------------------------------------------------------------------------
  104. void __fastcall Shred(UTF8String & Str)
  105. {
  106. DoShred(Str);
  107. }
  108. //---------------------------------------------------------------------------
  109. void __fastcall Shred(AnsiString & Str)
  110. {
  111. DoShred(Str);
  112. }
  113. //---------------------------------------------------------------------------
  114. void __fastcall Shred(RawByteString & Str)
  115. {
  116. DoShred(Str);
  117. }
  118. //---------------------------------------------------------------------------
  119. UnicodeString AnsiToString(const RawByteString & S)
  120. {
  121. return UnicodeString(AnsiString(S));
  122. }
  123. //---------------------------------------------------------------------------
  124. UnicodeString AnsiToString(const char * S, size_t Len)
  125. {
  126. return UnicodeString(AnsiString(S, Len));
  127. }
  128. //---------------------------------------------------------------------------
  129. UnicodeString UTFToString(const RawByteString & S)
  130. {
  131. // Simply casting RawByteString to UTF8String does not work
  132. return UnicodeString(UTF8String(S.c_str(), S.Length()));
  133. }
  134. //---------------------------------------------------------------------------
  135. // Note similar function ValidLocalFileName
  136. UnicodeString MakeValidFileName(UnicodeString FileName)
  137. {
  138. // Note similar list in LocalInvalidChars
  139. UnicodeString IllegalChars = L":;,=+<>|\"[] \\/?*";
  140. for (int Index = 0; Index < IllegalChars.Length(); Index++)
  141. {
  142. FileName = ReplaceChar(FileName, IllegalChars[Index+1], L'-');
  143. }
  144. return FileName;
  145. }
  146. //---------------------------------------------------------------------------
  147. UnicodeString RootKeyToStr(HKEY RootKey, const UnicodeString & Default)
  148. {
  149. if (RootKey == HKEY_USERS) return L"HKU";
  150. else
  151. if (RootKey == HKEY_LOCAL_MACHINE) return L"HKLM";
  152. else
  153. if (RootKey == HKEY_CURRENT_USER) return L"HKCU";
  154. else
  155. if (RootKey == HKEY_CLASSES_ROOT) return L"HKCR";
  156. else
  157. if (RootKey == HKEY_CURRENT_CONFIG) return L"HKCC";
  158. else
  159. if (RootKey == HKEY_DYN_DATA) return L"HKDD";
  160. else
  161. {
  162. if (Default.IsEmpty())
  163. {
  164. Abort();
  165. }
  166. return Default;
  167. };
  168. }
  169. //---------------------------------------------------------------------------
  170. UnicodeString BooleanToEngStr(bool B)
  171. {
  172. if (B)
  173. {
  174. return L"Yes";
  175. }
  176. else
  177. {
  178. return L"No";
  179. }
  180. }
  181. //---------------------------------------------------------------------------
  182. UnicodeString BooleanToStr(bool B)
  183. {
  184. if (B)
  185. {
  186. return LoadStr(YES_STR);
  187. }
  188. else
  189. {
  190. return LoadStr(NO_STR);
  191. }
  192. }
  193. //---------------------------------------------------------------------------
  194. UnicodeString DefaultStr(const UnicodeString & Str, const UnicodeString & Default)
  195. {
  196. if (!Str.IsEmpty())
  197. {
  198. return Str;
  199. }
  200. else
  201. {
  202. return Default;
  203. }
  204. }
  205. //---------------------------------------------------------------------------
  206. // For alternative with quoting support, see TFTPFileSystem::CutFeature
  207. UnicodeString CutToChar(UnicodeString &Str, wchar_t Ch, bool Trim)
  208. {
  209. Integer P = Str.Pos(Ch);
  210. UnicodeString Result;
  211. if (P)
  212. {
  213. Result = Str.SubString(1, P-1);
  214. Str.Delete(1, P);
  215. }
  216. else
  217. {
  218. Result = Str;
  219. Str = L"";
  220. }
  221. if (Trim)
  222. {
  223. Result = Result.TrimRight();
  224. Str = Str.TrimLeft();
  225. }
  226. return Result;
  227. }
  228. //---------------------------------------------------------------------------
  229. UnicodeString CopyToChars(const UnicodeString & Str, int & From, UnicodeString Chs, bool Trim,
  230. wchar_t * Delimiter, bool DoubleDelimiterEscapes)
  231. {
  232. UnicodeString Result;
  233. int P;
  234. for (P = From; P <= Str.Length(); P++)
  235. {
  236. if (IsDelimiter(Chs, Str, P))
  237. {
  238. if (DoubleDelimiterEscapes &&
  239. (P < Str.Length()) &&
  240. IsDelimiter(Chs, Str, P + 1) &&
  241. (Str[P + 1] == Str[P]))
  242. {
  243. Result += Str[P];
  244. P++;
  245. }
  246. else
  247. {
  248. break;
  249. }
  250. }
  251. else
  252. {
  253. Result += Str[P];
  254. }
  255. }
  256. if (P <= Str.Length())
  257. {
  258. if (Delimiter != NULL)
  259. {
  260. *Delimiter = Str[P];
  261. }
  262. }
  263. else
  264. {
  265. if (Delimiter != NULL)
  266. {
  267. *Delimiter = L'\0';
  268. }
  269. }
  270. // even if we reached the end, return index, as if there were the delimiter,
  271. // so caller can easily find index of the end of the piece by subtracting
  272. // 2 from From (as long as he did not asked for trimming)
  273. From = P+1;
  274. if (Trim)
  275. {
  276. Result = Result.TrimRight();
  277. while ((From <= Str.Length()) && (Str[From] == L' '))
  278. {
  279. From++;
  280. }
  281. }
  282. return Result;
  283. }
  284. //---------------------------------------------------------------------------
  285. UnicodeString CopyToChar(const UnicodeString & Str, wchar_t Ch, bool Trim)
  286. {
  287. int From = 1;
  288. return CopyToChars(Str, From, UnicodeString(Ch), Trim);
  289. }
  290. //---------------------------------------------------------------------------
  291. UnicodeString RemoveSuffix(const UnicodeString & Str, const UnicodeString & Suffix, bool RemoveNumbersAfterSuffix)
  292. {
  293. UnicodeString Result = Str;
  294. UnicodeString Buf = Str;
  295. if (RemoveNumbersAfterSuffix)
  296. {
  297. while (!Buf.IsEmpty() && IsDigit(Buf[Buf.Length()]))
  298. {
  299. Buf.SetLength(Buf.Length() - 1);
  300. }
  301. }
  302. if (EndsStr(Suffix, Buf))
  303. {
  304. Result.SetLength(Buf.Length() - Suffix.Length());
  305. }
  306. return Result;
  307. }
  308. //---------------------------------------------------------------------------
  309. UnicodeString DelimitStr(const UnicodeString & Str, wchar_t Quote)
  310. {
  311. UnicodeString SpecialChars;
  312. if (Quote != L'\'')
  313. {
  314. SpecialChars = L"$\\";
  315. if (Quote == L'"')
  316. {
  317. SpecialChars += L"`\"";
  318. }
  319. }
  320. UnicodeString Result(Str);
  321. for (int i = 1; i <= Result.Length(); i++)
  322. {
  323. if (Result.IsDelimiter(SpecialChars, i))
  324. {
  325. Result.Insert(L"\\", i);
  326. i++;
  327. }
  328. }
  329. if (Result.IsDelimiter(L"-", 1))
  330. {
  331. Result.Insert(L"./", 1);
  332. }
  333. return Result;
  334. }
  335. //---------------------------------------------------------------------------
  336. UnicodeString MidStr(const UnicodeString & Text, int Start)
  337. {
  338. return Text.SubString(Start, Text.Length() - Start + 1);
  339. }
  340. //---------------------------------------------------------------------------
  341. UnicodeString ShellQuoteStr(const UnicodeString & Str)
  342. {
  343. wchar_t Quote = L'"';
  344. UnicodeString QuoteStr(Quote);
  345. return QuoteStr + DelimitStr(Str, Quote) + QuoteStr;
  346. }
  347. //---------------------------------------------------------------------------
  348. UnicodeString ExceptionLogString(Exception *E)
  349. {
  350. DebugAssert(E);
  351. if (E->InheritsFrom(__classid(Exception)))
  352. {
  353. UnicodeString Msg;
  354. Msg = FORMAT(L"(%s) %s", (E->ClassName(), E->Message));
  355. if (E->InheritsFrom(__classid(ExtException)))
  356. {
  357. TStrings * MoreMessages = ((ExtException*)E)->MoreMessages;
  358. if (MoreMessages)
  359. {
  360. Msg += L"\n" +
  361. ReplaceStr(MoreMessages->Text, L"\r", L"");
  362. }
  363. }
  364. return Msg;
  365. }
  366. else
  367. {
  368. wchar_t Buffer[1024];
  369. ExceptionErrorMessage(ExceptObject(), ExceptAddr(), Buffer, LENOF(Buffer));
  370. return UnicodeString(Buffer);
  371. }
  372. }
  373. //---------------------------------------------------------------------------
  374. UnicodeString __fastcall MainInstructions(const UnicodeString & S)
  375. {
  376. UnicodeString MainMsgTag = LoadStr(MAIN_MSG_TAG);
  377. return MainMsgTag + S + MainMsgTag;
  378. }
  379. //---------------------------------------------------------------------------
  380. bool __fastcall HasParagraphs(const UnicodeString & S)
  381. {
  382. return (S.Pos(L"\n\n") > 0);
  383. }
  384. //---------------------------------------------------------------------------
  385. UnicodeString __fastcall MainInstructionsFirstParagraph(const UnicodeString & S)
  386. {
  387. // WORKAROUND, we consider it bad practice, the highlighting should better
  388. // be localized (but maybe we change our mind later)
  389. UnicodeString Result;
  390. int Pos = S.Pos(L"\n\n");
  391. // we would not be calling this on single paragraph message
  392. if (DebugAlwaysTrue(Pos > 0))
  393. {
  394. Result =
  395. MainInstructions(S.SubString(1, Pos - 1)) +
  396. S.SubString(Pos, S.Length() - Pos + 1);
  397. }
  398. else
  399. {
  400. Result = MainInstructions(S);
  401. }
  402. return Result;
  403. }
  404. //---------------------------------------------------------------------------
  405. bool ExtractMainInstructions(UnicodeString & S, UnicodeString & MainInstructions)
  406. {
  407. bool Result = false;
  408. UnicodeString MainMsgTag = LoadStr(MAIN_MSG_TAG);
  409. if (StartsStr(MainMsgTag, S))
  410. {
  411. int EndTagPos =
  412. S.SubString(MainMsgTag.Length() + 1, S.Length() - MainMsgTag.Length()).Pos(MainMsgTag);
  413. if (EndTagPos > 0)
  414. {
  415. MainInstructions = S.SubString(MainMsgTag.Length() + 1, EndTagPos - 1);
  416. S.Delete(1, EndTagPos + (2 * MainMsgTag.Length()) - 1);
  417. Result = true;
  418. }
  419. }
  420. DebugAssert(MainInstructions.Pos(MainMsgTag) == 0);
  421. DebugAssert(S.Pos(MainMsgTag) == 0);
  422. return Result;
  423. }
  424. //---------------------------------------------------------------------------
  425. static int FindInteractiveMsgStart(const UnicodeString & S)
  426. {
  427. int Result = 0;
  428. UnicodeString InteractiveMsgTag = LoadStr(INTERACTIVE_MSG_TAG);
  429. if (EndsStr(InteractiveMsgTag, S) &&
  430. (S.Length() >= 2 * InteractiveMsgTag.Length()))
  431. {
  432. Result = S.Length() - 2 * InteractiveMsgTag.Length() + 1;
  433. while ((Result > 0) && (S.SubString(Result, InteractiveMsgTag.Length()) != InteractiveMsgTag))
  434. {
  435. Result--;
  436. }
  437. }
  438. return Result;
  439. }
  440. //---------------------------------------------------------------------------
  441. UnicodeString RemoveMainInstructionsTag(UnicodeString S)
  442. {
  443. UnicodeString MainInstruction;
  444. if (ExtractMainInstructions(S, MainInstruction))
  445. {
  446. S = MainInstruction + S;
  447. }
  448. return S;
  449. }
  450. //---------------------------------------------------------------------------
  451. UnicodeString UnformatMessage(UnicodeString S)
  452. {
  453. S = RemoveMainInstructionsTag(S);
  454. int InteractiveMsgStart = FindInteractiveMsgStart(S);
  455. if (InteractiveMsgStart > 0)
  456. {
  457. S = S.SubString(1, InteractiveMsgStart - 1);
  458. }
  459. return S;
  460. }
  461. //---------------------------------------------------------------------------
  462. UnicodeString RemoveInteractiveMsgTag(UnicodeString S)
  463. {
  464. int InteractiveMsgStart = FindInteractiveMsgStart(S);
  465. if (InteractiveMsgStart > 0)
  466. {
  467. UnicodeString InteractiveMsgTag = LoadStr(INTERACTIVE_MSG_TAG);
  468. S.Delete(InteractiveMsgStart, InteractiveMsgTag.Length());
  469. S.Delete(S.Length() - InteractiveMsgTag.Length() + 1, InteractiveMsgTag.Length());
  470. }
  471. return S;
  472. }
  473. //---------------------------------------------------------------------------
  474. UnicodeString RemoveEmptyLines(const UnicodeString & S)
  475. {
  476. return
  477. ReplaceStr(
  478. ReplaceStr(S.TrimRight(), L"\n\n", L"\n"),
  479. L"\n \n", L"\n");
  480. }
  481. //---------------------------------------------------------------------------
  482. bool IsNumber(const UnicodeString Str)
  483. {
  484. bool Result = (Str.Length() > 0);
  485. for (int Index = 1; (Index < Str.Length()) && Result; Index++)
  486. {
  487. wchar_t C = Str[Index];
  488. if ((C < L'0') || (C > L'9'))
  489. {
  490. Result = false;
  491. }
  492. }
  493. return Result;
  494. }
  495. //---------------------------------------------------------------------------
  496. UnicodeString EncodeStrToBase64(const RawByteString & Str)
  497. {
  498. UnicodeString Result = EncodeBase64(Str.c_str(), Str.Length());
  499. Result = ReplaceStr(Result, sLineBreak, EmptyStr);
  500. return Result;
  501. }
  502. //---------------------------------------------------------------------------
  503. RawByteString DecodeBase64ToStr(const UnicodeString & Str)
  504. {
  505. TBytes Bytes = DecodeBase64(Str);
  506. // This might be the same as TEncoding::ASCII->GetString.
  507. // const_cast: The operator[] const is (badly?) implemented to return by value
  508. return RawByteString(reinterpret_cast<const char *>(&const_cast<TBytes &>(Bytes)[0]), Bytes.Length);
  509. }
  510. //---------------------------------------------------------------------------
  511. UnicodeString Base64ToUrlSafe(const UnicodeString & S)
  512. {
  513. UnicodeString Result = S;
  514. while (EndsStr(L"=", Result))
  515. {
  516. Result.SetLength(Result.Length() - 1);
  517. }
  518. // See https://en.wikipedia.org/wiki/Base64#Implementations_and_history
  519. Result = ReplaceChar(Result, L'+', L'-');
  520. Result = ReplaceChar(Result, L'/', L'_');
  521. return Result;
  522. }
  523. //---------------------------------------------------------------------------
  524. const wchar_t NormalizedFingerprintSeparator = L'-';
  525. //---------------------------------------------------------------------------
  526. UnicodeString MD5ToUrlSafe(const UnicodeString & S)
  527. {
  528. return ReplaceChar(S, L':', NormalizedFingerprintSeparator);
  529. }
  530. //---------------------------------------------------------------------------
  531. bool SameChecksum(const UnicodeString & AChecksum1, const UnicodeString & AChecksum2, bool Base64)
  532. {
  533. UnicodeString Checksum1(AChecksum1);
  534. UnicodeString Checksum2(AChecksum2);
  535. bool Result;
  536. if (Base64)
  537. {
  538. Checksum1 = Base64ToUrlSafe(Checksum1);
  539. Checksum2 = Base64ToUrlSafe(Checksum2);
  540. Result = SameStr(Checksum1, Checksum2);
  541. }
  542. else
  543. {
  544. Checksum1 = MD5ToUrlSafe(Checksum1);
  545. Checksum2 = MD5ToUrlSafe(Checksum2);
  546. Result = SameText(Checksum1, Checksum2);
  547. }
  548. return Result;
  549. }
  550. //---------------------------------------------------------------------------
  551. UnicodeString __fastcall SystemTemporaryDirectory()
  552. {
  553. UnicodeString TempDir;
  554. TempDir.SetLength(MAX_PATH);
  555. TempDir.SetLength(GetTempPath(MAX_PATH, TempDir.c_str()));
  556. return TempDir;
  557. }
  558. //---------------------------------------------------------------------------
  559. UnicodeString __fastcall GetShellFolderPath(int CSIdl)
  560. {
  561. UnicodeString Result;
  562. wchar_t Path[2 * MAX_PATH + 10] = L"\0";
  563. if (SUCCEEDED(SHGetFolderPath(NULL, CSIdl, NULL, SHGFP_TYPE_CURRENT, Path)))
  564. {
  565. Result = Path;
  566. }
  567. return Result;
  568. }
  569. //---------------------------------------------------------------------------
  570. static UnicodeString __fastcall GetWineHomeFolder()
  571. {
  572. UnicodeString Result;
  573. UnicodeString WineHostHome = GetEnvironmentVariable(L"WINE_HOST_HOME");
  574. if (!WineHostHome.IsEmpty())
  575. {
  576. Result = L"Z:" + FromUnixPath(WineHostHome);
  577. }
  578. else
  579. {
  580. // Should we use WinAPI GetUserName() instead?
  581. UnicodeString UserName = GetEnvironmentVariable(L"USERNAME");
  582. if (!UserName.IsEmpty())
  583. {
  584. Result = L"Z:\\home\\" + UserName;
  585. }
  586. }
  587. if (!DirectoryExists(Result))
  588. {
  589. Result = L"";
  590. }
  591. return Result;
  592. }
  593. //---------------------------------------------------------------------------
  594. UnicodeString __fastcall GetPersonalFolder()
  595. {
  596. UnicodeString Result = GetShellFolderPath(CSIDL_PERSONAL);
  597. if (IsWine())
  598. {
  599. UnicodeString WineHome = GetWineHomeFolder();
  600. if (!WineHome.IsEmpty())
  601. {
  602. // if at least home exists, use it
  603. Result = WineHome;
  604. // but try to go deeper to "Documents"
  605. UnicodeString WineDocuments =
  606. IncludeTrailingBackslash(WineHome) + L"Documents";
  607. if (DirectoryExists(WineDocuments))
  608. {
  609. Result = WineDocuments;
  610. }
  611. }
  612. }
  613. return Result;
  614. }
  615. //---------------------------------------------------------------------------
  616. UnicodeString __fastcall GetDesktopFolder()
  617. {
  618. UnicodeString Result = GetShellFolderPath(CSIDL_DESKTOPDIRECTORY);
  619. if (IsWine())
  620. {
  621. UnicodeString WineHome = GetWineHomeFolder();
  622. if (!WineHome.IsEmpty())
  623. {
  624. UnicodeString WineDesktop =
  625. IncludeTrailingBackslash(WineHome) + L"Desktop";
  626. if (DirectoryExists(WineHome))
  627. {
  628. Result = WineDesktop;
  629. }
  630. }
  631. }
  632. return Result;
  633. }
  634. //---------------------------------------------------------------------------
  635. // Particularly needed when using file name selected by TFilenameEdit,
  636. // as it wraps a path to double-quotes, when there is a space in the path.
  637. UnicodeString __fastcall StripPathQuotes(const UnicodeString Path)
  638. {
  639. if ((Path.Length() >= 2) &&
  640. (Path[1] == L'\"') && (Path[Path.Length()] == L'\"'))
  641. {
  642. return Path.SubString(2, Path.Length() - 2);
  643. }
  644. else
  645. {
  646. return Path;
  647. }
  648. }
  649. //---------------------------------------------------------------------------
  650. UnicodeString __fastcall AddQuotes(UnicodeString Str)
  651. {
  652. if (Str.Pos(L" ") > 0)
  653. {
  654. Str = L"\"" + Str + L"\"";
  655. }
  656. return Str;
  657. }
  658. //---------------------------------------------------------------------------
  659. UnicodeString __fastcall AddPathQuotes(UnicodeString Path)
  660. {
  661. Path = StripPathQuotes(Path);
  662. return AddQuotes(Path);
  663. }
  664. //---------------------------------------------------------------------------
  665. static wchar_t * __fastcall ReplaceChar(
  666. UnicodeString & FileName, wchar_t * InvalidChar, wchar_t InvalidCharsReplacement)
  667. {
  668. int Index = InvalidChar - FileName.c_str() + 1;
  669. if (InvalidCharsReplacement == TokenReplacement)
  670. {
  671. // currently we do not support unicode chars replacement
  672. if (FileName[Index] > 0xFF)
  673. {
  674. EXCEPTION;
  675. }
  676. FileName.Insert(ByteToHex(static_cast<unsigned char>(FileName[Index])), Index + 1);
  677. FileName[Index] = TokenPrefix;
  678. InvalidChar = FileName.c_str() + Index + 2;
  679. }
  680. else
  681. {
  682. FileName[Index] = InvalidCharsReplacement;
  683. InvalidChar = FileName.c_str() + Index;
  684. }
  685. return InvalidChar;
  686. }
  687. //---------------------------------------------------------------------------
  688. // Note similar function MakeValidFileName
  689. UnicodeString __fastcall ValidLocalFileName(UnicodeString FileName)
  690. {
  691. return ValidLocalFileName(FileName, L'_', L"", LocalInvalidChars);
  692. }
  693. //---------------------------------------------------------------------------
  694. UnicodeString __fastcall ValidLocalFileName(
  695. UnicodeString FileName, wchar_t InvalidCharsReplacement,
  696. const UnicodeString & TokenizibleChars, const UnicodeString & LocalInvalidChars)
  697. {
  698. if (InvalidCharsReplacement != NoReplacement)
  699. {
  700. bool ATokenReplacement = (InvalidCharsReplacement == TokenReplacement);
  701. const wchar_t * Chars =
  702. (ATokenReplacement ? TokenizibleChars : LocalInvalidChars).c_str();
  703. wchar_t * InvalidChar = FileName.c_str();
  704. while ((InvalidChar = wcspbrk(InvalidChar, Chars)) != NULL)
  705. {
  706. int Pos = (InvalidChar - FileName.c_str() + 1);
  707. wchar_t Char;
  708. if (ATokenReplacement &&
  709. (*InvalidChar == TokenPrefix) &&
  710. (((FileName.Length() - Pos) <= 1) ||
  711. (((Char = static_cast<wchar_t>(HexToByte(FileName.SubString(Pos + 1, 2)))) == L'\0') ||
  712. (TokenizibleChars.Pos(Char) == 0))))
  713. {
  714. InvalidChar++;
  715. }
  716. else
  717. {
  718. InvalidChar = ReplaceChar(FileName, InvalidChar, InvalidCharsReplacement);
  719. }
  720. }
  721. // Windows trim trailing space or dot, hence we must encode it to preserve it
  722. if (!FileName.IsEmpty() &&
  723. ((FileName[FileName.Length()] == L' ') ||
  724. (FileName[FileName.Length()] == L'.')))
  725. {
  726. ReplaceChar(FileName, FileName.c_str() + FileName.Length() - 1, InvalidCharsReplacement);
  727. }
  728. if (IsReservedName(FileName))
  729. {
  730. int P = FileName.Pos(".");
  731. if (P == 0)
  732. {
  733. P = FileName.Length() + 1;
  734. }
  735. FileName.Insert(L"%00", P);
  736. }
  737. }
  738. return FileName;
  739. }
  740. //---------------------------------------------------------------------------
  741. void __fastcall SplitCommand(UnicodeString Command, UnicodeString &Program,
  742. UnicodeString & Params, UnicodeString & Dir)
  743. {
  744. Command = Command.Trim();
  745. Params = L"";
  746. Dir = L"";
  747. if (!Command.IsEmpty() && (Command[1] == L'\"'))
  748. {
  749. Command.Delete(1, 1);
  750. int P = Command.Pos(L'"');
  751. if (P)
  752. {
  753. Program = Command.SubString(1, P-1).Trim();
  754. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  755. }
  756. else
  757. {
  758. throw Exception(FMTLOAD(INVALID_SHELL_COMMAND, (L"\"" + Command)));
  759. }
  760. }
  761. else
  762. {
  763. int P = Command.Pos(L" ");
  764. if (P)
  765. {
  766. Program = Command.SubString(1, P).Trim();
  767. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  768. }
  769. else
  770. {
  771. Program = Command;
  772. }
  773. }
  774. int B = Program.LastDelimiter(L"\\/");
  775. if (B)
  776. {
  777. Dir = Program.SubString(1, B).Trim();
  778. }
  779. }
  780. //---------------------------------------------------------------------------
  781. UnicodeString __fastcall ExtractProgram(UnicodeString Command)
  782. {
  783. UnicodeString Program;
  784. UnicodeString Params;
  785. UnicodeString Dir;
  786. SplitCommand(Command, Program, Params, Dir);
  787. return Program;
  788. }
  789. //---------------------------------------------------------------------------
  790. UnicodeString __fastcall ExtractProgramName(UnicodeString Command)
  791. {
  792. UnicodeString Name = ExtractFileName(ExtractProgram(Command));
  793. int Dot = Name.LastDelimiter(L".");
  794. if (Dot > 0)
  795. {
  796. Name = Name.SubString(1, Dot - 1);
  797. }
  798. return Name;
  799. }
  800. //---------------------------------------------------------------------------
  801. UnicodeString __fastcall FormatCommand(UnicodeString Program, UnicodeString Params)
  802. {
  803. Program = Program.Trim();
  804. Params = Params.Trim();
  805. if (!Params.IsEmpty()) Params = L" " + Params;
  806. Program = AddQuotes(Program);
  807. return Program + Params;
  808. }
  809. //---------------------------------------------------------------------------
  810. const wchar_t ShellCommandFileNamePattern[] = L"!.!";
  811. //---------------------------------------------------------------------------
  812. void __fastcall ReformatFileNameCommand(UnicodeString & Command)
  813. {
  814. if (!Command.IsEmpty())
  815. {
  816. UnicodeString Program, Params, Dir;
  817. SplitCommand(Command, Program, Params, Dir);
  818. if (Params.Pos(ShellCommandFileNamePattern) == 0)
  819. {
  820. Params = Params + (Params.IsEmpty() ? L"" : L" ") + ShellCommandFileNamePattern;
  821. }
  822. Command = FormatCommand(Program, Params);
  823. }
  824. }
  825. //---------------------------------------------------------------------------
  826. UnicodeString __fastcall ExpandFileNameCommand(const UnicodeString Command,
  827. const UnicodeString FileName)
  828. {
  829. return AnsiReplaceStr(Command, ShellCommandFileNamePattern,
  830. AddPathQuotes(FileName));
  831. }
  832. //---------------------------------------------------------------------------
  833. UnicodeString __fastcall EscapeParam(const UnicodeString & Param)
  834. {
  835. // Make sure this won't break RTF syntax
  836. return ReplaceStr(Param, L"\"", L"\"\"");
  837. }
  838. //---------------------------------------------------------------------------
  839. UnicodeString __fastcall EscapePuttyCommandParam(UnicodeString Param)
  840. {
  841. bool Space = false;
  842. for (int i = 1; i <= Param.Length(); i++)
  843. {
  844. switch (Param[i])
  845. {
  846. case L'"':
  847. Param.Insert(L"\\", i);
  848. i++;
  849. break;
  850. case L' ':
  851. Space = true;
  852. break;
  853. case L'\\':
  854. int i2 = i;
  855. while ((i2 <= Param.Length()) && (Param[i2] == L'\\'))
  856. {
  857. i2++;
  858. }
  859. if ((i2 <= Param.Length()) && (Param[i2] == L'"'))
  860. {
  861. while (Param[i] == L'\\')
  862. {
  863. Param.Insert(L"\\", i);
  864. i += 2;
  865. }
  866. i--;
  867. }
  868. break;
  869. }
  870. }
  871. if (Space)
  872. {
  873. Param = L"\"" + Param + L'"';
  874. }
  875. return Param;
  876. }
  877. //---------------------------------------------------------------------------
  878. UnicodeString __fastcall StringsToParams(TStrings * Strings)
  879. {
  880. UnicodeString Result;
  881. for (int Index = 0; Index < Strings->Count; Index++)
  882. {
  883. UnicodeString Name = Strings->Names[Index];
  884. UnicodeString Value = Strings->ValueFromIndex[Index];
  885. // Do not quote if it is all-numeric
  886. if (IntToStr(StrToIntDef(Value, -1)) != Value)
  887. {
  888. Value = FORMAT(L"\"%s\"", (EscapeParam(Value)));
  889. }
  890. Result += FORMAT(L" %s=%s", (Name, Value));
  891. }
  892. return Result;
  893. }
  894. //---------------------------------------------------------------------------
  895. UnicodeString __fastcall ExpandEnvironmentVariables(const UnicodeString & Str)
  896. {
  897. UnicodeString Buf;
  898. unsigned int Size = 1024;
  899. Buf.SetLength(Size);
  900. Buf.Unique();
  901. unsigned int Len = ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Size);
  902. if (Len > Size)
  903. {
  904. Buf.SetLength(Len);
  905. Buf.Unique();
  906. ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Len);
  907. }
  908. PackStr(Buf);
  909. return Buf;
  910. }
  911. //---------------------------------------------------------------------------
  912. UnicodeString GetNormalizedPath(const UnicodeString & Path)
  913. {
  914. UnicodeString Result = ExcludeTrailingBackslash(Path);
  915. Result = FromUnixPath(Result);
  916. return Result;
  917. }
  918. //---------------------------------------------------------------------------
  919. UnicodeString GetCanonicalPath(const UnicodeString & Path)
  920. {
  921. UnicodeString Result = ExtractShortPathName(Path);
  922. if (Result.IsEmpty())
  923. {
  924. Result = Path;
  925. }
  926. Result = GetNormalizedPath(Result);
  927. return Result;
  928. }
  929. //---------------------------------------------------------------------------
  930. bool __fastcall IsPathToSameFile(const UnicodeString & Path1, const UnicodeString & Path2)
  931. {
  932. UnicodeString CanonicalPath1 = GetCanonicalPath(Path1);
  933. UnicodeString CanonicalPath2 = GetCanonicalPath(Path2);
  934. bool Result = SameText(CanonicalPath1, CanonicalPath2);
  935. return Result;
  936. }
  937. //---------------------------------------------------------------------------
  938. bool __fastcall SamePaths(const UnicodeString & Path1, const UnicodeString & Path2)
  939. {
  940. // TODO: ExpandUNCFileName
  941. return AnsiSameText(IncludeTrailingBackslash(Path1), IncludeTrailingBackslash(Path2));
  942. }
  943. //---------------------------------------------------------------------------
  944. UnicodeString CombinePaths(const UnicodeString & Path1, const UnicodeString & Path2)
  945. {
  946. // Make sure that C: + foo => C:\foo and not C:foo
  947. UnicodeString Path1Terminated = Path1;
  948. if (EndsStr(L":", Path1Terminated))
  949. {
  950. Path1Terminated = IncludeTrailingBackslash(Path1Terminated);
  951. }
  952. return TPath::Combine(Path1Terminated, Path2);
  953. }
  954. //---------------------------------------------------------------------------
  955. int __fastcall CompareLogicalText(
  956. const UnicodeString & S1, const UnicodeString & S2, bool NaturalOrderNumericalSorting)
  957. {
  958. // Keep in sync with CompareLogicalTextPas
  959. int Result;
  960. if (NaturalOrderNumericalSorting)
  961. {
  962. Result = StrCmpLogicalW(S1.c_str(), S2.c_str());
  963. }
  964. else
  965. {
  966. Result = lstrcmpi(S1.c_str(), S2.c_str());
  967. }
  968. // For deterministic results
  969. if (Result == 0)
  970. {
  971. Result = lstrcmp(S1.c_str(), S2.c_str());
  972. }
  973. return Result;
  974. }
  975. //---------------------------------------------------------------------------
  976. int __fastcall CompareNumber(__int64 Value1, __int64 Value2)
  977. {
  978. int Result;
  979. if (Value1 < Value2)
  980. {
  981. Result = -1;
  982. }
  983. else if (Value1 == Value2)
  984. {
  985. Result = 0;
  986. }
  987. else
  988. {
  989. Result = 1;
  990. }
  991. return Result;
  992. }
  993. //---------------------------------------------------------------------------
  994. bool ContainsTextSemiCaseSensitive(const UnicodeString & Text, const UnicodeString & SubText)
  995. {
  996. bool Result;
  997. if (AnsiLowerCase(SubText) == SubText)
  998. {
  999. Result = ContainsText(Text, SubText);
  1000. }
  1001. else
  1002. {
  1003. Result = ContainsStr(Text, SubText);
  1004. }
  1005. return Result;
  1006. }
  1007. //---------------------------------------------------------------------------
  1008. bool __fastcall IsReservedName(UnicodeString FileName)
  1009. {
  1010. int P = FileName.Pos(L".");
  1011. int Len = (P > 0) ? P - 1 : FileName.Length();
  1012. if ((Len == 3) || (Len == 4))
  1013. {
  1014. if (P > 0)
  1015. {
  1016. FileName.SetLength(P - 1);
  1017. }
  1018. static UnicodeString Reserved[] = {
  1019. L"CON", L"PRN", L"AUX", L"NUL",
  1020. L"COM1", L"COM2", L"COM3", L"COM4", L"COM5", L"COM6", L"COM7", L"COM8", L"COM9",
  1021. L"LPT1", L"LPT2", L"LPT3", L"LPT4", L"LPT5", L"LPT6", L"LPT7", L"LPT8", L"LPT9" };
  1022. for (unsigned int Index = 0; Index < LENOF(Reserved); Index++)
  1023. {
  1024. if (SameText(FileName, Reserved[Index]))
  1025. {
  1026. return true;
  1027. }
  1028. }
  1029. }
  1030. return false;
  1031. }
  1032. //---------------------------------------------------------------------------
  1033. // ApiPath support functions
  1034. // Inspired by
  1035. // https://stackoverflow.com/q/18580945/850848
  1036. // This can be reimplemented using PathCchCanonicalizeEx on Windows 8 and later
  1037. enum PATH_PREFIX_TYPE
  1038. {
  1039. PPT_UNKNOWN,
  1040. PPT_ABSOLUTE, //Found absolute path that is none of the other types
  1041. PPT_UNC, //Found \\server\share\ prefix
  1042. PPT_LONG_UNICODE, //Found \\?\ prefix
  1043. PPT_LONG_UNICODE_UNC, //Found \\?\UNC\ prefix
  1044. };
  1045. //---------------------------------------------------------------------------
  1046. static int GetOffsetAfterPathRoot(const UnicodeString & Path, PATH_PREFIX_TYPE & PrefixType)
  1047. {
  1048. // Checks if 'pPath' begins with the drive, share, prefix, etc
  1049. // EXAMPLES:
  1050. // Path Return: Points at: PrefixType:
  1051. // Relative\Folder\File.txt 0 Relative\Folder\File.txt PPT_UNKNOWN
  1052. // \RelativeToRoot\Folder 1 RelativeToRoot\Folder PPT_ABSOLUTE
  1053. // C:\Windows\Folder 3 Windows\Folder PPT_ABSOLUTE
  1054. // \\server\share\Desktop 15 Desktop PPT_UNC
  1055. // \\?\C:\Windows\Folder 7 Windows\Folder PPT_LONG_UNICODE
  1056. // \\?\UNC\server\share\Desktop 21 Desktop PPT_LONG_UNICODE_UNC
  1057. // RETURN:
  1058. // = Index in 'pPath' after the root, or
  1059. // = 0 if no root was found
  1060. int Result = 0;
  1061. PrefixType = PPT_UNKNOWN;
  1062. if (!Path.IsEmpty())
  1063. {
  1064. int Len = Path.Length();
  1065. // Replace all /'s with \'s because PathSkipRoot and PathIsRelative can't handle /'s
  1066. UnicodeString WinPath = ReplaceChar(Path, L'/', L'\\');
  1067. // Now call the API
  1068. LPCTSTR Buffer = PathSkipRoot(WinPath.c_str());
  1069. if (Buffer != NULL)
  1070. {
  1071. Result = (Buffer - WinPath.c_str()) + 1;
  1072. }
  1073. // Now determine the type of prefix
  1074. int IndCheckUNC = -1;
  1075. if ((Len >= 8) &&
  1076. (Path[1] == L'\\' || Path[1] == L'/') &&
  1077. (Path[2] == L'\\' || Path[2] == L'/') &&
  1078. (Path[3] == L'?') &&
  1079. (Path[4] == L'\\' || Path[4] == L'/') &&
  1080. (Path[5] == L'U' || Path[5] == L'u') &&
  1081. (Path[6] == L'N' || Path[6] == L'n') &&
  1082. (Path[7] == L'C' || Path[7] == L'c') &&
  1083. (Path[8] == L'\\' || Path[8] == L'/'))
  1084. {
  1085. // Found \\?\UNC\ prefix
  1086. PrefixType = PPT_LONG_UNICODE_UNC;
  1087. //Check for UNC share later
  1088. IndCheckUNC = 8;
  1089. }
  1090. else if ((Len >= 4) &&
  1091. (Path[1] == L'\\' || Path[1] == L'/') &&
  1092. (Path[2] == L'\\' || Path[2] == L'/') &&
  1093. (Path[3] == L'?') &&
  1094. (Path[4] == L'\\' || Path[4] == L'/'))
  1095. {
  1096. // Found \\?\ prefix
  1097. PrefixType = PPT_LONG_UNICODE;
  1098. }
  1099. else if ((Len >= 2) &&
  1100. (Path[1] == L'\\' || Path[1] == L'/') &&
  1101. (Path[2] == L'\\' || Path[2] == L'/'))
  1102. {
  1103. // Check for UNC share later
  1104. IndCheckUNC = 2;
  1105. }
  1106. if (IndCheckUNC >= 0)
  1107. {
  1108. // Check for UNC, i.e. \\server\share\ part
  1109. int Index = IndCheckUNC;
  1110. for (int SkipSlashes = 2; SkipSlashes > 0; SkipSlashes--)
  1111. {
  1112. for(; Index <= Len; Index++)
  1113. {
  1114. TCHAR z = Path[Index];
  1115. if ((z == L'\\') || (z == L'/') || (Index >= Len))
  1116. {
  1117. Index++;
  1118. if (SkipSlashes == 1)
  1119. {
  1120. if (PrefixType == PPT_UNKNOWN)
  1121. {
  1122. PrefixType = PPT_UNC;
  1123. }
  1124. }
  1125. break;
  1126. }
  1127. }
  1128. }
  1129. }
  1130. // Only if we didn't determine any other type
  1131. if (PrefixType == PPT_UNKNOWN)
  1132. {
  1133. if (!PathIsRelative(WinPath.c_str()))
  1134. {
  1135. PrefixType = PPT_ABSOLUTE;
  1136. }
  1137. }
  1138. }
  1139. return Result;
  1140. }
  1141. //---------------------------------------------------------------------------
  1142. UnicodeString __fastcall MakeUnicodeLargePath(UnicodeString Path)
  1143. {
  1144. // Convert path from 'into a larger Unicode path, that allows up to 32,767 character length
  1145. UnicodeString Result;
  1146. if (!Path.IsEmpty())
  1147. {
  1148. // Determine the type of the existing prefix
  1149. PATH_PREFIX_TYPE PrefixType;
  1150. GetOffsetAfterPathRoot(Path, PrefixType);
  1151. // Assume path to be without change
  1152. Result = Path;
  1153. switch (PrefixType)
  1154. {
  1155. case PPT_ABSOLUTE:
  1156. {
  1157. // First we need to check if its an absolute path relative to the root
  1158. bool AddPrefix = true;
  1159. if ((Path.Length() >= 1) &&
  1160. ((Path[1] == L'\\') || (Path[1] == L'/')))
  1161. {
  1162. AddPrefix = FALSE;
  1163. // Get current root path
  1164. UnicodeString CurrentDir = GetCurrentDir();
  1165. PATH_PREFIX_TYPE PrefixType2; // unused
  1166. int Following = GetOffsetAfterPathRoot(CurrentDir, PrefixType2);
  1167. if (Following > 0)
  1168. {
  1169. AddPrefix = true;
  1170. Result = CurrentDir.SubString(1, Following - 1) + Result.SubString(2, Result.Length() - 1);
  1171. }
  1172. }
  1173. if (AddPrefix)
  1174. {
  1175. // Add \\?\ prefix
  1176. Result = L"\\\\?\\" + Result;
  1177. }
  1178. }
  1179. break;
  1180. case PPT_UNC:
  1181. // First we need to remove the opening slashes for UNC share
  1182. if ((Result.Length() >= 2) &&
  1183. ((Result[1] == L'\\') || (Result[1] == L'/')) &&
  1184. ((Result[2] == L'\\') || (Result[2] == L'/')))
  1185. {
  1186. Result = Result.SubString(3, Result.Length() - 2);
  1187. }
  1188. // Add \\?\UNC\ prefix
  1189. Result = L"\\\\?\\UNC\\" + Result;
  1190. break;
  1191. case PPT_LONG_UNICODE:
  1192. case PPT_LONG_UNICODE_UNC:
  1193. // nothing to do
  1194. break;
  1195. }
  1196. }
  1197. return Result;
  1198. }
  1199. //---------------------------------------------------------------------------
  1200. UnicodeString __fastcall ApiPath(UnicodeString Path)
  1201. {
  1202. UnicodeString Drive = ExtractFileDrive(Path);
  1203. // This may match even a path like "C:" or "\\server\\share", but we do not really care
  1204. if (Drive.IsEmpty() || (Path.SubString(Drive.Length() + 1, 1) != L"\\"))
  1205. {
  1206. Path = ExpandFileName(Path);
  1207. }
  1208. // Max path for directories is 12 characters shorter than max path for files
  1209. if (Path.Length() >= MAX_PATH - 12)
  1210. {
  1211. if (Configuration != NULL)
  1212. {
  1213. Configuration->Usage->Inc(L"LongPath");
  1214. }
  1215. Path = MakeUnicodeLargePath(Path);
  1216. }
  1217. return Path;
  1218. }
  1219. //---------------------------------------------------------------------------
  1220. UnicodeString __fastcall DisplayableStr(const RawByteString & Str)
  1221. {
  1222. bool Displayable = true;
  1223. int Index = 1;
  1224. while ((Index <= Str.Length()) && Displayable)
  1225. {
  1226. if (((Str[Index] < '\x20') || IsWideChar(Str[Index])) &&
  1227. (Str[Index] != '\n') && (Str[Index] != '\r') && (Str[Index] != '\t') && (Str[Index] != '\b'))
  1228. {
  1229. Displayable = false;
  1230. }
  1231. Index++;
  1232. }
  1233. UnicodeString Result;
  1234. if (Displayable)
  1235. {
  1236. Result = L"\"";
  1237. for (int Index = 1; Index <= Str.Length(); Index++)
  1238. {
  1239. switch (Str[Index])
  1240. {
  1241. case '\n':
  1242. Result += L"\\n";
  1243. break;
  1244. case '\r':
  1245. Result += L"\\r";
  1246. break;
  1247. case '\t':
  1248. Result += L"\\t";
  1249. break;
  1250. case '\b':
  1251. Result += L"\\b";
  1252. break;
  1253. case '\\':
  1254. Result += L"\\\\";
  1255. break;
  1256. case '"':
  1257. Result += L"\\\"";
  1258. break;
  1259. default:
  1260. Result += wchar_t(Str[Index]);
  1261. break;
  1262. }
  1263. }
  1264. Result += L"\"";
  1265. }
  1266. else
  1267. {
  1268. Result = L"0x" + BytesToHex(Str);
  1269. }
  1270. return Result;
  1271. }
  1272. //---------------------------------------------------------------------------
  1273. UnicodeString __fastcall ByteToHex(unsigned char B, bool UpperCase)
  1274. {
  1275. static wchar_t UpperDigits[] = L"0123456789ABCDEF";
  1276. static wchar_t LowerDigits[] = L"0123456789abcdef";
  1277. const wchar_t * Digits = (UpperCase ? UpperDigits : LowerDigits);
  1278. UnicodeString Result;
  1279. Result.SetLength(2);
  1280. Result[1] = Digits[(B & 0xF0) >> 4];
  1281. Result[2] = Digits[(B & 0x0F) >> 0];
  1282. return Result;
  1283. }
  1284. //---------------------------------------------------------------------------
  1285. UnicodeString __fastcall BytesToHex(const unsigned char * B, size_t Length, bool UpperCase, wchar_t Separator)
  1286. {
  1287. UnicodeString Result;
  1288. for (size_t i = 0; i < Length; i++)
  1289. {
  1290. Result += ByteToHex(B[i], UpperCase);
  1291. if ((Separator != L'\0') && (i < Length - 1))
  1292. {
  1293. Result += Separator;
  1294. }
  1295. }
  1296. return Result;
  1297. }
  1298. //---------------------------------------------------------------------------
  1299. UnicodeString __fastcall BytesToHex(RawByteString Str, bool UpperCase, wchar_t Separator)
  1300. {
  1301. return BytesToHex(reinterpret_cast<const unsigned char *>(Str.c_str()), Str.Length(), UpperCase, Separator);
  1302. }
  1303. //---------------------------------------------------------------------------
  1304. UnicodeString __fastcall CharToHex(wchar_t Ch, bool UpperCase)
  1305. {
  1306. // BytesToHex would encode with opposite/unexpected endianness
  1307. return ByteToHex(Ch >> 8, UpperCase) + ByteToHex(Ch & 0xFF, UpperCase);
  1308. }
  1309. //---------------------------------------------------------------------------
  1310. RawByteString __fastcall HexToBytes(const UnicodeString Hex)
  1311. {
  1312. static UnicodeString Digits = L"0123456789ABCDEF";
  1313. RawByteString Result;
  1314. int L, P1, P2;
  1315. L = Hex.Length();
  1316. if (L % 2 == 0)
  1317. {
  1318. for (int i = 1; i <= Hex.Length(); i += 2)
  1319. {
  1320. P1 = Digits.Pos(towupper(Hex[i]));
  1321. P2 = Digits.Pos(towupper(Hex[i + 1]));
  1322. if (P1 <= 0 || P2 <= 0)
  1323. {
  1324. Result = L"";
  1325. break;
  1326. }
  1327. else
  1328. {
  1329. Result += static_cast<char>((P1 - 1) * 16 + P2 - 1);
  1330. }
  1331. }
  1332. }
  1333. return Result;
  1334. }
  1335. //---------------------------------------------------------------------------
  1336. unsigned char __fastcall HexToByte(const UnicodeString Hex)
  1337. {
  1338. static UnicodeString Digits = L"0123456789ABCDEF";
  1339. DebugAssert(Hex.Length() == 2);
  1340. int P1 = Digits.Pos(towupper(Hex[1]));
  1341. int P2 = Digits.Pos(towupper(Hex[2]));
  1342. return
  1343. static_cast<unsigned char>(((P1 <= 0) || (P2 <= 0)) ? 0 : (((P1 - 1) << 4) + (P2 - 1)));
  1344. }
  1345. //---------------------------------------------------------------------------
  1346. bool __fastcall IsLowerCaseLetter(wchar_t Ch)
  1347. {
  1348. return (Ch >= 'a') && (Ch <= 'z');
  1349. }
  1350. //---------------------------------------------------------------------------
  1351. bool __fastcall IsUpperCaseLetter(wchar_t Ch)
  1352. {
  1353. return (Ch >= 'A') && (Ch <= 'Z');
  1354. }
  1355. //---------------------------------------------------------------------------
  1356. bool __fastcall IsLetter(wchar_t Ch)
  1357. {
  1358. return IsLowerCaseLetter(Ch) || IsUpperCaseLetter(Ch);
  1359. }
  1360. //---------------------------------------------------------------------------
  1361. bool __fastcall IsDigit(wchar_t Ch)
  1362. {
  1363. return (Ch >= '0') && (Ch <= '9');
  1364. }
  1365. //---------------------------------------------------------------------------
  1366. bool __fastcall IsHex(wchar_t Ch)
  1367. {
  1368. return
  1369. IsDigit(Ch) ||
  1370. ((Ch >= 'A') && (Ch <= 'F')) ||
  1371. ((Ch >= 'a') && (Ch <= 'f'));
  1372. }
  1373. //---------------------------------------------------------------------------
  1374. TSearchRecSmart::TSearchRecSmart()
  1375. {
  1376. FLastWriteTimeSource.dwLowDateTime = 0;
  1377. FLastWriteTimeSource.dwHighDateTime = 0;
  1378. }
  1379. //---------------------------------------------------------------------------
  1380. void TSearchRecSmart::Clear()
  1381. {
  1382. Size = 0;
  1383. Attr = 0;
  1384. Name = TFileName();
  1385. ExcludeAttr = 0;
  1386. FindHandle = 0;
  1387. memset(&FindData, 0, sizeof(FindData));
  1388. FLastWriteTimeSource.dwLowDateTime = 0;
  1389. FLastWriteTimeSource.dwHighDateTime = 0;
  1390. }
  1391. //---------------------------------------------------------------------------
  1392. // This can be replaced with TSearchRec.TimeStamp
  1393. TDateTime TSearchRecSmart::GetLastWriteTime() const
  1394. {
  1395. if ((FindData.ftLastWriteTime.dwLowDateTime != FLastWriteTimeSource.dwLowDateTime) ||
  1396. (FindData.ftLastWriteTime.dwHighDateTime != FLastWriteTimeSource.dwHighDateTime))
  1397. {
  1398. FLastWriteTimeSource = FindData.ftLastWriteTime;
  1399. FLastWriteTime = FileTimeToDateTime(FLastWriteTimeSource);
  1400. }
  1401. return FLastWriteTime;
  1402. }
  1403. //---------------------------------------------------------------------------
  1404. bool TSearchRecSmart::IsRealFile() const
  1405. {
  1406. return ::IsRealFile(Name);
  1407. }
  1408. //---------------------------------------------------------------------------
  1409. bool TSearchRecSmart::IsDirectory() const
  1410. {
  1411. return FLAGSET(Attr, faDirectory);
  1412. }
  1413. //---------------------------------------------------------------------------
  1414. bool TSearchRecSmart::IsHidden() const
  1415. {
  1416. return FLAGSET(Attr, faHidden);
  1417. }
  1418. //---------------------------------------------------------------------------
  1419. UnicodeString TSearchRecChecked::GetFilePath() const
  1420. {
  1421. return CombinePaths(Dir, Name);
  1422. }
  1423. //---------------------------------------------------------------------------
  1424. TSearchRecOwned::~TSearchRecOwned()
  1425. {
  1426. if (Opened)
  1427. {
  1428. FindClose(*this);
  1429. }
  1430. }
  1431. //---------------------------------------------------------------------------
  1432. void TSearchRecOwned::Close()
  1433. {
  1434. FindClose(*this);
  1435. Opened = false;
  1436. }
  1437. //---------------------------------------------------------------------------
  1438. int __fastcall FindCheck(int Result, const UnicodeString & Path)
  1439. {
  1440. if ((Result != ERROR_SUCCESS) &&
  1441. (Result != ERROR_FILE_NOT_FOUND) &&
  1442. (Result != ERROR_NO_MORE_FILES))
  1443. {
  1444. throw EOSExtException(FMTLOAD(FIND_FILE_ERROR, (Path)), Result);
  1445. }
  1446. return Result;
  1447. }
  1448. //---------------------------------------------------------------------------
  1449. int __fastcall FindFirstUnchecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  1450. {
  1451. F.Path = Path;
  1452. F.Dir = ExtractFilePath(Path);
  1453. int Result = FindFirst(ApiPath(Path), Attr, F);
  1454. F.Opened = (Result == 0);
  1455. return Result;
  1456. }
  1457. //---------------------------------------------------------------------------
  1458. int __fastcall FindFirstChecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  1459. {
  1460. int Result = FindFirstUnchecked(Path, Attr, F);
  1461. return FindCheck(Result, F.Path);
  1462. }
  1463. //---------------------------------------------------------------------------
  1464. // Equivalent to FindNext, just to complement to FindFirstUnchecked
  1465. int __fastcall FindNextUnchecked(TSearchRecChecked & F)
  1466. {
  1467. return FindNext(F);
  1468. }
  1469. //---------------------------------------------------------------------------
  1470. // It can make sense to use FindNextChecked, even if unchecked FindFirst is used.
  1471. // I.e. even if we do not care that FindFirst failed, if FindNext
  1472. // fails after successful FindFirst, it means some terrible problem
  1473. int __fastcall FindNextChecked(TSearchRecChecked & F)
  1474. {
  1475. return FindCheck(FindNextUnchecked(F), F.Path);
  1476. }
  1477. //---------------------------------------------------------------------------
  1478. bool __fastcall FileSearchRec(const UnicodeString FileName, TSearchRec & Rec)
  1479. {
  1480. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1481. bool Result = (FindFirst(ApiPath(FileName), FindAttrs, Rec) == 0);
  1482. if (Result)
  1483. {
  1484. FindClose(Rec);
  1485. }
  1486. return Result;
  1487. }
  1488. //---------------------------------------------------------------------------
  1489. void CopySearchRec(const TSearchRec & Source, TSearchRec & Dest)
  1490. {
  1491. // Strangely issues a compiler warning (W8111 due to TSearchRec::Time), when used in Script.cpp, but not here.
  1492. Dest = Source;
  1493. }
  1494. //---------------------------------------------------------------------------
  1495. bool __fastcall IsRealFile(const UnicodeString & FileName)
  1496. {
  1497. return (FileName != THISDIRECTORY) && (FileName != PARENTDIRECTORY);
  1498. }
  1499. //---------------------------------------------------------------------------
  1500. UnicodeString GetOSInfo()
  1501. {
  1502. UnicodeString Result = WindowsVersionLong();
  1503. AddToList(Result, WindowsProductName(), TitleSeparator);
  1504. return Result;
  1505. }
  1506. //---------------------------------------------------------------------------
  1507. UnicodeString GetEnvironmentInfo()
  1508. {
  1509. UnicodeString Result = FORMAT(L"WinSCP %s (OS %s)", (Configuration->VersionStr, GetOSInfo()));
  1510. return Result;
  1511. }
  1512. //---------------------------------------------------------------------------
  1513. void __fastcall ProcessLocalDirectory(UnicodeString DirName,
  1514. TProcessLocalFileEvent CallBackFunc, void * Param,
  1515. int FindAttrs)
  1516. {
  1517. DebugAssert(CallBackFunc);
  1518. if (FindAttrs < 0)
  1519. {
  1520. FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1521. }
  1522. TSearchRecOwned SearchRec;
  1523. if (FindFirstChecked(CombinePaths(DirName, AnyMask), FindAttrs, SearchRec) == 0)
  1524. {
  1525. do
  1526. {
  1527. if (SearchRec.IsRealFile())
  1528. {
  1529. CallBackFunc(SearchRec.GetFilePath(), SearchRec, Param);
  1530. }
  1531. } while (FindNextChecked(SearchRec) == 0);
  1532. }
  1533. }
  1534. //---------------------------------------------------------------------------
  1535. int __fastcall FileGetAttrFix(const UnicodeString & FileName)
  1536. {
  1537. // Already called with ApiPath
  1538. int Result;
  1539. int Tries = 2;
  1540. do
  1541. {
  1542. // WORKAROUND:
  1543. // FileGetAttr when called for link with FollowLink set (default) will always fail on pre-Vista
  1544. // as it calls InternalGetFileNameFromSymLink, which test for CheckWin32Version(6, 0)
  1545. Result = GetFileAttributes(FileName.c_str());
  1546. if ((Result >= 0) && FLAGSET(Result, faSymLink))
  1547. {
  1548. try
  1549. {
  1550. UnicodeString TargetName;
  1551. // WORKAROUND:
  1552. // On Samba, InternalGetFileNameFromSymLink fails and returns true but empty target.
  1553. // That confuses FileGetAttr, which returns attributes of the parent folder instead.
  1554. // Using FileGetSymLinkTarget solves the problem, as it returns false.
  1555. if (!FileGetSymLinkTarget(FileName, TargetName))
  1556. {
  1557. // FileGetAttr would return faInvalid (-1), but we want to allow an upload from Samba,
  1558. // so returning the symlink attributes => noop
  1559. }
  1560. else
  1561. {
  1562. Result = GetFileAttributes(ApiPath(TargetName).c_str());
  1563. }
  1564. }
  1565. catch (EOSError & E)
  1566. {
  1567. Result = -1;
  1568. }
  1569. catch (EDirectoryNotFoundException & E) // throws by FileSystemAttributes
  1570. {
  1571. Result = -1;
  1572. }
  1573. }
  1574. Tries--;
  1575. }
  1576. // When referring to files in some special symlinked locations
  1577. // (like a deduplicated drive or a commvault archive), the first call to FileGetAttr failed.
  1578. // Possibly this issue is resolved by our re-implementation of FileGetAttr above.
  1579. // But as we have no way to test it, keeping the retry here.
  1580. while ((Result < 0) && (Tries > 0));
  1581. return Result;
  1582. }
  1583. //---------------------------------------------------------------------------
  1584. TDateTime __fastcall EncodeDateVerbose(Word Year, Word Month, Word Day)
  1585. {
  1586. try
  1587. {
  1588. TDateTime DateTime = EncodeDate(Year, Month, Day);
  1589. return DateTime;
  1590. }
  1591. catch (EConvertError & E)
  1592. {
  1593. throw EConvertError(FORMAT(L"%s [%d-%d-%d]", (E.Message, int(Year), int(Month), int(Day))));
  1594. }
  1595. }
  1596. //---------------------------------------------------------------------------
  1597. TDateTime __fastcall EncodeTimeVerbose(Word Hour, Word Min, Word Sec, Word MSec)
  1598. {
  1599. try
  1600. {
  1601. TDateTime DateTime = EncodeTime(Hour, Min, Sec, MSec);
  1602. return DateTime;
  1603. }
  1604. catch (EConvertError & E)
  1605. {
  1606. throw EConvertError(FORMAT(L"%s [%d:%d:%d.%d]", (E.Message, int(Hour), int(Min), int(Sec), int(MSec))));
  1607. }
  1608. }
  1609. //---------------------------------------------------------------------------
  1610. TDateTime __fastcall SystemTimeToDateTimeVerbose(const SYSTEMTIME & SystemTime)
  1611. {
  1612. try
  1613. {
  1614. TDateTime DateTime = SystemTimeToDateTime(SystemTime);
  1615. return DateTime;
  1616. }
  1617. catch (EConvertError & E)
  1618. {
  1619. throw EConvertError(FORMAT(L"%s [%d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d.%3.3d]", (E.Message, int(SystemTime.wYear), int(SystemTime.wMonth), int(SystemTime.wDay), int(SystemTime.wHour), int(SystemTime.wMinute), int(SystemTime.wSecond), int(SystemTime.wMilliseconds))));
  1620. }
  1621. }
  1622. //---------------------------------------------------------------------------
  1623. struct TDateTimeParams
  1624. {
  1625. TDateTime UnixEpoch;
  1626. double BaseDifference;
  1627. long BaseDifferenceSec;
  1628. // All Current* are actually global, not per-year and
  1629. // are valid for Year 0 (current) only
  1630. double CurrentDaylightDifference;
  1631. long CurrentDaylightDifferenceSec;
  1632. double CurrentDifference;
  1633. long CurrentDifferenceSec;
  1634. double StandardDifference;
  1635. long StandardDifferenceSec;
  1636. double DaylightDifference;
  1637. long DaylightDifferenceSec;
  1638. SYSTEMTIME SystemStandardDate;
  1639. SYSTEMTIME SystemDaylightDate;
  1640. TDateTime StandardDate;
  1641. TDateTime DaylightDate;
  1642. UnicodeString StandardName;
  1643. UnicodeString DaylightName;
  1644. // This is actually global, not per-year
  1645. bool DaylightHack;
  1646. bool HasDST() const
  1647. {
  1648. // On some systems it occurs that StandardDate is unset, while
  1649. // DaylightDate is set. MSDN states that this is invalid and
  1650. // should be treated as if there is no daylight saving.
  1651. // So check both.
  1652. return
  1653. (SystemStandardDate.wMonth != 0) &&
  1654. (SystemDaylightDate.wMonth != 0);
  1655. }
  1656. bool SummerDST() const
  1657. {
  1658. return HasDST() && (DaylightDate < StandardDate);
  1659. }
  1660. };
  1661. typedef std::map<int, TDateTimeParams> TYearlyDateTimeParams;
  1662. static TYearlyDateTimeParams YearlyDateTimeParams;
  1663. static std::unique_ptr<TCriticalSection> DateTimeParamsSection(TraceInitPtr(new TCriticalSection()));
  1664. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1665. TDateTime & Result);
  1666. //---------------------------------------------------------------------------
  1667. static unsigned short __fastcall DecodeYear(const TDateTime & DateTime)
  1668. {
  1669. unsigned short Year, Month, Day;
  1670. DecodeDate(DateTime, Year, Month, Day);
  1671. return Year;
  1672. }
  1673. //---------------------------------------------------------------------------
  1674. static const TDateTimeParams * __fastcall GetDateTimeParams(unsigned short Year)
  1675. {
  1676. TGuard Guard(DateTimeParamsSection.get());
  1677. TDateTimeParams * Result;
  1678. TYearlyDateTimeParams::iterator i = YearlyDateTimeParams.find(Year);
  1679. if (i != YearlyDateTimeParams.end())
  1680. {
  1681. Result = &(*i).second;
  1682. }
  1683. else
  1684. {
  1685. // creates new entry as a side effect
  1686. Result = &YearlyDateTimeParams[Year];
  1687. TIME_ZONE_INFORMATION TZI;
  1688. unsigned long GTZI;
  1689. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  1690. typedef BOOL WINAPI (* TGetTimeZoneInformationForYear)(USHORT wYear, PDYNAMIC_TIME_ZONE_INFORMATION pdtzi, LPTIME_ZONE_INFORMATION ptzi);
  1691. TGetTimeZoneInformationForYear GetTimeZoneInformationForYear =
  1692. (TGetTimeZoneInformationForYear)GetProcAddress(Kernel32, "GetTimeZoneInformationForYear");
  1693. if ((Year == 0) || (GetTimeZoneInformationForYear == NULL))
  1694. {
  1695. GTZI = GetTimeZoneInformation(&TZI);
  1696. }
  1697. else
  1698. {
  1699. GetTimeZoneInformationForYear(Year, NULL, &TZI);
  1700. GTZI = TIME_ZONE_ID_UNKNOWN;
  1701. }
  1702. switch (GTZI)
  1703. {
  1704. case TIME_ZONE_ID_UNKNOWN:
  1705. Result->CurrentDaylightDifferenceSec = 0;
  1706. break;
  1707. case TIME_ZONE_ID_STANDARD:
  1708. Result->CurrentDaylightDifferenceSec = TZI.StandardBias;
  1709. break;
  1710. case TIME_ZONE_ID_DAYLIGHT:
  1711. Result->CurrentDaylightDifferenceSec = TZI.DaylightBias;
  1712. break;
  1713. case TIME_ZONE_ID_INVALID:
  1714. default:
  1715. throw Exception(TIMEZONE_ERROR);
  1716. }
  1717. Result->BaseDifferenceSec = TZI.Bias;
  1718. Result->BaseDifference = double(TZI.Bias) / MinsPerDay;
  1719. Result->BaseDifferenceSec *= SecsPerMin;
  1720. Result->CurrentDifferenceSec = TZI.Bias +
  1721. Result->CurrentDaylightDifferenceSec;
  1722. Result->CurrentDifference =
  1723. double(Result->CurrentDifferenceSec) / MinsPerDay;
  1724. Result->CurrentDifferenceSec *= SecsPerMin;
  1725. Result->CurrentDaylightDifference =
  1726. double(Result->CurrentDaylightDifferenceSec) / MinsPerDay;
  1727. Result->CurrentDaylightDifferenceSec *= SecsPerMin;
  1728. Result->DaylightDifferenceSec = TZI.DaylightBias * SecsPerMin;
  1729. Result->DaylightDifference = double(TZI.DaylightBias) / MinsPerDay;
  1730. Result->StandardDifferenceSec = TZI.StandardBias * SecsPerMin;
  1731. Result->StandardDifference = double(TZI.StandardBias) / MinsPerDay;
  1732. Result->SystemStandardDate = TZI.StandardDate;
  1733. Result->SystemDaylightDate = TZI.DaylightDate;
  1734. unsigned short AYear = (Year != 0) ? Year : DecodeYear(Now());
  1735. if (Result->HasDST())
  1736. {
  1737. EncodeDSTMargin(Result->SystemStandardDate, AYear, Result->StandardDate);
  1738. EncodeDSTMargin(Result->SystemDaylightDate, AYear, Result->DaylightDate);
  1739. }
  1740. Result->StandardName = TZI.StandardName;
  1741. Result->DaylightName = TZI.DaylightName;
  1742. Result->DaylightHack = !IsWin7();
  1743. }
  1744. return Result;
  1745. }
  1746. //---------------------------------------------------------------------------
  1747. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1748. TDateTime & Result)
  1749. {
  1750. if (Date.wYear == 0)
  1751. {
  1752. TDateTime Temp = EncodeDateVerbose(Year, Date.wMonth, 1);
  1753. Result = Temp + ((Date.wDayOfWeek - DayOfWeek(Temp) + 8) % 7) +
  1754. (7 * (Date.wDay - 1));
  1755. // Day 5 means, the last occurence of day-of-week in month
  1756. if (Date.wDay == 5)
  1757. {
  1758. unsigned short Month = static_cast<unsigned short>(Date.wMonth + 1);
  1759. if (Month > 12)
  1760. {
  1761. Month = static_cast<unsigned short>(Month - 12);
  1762. Year++;
  1763. }
  1764. if (Result >= EncodeDateVerbose(Year, Month, 1))
  1765. {
  1766. Result -= 7;
  1767. }
  1768. }
  1769. Result += EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond,
  1770. Date.wMilliseconds);
  1771. }
  1772. else
  1773. {
  1774. Result = EncodeDateVerbose(Year, Date.wMonth, Date.wDay) +
  1775. EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond, Date.wMilliseconds);
  1776. }
  1777. }
  1778. //---------------------------------------------------------------------------
  1779. static bool __fastcall IsDateInDST(const TDateTime & DateTime)
  1780. {
  1781. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1782. bool Result;
  1783. // On some systems it occurs that StandardDate is unset, while
  1784. // DaylightDate is set. MSDN states that this is invalid and
  1785. // should be treated as if there is no daylight saving.
  1786. // So check both.
  1787. if (!Params->HasDST())
  1788. {
  1789. Result = false;
  1790. }
  1791. else
  1792. {
  1793. if (Params->SummerDST())
  1794. {
  1795. Result =
  1796. (DateTime >= Params->DaylightDate) &&
  1797. (DateTime < Params->StandardDate);
  1798. }
  1799. else
  1800. {
  1801. Result =
  1802. (DateTime < Params->StandardDate) ||
  1803. (DateTime >= Params->DaylightDate);
  1804. }
  1805. }
  1806. return Result;
  1807. }
  1808. //---------------------------------------------------------------------------
  1809. bool __fastcall UsesDaylightHack()
  1810. {
  1811. return GetDateTimeParams(0)->DaylightHack;
  1812. }
  1813. //---------------------------------------------------------------------------
  1814. TDateTime __fastcall UnixToDateTime(__int64 TimeStamp, TDSTMode DSTMode)
  1815. {
  1816. DebugAssert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1817. TDateTime Result = UnixDateDelta + (double(TimeStamp) / SecsPerDay);
  1818. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(Result));
  1819. if (Params->DaylightHack)
  1820. {
  1821. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1822. {
  1823. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1824. Result -= CurrentParams->CurrentDifference;
  1825. }
  1826. else if (DSTMode == dstmKeep)
  1827. {
  1828. Result -= Params->BaseDifference;
  1829. }
  1830. }
  1831. else
  1832. {
  1833. Result -= Params->BaseDifference;
  1834. }
  1835. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1836. {
  1837. Result -= DSTDifferenceForTime(Result);
  1838. }
  1839. return Result;
  1840. }
  1841. //---------------------------------------------------------------------------
  1842. __int64 __fastcall Round(double Number)
  1843. {
  1844. double Floor = floor(Number);
  1845. double Ceil = ceil(Number);
  1846. return static_cast<__int64>(((Number - Floor) > (Ceil - Number)) ? Ceil : Floor);
  1847. }
  1848. //---------------------------------------------------------------------------
  1849. bool __fastcall TryRelativeStrToDateTime(UnicodeString S, TDateTime & DateTime, bool Add)
  1850. {
  1851. S = S.Trim();
  1852. int Index = 1;
  1853. if (SameText(S, L"today"))
  1854. {
  1855. S = L"0DS";
  1856. }
  1857. else if (SameText(S, L"yesterday"))
  1858. {
  1859. S = L"1DS";
  1860. }
  1861. while ((Index <= S.Length()) && IsDigit(S[Index]))
  1862. {
  1863. Index++;
  1864. }
  1865. UnicodeString NumberStr = S.SubString(1, Index - 1);
  1866. int Number;
  1867. bool Result = TryStrToInt(NumberStr, Number);
  1868. if (Result)
  1869. {
  1870. if (!Add)
  1871. {
  1872. Number = -Number;
  1873. }
  1874. S.Delete(1, Index - 1);
  1875. S = S.Trim().UpperCase();
  1876. bool Start = (S.Length() == 2) && (S[2] == L'S');
  1877. if (Start)
  1878. {
  1879. S.SetLength(S.Length() - 1);
  1880. }
  1881. DateTime = Now();
  1882. // These may not overlap with ParseSize (K, M and G)
  1883. if (S == L"S")
  1884. {
  1885. DateTime = IncSecond(DateTime, Number);
  1886. if (Start)
  1887. {
  1888. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheSecond(DateTime)));
  1889. }
  1890. }
  1891. else if (S == L"N")
  1892. {
  1893. DateTime = IncMinute(DateTime, Number);
  1894. if (Start)
  1895. {
  1896. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheMinute(DateTime)));
  1897. }
  1898. }
  1899. else if (S == L"H")
  1900. {
  1901. DateTime = IncHour(DateTime, Number);
  1902. if (Start)
  1903. {
  1904. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheHour(DateTime)));
  1905. }
  1906. }
  1907. else if (S == L"D")
  1908. {
  1909. DateTime = IncDay(DateTime, Number);
  1910. if (Start)
  1911. {
  1912. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheDay(DateTime)));
  1913. }
  1914. }
  1915. else if (S == L"Y")
  1916. {
  1917. DateTime = IncYear(DateTime, Number);
  1918. if (Start)
  1919. {
  1920. DateTime = IncMilliSecond(DateTime, -MilliSecondOfTheYear(DateTime));
  1921. }
  1922. }
  1923. else
  1924. {
  1925. Result = false;
  1926. }
  1927. }
  1928. return Result;
  1929. }
  1930. //---------------------------------------------------------------------------
  1931. bool TryStrToDateTimeStandard(const UnicodeString & S, TDateTime & Value)
  1932. {
  1933. TFormatSettings FormatSettings = TFormatSettings::Create(GetDefaultLCID());
  1934. FormatSettings.DateSeparator = L'-';
  1935. FormatSettings.TimeSeparator = L':';
  1936. FormatSettings.ShortDateFormat = "yyyy/mm/dd";
  1937. FormatSettings.ShortTimeFormat = "hh:nn:ss";
  1938. return TryStrToDateTime(S, Value, FormatSettings);
  1939. }
  1940. //---------------------------------------------------------------------------
  1941. const wchar_t KiloSize = L'K';
  1942. const wchar_t MegaSize = L'M';
  1943. const wchar_t GigaSize = L'G';
  1944. //---------------------------------------------------------------------------
  1945. // Keep consistent with parse_blocksize
  1946. bool __fastcall TryStrToSize(UnicodeString SizeStr, __int64 & Size)
  1947. {
  1948. int Index = 0;
  1949. while ((Index + 1 <= SizeStr.Length()) && IsDigit(SizeStr[Index + 1]))
  1950. {
  1951. Index++;
  1952. }
  1953. bool Result =
  1954. (Index > 0) && TryStrToInt64(SizeStr.SubString(1, Index), Size);
  1955. if (Result)
  1956. {
  1957. SizeStr = SizeStr.SubString(Index + 1, SizeStr.Length() - Index).Trim();
  1958. if (!SizeStr.IsEmpty())
  1959. {
  1960. Result = (SizeStr.Length() == 1);
  1961. if (Result)
  1962. {
  1963. wchar_t Unit = towupper(SizeStr[1]);
  1964. switch (Unit)
  1965. {
  1966. case GigaSize:
  1967. Size *= 1024;
  1968. // fallthru
  1969. case MegaSize:
  1970. Size *= 1024;
  1971. // fallthru
  1972. case KiloSize:
  1973. Size *= 1024;
  1974. break;
  1975. default:
  1976. Result = false;
  1977. }
  1978. }
  1979. }
  1980. }
  1981. return Result;
  1982. }
  1983. //---------------------------------------------------------------------------
  1984. UnicodeString __fastcall SizeToStr(__int64 Size)
  1985. {
  1986. UnicodeString Result;
  1987. if ((Size <= 0) || ((Size % 1024) != 0))
  1988. {
  1989. Result = IntToStr(Size);
  1990. }
  1991. else
  1992. {
  1993. Size /= 1024;
  1994. if ((Size % 1024) != 0)
  1995. {
  1996. Result = IntToStr(Size) + KiloSize;
  1997. }
  1998. else
  1999. {
  2000. Size /= 1024;
  2001. if ((Size % 1024) != 0)
  2002. {
  2003. Result = IntToStr(Size) + MegaSize;
  2004. }
  2005. else
  2006. {
  2007. Size /= 1024;
  2008. Result = IntToStr(Size) + GigaSize;
  2009. }
  2010. }
  2011. }
  2012. return Result;
  2013. }
  2014. //---------------------------------------------------------------------------
  2015. static __int64 __fastcall DateTimeToUnix(const TDateTime DateTime)
  2016. {
  2017. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2018. DebugAssert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  2019. return Round(double(DateTime - UnixDateDelta) * SecsPerDay) +
  2020. CurrentParams->CurrentDifferenceSec;
  2021. }
  2022. //---------------------------------------------------------------------------
  2023. FILETIME __fastcall DateTimeToFileTime(const TDateTime DateTime,
  2024. TDSTMode /*DSTMode*/)
  2025. {
  2026. __int64 UnixTimeStamp = ::DateTimeToUnix(DateTime);
  2027. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2028. if (!Params->DaylightHack)
  2029. {
  2030. // We should probably use reversed code of FileTimeToDateTime here instead of custom implementation
  2031. // We are incrementing and decrementing BaseDifferenceSec because it
  2032. // can actually change between years
  2033. // (as it did in Belarus from GMT+2 to GMT+3 between 2011 and 2012)
  2034. UnixTimeStamp += (IsDateInDST(DateTime) ?
  2035. Params->DaylightDifferenceSec : Params->StandardDifferenceSec) +
  2036. Params->BaseDifferenceSec;
  2037. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2038. UnixTimeStamp -=
  2039. CurrentParams->CurrentDaylightDifferenceSec +
  2040. CurrentParams->BaseDifferenceSec;
  2041. }
  2042. FILETIME Result;
  2043. (*(__int64*)&(Result) = (__int64(UnixTimeStamp) + 11644473600LL) * 10000000LL);
  2044. return Result;
  2045. }
  2046. //---------------------------------------------------------------------------
  2047. // This can be replaced with TSearchRec.TimeStamp
  2048. TDateTime __fastcall FileTimeToDateTime(const FILETIME & FileTime)
  2049. {
  2050. // duplicated in DirView.pas
  2051. TDateTime Result;
  2052. // The 0xFFF... is sometimes seen for invalid timestamps,
  2053. // it would cause failure in SystemTimeToDateTime below
  2054. if (FileTime.dwLowDateTime == std::numeric_limits<DWORD>::max())
  2055. {
  2056. Result = MinDateTime;
  2057. }
  2058. else
  2059. {
  2060. SYSTEMTIME SysTime;
  2061. if (!UsesDaylightHack())
  2062. {
  2063. SYSTEMTIME UniverzalSysTime;
  2064. FileTimeToSystemTime(&FileTime, &UniverzalSysTime);
  2065. SystemTimeToTzSpecificLocalTime(NULL, &UniverzalSysTime, &SysTime);
  2066. }
  2067. else
  2068. {
  2069. FILETIME LocalFileTime;
  2070. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  2071. FileTimeToSystemTime(&LocalFileTime, &SysTime);
  2072. }
  2073. Result = SystemTimeToDateTimeVerbose(SysTime);
  2074. }
  2075. return Result;
  2076. }
  2077. //---------------------------------------------------------------------------
  2078. __int64 __fastcall ConvertTimestampToUnix(const FILETIME & FileTime,
  2079. TDSTMode DSTMode)
  2080. {
  2081. __int64 Result = ((*(__int64*)&(FileTime)) / 10000000LL - 11644473600LL);
  2082. if (UsesDaylightHack())
  2083. {
  2084. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  2085. {
  2086. FILETIME LocalFileTime;
  2087. SYSTEMTIME SystemTime;
  2088. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  2089. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  2090. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  2091. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2092. Result += (IsDateInDST(DateTime) ?
  2093. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  2094. if (DSTMode == dstmKeep)
  2095. {
  2096. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2097. Result -= CurrentParams->CurrentDaylightDifferenceSec;
  2098. }
  2099. }
  2100. }
  2101. else
  2102. {
  2103. if (DSTMode == dstmWin)
  2104. {
  2105. FILETIME LocalFileTime;
  2106. SYSTEMTIME SystemTime;
  2107. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  2108. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  2109. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  2110. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2111. Result -= (IsDateInDST(DateTime) ?
  2112. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  2113. }
  2114. }
  2115. return Result;
  2116. }
  2117. //---------------------------------------------------------------------------
  2118. TDateTime __fastcall ConvertTimestampToUTC(TDateTime DateTime)
  2119. {
  2120. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2121. DateTime += DSTDifferenceForTime(DateTime);
  2122. DateTime += Params->BaseDifference;
  2123. if (Params->DaylightHack)
  2124. {
  2125. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2126. DateTime += CurrentParams->CurrentDaylightDifference;
  2127. }
  2128. return DateTime;
  2129. }
  2130. //---------------------------------------------------------------------------
  2131. TDateTime __fastcall ConvertTimestampFromUTC(TDateTime DateTime)
  2132. {
  2133. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2134. DateTime -= DSTDifferenceForTime(DateTime);
  2135. DateTime -= Params->BaseDifference;
  2136. if (Params->DaylightHack)
  2137. {
  2138. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2139. DateTime -= CurrentParams->CurrentDaylightDifference;
  2140. }
  2141. return DateTime;
  2142. }
  2143. //---------------------------------------------------------------------------
  2144. __int64 __fastcall ConvertTimestampToUnixSafe(const FILETIME & FileTime,
  2145. TDSTMode DSTMode)
  2146. {
  2147. __int64 Result;
  2148. if ((FileTime.dwLowDateTime == 0) &&
  2149. (FileTime.dwHighDateTime == 0))
  2150. {
  2151. Result = ::DateTimeToUnix(Now());
  2152. }
  2153. else
  2154. {
  2155. Result = ConvertTimestampToUnix(FileTime, DSTMode);
  2156. }
  2157. return Result;
  2158. }
  2159. //---------------------------------------------------------------------------
  2160. double __fastcall DSTDifferenceForTime(TDateTime DateTime)
  2161. {
  2162. double Result;
  2163. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2164. if (IsDateInDST(DateTime))
  2165. {
  2166. Result = Params->DaylightDifference;
  2167. }
  2168. else
  2169. {
  2170. Result = Params->StandardDifference;
  2171. }
  2172. return Result;
  2173. }
  2174. //---------------------------------------------------------------------------
  2175. TDateTime __fastcall AdjustDateTimeFromUnix(TDateTime DateTime, TDSTMode DSTMode)
  2176. {
  2177. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2178. if (Params->DaylightHack)
  2179. {
  2180. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  2181. {
  2182. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2183. DateTime = DateTime - CurrentParams->CurrentDaylightDifference;
  2184. }
  2185. if (!IsDateInDST(DateTime))
  2186. {
  2187. if (DSTMode == dstmWin)
  2188. {
  2189. DateTime = DateTime - Params->DaylightDifference;
  2190. }
  2191. }
  2192. else
  2193. {
  2194. DateTime = DateTime - Params->StandardDifference;
  2195. }
  2196. }
  2197. else
  2198. {
  2199. if (DSTMode == dstmWin)
  2200. {
  2201. DateTime = DateTime + DSTDifferenceForTime(DateTime);
  2202. }
  2203. }
  2204. return DateTime;
  2205. }
  2206. //---------------------------------------------------------------------------
  2207. UnicodeString __fastcall FixedLenDateTimeFormat(const UnicodeString & Format)
  2208. {
  2209. UnicodeString Result = Format;
  2210. bool AsIs = false;
  2211. int Index = 1;
  2212. while (Index <= Result.Length())
  2213. {
  2214. wchar_t F = Result[Index];
  2215. if ((F == L'\'') || (F == L'\"'))
  2216. {
  2217. AsIs = !AsIs;
  2218. Index++;
  2219. }
  2220. else if (!AsIs && ((F == L'a') || (F == L'A')))
  2221. {
  2222. if (Result.SubString(Index, 5).LowerCase() == L"am/pm")
  2223. {
  2224. Index += 5;
  2225. }
  2226. else if (Result.SubString(Index, 3).LowerCase() == L"a/p")
  2227. {
  2228. Index += 3;
  2229. }
  2230. else if (Result.SubString(Index, 4).LowerCase() == L"ampm")
  2231. {
  2232. Index += 4;
  2233. }
  2234. else
  2235. {
  2236. Index++;
  2237. }
  2238. }
  2239. else
  2240. {
  2241. if (!AsIs && (wcschr(L"dDeEmMhHnNsS", F) != NULL) &&
  2242. ((Index == Result.Length()) || (Result[Index + 1] != F)))
  2243. {
  2244. Result.Insert(F, Index);
  2245. }
  2246. while ((Index <= Result.Length()) && (F == Result[Index]))
  2247. {
  2248. Index++;
  2249. }
  2250. }
  2251. }
  2252. return Result;
  2253. }
  2254. //---------------------------------------------------------------------------
  2255. UnicodeString __fastcall FormatTimeZone(long Sec)
  2256. {
  2257. TTimeSpan Span = TTimeSpan::FromSeconds(Sec);
  2258. UnicodeString Str;
  2259. if ((Span.Seconds == 0) && (Span.Minutes == 0))
  2260. {
  2261. Str = FORMAT(L"%d", (-Span.Hours));
  2262. }
  2263. else if (Span.Seconds == 0)
  2264. {
  2265. Str = FORMAT(L"%d:%2.2d", (-Span.Hours, abs(Span.Minutes)));
  2266. }
  2267. else
  2268. {
  2269. Str = FORMAT(L"%d:%2.2d:%2.2d", (-Span.Hours, abs(Span.Minutes), abs(Span.Seconds)));
  2270. }
  2271. Str = ((Span <= TTimeSpan::Zero) ? L"+" : L"") + Str;
  2272. return Str;
  2273. }
  2274. //---------------------------------------------------------------------------
  2275. UnicodeString __fastcall GetTimeZoneLogString()
  2276. {
  2277. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2278. UnicodeString Result =
  2279. FORMAT(L"Current: GMT%s", (FormatTimeZone(CurrentParams->CurrentDifferenceSec)));
  2280. if (!CurrentParams->HasDST())
  2281. {
  2282. Result += FORMAT(L" (%s), No DST", (CurrentParams->StandardName));
  2283. }
  2284. else
  2285. {
  2286. Result +=
  2287. FORMAT(L", Standard: GMT%s (%s), DST: GMT%s (%s), DST Start: %s, DST End: %s",
  2288. (FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->StandardDifferenceSec),
  2289. CurrentParams->StandardName,
  2290. FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->DaylightDifferenceSec),
  2291. CurrentParams->DaylightName,
  2292. CurrentParams->DaylightDate.DateString(),
  2293. CurrentParams->StandardDate.DateString()));
  2294. }
  2295. return Result;
  2296. }
  2297. //---------------------------------------------------------------------------
  2298. bool __fastcall AdjustClockForDSTEnabled()
  2299. {
  2300. // Windows XP deletes the DisableAutoDaylightTimeSet value when it is off
  2301. // (the later versions set it to DynamicDaylightTimeDisabled to 0)
  2302. bool DynamicDaylightTimeDisabled = false;
  2303. TRegistry * Registry = new TRegistry(KEY_READ);
  2304. try
  2305. {
  2306. Registry->RootKey = HKEY_LOCAL_MACHINE;
  2307. if (Registry->OpenKey(L"SYSTEM", false) &&
  2308. Registry->OpenKey(L"CurrentControlSet", false) &&
  2309. Registry->OpenKey(L"Control", false) &&
  2310. Registry->OpenKey(L"TimeZoneInformation", false))
  2311. {
  2312. if (Registry->ValueExists(L"DynamicDaylightTimeDisabled"))
  2313. {
  2314. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DynamicDaylightTimeDisabled");
  2315. }
  2316. // WORKAROUND
  2317. // Windows XP equivalent
  2318. else if (Registry->ValueExists(L"DisableAutoDaylightTimeSet"))
  2319. {
  2320. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DisableAutoDaylightTimeSet");
  2321. }
  2322. }
  2323. delete Registry;
  2324. }
  2325. catch(...)
  2326. {
  2327. }
  2328. return !DynamicDaylightTimeDisabled;
  2329. }
  2330. //---------------------------------------------------------------------------
  2331. UnicodeString __fastcall StandardDatestamp()
  2332. {
  2333. return FormatDateTime(L"yyyy'-'mm'-'dd", ConvertTimestampToUTC(Now()));
  2334. }
  2335. //---------------------------------------------------------------------------
  2336. UnicodeString __fastcall StandardTimestamp(const TDateTime & DateTime)
  2337. {
  2338. return FormatDateTime(L"yyyy'-'mm'-'dd'T'hh':'nn':'ss'.'zzz'Z'", ConvertTimestampToUTC(DateTime));
  2339. }
  2340. //---------------------------------------------------------------------------
  2341. UnicodeString __fastcall StandardTimestamp()
  2342. {
  2343. return StandardTimestamp(Now());
  2344. }
  2345. //---------------------------------------------------------------------------
  2346. static TDateTime TwoSeconds(0, 0, 2, 0);
  2347. int __fastcall CompareFileTime(TDateTime T1, TDateTime T2)
  2348. {
  2349. // "FAT" time precision
  2350. // (when one time is seconds-precision and other is millisecond-precision,
  2351. // we may have times like 12:00:00.000 and 12:00:01.999, which should
  2352. // be treated the same)
  2353. int Result;
  2354. if (T1 == T2)
  2355. {
  2356. // just optimization
  2357. Result = 0;
  2358. }
  2359. else if ((T1 < T2) && (T2 - T1 >= TwoSeconds))
  2360. {
  2361. Result = -1;
  2362. }
  2363. else if ((T1 > T2) && (T1 - T2 >= TwoSeconds))
  2364. {
  2365. Result = 1;
  2366. }
  2367. else
  2368. {
  2369. Result = 0;
  2370. }
  2371. return Result;
  2372. }
  2373. //---------------------------------------------------------------------------
  2374. int __fastcall TimeToMSec(TDateTime T)
  2375. {
  2376. return int(Round(double(T) * double(MSecsPerDay)));
  2377. }
  2378. //---------------------------------------------------------------------------
  2379. int __fastcall TimeToSeconds(TDateTime T)
  2380. {
  2381. return TimeToMSec(T) / MSecsPerSec;
  2382. }
  2383. //---------------------------------------------------------------------------
  2384. int __fastcall TimeToMinutes(TDateTime T)
  2385. {
  2386. return TimeToSeconds(T) / SecsPerMin;
  2387. }
  2388. //---------------------------------------------------------------------------
  2389. static bool __fastcall DoRecursiveDeleteFile(
  2390. const UnicodeString FileName, bool ToRecycleBin, UnicodeString & ErrorPath, int & Deleted)
  2391. {
  2392. bool Result;
  2393. Deleted = 0;
  2394. UnicodeString AErrorPath = FileName;
  2395. if (!ToRecycleBin)
  2396. {
  2397. TSearchRecChecked InitialSearchRec;
  2398. Result = FileSearchRec(FileName, InitialSearchRec);
  2399. if (Result)
  2400. {
  2401. if (!InitialSearchRec.IsDirectory())
  2402. {
  2403. Result = DeleteFile(ApiPath(FileName));
  2404. if (Result)
  2405. {
  2406. Deleted++;
  2407. }
  2408. }
  2409. else
  2410. {
  2411. TSearchRecOwned SearchRec;
  2412. Result = (FindFirstUnchecked(FileName + L"\\*", faAnyFile, SearchRec) == 0);
  2413. if (Result)
  2414. {
  2415. do
  2416. {
  2417. UnicodeString FileName2 = SearchRec.GetFilePath();
  2418. if (SearchRec.IsDirectory())
  2419. {
  2420. if (SearchRec.IsRealFile())
  2421. {
  2422. Result = DoRecursiveDeleteFile(FileName2, DebugAlwaysFalse(ToRecycleBin), AErrorPath, Deleted);
  2423. }
  2424. }
  2425. else
  2426. {
  2427. Result = DeleteFile(ApiPath(FileName2));
  2428. if (!Result)
  2429. {
  2430. AErrorPath = FileName2;
  2431. }
  2432. else
  2433. {
  2434. Deleted++;
  2435. }
  2436. }
  2437. }
  2438. while (Result && (FindNextUnchecked(SearchRec) == 0));
  2439. if (Result)
  2440. {
  2441. Result = RemoveDir(ApiPath(FileName));
  2442. if (Result)
  2443. {
  2444. Deleted++;
  2445. }
  2446. }
  2447. }
  2448. }
  2449. }
  2450. }
  2451. else
  2452. {
  2453. SHFILEOPSTRUCT Data;
  2454. memset(&Data, 0, sizeof(Data));
  2455. Data.hwnd = NULL;
  2456. Data.wFunc = FO_DELETE;
  2457. // SHFileOperation does not support long paths anyway
  2458. UnicodeString FileList(ApiPath(FileName));
  2459. FileList.SetLength(FileList.Length() + 2);
  2460. FileList[FileList.Length() - 1] = L'\0';
  2461. FileList[FileList.Length()] = L'\0';
  2462. Data.pFrom = FileList.c_str();
  2463. Data.pTo = L"\0\0"; // this will actually give one null more than needed
  2464. Data.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION | FOF_NOCONFIRMMKDIR |
  2465. FOF_NOERRORUI | FOF_SILENT;
  2466. if (DebugAlwaysTrue(ToRecycleBin))
  2467. {
  2468. Data.fFlags |= FOF_ALLOWUNDO;
  2469. }
  2470. int ErrorCode = SHFileOperation(&Data);
  2471. Result = (ErrorCode == 0);
  2472. if (!Result)
  2473. {
  2474. // according to MSDN, SHFileOperation may return following non-Win32
  2475. // error codes
  2476. if (((ErrorCode >= 0x71) && (ErrorCode <= 0x88)) ||
  2477. (ErrorCode == 0xB7) || (ErrorCode == 0x402) || (ErrorCode == 0x10000) ||
  2478. (ErrorCode == 0x10074))
  2479. {
  2480. ErrorCode = 0;
  2481. }
  2482. SetLastError(ErrorCode);
  2483. }
  2484. if (Result)
  2485. {
  2486. Deleted = 1;
  2487. }
  2488. }
  2489. if (!Result)
  2490. {
  2491. ErrorPath = AErrorPath;
  2492. }
  2493. return Result;
  2494. }
  2495. //---------------------------------------------------------------------------
  2496. bool __fastcall RecursiveDeleteFile(const UnicodeString & FileName, bool ToRecycleBin)
  2497. {
  2498. UnicodeString ErrorPath; // unused
  2499. int Deleted;
  2500. bool Result = DoRecursiveDeleteFile(FileName, ToRecycleBin, ErrorPath, Deleted);
  2501. return Result;
  2502. }
  2503. //---------------------------------------------------------------------------
  2504. int __fastcall RecursiveDeleteFileChecked(const UnicodeString & FileName, bool ToRecycleBin)
  2505. {
  2506. UnicodeString ErrorPath;
  2507. int Deleted;
  2508. if (!DoRecursiveDeleteFile(FileName, ToRecycleBin, ErrorPath, Deleted))
  2509. {
  2510. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (ErrorPath)));
  2511. }
  2512. return Deleted;
  2513. }
  2514. //---------------------------------------------------------------------------
  2515. void __fastcall DeleteFileChecked(const UnicodeString & FileName)
  2516. {
  2517. if (!DeleteFile(ApiPath(FileName)))
  2518. {
  2519. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  2520. }
  2521. }
  2522. //---------------------------------------------------------------------------
  2523. unsigned int __fastcall CancelAnswer(unsigned int Answers)
  2524. {
  2525. unsigned int Result;
  2526. if ((Answers & qaCancel) != 0)
  2527. {
  2528. Result = qaCancel;
  2529. }
  2530. else if ((Answers & qaNo) != 0)
  2531. {
  2532. Result = qaNo;
  2533. }
  2534. else if ((Answers & qaAbort) != 0)
  2535. {
  2536. Result = qaAbort;
  2537. }
  2538. else if ((Answers & qaOK) != 0)
  2539. {
  2540. Result = qaOK;
  2541. }
  2542. else
  2543. {
  2544. DebugFail();
  2545. Result = qaCancel;
  2546. }
  2547. return Result;
  2548. }
  2549. //---------------------------------------------------------------------------
  2550. unsigned int __fastcall AbortAnswer(unsigned int Answers)
  2551. {
  2552. unsigned int Result;
  2553. if (FLAGSET(Answers, qaAbort))
  2554. {
  2555. Result = qaAbort;
  2556. }
  2557. else
  2558. {
  2559. Result = CancelAnswer(Answers);
  2560. }
  2561. return Result;
  2562. }
  2563. //---------------------------------------------------------------------------
  2564. unsigned int __fastcall ContinueAnswer(unsigned int Answers)
  2565. {
  2566. unsigned int Result;
  2567. if (FLAGSET(Answers, qaSkip))
  2568. {
  2569. Result = qaSkip;
  2570. }
  2571. else if (FLAGSET(Answers, qaIgnore))
  2572. {
  2573. Result = qaIgnore;
  2574. }
  2575. else if (FLAGSET(Answers, qaYes))
  2576. {
  2577. Result = qaYes;
  2578. }
  2579. else if (FLAGSET(Answers, qaOK))
  2580. {
  2581. Result = qaOK;
  2582. }
  2583. else if (FLAGSET(Answers, qaRetry))
  2584. {
  2585. Result = qaRetry;
  2586. }
  2587. else
  2588. {
  2589. Result = CancelAnswer(Answers);
  2590. }
  2591. return Result;
  2592. }
  2593. //---------------------------------------------------------------------------
  2594. TLibModule * __fastcall FindModule(void * Instance)
  2595. {
  2596. TLibModule * CurModule;
  2597. CurModule = reinterpret_cast<TLibModule*>(LibModuleList);
  2598. while (CurModule)
  2599. {
  2600. if (CurModule->Instance == (unsigned)Instance)
  2601. {
  2602. break;
  2603. }
  2604. else
  2605. {
  2606. CurModule = CurModule->Next;
  2607. }
  2608. }
  2609. return CurModule;
  2610. }
  2611. //---------------------------------------------------------------------------
  2612. static UnicodeString __fastcall DoLoadStrFrom(HINSTANCE Module, int Ident, unsigned int MaxLength)
  2613. {
  2614. UnicodeString Result;
  2615. Result.SetLength(MaxLength);
  2616. int Length = LoadString(Module, Ident, Result.c_str(), MaxLength);
  2617. Result.SetLength(Length);
  2618. return Result;
  2619. }
  2620. //---------------------------------------------------------------------------
  2621. UnicodeString __fastcall LoadStrFrom(HINSTANCE Module, int Ident)
  2622. {
  2623. // 1024 = what VCL LoadStr limits the string to
  2624. return DoLoadStrFrom(Module, Ident, 1024);
  2625. }
  2626. //---------------------------------------------------------------------------
  2627. UnicodeString __fastcall LoadStr(int Ident, unsigned int MaxLength)
  2628. {
  2629. TLibModule * MainModule = FindModule(HInstance);
  2630. DebugAssert(MainModule != NULL);
  2631. return DoLoadStrFrom((HINSTANCE)MainModule->ResInstance, Ident, MaxLength);
  2632. }
  2633. //---------------------------------------------------------------------------
  2634. UnicodeString __fastcall LoadStrPart(int Ident, int Part)
  2635. {
  2636. UnicodeString Result;
  2637. UnicodeString Str = LoadStr(Ident);
  2638. while (Part > 0)
  2639. {
  2640. Result = CutToChar(Str, L'|', false);
  2641. Part--;
  2642. }
  2643. return Result;
  2644. }
  2645. //---------------------------------------------------------------------------
  2646. UnicodeString __fastcall DecodeUrlChars(UnicodeString S)
  2647. {
  2648. int i = 1;
  2649. while (i <= S.Length())
  2650. {
  2651. switch (S[i])
  2652. {
  2653. case L'+':
  2654. S[i] = ' ';
  2655. break;
  2656. case L'%':
  2657. {
  2658. UnicodeString Hex;
  2659. while ((i + 2 <= S.Length()) && (S[i] == L'%') &&
  2660. IsHex(S[i + 1]) && IsHex(S[i + 2]))
  2661. {
  2662. Hex += S.SubString(i + 1, 2);
  2663. S.Delete(i, 3);
  2664. }
  2665. if (!Hex.IsEmpty())
  2666. {
  2667. RawByteString Bytes = HexToBytes(Hex);
  2668. UnicodeString Chars(UTF8ToString(Bytes));
  2669. S.Insert(Chars, i);
  2670. i += Chars.Length() - 1;
  2671. }
  2672. }
  2673. break;
  2674. }
  2675. i++;
  2676. }
  2677. return S;
  2678. }
  2679. //---------------------------------------------------------------------------
  2680. UnicodeString __fastcall DoEncodeUrl(UnicodeString S, const UnicodeString & DoNotEncode)
  2681. {
  2682. int Index = 1;
  2683. while (Index <= S.Length())
  2684. {
  2685. wchar_t C = S[Index];
  2686. if (IsLetter(C) ||
  2687. IsDigit(C) ||
  2688. (C == L'_') || (C == L'-') || (C == L'.') || (C == L'*') ||
  2689. (DoNotEncode.Pos(C) > 0))
  2690. {
  2691. Index++;
  2692. }
  2693. else
  2694. {
  2695. UTF8String UtfS(S.SubString(Index, 1));
  2696. UnicodeString H;
  2697. // BytesToHex with separator would do the same
  2698. for (int Index2 = 1; Index2 <= UtfS.Length(); Index2++)
  2699. {
  2700. H += L"%" + ByteToHex(static_cast<unsigned char>(UtfS[Index2]));
  2701. }
  2702. S.Delete(Index, 1);
  2703. S.Insert(H, Index);
  2704. Index += H.Length();
  2705. }
  2706. }
  2707. return S;
  2708. }
  2709. //---------------------------------------------------------------------------
  2710. UnicodeString __fastcall EncodeUrlString(UnicodeString S)
  2711. {
  2712. return DoEncodeUrl(S, UnicodeString());
  2713. }
  2714. //---------------------------------------------------------------------------
  2715. UnicodeString __fastcall EncodeUrlPath(UnicodeString S)
  2716. {
  2717. return DoEncodeUrl(S, L"/");
  2718. }
  2719. //---------------------------------------------------------------------------
  2720. UnicodeString __fastcall AppendUrlParams(UnicodeString AURL, UnicodeString Params)
  2721. {
  2722. // see also TWebHelpSystem::ShowHelp
  2723. const wchar_t FragmentSeparator = L'#';
  2724. UnicodeString URL = CutToChar(AURL, FragmentSeparator, false);
  2725. if (URL.Pos(L"?") == 0)
  2726. {
  2727. URL += L"?";
  2728. }
  2729. else
  2730. {
  2731. URL += L"&";
  2732. }
  2733. URL += Params;
  2734. AddToList(URL, AURL, FragmentSeparator);
  2735. return URL;
  2736. }
  2737. //---------------------------------------------------------------------------
  2738. UnicodeString __fastcall ExtractFileNameFromUrl(const UnicodeString & Url)
  2739. {
  2740. UnicodeString Result = Url;
  2741. int P = Result.Pos(L"?");
  2742. if (P > 0)
  2743. {
  2744. Result.SetLength(P - 1);
  2745. }
  2746. P = Result.LastDelimiter("/");
  2747. if (DebugAlwaysTrue(P > 0))
  2748. {
  2749. Result.Delete(1, P);
  2750. }
  2751. return Result;
  2752. }
  2753. //---------------------------------------------------------------------
  2754. bool IsDomainOrSubdomain(const UnicodeString & FullDomain, const UnicodeString & Domain)
  2755. {
  2756. return
  2757. SameText(FullDomain, Domain) ||
  2758. EndsText(L"." + Domain, FullDomain);
  2759. }
  2760. //---------------------------------------------------------------------------
  2761. UnicodeString __fastcall EscapeHotkey(const UnicodeString & Caption)
  2762. {
  2763. return ReplaceStr(Caption, L"&", L"&&");
  2764. }
  2765. //---------------------------------------------------------------------------
  2766. // duplicated in console's Main.cpp
  2767. static bool __fastcall DoCutToken(UnicodeString & Str, UnicodeString & Token,
  2768. UnicodeString * RawToken, UnicodeString * Separator, bool EscapeQuotesInQuotesOnly)
  2769. {
  2770. bool Result;
  2771. Token = L"";
  2772. // inspired by Putty's sftp_getcmd() from PSFTP.C
  2773. int Index = 1;
  2774. while ((Index <= Str.Length()) &&
  2775. ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2776. {
  2777. Index++;
  2778. }
  2779. if (Index <= Str.Length())
  2780. {
  2781. bool Quoting = false;
  2782. while (Index <= Str.Length())
  2783. {
  2784. if (!Quoting && ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2785. {
  2786. break;
  2787. }
  2788. // With EscapeQuotesInQuotesOnly we escape quotes only within quotes
  2789. // otherwise the "" means " (quote), but it should mean empty string.
  2790. else if ((Str[Index] == L'"') && (Index + 1 <= Str.Length()) &&
  2791. (Str[Index + 1] == L'"') && (!EscapeQuotesInQuotesOnly || Quoting))
  2792. {
  2793. Index += 2;
  2794. Token += L'"';
  2795. }
  2796. else if (Str[Index] == L'"')
  2797. {
  2798. Index++;
  2799. Quoting = !Quoting;
  2800. }
  2801. else
  2802. {
  2803. Token += Str[Index];
  2804. Index++;
  2805. }
  2806. }
  2807. if (RawToken != NULL)
  2808. {
  2809. (*RawToken) = Str.SubString(1, Index - 1);
  2810. }
  2811. if (Index <= Str.Length())
  2812. {
  2813. if (Separator != NULL)
  2814. {
  2815. *Separator = Str.SubString(Index, 1);
  2816. }
  2817. Index++;
  2818. }
  2819. else
  2820. {
  2821. if (Separator != NULL)
  2822. {
  2823. *Separator = UnicodeString();
  2824. }
  2825. }
  2826. Str = Str.SubString(Index, Str.Length());
  2827. Result = true;
  2828. }
  2829. else
  2830. {
  2831. Result = false;
  2832. Str = L"";
  2833. }
  2834. return Result;
  2835. }
  2836. //---------------------------------------------------------------------------
  2837. bool __fastcall CutToken(UnicodeString & Str, UnicodeString & Token,
  2838. UnicodeString * RawToken, UnicodeString * Separator)
  2839. {
  2840. return DoCutToken(Str, Token, RawToken, Separator, false);
  2841. }
  2842. //---------------------------------------------------------------------------
  2843. bool __fastcall CutTokenEx(UnicodeString & Str, UnicodeString & Token,
  2844. UnicodeString * RawToken, UnicodeString * Separator)
  2845. {
  2846. return DoCutToken(Str, Token, RawToken, Separator, true);
  2847. }
  2848. //---------------------------------------------------------------------------
  2849. void __fastcall AddToList(UnicodeString & List, const UnicodeString & Value, const UnicodeString & Delimiter)
  2850. {
  2851. if (!Value.IsEmpty())
  2852. {
  2853. if (!List.IsEmpty() &&
  2854. ((List.Length() < Delimiter.Length()) ||
  2855. (List.SubString(List.Length() - Delimiter.Length() + 1, Delimiter.Length()) != Delimiter)))
  2856. {
  2857. List += Delimiter;
  2858. }
  2859. List += Value;
  2860. }
  2861. }
  2862. //---------------------------------------------------------------------------
  2863. void AddToShellFileListCommandLine(UnicodeString & List, const UnicodeString & Value)
  2864. {
  2865. UnicodeString Arg = ShellQuoteStr(Value);
  2866. AddToList(List, Arg, L" ");
  2867. }
  2868. //---------------------------------------------------------------------------
  2869. bool IsWin64()
  2870. {
  2871. static int Result = -1;
  2872. if (Result < 0)
  2873. {
  2874. Result = 0;
  2875. BOOL Wow64Process = FALSE;
  2876. if (IsWow64Process(GetCurrentProcess(), &Wow64Process))
  2877. {
  2878. if (Wow64Process)
  2879. {
  2880. Result = 1;
  2881. }
  2882. }
  2883. }
  2884. return (Result > 0);
  2885. }
  2886. //---------------------------------------------------------------------------
  2887. bool __fastcall IsWin7()
  2888. {
  2889. return CheckWin32Version(6, 1);
  2890. }
  2891. //---------------------------------------------------------------------------
  2892. bool __fastcall IsWin8()
  2893. {
  2894. return CheckWin32Version(6, 2);
  2895. }
  2896. //---------------------------------------------------------------------------
  2897. bool __fastcall IsWin10()
  2898. {
  2899. return CheckWin32Version(10, 0);
  2900. }
  2901. //---------------------------------------------------------------------------
  2902. bool IsWin10Build(int BuildNumber)
  2903. {
  2904. // It might be enough to check the dwBuildNumber, as we do in TWinConfiguration::IsDDExtBroken()
  2905. return IsWin10() && (Win32BuildNumber() >= BuildNumber);
  2906. }
  2907. //---------------------------------------------------------------------------
  2908. bool IsWin11()
  2909. {
  2910. return IsWin10Build(22000);
  2911. }
  2912. //---------------------------------------------------------------------------
  2913. bool __fastcall IsWine()
  2914. {
  2915. HMODULE NtDll = GetModuleHandle(L"ntdll.dll");
  2916. return
  2917. DebugAlwaysTrue(NtDll != NULL) &&
  2918. (GetProcAddress(NtDll, "wine_get_version") != NULL);
  2919. }
  2920. //---------------------------------------------------------------------------
  2921. int GIsUWP = -1;
  2922. UnicodeString GPackageName;
  2923. //---------------------------------------------------------------------------
  2924. void EnableUWPTestMode()
  2925. {
  2926. GIsUWP = 1;
  2927. AppLog(L"UWP test mode");
  2928. }
  2929. //---------------------------------------------------------------------------
  2930. static void NeedUWPData()
  2931. {
  2932. if (GIsUWP < 0)
  2933. {
  2934. GIsUWP = 0;
  2935. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  2936. typedef LONG WINAPI (* GetCurrentPackageFamilyNameProc)(UINT32 * packageFamilyNameLength, PWSTR packageFamilyName);
  2937. GetCurrentPackageFamilyNameProc GetCurrentPackageFamilyName =
  2938. (GetCurrentPackageFamilyNameProc)GetProcAddress(Kernel32, "GetCurrentPackageFamilyName");
  2939. UINT32 NameLen = 0;
  2940. if ((GetCurrentPackageFamilyName != NULL) &&
  2941. (GetCurrentPackageFamilyName(&NameLen, NULL) == ERROR_INSUFFICIENT_BUFFER))
  2942. {
  2943. GIsUWP = 1;
  2944. AppLog(L"Is UWP application");
  2945. GPackageName.SetLength(NameLen);
  2946. if (GetCurrentPackageFamilyName(&NameLen, GPackageName.c_str()) == ERROR_SUCCESS)
  2947. {
  2948. PackStr(GPackageName);
  2949. }
  2950. else
  2951. {
  2952. GPackageName = L"err";
  2953. }
  2954. AppLogFmt(L"Package name: %s", (GPackageName));
  2955. }
  2956. else
  2957. {
  2958. AppLog(L"Is not UWP application");
  2959. }
  2960. }
  2961. }
  2962. //---------------------------------------------------------------------------
  2963. bool __fastcall IsUWP()
  2964. {
  2965. NeedUWPData();
  2966. return (GIsUWP > 0);
  2967. }
  2968. //---------------------------------------------------------------------------
  2969. UnicodeString GetPackageName()
  2970. {
  2971. NeedUWPData();
  2972. return GPackageName;
  2973. }
  2974. //---------------------------------------------------------------------------
  2975. bool IsOfficialPackage()
  2976. {
  2977. return (GetPackageName() == OfficialPackage);
  2978. }
  2979. //---------------------------------------------------------------------------
  2980. LCID __fastcall GetDefaultLCID()
  2981. {
  2982. return GetUserDefaultLCID();
  2983. }
  2984. //---------------------------------------------------------------------------
  2985. static UnicodeString ADefaultEncodingName;
  2986. UnicodeString __fastcall DefaultEncodingName()
  2987. {
  2988. if (ADefaultEncodingName.IsEmpty())
  2989. {
  2990. CPINFOEX Info;
  2991. GetCPInfoEx(CP_ACP, 0, &Info);
  2992. ADefaultEncodingName = Info.CodePageName;
  2993. }
  2994. return ADefaultEncodingName;
  2995. }
  2996. //---------------------------------------------------------------------------
  2997. DWORD GetWindowsProductType()
  2998. {
  2999. DWORD Result = 0;
  3000. GetProductInfo(Win32MajorVersion(), Win32MinorVersion(), 0, 0, &Result);
  3001. return Result;
  3002. }
  3003. //---------------------------------------------------------------------------
  3004. UnicodeString __fastcall WindowsProductName()
  3005. {
  3006. UnicodeString Result;
  3007. // On Windows 11 "ProductName" is still "Windows 10"
  3008. if (IsWin11())
  3009. {
  3010. Result = L"Windows 11"; // fallback value
  3011. HMODULE WinBrandLib = LoadLibrary(L"winbrand.dll");
  3012. if (WinBrandLib != NULL)
  3013. {
  3014. typedef LPWSTR WINAPI (* TBrandingFormatString)(LPCWSTR);
  3015. TBrandingFormatString BrandingFormatString =
  3016. reinterpret_cast<TBrandingFormatString>(GetProcAddress(WinBrandLib, "BrandingFormatString"));
  3017. if (BrandingFormatString != NULL)
  3018. {
  3019. LPWSTR Brand = BrandingFormatString(L"%WINDOWS_LONG%");
  3020. if (Brand != NULL)
  3021. {
  3022. Result = Brand;
  3023. GlobalFree(Brand);
  3024. }
  3025. }
  3026. FreeLibrary(WinBrandLib);
  3027. }
  3028. }
  3029. else
  3030. {
  3031. try
  3032. {
  3033. // JCL GetWindowsProductName claims that reading 64-bit key gets correct values, but on Windows 11, neither works
  3034. unsigned int Access = KEY_READ | FLAGMASK(IsWin64(), KEY_WOW64_64KEY);
  3035. std::unique_ptr<TRegistry> Registry(new TRegistry(Access));
  3036. Registry->RootKey = HKEY_LOCAL_MACHINE;
  3037. if (Registry->OpenKey(L"SOFTWARE", false) &&
  3038. Registry->OpenKey(L"Microsoft", false) &&
  3039. Registry->OpenKey(L"Windows NT", false) &&
  3040. Registry->OpenKey(L"CurrentVersion", false))
  3041. {
  3042. Result = Registry->ReadString(L"ProductName");
  3043. }
  3044. }
  3045. catch(...)
  3046. {
  3047. }
  3048. }
  3049. return Result;
  3050. }
  3051. //---------------------------------------------------------------------------
  3052. UnicodeString __fastcall WindowsVersion()
  3053. {
  3054. UnicodeString Result = FORMAT(L"%d.%d.%d", (Win32MajorVersion(), Win32MinorVersion(), Win32BuildNumber()));
  3055. return Result;
  3056. }
  3057. //---------------------------------------------------------------------------
  3058. UnicodeString __fastcall WindowsVersionLong()
  3059. {
  3060. UnicodeString Result = WindowsVersion();
  3061. AddToList(Result, Win32CSDVersion(), L" ");
  3062. return Result;
  3063. }
  3064. //---------------------------------------------------------------------------
  3065. bool __fastcall IsDirectoryWriteable(const UnicodeString & Path)
  3066. {
  3067. UnicodeString FileName =
  3068. IncludeTrailingPathDelimiter(Path) +
  3069. FORMAT(L"wscp_%s_%d.tmp", (FormatDateTime(L"nnzzz", Now()), int(GetCurrentProcessId())));
  3070. HANDLE Handle = CreateFile(ApiPath(FileName).c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL,
  3071. CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, 0);
  3072. bool Result = (Handle != INVALID_HANDLE_VALUE);
  3073. if (Result)
  3074. {
  3075. CloseHandle(Handle);
  3076. }
  3077. return Result;
  3078. }
  3079. //---------------------------------------------------------------------------
  3080. UnicodeString __fastcall FormatNumber(__int64 Number)
  3081. {
  3082. return FormatFloat(L"#,##0", Number);
  3083. }
  3084. //---------------------------------------------------------------------------
  3085. // simple alternative to FormatBytes
  3086. UnicodeString __fastcall FormatSize(__int64 Size)
  3087. {
  3088. return FormatNumber(Size);
  3089. }
  3090. //---------------------------------------------------------------------------
  3091. UnicodeString FormatDateTimeSpan(const TDateTime & DateTime)
  3092. {
  3093. UnicodeString Result;
  3094. if ((0 <= DateTime) && (DateTime <= MaxDateTime))
  3095. {
  3096. TTimeStamp TimeStamp = DateTimeToTimeStamp(DateTime);
  3097. int Days = TimeStamp.Date - DateDelta;
  3098. if (abs(Days) >= 4)
  3099. {
  3100. Result = FMTLOAD(DAYS_SPAN, (Days));
  3101. }
  3102. else
  3103. {
  3104. unsigned short Hour, Min, Sec, Dummy;
  3105. DecodeTime(DateTime, Hour, Min, Sec, Dummy);
  3106. int TotalHours = static_cast<int>(Hour) + (Days * HoursPerDay);
  3107. Result = FORMAT(L"%d%s%.2d%s%.2d", (TotalHours, FormatSettings.TimeSeparator, Min, FormatSettings.TimeSeparator, Sec));
  3108. }
  3109. }
  3110. return Result;
  3111. }
  3112. //---------------------------------------------------------------------------
  3113. UnicodeString FormatRelativeTime(const TDateTime & ANow, const TDateTime & AThen, bool DateOnly)
  3114. {
  3115. UnicodeString Result;
  3116. if (DateOnly)
  3117. {
  3118. if (IsSameDay(AThen, ANow - 1))
  3119. {
  3120. Result = LoadStrPart(TIME_RELATIVE, 3);
  3121. }
  3122. else if (IsSameDay(AThen, ANow))
  3123. {
  3124. Result = LoadStrPart(TIME_RELATIVE, 2);
  3125. }
  3126. }
  3127. if (Result.IsEmpty())
  3128. {
  3129. int Part, Num;
  3130. Num = YearsBetween(ANow, AThen);
  3131. if (Num > 1)
  3132. {
  3133. Part = 18;
  3134. }
  3135. else if (Num == 1)
  3136. {
  3137. Part = 17;
  3138. }
  3139. else
  3140. {
  3141. Num = MonthsBetween(ANow, AThen);
  3142. if (Num > 1)
  3143. {
  3144. Part = 16;
  3145. }
  3146. else if (Num == 1)
  3147. {
  3148. Part = 15;
  3149. }
  3150. else
  3151. {
  3152. Num = DaysBetween(ANow, AThen);
  3153. if (Num > 1)
  3154. {
  3155. Part = 12;
  3156. }
  3157. else if (Num == 1)
  3158. {
  3159. Part = 11;
  3160. }
  3161. else
  3162. {
  3163. Num = static_cast<int>(HoursBetween(ANow, AThen));
  3164. if (Num > 1)
  3165. {
  3166. Part = 10;
  3167. }
  3168. else if (Num == 1)
  3169. {
  3170. Part = 9;
  3171. }
  3172. else
  3173. {
  3174. Num = static_cast<int>(MinutesBetween(ANow, AThen));
  3175. if (Num > 1)
  3176. {
  3177. Part = 8;
  3178. }
  3179. else if (Num == 1)
  3180. {
  3181. Part = 7;
  3182. }
  3183. else
  3184. {
  3185. Num = static_cast<int>(SecondsBetween(ANow, AThen));
  3186. if (Num > 1)
  3187. {
  3188. Part = 6;
  3189. }
  3190. else if (Num == 1)
  3191. {
  3192. Part = 5;
  3193. }
  3194. else if (Num == 0)
  3195. {
  3196. Part = 1;
  3197. }
  3198. else
  3199. {
  3200. DebugFail();
  3201. Part = -1;
  3202. }
  3203. }
  3204. }
  3205. }
  3206. }
  3207. }
  3208. if (DebugAlwaysTrue(Part >= 0))
  3209. {
  3210. Result = FORMAT(LoadStrPart(TIME_RELATIVE, Part), (abs(Num)));
  3211. }
  3212. else
  3213. {
  3214. Result = FormatDateTime(L"ddddd", AThen);
  3215. }
  3216. }
  3217. return Result;
  3218. }
  3219. //---------------------------------------------------------------------------
  3220. UnicodeString __fastcall ExtractFileBaseName(const UnicodeString & Path)
  3221. {
  3222. return ChangeFileExt(ExtractFileName(Path), L"");
  3223. }
  3224. //---------------------------------------------------------------------------
  3225. TStringList * __fastcall TextToStringList(const UnicodeString & Text)
  3226. {
  3227. std::unique_ptr<TStringList> List(new TStringList());
  3228. List->Text = Text;
  3229. return List.release();
  3230. }
  3231. //---------------------------------------------------------------------------
  3232. UnicodeString __fastcall StringsToText(TStrings * Strings)
  3233. {
  3234. UnicodeString Result;
  3235. if (Strings->Count == 1)
  3236. {
  3237. Result = Strings->Strings[0];
  3238. }
  3239. else
  3240. {
  3241. Result = Strings->Text;
  3242. }
  3243. return Result;
  3244. }
  3245. //---------------------------------------------------------------------------
  3246. TStringList * __fastcall CommaTextToStringList(const UnicodeString & CommaText)
  3247. {
  3248. std::unique_ptr<TStringList> List(new TStringList());
  3249. List->CommaText = CommaText;
  3250. return List.release();
  3251. }
  3252. //---------------------------------------------------------------------------
  3253. TStrings * __fastcall CloneStrings(TStrings * Strings)
  3254. {
  3255. std::unique_ptr<TStringList> List(new TStringList());
  3256. List->AddStrings(Strings);
  3257. return List.release();
  3258. }
  3259. //---------------------------------------------------------------------------
  3260. UnicodeString __fastcall TrimVersion(UnicodeString Version)
  3261. {
  3262. while ((Version.Pos(L".") != Version.LastDelimiter(L".")) &&
  3263. (Version.SubString(Version.Length() - 1, 2) == L".0"))
  3264. {
  3265. Version.SetLength(Version.Length() - 2);
  3266. }
  3267. return Version;
  3268. }
  3269. //---------------------------------------------------------------------------
  3270. UnicodeString __fastcall FormatVersion(int MajorVersion, int MinorVersion, int Release)
  3271. {
  3272. return
  3273. TrimVersion(FORMAT(L"%d.%d.%d",
  3274. (MajorVersion, MinorVersion, Release)));
  3275. }
  3276. //---------------------------------------------------------------------------
  3277. TFormatSettings __fastcall GetEngFormatSettings()
  3278. {
  3279. return TFormatSettings::Create((TLocaleID)1033);
  3280. }
  3281. //---------------------------------------------------------------------------
  3282. int __fastcall ParseShortEngMonthName(const UnicodeString & MonthStr)
  3283. {
  3284. TFormatSettings FormatSettings = GetEngFormatSettings();
  3285. return IndexStr(MonthStr, FormatSettings.ShortMonthNames, FormatSettings.ShortMonthNames.Size()) + 1;
  3286. }
  3287. //---------------------------------------------------------------------------
  3288. TStringList * __fastcall CreateSortedStringList(bool CaseSensitive, System::Types::TDuplicates Duplicates)
  3289. {
  3290. TStringList * Result = new TStringList();
  3291. Result->CaseSensitive = CaseSensitive;
  3292. Result->Sorted = true;
  3293. Result->Duplicates = Duplicates;
  3294. return Result;
  3295. }
  3296. //---------------------------------------------------------------------------
  3297. bool SameIdent(const UnicodeString & Ident1, const UnicodeString & Ident2)
  3298. {
  3299. const UnicodeString Dash(L"-");
  3300. return SameText(ReplaceStr(Ident1, Dash, EmptyStr), ReplaceStr(Ident2, Dash, EmptyStr));
  3301. }
  3302. //---------------------------------------------------------------------------
  3303. UnicodeString __fastcall FindIdent(const UnicodeString & Ident, TStrings * Idents)
  3304. {
  3305. for (int Index = 0; Index < Idents->Count; Index++)
  3306. {
  3307. if (SameIdent(Ident, Idents->Strings[Index]))
  3308. {
  3309. return Idents->Strings[Index];
  3310. }
  3311. }
  3312. return Ident;
  3313. }
  3314. //---------------------------------------------------------------------------
  3315. UnicodeString GetTlsErrorStr(unsigned long Err)
  3316. {
  3317. char Buffer[512];
  3318. ERR_error_string_n(Err, Buffer, sizeof(Buffer));
  3319. UnicodeString S = UnicodeString(UTF8String(Buffer));
  3320. for (int I = 0; I < 4; I++)
  3321. {
  3322. CutToChar(S, L':', false);
  3323. }
  3324. UnicodeString ErrStr = IntToHex(static_cast<unsigned int>(Err));
  3325. return FORMAT(L"OpenSSL %s: %s", (ErrStr, S.TrimRight()));
  3326. }
  3327. //---------------------------------------------------------------------------
  3328. UnicodeString GetTlsErrorStrs()
  3329. {
  3330. UnicodeString Result;
  3331. int Error;
  3332. const char * Data;
  3333. while ((Error = ERR_get_error_all(NULL, NULL, NULL, &Data, NULL)) != 0)
  3334. {
  3335. UnicodeString S = GetTlsErrorStr(Error);
  3336. if ((Data != NULL) && (strlen(Data) > 0))
  3337. {
  3338. UnicodeString DataStr = UnicodeString(UTF8String(Data)).TrimRight();
  3339. S += FORMAT(L" (%s)", (DataStr));
  3340. }
  3341. AddToList(Result, S, L"\n");
  3342. }
  3343. return Result;
  3344. }
  3345. //---------------------------------------------------------------------------
  3346. static FILE * __fastcall OpenCertificate(const UnicodeString & Path)
  3347. {
  3348. FILE * Result = _wfopen(ApiPath(Path).c_str(), L"rb");
  3349. if (Result == NULL)
  3350. {
  3351. int Error = errno;
  3352. throw EOSExtException(MainInstructions(FMTLOAD(CERTIFICATE_OPEN_ERROR, (Path))), Error);
  3353. }
  3354. return Result;
  3355. }
  3356. //---------------------------------------------------------------------------
  3357. struct TPemPasswordCallbackData
  3358. {
  3359. UnicodeString * Passphrase;
  3360. };
  3361. //---------------------------------------------------------------------------
  3362. static int PemPasswordCallback(char * Buf, int Size, int /*RWFlag*/, void * UserData)
  3363. {
  3364. TPemPasswordCallbackData & Data = *reinterpret_cast<TPemPasswordCallbackData *>(UserData);
  3365. UTF8String UtfPassphrase = UTF8String(*Data.Passphrase);
  3366. strncpy(Buf, UtfPassphrase.c_str(), Size);
  3367. Shred(UtfPassphrase);
  3368. Buf[Size - 1] = '\0';
  3369. return strlen(Buf);
  3370. }
  3371. //---------------------------------------------------------------------------
  3372. static bool __fastcall IsTlsPassphraseError(unsigned long Error, bool HasPassphrase)
  3373. {
  3374. int ErrorLib = ERR_GET_LIB(Error);
  3375. int ErrorReason = ERR_GET_REASON(Error);
  3376. bool Result =
  3377. ((ErrorLib == ERR_LIB_PKCS12) &&
  3378. (ErrorReason == PKCS12_R_MAC_VERIFY_FAILURE)) ||
  3379. ((ErrorLib == ERR_LIB_PEM) &&
  3380. (ErrorReason == PEM_R_BAD_PASSWORD_READ)) ||
  3381. (HasPassphrase && (ERR_LIB_EVP == ERR_LIB_EVP) &&
  3382. ((ErrorReason == PEM_R_BAD_DECRYPT) || (ErrorReason == PEM_R_BAD_BASE64_DECODE)));
  3383. return Result;
  3384. }
  3385. //---------------------------------------------------------------------------
  3386. static void __fastcall ThrowTlsCertificateErrorIgnorePassphraseErrors(const UnicodeString & Path, bool HasPassphrase)
  3387. {
  3388. unsigned long Error = ERR_get_error();
  3389. if (!IsTlsPassphraseError(Error, HasPassphrase))
  3390. {
  3391. throw ExtException(MainInstructions(FMTLOAD(CERTIFICATE_READ_ERROR, (Path))), GetTlsErrorStr(Error));
  3392. }
  3393. }
  3394. //---------------------------------------------------------------------------
  3395. void __fastcall ParseCertificate(const UnicodeString & Path,
  3396. const UnicodeString & Passphrase, X509 *& Certificate, EVP_PKEY *& PrivateKey,
  3397. bool & WrongPassphrase)
  3398. {
  3399. Certificate = NULL;
  3400. PrivateKey = NULL;
  3401. WrongPassphrase = false;
  3402. bool Discard = false;
  3403. try
  3404. {
  3405. try
  3406. {
  3407. bool HasPassphrase = !Passphrase.IsEmpty();
  3408. FILE * File;
  3409. // Inspired by neon's ne_ssl_clicert_read
  3410. File = OpenCertificate(Path);
  3411. // openssl pkcs12 -inkey cert.pem -in cert.crt -export -out cert.pfx
  3412. // Binary file
  3413. PKCS12 * Pkcs12 = d2i_PKCS12_fp(File, NULL);
  3414. fclose(File);
  3415. if (Pkcs12 != NULL)
  3416. {
  3417. UTF8String PassphraseUtf(Passphrase);
  3418. bool Result =
  3419. (PKCS12_parse(Pkcs12, PassphraseUtf.c_str(), &PrivateKey, &Certificate, NULL) == 1);
  3420. PKCS12_free(Pkcs12);
  3421. if (!Result)
  3422. {
  3423. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path, HasPassphrase);
  3424. WrongPassphrase = true;
  3425. }
  3426. if (!WrongPassphrase && (PrivateKey == NULL))
  3427. {
  3428. throw Exception(FMTLOAD(NO_PRIVATE_KEY, (Path)));
  3429. }
  3430. }
  3431. else
  3432. {
  3433. ERR_clear_error();
  3434. TPemPasswordCallbackData CallbackUserData;
  3435. // PemPasswordCallback never writes to the .Passphrase
  3436. CallbackUserData.Passphrase = const_cast<UnicodeString *>(&Passphrase);
  3437. File = OpenCertificate(Path);
  3438. // Encrypted:
  3439. // openssl req -x509 -newkey rsa:2048 -keyout cert.pem -out cert.crt
  3440. // -----BEGIN ENCRYPTED PRIVATE KEY-----
  3441. // ...
  3442. // -----END ENCRYPTED PRIVATE KEY-----
  3443. // Not encrypted (add -nodes):
  3444. // -----BEGIN PRIVATE KEY-----
  3445. // ...
  3446. // -----END PRIVATE KEY-----
  3447. // Or (openssl genrsa -out client.key 1024 # used for certificate signing request)
  3448. // -----BEGIN RSA PRIVATE KEY-----
  3449. // ...
  3450. // -----END RSA PRIVATE KEY-----
  3451. PrivateKey = PEM_read_PrivateKey(File, NULL, PemPasswordCallback, &CallbackUserData);
  3452. fclose(File);
  3453. if (PrivateKey == NULL)
  3454. {
  3455. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path, HasPassphrase);
  3456. WrongPassphrase = true;
  3457. }
  3458. File = OpenCertificate(Path);
  3459. // The file can contain both private and public key
  3460. // (basically cert.pem and cert.crt appended one to each other)
  3461. // -----BEGIN ENCRYPTED PRIVATE KEY-----
  3462. // ...
  3463. // -----END ENCRYPTED PRIVATE KEY-----
  3464. // -----BEGIN CERTIFICATE-----
  3465. // ...
  3466. // -----END CERTIFICATE-----
  3467. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  3468. fclose(File);
  3469. if (Certificate == NULL)
  3470. {
  3471. unsigned long Error = ERR_get_error();
  3472. // unlikely
  3473. if (IsTlsPassphraseError(Error, HasPassphrase))
  3474. {
  3475. WrongPassphrase = true;
  3476. }
  3477. else
  3478. {
  3479. UnicodeString CertificatePath = ChangeFileExt(Path, L".cer");
  3480. if (!FileExists(CertificatePath))
  3481. {
  3482. CertificatePath = ChangeFileExt(Path, L".crt");
  3483. }
  3484. if (!FileExists(CertificatePath))
  3485. {
  3486. throw Exception(MainInstructions(FMTLOAD(CERTIFICATE_PUBLIC_KEY_NOT_FOUND, (Path))));
  3487. }
  3488. else
  3489. {
  3490. File = OpenCertificate(CertificatePath);
  3491. // -----BEGIN CERTIFICATE-----
  3492. // ...
  3493. // -----END CERTIFICATE-----
  3494. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  3495. fclose(File);
  3496. if (Certificate == NULL)
  3497. {
  3498. unsigned long Base64Error = ERR_get_error();
  3499. File = OpenCertificate(CertificatePath);
  3500. // Binary DER-encoded certificate
  3501. // (as above, with BEGIN/END removed, and decoded from Base64 to binary)
  3502. // openssl x509 -in cert.crt -out client.der.crt -outform DER
  3503. Certificate = d2i_X509_fp(File, NULL);
  3504. fclose(File);
  3505. if (Certificate == NULL)
  3506. {
  3507. unsigned long DERError = ERR_get_error();
  3508. UnicodeString Message = MainInstructions(FMTLOAD(CERTIFICATE_READ_ERROR, (CertificatePath)));
  3509. UnicodeString MoreMessages =
  3510. FORMAT(L"Base64: %s\nDER: %s", (GetTlsErrorStr(Base64Error), GetTlsErrorStr(DERError)));
  3511. throw ExtException(Message, MoreMessages);
  3512. }
  3513. }
  3514. }
  3515. }
  3516. }
  3517. }
  3518. }
  3519. catch (...)
  3520. {
  3521. Discard = true;
  3522. throw;
  3523. }
  3524. }
  3525. __finally
  3526. {
  3527. if (Discard || WrongPassphrase)
  3528. {
  3529. if (PrivateKey != NULL)
  3530. {
  3531. EVP_PKEY_free(PrivateKey);
  3532. PrivateKey = NULL;
  3533. }
  3534. if (Certificate != NULL)
  3535. {
  3536. X509_free(Certificate);
  3537. Certificate = NULL;
  3538. }
  3539. }
  3540. }
  3541. }
  3542. //---------------------------------------------------------------------------
  3543. void __fastcall CheckCertificate(const UnicodeString & Path)
  3544. {
  3545. X509 * Certificate;
  3546. EVP_PKEY * PrivateKey;
  3547. bool WrongPassphrase;
  3548. ParseCertificate(Path, L"", Certificate, PrivateKey, WrongPassphrase);
  3549. if (PrivateKey != NULL)
  3550. {
  3551. EVP_PKEY_free(PrivateKey);
  3552. }
  3553. if (Certificate != NULL)
  3554. {
  3555. X509_free(Certificate);
  3556. }
  3557. }
  3558. //---------------------------------------------------------------------------
  3559. const UnicodeString HttpProtocol(L"http");
  3560. const UnicodeString HttpsProtocol(L"https");
  3561. const UnicodeString ProtocolSeparator(L"://");
  3562. //---------------------------------------------------------------------------
  3563. bool __fastcall IsHttpUrl(const UnicodeString & S)
  3564. {
  3565. return StartsText(HttpProtocol + ProtocolSeparator, S);
  3566. }
  3567. //---------------------------------------------------------------------------
  3568. bool __fastcall IsHttpOrHttpsUrl(const UnicodeString & S)
  3569. {
  3570. return
  3571. IsHttpUrl(S) ||
  3572. StartsText(HttpsProtocol + ProtocolSeparator, S);
  3573. }
  3574. //---------------------------------------------------------------------------
  3575. UnicodeString __fastcall ChangeUrlProtocol(const UnicodeString & S, const UnicodeString & Protocol)
  3576. {
  3577. int P = S.Pos(ProtocolSeparator);
  3578. DebugAssert(P > 0);
  3579. return Protocol + ProtocolSeparator + RightStr(S, S.Length() - P - ProtocolSeparator.Length() + 1);
  3580. }
  3581. //---------------------------------------------------------------------------
  3582. const UnicodeString RtfPara(TraceInitStr(L"\\par\n"));
  3583. const UnicodeString AssemblyNamespace(TraceInitStr(L"WinSCP"));
  3584. const UnicodeString TransferOptionsClassName(TraceInitStr(L"TransferOptions"));
  3585. const UnicodeString SessionClassName(TraceInitStr(L"Session"));
  3586. const UnicodeString RtfHyperlinkField(TraceInitStr(L"HYPERLINK"));
  3587. const UnicodeString RtfHyperlinkFieldPrefix(TraceInitStr(RtfHyperlinkField + L" \""));
  3588. const UnicodeString RtfHyperlinkFieldSuffix(TraceInitStr(L"\" "));
  3589. //---------------------------------------------------------------------
  3590. UnicodeString __fastcall RtfColor(int Index)
  3591. {
  3592. return FORMAT(L"\\cf%d", (Index));
  3593. }
  3594. //---------------------------------------------------------------------
  3595. UnicodeString __fastcall RtfText(const UnicodeString & Text, bool Rtf)
  3596. {
  3597. UnicodeString Result = Text;
  3598. if (Rtf)
  3599. {
  3600. int Index = 1;
  3601. while (Index <= Result.Length())
  3602. {
  3603. UnicodeString Replacement;
  3604. wchar_t Ch = Result[Index];
  3605. if ((Ch == L'\\') || (Ch == L'{') || (Ch == L'}'))
  3606. {
  3607. Replacement = FORMAT(L"\\%s", (Ch));
  3608. }
  3609. else if (Ch >= 0x0080)
  3610. {
  3611. Replacement = FORMAT(L"\\u%d?", (int(Ch)));
  3612. }
  3613. if (!Replacement.IsEmpty())
  3614. {
  3615. Result.Delete(Index, 1);
  3616. Result.Insert(Replacement, Index);
  3617. Index += Replacement.Length();
  3618. }
  3619. else
  3620. {
  3621. Index++;
  3622. }
  3623. }
  3624. }
  3625. return Result;
  3626. }
  3627. //---------------------------------------------------------------------
  3628. UnicodeString __fastcall RtfColorText(int Color, const UnicodeString & Text)
  3629. {
  3630. return RtfColor(Color) + L" " + RtfText(Text) + RtfColor(0) + L" ";
  3631. }
  3632. //---------------------------------------------------------------------
  3633. UnicodeString __fastcall RtfColorItalicText(int Color, const UnicodeString & Text)
  3634. {
  3635. return RtfColor(Color) + L"\\i " + RtfText(Text) + L"\\i0" + RtfColor(0) + L" ";
  3636. }
  3637. //---------------------------------------------------------------------
  3638. UnicodeString __fastcall RtfOverrideColorText(const UnicodeString & Text)
  3639. {
  3640. return RtfColorText(1, Text);
  3641. }
  3642. //---------------------------------------------------------------------
  3643. UnicodeString __fastcall RtfKeyword(const UnicodeString & Text)
  3644. {
  3645. return RtfColorText(5, Text);
  3646. }
  3647. //---------------------------------------------------------------------
  3648. UnicodeString __fastcall RtfParameter(const UnicodeString & Text)
  3649. {
  3650. return RtfColorText(6, Text);
  3651. }
  3652. //---------------------------------------------------------------------
  3653. UnicodeString __fastcall RtfString(const UnicodeString & Text)
  3654. {
  3655. return RtfColorText(4, Text);
  3656. }
  3657. //---------------------------------------------------------------------
  3658. UnicodeString __fastcall RtfLink(const UnicodeString & Link, const UnicodeString & RtfText)
  3659. {
  3660. return
  3661. L"{\\field{\\*\\fldinst{" + RtfHyperlinkFieldPrefix + Link + RtfHyperlinkFieldSuffix + L"}}{\\fldrslt{" +
  3662. RtfText + L"}}}";
  3663. }
  3664. //---------------------------------------------------------------------
  3665. UnicodeString __fastcall ScriptCommandLink(const UnicodeString & Command)
  3666. {
  3667. return L"scriptcommand_" + Command;
  3668. }
  3669. //---------------------------------------------------------------------
  3670. UnicodeString __fastcall RtfSwitch(
  3671. const UnicodeString & Switch, const UnicodeString & Link, bool Rtf)
  3672. {
  3673. UnicodeString Result = FORMAT(L"-%s", (Switch));
  3674. if (Rtf)
  3675. {
  3676. Result = RtfLink(Link + L"#" + Switch.LowerCase(), RtfParameter(Result));
  3677. }
  3678. return L" " + Result;
  3679. }
  3680. //---------------------------------------------------------------------
  3681. UnicodeString __fastcall RtfSwitchValue(
  3682. const UnicodeString & Name, const UnicodeString & Link, const UnicodeString & Value, bool Rtf)
  3683. {
  3684. return RtfSwitch(Name, Link, Rtf) + L"=" + Value;
  3685. }
  3686. //---------------------------------------------------------------------
  3687. UnicodeString __fastcall RtfSwitch(
  3688. const UnicodeString & Name, const UnicodeString & Link, const UnicodeString & Value, bool Rtf)
  3689. {
  3690. return RtfSwitchValue(Name, Link, RtfText(FORMAT("\"%s\"", (EscapeParam(Value))), Rtf), Rtf);
  3691. }
  3692. //---------------------------------------------------------------------
  3693. UnicodeString __fastcall RtfSwitch(
  3694. const UnicodeString & Name, const UnicodeString & Link, int Value, bool Rtf)
  3695. {
  3696. return RtfSwitchValue(Name, Link, RtfText(IntToStr(Value), Rtf), Rtf);
  3697. }
  3698. //---------------------------------------------------------------------
  3699. UnicodeString __fastcall RtfRemoveHyperlinks(UnicodeString Text)
  3700. {
  3701. // Remove all tags HYPERLINK "https://www.example.com".
  3702. // See also RtfEscapeParam
  3703. int Index = 1;
  3704. int P;
  3705. while ((P = PosEx(RtfHyperlinkFieldPrefix, Text, Index)) > 0)
  3706. {
  3707. int Index2 = P + RtfHyperlinkFieldPrefix.Length();
  3708. int P2 = PosEx(RtfHyperlinkFieldSuffix, Text, Index2);
  3709. if (P2 > 0)
  3710. {
  3711. Text.Delete(P, P2 - P + RtfHyperlinkFieldSuffix.Length());
  3712. }
  3713. else
  3714. {
  3715. Index = Index2;
  3716. }
  3717. }
  3718. return Text;
  3719. }
  3720. //---------------------------------------------------------------------
  3721. UnicodeString __fastcall RtfEscapeParam(UnicodeString Param, bool PowerShellEscape)
  3722. {
  3723. const UnicodeString Quote(L"\"");
  3724. UnicodeString Escape(Quote);
  3725. if (PowerShellEscape)
  3726. {
  3727. Escape = "`" + Escape + "`";
  3728. }
  3729. // Equivalent of EscapeParam, except that it does not double quotes in HYPERLINK.
  3730. // See also RtfRemoveHyperlinks.
  3731. int Index = 1;
  3732. while (true)
  3733. {
  3734. int P1 = PosEx(Quote, Param, Index);
  3735. if (P1 == 0)
  3736. {
  3737. // no more quotes
  3738. break;
  3739. }
  3740. else
  3741. {
  3742. int P2 = PosEx(RtfHyperlinkFieldPrefix, Param, Index);
  3743. int P3;
  3744. if ((P2 > 0) && (P2 < P1) && ((P3 = PosEx(RtfHyperlinkFieldSuffix, Param, P2)) > 0))
  3745. {
  3746. // skip HYPERLINK
  3747. Index = P3 + RtfHyperlinkFieldSuffix.Length();
  3748. }
  3749. else
  3750. {
  3751. Param.Insert(Escape, P1);
  3752. Index = P1 + (Escape.Length() + Quote.Length());
  3753. }
  3754. }
  3755. }
  3756. return Param;
  3757. }
  3758. //---------------------------------------------------------------------
  3759. static UnicodeString __fastcall RtfCodeComment(const UnicodeString & Text)
  3760. {
  3761. return RtfColorItalicText(2, Text);
  3762. }
  3763. //---------------------------------------------------------------------
  3764. UnicodeString __fastcall AssemblyCommentLine(TAssemblyLanguage Language, const UnicodeString & Text)
  3765. {
  3766. UnicodeString Prefix;
  3767. switch (Language)
  3768. {
  3769. case alCSharp:
  3770. Prefix = L"//";
  3771. break;
  3772. case alVBNET:
  3773. Prefix = L"'";
  3774. break;
  3775. case alPowerShell:
  3776. Prefix = L"#";
  3777. break;
  3778. }
  3779. return RtfCodeComment(Prefix + L" " + Text) + RtfPara;
  3780. }
  3781. //---------------------------------------------------------------------
  3782. UnicodeString __fastcall AssemblyString(TAssemblyLanguage Language, UnicodeString S)
  3783. {
  3784. switch (Language)
  3785. {
  3786. case alCSharp:
  3787. if (S.Pos(L"\\") > 0)
  3788. {
  3789. S = FORMAT(L"@\"%s\"", (ReplaceStr(S, L"\"", L"\"\"")));
  3790. }
  3791. else
  3792. {
  3793. S = FORMAT(L"\"%s\"", (ReplaceStr(S, L"\"", L"\\\"")));
  3794. }
  3795. break;
  3796. case alVBNET:
  3797. S = FORMAT(L"\"%s\"", (ReplaceStr(S, L"\"", L"\"\"")));
  3798. break;
  3799. case alPowerShell:
  3800. S = FORMAT(L"\"%s\"", (ReplaceStr(ReplaceStr(ReplaceStr(S, L"`", L"``"), L"$", L"`$"), L"\"", L"`\"")));
  3801. break;
  3802. default:
  3803. DebugFail();
  3804. break;
  3805. }
  3806. return RtfString(S);
  3807. }
  3808. //---------------------------------------------------------------------
  3809. static UnicodeString __fastcall RtfClass(const UnicodeString & Text)
  3810. {
  3811. return RtfColorText(3, Text);
  3812. }
  3813. //---------------------------------------------------------------------
  3814. UnicodeString __fastcall RtfLibraryClass(const UnicodeString & ClassName)
  3815. {
  3816. return RtfLink(L"library_" + ClassName.LowerCase(), RtfClass(ClassName));
  3817. }
  3818. //---------------------------------------------------------------------
  3819. UnicodeString __fastcall RtfLibraryMethod(const UnicodeString & ClassName, const UnicodeString & MethodName, bool InPage)
  3820. {
  3821. return RtfLink(L"library_" + ClassName.LowerCase() + (InPage ? L"#" : L"_") + MethodName.LowerCase(), RtfOverrideColorText(MethodName));
  3822. }
  3823. //---------------------------------------------------------------------
  3824. static UnicodeString __fastcall RtfLibraryProperty(const UnicodeString & ClassName, const UnicodeString & PropertyName)
  3825. {
  3826. return RtfLink(L"library_" + ClassName.LowerCase() + L"#" + PropertyName.LowerCase(), RtfOverrideColorText(PropertyName));
  3827. }
  3828. //---------------------------------------------------------------------
  3829. UnicodeString __fastcall AssemblyVariableName(TAssemblyLanguage Language, const UnicodeString & ClassName)
  3830. {
  3831. UnicodeString Result = ClassName.SubString(1, 1).LowerCase() + ClassName.SubString(2, ClassName.Length() - 1);
  3832. if (Language == alPowerShell)
  3833. {
  3834. Result = L"$" + Result;
  3835. }
  3836. return Result;
  3837. }
  3838. //---------------------------------------------------------------------
  3839. UnicodeString __fastcall AssemblyStatementSeparator(TAssemblyLanguage Language)
  3840. {
  3841. UnicodeString Result;
  3842. switch (Language)
  3843. {
  3844. case alCSharp:
  3845. Result = L";";
  3846. break;
  3847. case alVBNET:
  3848. case alPowerShell:
  3849. // noop
  3850. break;
  3851. }
  3852. return Result;
  3853. }
  3854. //---------------------------------------------------------------------
  3855. UnicodeString __fastcall AssemblyPropertyRaw(
  3856. TAssemblyLanguage Language, const UnicodeString & ClassName, const UnicodeString & Name,
  3857. const UnicodeString & Value, bool Inline)
  3858. {
  3859. UnicodeString Result;
  3860. UnicodeString RtfPropertyAndValue = RtfLibraryProperty(ClassName, Name) + L" = " + Value;
  3861. UnicodeString Indetation = (Inline ? L"" : L" ");
  3862. UnicodeString SpaceOrPara = (Inline ? UnicodeString(L" ") : RtfPara);
  3863. switch (Language)
  3864. {
  3865. case alCSharp:
  3866. Result = Indetation + RtfPropertyAndValue + (Inline ? L"" : L",") + SpaceOrPara;
  3867. break;
  3868. case alVBNET:
  3869. Result = Indetation + L"." + RtfPropertyAndValue + SpaceOrPara;
  3870. break;
  3871. case alPowerShell:
  3872. Result = Indetation + RtfPropertyAndValue + SpaceOrPara;
  3873. break;
  3874. }
  3875. return Result;
  3876. }
  3877. //---------------------------------------------------------------------
  3878. UnicodeString __fastcall AssemblyProperty(
  3879. TAssemblyLanguage Language, const UnicodeString & ClassName, const UnicodeString & Name,
  3880. const UnicodeString & Type, const UnicodeString & Member, bool Inline)
  3881. {
  3882. UnicodeString PropertyValue;
  3883. switch (Language)
  3884. {
  3885. case alCSharp:
  3886. case alVBNET:
  3887. PropertyValue = RtfClass(Type) + RtfText(L"." + Member);
  3888. break;
  3889. case alPowerShell:
  3890. PropertyValue = RtfText(L"[" + AssemblyNamespace + L".") + RtfClass(Type) + RtfText(L"]::" + Member);
  3891. break;
  3892. }
  3893. return AssemblyPropertyRaw(Language, ClassName, Name, PropertyValue, Inline);
  3894. }
  3895. //---------------------------------------------------------------------
  3896. UnicodeString __fastcall AssemblyProperty(
  3897. TAssemblyLanguage Language, const UnicodeString & ClassName,
  3898. const UnicodeString & Name, const UnicodeString & Value, bool Inline)
  3899. {
  3900. return AssemblyPropertyRaw(Language, ClassName, Name, AssemblyString(Language, Value), Inline);
  3901. }
  3902. //---------------------------------------------------------------------
  3903. UnicodeString __fastcall AssemblyProperty(
  3904. TAssemblyLanguage Language, const UnicodeString & ClassName,
  3905. const UnicodeString & Name, int Value, bool Inline)
  3906. {
  3907. return AssemblyPropertyRaw(Language, ClassName, Name, IntToStr(Value), Inline);
  3908. }
  3909. //---------------------------------------------------------------------
  3910. UnicodeString __fastcall AssemblyBoolean(TAssemblyLanguage Language, bool Value)
  3911. {
  3912. UnicodeString Result;
  3913. switch (Language)
  3914. {
  3915. case alCSharp:
  3916. Result = (Value ? L"true" : L"false");
  3917. break;
  3918. case alVBNET:
  3919. Result = (Value ? L"True" : L"False");
  3920. break;
  3921. case alPowerShell:
  3922. Result = (Value ? L"$True" : L"$False");
  3923. break;
  3924. }
  3925. return Result;
  3926. }
  3927. //---------------------------------------------------------------------
  3928. UnicodeString __fastcall AssemblyProperty(
  3929. TAssemblyLanguage Language, const UnicodeString & ClassName, const UnicodeString & Name, bool Value, bool Inline)
  3930. {
  3931. UnicodeString PropertyValue = AssemblyBoolean(Language, Value);
  3932. return AssemblyPropertyRaw(Language, ClassName, Name, PropertyValue, Inline);
  3933. }
  3934. //---------------------------------------------------------------------
  3935. UnicodeString __fastcall AssemblyNewClassInstance(TAssemblyLanguage Language, const UnicodeString & ClassName, bool Inline)
  3936. {
  3937. UnicodeString VariableName = AssemblyVariableName(Language, ClassName);
  3938. UnicodeString RtfClass = RtfLibraryClass(ClassName);
  3939. UnicodeString Result;
  3940. switch (Language)
  3941. {
  3942. case alCSharp:
  3943. if (!Inline)
  3944. {
  3945. Result += RtfClass + RtfText(L" " + VariableName + L" = ");
  3946. }
  3947. Result += RtfKeyword(L"new") + RtfText(L" ") + RtfClass;
  3948. break;
  3949. case alVBNET:
  3950. if (!Inline)
  3951. {
  3952. Result += RtfText(VariableName + L" ") + RtfKeyword(L"As") + RtfText(L" ");
  3953. }
  3954. Result += RtfKeyword(L"New") + RtfText(" ") + RtfClass;
  3955. break;
  3956. case alPowerShell:
  3957. if (!Inline)
  3958. {
  3959. Result += RtfText(VariableName + L" = ");
  3960. }
  3961. Result += RtfKeyword(L"New-Object") + RtfText(L" " + AssemblyNamespace + L".") + RtfClass;
  3962. break;
  3963. }
  3964. return Result;
  3965. }
  3966. //---------------------------------------------------------------------
  3967. UnicodeString __fastcall AssemblyVariableDeclaration(TAssemblyLanguage Language)
  3968. {
  3969. UnicodeString Result;
  3970. switch (Language)
  3971. {
  3972. case alVBNET:
  3973. Result = RtfKeyword(L"Dim") + RtfText(L" ");
  3974. break;
  3975. }
  3976. return Result;
  3977. }
  3978. //---------------------------------------------------------------------
  3979. UnicodeString __fastcall AssemblyNewClassInstanceStart(
  3980. TAssemblyLanguage Language, const UnicodeString & ClassName, bool Inline)
  3981. {
  3982. UnicodeString SpaceOrPara = (Inline ? UnicodeString(L" ") : RtfPara);
  3983. UnicodeString Result;
  3984. if (!Inline)
  3985. {
  3986. Result += AssemblyVariableDeclaration(Language);
  3987. }
  3988. Result += AssemblyNewClassInstance(Language, ClassName, Inline);
  3989. switch (Language)
  3990. {
  3991. case alCSharp:
  3992. Result += SpaceOrPara + RtfText(L"{") + SpaceOrPara;
  3993. break;
  3994. case alVBNET:
  3995. // Historically we use Dim .. With instead of object initializer.
  3996. // But for inline use, we have to use object initialize.
  3997. // We should consistently always use object initializers.
  3998. // Unfortunately VB.NET object initializer (contrary to C#) does not allow trailing comma.
  3999. Result += SpaceOrPara + RtfKeyword(L"With");
  4000. if (Inline)
  4001. {
  4002. Result += RtfText(L" { ");
  4003. }
  4004. else
  4005. {
  4006. Result += RtfText(L" " + AssemblyVariableName(Language, ClassName)) + RtfPara;
  4007. }
  4008. break;
  4009. case alPowerShell:
  4010. Result += RtfText(" -Property @{") + SpaceOrPara;
  4011. break;
  4012. }
  4013. return Result;
  4014. }
  4015. //---------------------------------------------------------------------
  4016. UnicodeString __fastcall AssemblyNewClassInstanceEnd(TAssemblyLanguage Language, bool Inline)
  4017. {
  4018. UnicodeString InlineEnd = RtfText(L"}");
  4019. UnicodeString Result;
  4020. switch (Language)
  4021. {
  4022. case alCSharp:
  4023. if (Inline)
  4024. {
  4025. Result = InlineEnd;
  4026. }
  4027. else
  4028. {
  4029. Result = RtfText(L"};") + RtfPara;
  4030. }
  4031. break;
  4032. case alVBNET:
  4033. if (Inline)
  4034. {
  4035. Result = InlineEnd;
  4036. }
  4037. else
  4038. {
  4039. Result = RtfKeyword(L"End With") + RtfPara;
  4040. }
  4041. break;
  4042. case alPowerShell:
  4043. if (Inline)
  4044. {
  4045. Result = InlineEnd;
  4046. }
  4047. else
  4048. {
  4049. Result = RtfText(L"}") + RtfPara;
  4050. }
  4051. break;
  4052. }
  4053. return Result;
  4054. }
  4055. //---------------------------------------------------------------------------
  4056. UnicodeString __fastcall AssemblyAddRawSettings(
  4057. TAssemblyLanguage Language, TStrings * RawSettings, const UnicodeString & ClassName,
  4058. const UnicodeString & MethodName)
  4059. {
  4060. UnicodeString Result;
  4061. for (int Index = 0; Index < RawSettings->Count; Index++)
  4062. {
  4063. UnicodeString Name = RawSettings->Names[Index];
  4064. UnicodeString Value = RawSettings->ValueFromIndex[Index];
  4065. UnicodeString AddRawSettingsMethod =
  4066. RtfLibraryMethod(ClassName, MethodName, false) +
  4067. FORMAT(L"(%s, %s)", (AssemblyString(Language, Name), AssemblyString(Language, Value)));
  4068. UnicodeString VariableName = AssemblyVariableName(Language, ClassName);
  4069. Result += RtfText(VariableName + L".") + AddRawSettingsMethod + AssemblyStatementSeparator(Language) + RtfPara;
  4070. }
  4071. return Result;
  4072. }
  4073. //---------------------------------------------------------------------------
  4074. void __fastcall LoadScriptFromFile(UnicodeString FileName, TStrings * Lines, bool FallbackToAnsi)
  4075. {
  4076. std::unique_ptr<TFileStream> Stream(new TFileStream(ApiPath(FileName), fmOpenRead | fmShareDenyWrite));
  4077. // Simple stream reading, to make it work with named pipes too, not only with physical files
  4078. TBytes Buffer;
  4079. Buffer.Length = 10*1024;
  4080. int Read;
  4081. int Offset = 0;
  4082. do
  4083. {
  4084. Read = Stream->Read(Buffer, Offset, Buffer.Length - Offset);
  4085. Offset += Read;
  4086. if (Offset > Buffer.Length / 2)
  4087. {
  4088. Buffer.Length = Buffer.Length * 2;
  4089. }
  4090. }
  4091. while (Read > 0);
  4092. Buffer.Length = Offset;
  4093. TEncoding * Encoding = NULL;
  4094. int PreambleSize = TEncoding::GetBufferEncoding(Buffer, Encoding, TEncoding::UTF8);
  4095. UnicodeString S;
  4096. try
  4097. {
  4098. S = Encoding->GetString(Buffer, PreambleSize, Buffer.Length - PreambleSize);
  4099. }
  4100. catch (EEncodingError & E)
  4101. {
  4102. if (FallbackToAnsi)
  4103. {
  4104. S = TEncoding::ANSI->GetString(Buffer);
  4105. }
  4106. else
  4107. {
  4108. throw ExtException(LoadStr(TEXT_FILE_ENCODING), &E);
  4109. }
  4110. }
  4111. Lines->Text = S;
  4112. }
  4113. //---------------------------------------------------------------------------
  4114. UnicodeString __fastcall StripEllipsis(const UnicodeString & S)
  4115. {
  4116. UnicodeString Result = S;
  4117. if (Result.SubString(Result.Length() - Ellipsis.Length() + 1, Ellipsis.Length()) == Ellipsis)
  4118. {
  4119. Result.SetLength(Result.Length() - Ellipsis.Length());
  4120. Result = Result.TrimRight();
  4121. }
  4122. return Result;
  4123. }
  4124. //---------------------------------------------------------------------------
  4125. UnicodeString __fastcall GetFileMimeType(const UnicodeString & FileName)
  4126. {
  4127. wchar_t * MimeOut = NULL;
  4128. UnicodeString Result;
  4129. if (FindMimeFromData(NULL, FileName.c_str(), NULL, 0, NULL, FMFD_URLASFILENAME, &MimeOut, 0) == S_OK)
  4130. {
  4131. Result = MimeOut;
  4132. CoTaskMemFree(MimeOut);
  4133. }
  4134. return Result;
  4135. }
  4136. //---------------------------------------------------------------------------
  4137. TStrings * TlsCipherList()
  4138. {
  4139. std::unique_ptr<TStrings> Result(new TStringList());
  4140. // Exact method that neon uses. FTP uses TLS_method() (FTP needs server method too). But they have the same ciphers.
  4141. const SSL_METHOD * Method = TLS_client_method();
  4142. SSL_CTX * Ctx = SSL_CTX_new(Method);
  4143. SSL * Ssl = SSL_new(Ctx);
  4144. int Index = 0;
  4145. const char * CipherName;
  4146. do
  4147. {
  4148. CipherName = SSL_get_cipher_list(Ssl, Index);
  4149. Index++;
  4150. if (CipherName != NULL)
  4151. {
  4152. Result->Add(UnicodeString(CipherName));
  4153. }
  4154. }
  4155. while (CipherName != NULL);
  4156. return Result.release();
  4157. }
  4158. //---------------------------------------------------------------------------
  4159. void SetStringValueEvenIfEmpty(TStrings * Strings, const UnicodeString & Name, const UnicodeString & Value)
  4160. {
  4161. if (Value.IsEmpty())
  4162. {
  4163. int Index = Strings->IndexOfName(Name);
  4164. if (Index < 0)
  4165. {
  4166. Index = Strings->Add(L"");
  4167. }
  4168. UnicodeString Line = Name + Strings->NameValueSeparator;
  4169. Strings->Strings[Index] = Line;
  4170. }
  4171. else
  4172. {
  4173. Strings->Values[Name] = Value;
  4174. }
  4175. }
  4176. //---------------------------------------------------------------------------
  4177. DWORD __fastcall GetParentProcessId(HANDLE Snapshot, DWORD ProcessId)
  4178. {
  4179. DWORD Result = 0;
  4180. PROCESSENTRY32 ProcessEntry;
  4181. memset(&ProcessEntry, sizeof(ProcessEntry), 0);
  4182. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  4183. if (Process32First(Snapshot, &ProcessEntry))
  4184. {
  4185. do
  4186. {
  4187. if (ProcessEntry.th32ProcessID == ProcessId)
  4188. {
  4189. Result = ProcessEntry.th32ParentProcessID;
  4190. }
  4191. } while (Process32Next(Snapshot, &ProcessEntry));
  4192. }
  4193. return Result;
  4194. }
  4195. //---------------------------------------------------------------------------
  4196. static UnicodeString GetProcessName(DWORD ProcessId)
  4197. {
  4198. UnicodeString Result;
  4199. HANDLE Process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessId);
  4200. // is common, when the parent process is installer, so we ignore it
  4201. if (Process)
  4202. {
  4203. Result.SetLength(MAX_PATH);
  4204. DWORD Len = GetModuleFileNameEx(Process, NULL, Result.c_str(), Result.Length());
  4205. Result.SetLength(Len);
  4206. // is common too, for some reason
  4207. if (!Result.IsEmpty())
  4208. {
  4209. Result = ExtractProgramName(FormatCommand(Result, UnicodeString()));
  4210. }
  4211. CloseHandle(Process);
  4212. }
  4213. return Result;
  4214. }
  4215. //---------------------------------------------------------------------------
  4216. UnicodeString ParentProcessName;
  4217. //---------------------------------------------------------------------------
  4218. UnicodeString __fastcall GetAncestorProcessName(int Levels)
  4219. {
  4220. UnicodeString Result;
  4221. bool Parent = (Levels == 1);
  4222. if (Parent && !ParentProcessName.IsEmpty())
  4223. {
  4224. Result = ParentProcessName;
  4225. }
  4226. else
  4227. {
  4228. try
  4229. {
  4230. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  4231. DWORD ProcessId = GetCurrentProcessId();
  4232. typedef std::vector<DWORD> TProcesses;
  4233. TProcesses Processes;
  4234. // Either more to go (>0) or collecting all levels (-1 from GetAncestorProcessNames)
  4235. while ((Levels != 0) &&
  4236. (Levels > -20) && // prevent infinite loops
  4237. (ProcessId != 0))
  4238. {
  4239. const UnicodeString Sep(L", ");
  4240. ProcessId = GetParentProcessId(Snapshot, ProcessId);
  4241. // When ancestor process is terminated and another process reuses its ID, we may get a cycle.
  4242. TProcesses::const_iterator I = std::find(Processes.begin(), Processes.end(), ProcessId);
  4243. if (I != Processes.end())
  4244. {
  4245. int Index = I - Processes.begin();
  4246. AddToList(Result, FORMAT(L"cycle-%d", (Index)), Sep);
  4247. ProcessId = 0;
  4248. }
  4249. else
  4250. {
  4251. Processes.push_back(ProcessId);
  4252. if ((Levels < 0) && (ProcessId != 0))
  4253. {
  4254. UnicodeString Name = GetProcessName(ProcessId);
  4255. if (Name.IsEmpty())
  4256. {
  4257. Name = L"...";
  4258. ProcessId = 0;
  4259. }
  4260. AddToList(Result, Name, Sep);
  4261. }
  4262. Levels--;
  4263. }
  4264. }
  4265. if (Levels >= 0)
  4266. {
  4267. if (ProcessId == 0)
  4268. {
  4269. Result = L"err-notfound";
  4270. }
  4271. else
  4272. {
  4273. Result = GetProcessName(ProcessId);
  4274. }
  4275. }
  4276. else if (Result.IsEmpty())
  4277. {
  4278. Result = L"n/a";
  4279. }
  4280. CloseHandle(Snapshot);
  4281. }
  4282. catch (...)
  4283. {
  4284. Result = L"err-except";
  4285. }
  4286. if (Parent)
  4287. {
  4288. ParentProcessName = Result;
  4289. }
  4290. }
  4291. return Result;
  4292. }
  4293. //---------------------------------------------------------------------------
  4294. UnicodeString AncestorProcessNames;
  4295. //---------------------------------------------------------------------------
  4296. UnicodeString GetAncestorProcessNames()
  4297. {
  4298. if (AncestorProcessNames.IsEmpty())
  4299. {
  4300. AncestorProcessNames = GetAncestorProcessName(-1);
  4301. }
  4302. return AncestorProcessNames;
  4303. }
  4304. //---------------------------------------------------------------------------
  4305. void NotImplemented()
  4306. {
  4307. DebugFail();
  4308. throw Exception(L"Not implemented");
  4309. }
  4310. //---------------------------------------------------------------------------
  4311. void NotSupported()
  4312. {
  4313. throw Exception(MainInstructions(LoadStr(NOTSUPPORTED)));
  4314. }
  4315. //---------------------------------------------------------------------------
  4316. UnicodeString GetDividerLine()
  4317. {
  4318. return UnicodeString::StringOfChar(L'-', 27);
  4319. }
  4320. //---------------------------------------------------------------------------
  4321. static UnicodeString CutFeature(UnicodeString & Buf)
  4322. {
  4323. UnicodeString Result;
  4324. if (Buf.SubString(1, 1) == L"\"")
  4325. {
  4326. Buf.Delete(1, 1);
  4327. int P = Buf.Pos(L"\",");
  4328. if (P == 0)
  4329. {
  4330. Result = Buf;
  4331. Buf = UnicodeString();
  4332. // there should be the ending quote, but if not, just do nothing
  4333. if (Result.SubString(Result.Length(), 1) == L"\"")
  4334. {
  4335. Result.SetLength(Result.Length() - 1);
  4336. }
  4337. }
  4338. else
  4339. {
  4340. Result = Buf.SubString(1, P - 1);
  4341. Buf.Delete(1, P + 1);
  4342. }
  4343. Buf = Buf.TrimLeft();
  4344. }
  4345. else
  4346. {
  4347. Result = CutToChar(Buf, L',', true);
  4348. }
  4349. return Result;
  4350. }
  4351. //---------------------------------------------------------------------------
  4352. TStrings * ProcessFeatures(TStrings * Features, const UnicodeString & AFeaturesOverride)
  4353. {
  4354. std::unique_ptr<TStrings> Result(new TStringList());
  4355. UnicodeString FeaturesOverride = AFeaturesOverride;
  4356. if (FeaturesOverride.SubString(1, 1) == L"*")
  4357. {
  4358. FeaturesOverride.Delete(1, 1);
  4359. while (!FeaturesOverride.IsEmpty())
  4360. {
  4361. UnicodeString Feature = CutFeature(FeaturesOverride);
  4362. Result->Add(Feature);
  4363. }
  4364. }
  4365. else
  4366. {
  4367. std::unique_ptr<TStrings> DeleteFeatures(CreateSortedStringList());
  4368. std::unique_ptr<TStrings> AddFeatures(new TStringList());
  4369. while (!FeaturesOverride.IsEmpty())
  4370. {
  4371. UnicodeString Feature = CutFeature(FeaturesOverride);
  4372. if (Feature.SubString(1, 1) == L"-")
  4373. {
  4374. Feature.Delete(1, 1);
  4375. DeleteFeatures->Add(Feature.LowerCase());
  4376. }
  4377. else
  4378. {
  4379. if (Feature.SubString(1, 1) == L"+")
  4380. {
  4381. Feature.Delete(1, 1);
  4382. }
  4383. AddFeatures->Add(Feature);
  4384. }
  4385. }
  4386. for (int Index = 0; Index < Features->Count; Index++)
  4387. {
  4388. UnicodeString Feature = Features->Strings[Index];
  4389. if (DeleteFeatures->IndexOf(Feature) < 0)
  4390. {
  4391. Result->Add(Feature);
  4392. }
  4393. }
  4394. Result->AddStrings(AddFeatures.get());
  4395. }
  4396. return Result.release();
  4397. }
  4398. //---------------------------------------------------------------------