Common.cpp 121 KB

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