Common.cpp 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854
  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. //---------------------------------------------------------------------------
  20. #pragma package(smart_init)
  21. //---------------------------------------------------------------------------
  22. const wchar_t * DSTModeNames = L"Win;Unix;Keep";
  23. //---------------------------------------------------------------------------
  24. //---------------------------------------------------------------------------
  25. const wchar_t EngShortMonthNames[12][4] =
  26. {L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun",
  27. L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec"};
  28. const char Bom[3] = "\xEF\xBB\xBF";
  29. const wchar_t TokenPrefix = L'%';
  30. const wchar_t NoReplacement = wchar_t(false);
  31. const wchar_t TokenReplacement = wchar_t(true);
  32. const UnicodeString LocalInvalidChars = L"/\\:*?\"<>|";
  33. const UnicodeString PasswordMask = L"***";
  34. //---------------------------------------------------------------------------
  35. UnicodeString ReplaceChar(UnicodeString Str, wchar_t A, wchar_t B)
  36. {
  37. for (Integer Index = 0; Index < Str.Length(); Index++)
  38. if (Str[Index+1] == A) Str[Index+1] = B;
  39. return Str;
  40. }
  41. //---------------------------------------------------------------------------
  42. UnicodeString DeleteChar(UnicodeString Str, wchar_t C)
  43. {
  44. int P;
  45. while ((P = Str.Pos(C)) > 0)
  46. {
  47. Str.Delete(P, 1);
  48. }
  49. return Str;
  50. }
  51. //---------------------------------------------------------------------------
  52. template<typename T>
  53. void DoPackStr(T & Str)
  54. {
  55. // Following will free unnecessary bytes
  56. Str = Str.c_str();
  57. }
  58. //---------------------------------------------------------------------------
  59. void PackStr(UnicodeString & Str)
  60. {
  61. DoPackStr(Str);
  62. }
  63. //---------------------------------------------------------------------------
  64. void PackStr(RawByteString & Str)
  65. {
  66. DoPackStr(Str);
  67. }
  68. //---------------------------------------------------------------------------
  69. void PackStr(AnsiString & Str)
  70. {
  71. DoPackStr(Str);
  72. }
  73. //---------------------------------------------------------------------------
  74. template<typename T>
  75. void __fastcall DoShred(T & Str)
  76. {
  77. if (!Str.IsEmpty())
  78. {
  79. Str.Unique();
  80. memset(Str.c_str(), 0, Str.Length() * sizeof(*Str.c_str()));
  81. Str = L"";
  82. }
  83. }
  84. //---------------------------------------------------------------------------
  85. void __fastcall Shred(UnicodeString & Str)
  86. {
  87. DoShred(Str);
  88. }
  89. //---------------------------------------------------------------------------
  90. void __fastcall Shred(UTF8String & Str)
  91. {
  92. DoShred(Str);
  93. }
  94. //---------------------------------------------------------------------------
  95. void __fastcall Shred(AnsiString & Str)
  96. {
  97. DoShred(Str);
  98. }
  99. //---------------------------------------------------------------------------
  100. UnicodeString AnsiToString(const RawByteString & S)
  101. {
  102. return UnicodeString(AnsiString(S));
  103. }
  104. //---------------------------------------------------------------------------
  105. UnicodeString AnsiToString(const char * S, size_t Len)
  106. {
  107. return UnicodeString(AnsiString(S, Len));
  108. }
  109. //---------------------------------------------------------------------------
  110. UnicodeString MakeValidFileName(UnicodeString FileName)
  111. {
  112. UnicodeString IllegalChars = L":;,=+<>|\"[] \\/?*";
  113. for (int Index = 0; Index < IllegalChars.Length(); Index++)
  114. {
  115. FileName = ReplaceChar(FileName, IllegalChars[Index+1], L'-');
  116. }
  117. return FileName;
  118. }
  119. //---------------------------------------------------------------------------
  120. UnicodeString RootKeyToStr(HKEY RootKey)
  121. {
  122. if (RootKey == HKEY_USERS) return L"HKU";
  123. else
  124. if (RootKey == HKEY_LOCAL_MACHINE) return L"HKLM";
  125. else
  126. if (RootKey == HKEY_CURRENT_USER) return L"HKCU";
  127. else
  128. if (RootKey == HKEY_CLASSES_ROOT) return L"HKCR";
  129. else
  130. if (RootKey == HKEY_CURRENT_CONFIG) return L"HKCC";
  131. else
  132. if (RootKey == HKEY_DYN_DATA) return L"HKDD";
  133. else
  134. { Abort(); return L""; };
  135. }
  136. //---------------------------------------------------------------------------
  137. UnicodeString BooleanToEngStr(bool B)
  138. {
  139. if (B)
  140. {
  141. return L"Yes";
  142. }
  143. else
  144. {
  145. return L"No";
  146. }
  147. }
  148. //---------------------------------------------------------------------------
  149. UnicodeString BooleanToStr(bool B)
  150. {
  151. if (B)
  152. {
  153. return LoadStr(YES_STR);
  154. }
  155. else
  156. {
  157. return LoadStr(NO_STR);
  158. }
  159. }
  160. //---------------------------------------------------------------------------
  161. UnicodeString DefaultStr(const UnicodeString & Str, const UnicodeString & Default)
  162. {
  163. if (!Str.IsEmpty())
  164. {
  165. return Str;
  166. }
  167. else
  168. {
  169. return Default;
  170. }
  171. }
  172. //---------------------------------------------------------------------------
  173. UnicodeString CutToChar(UnicodeString &Str, wchar_t Ch, bool Trim)
  174. {
  175. Integer P = Str.Pos(Ch);
  176. UnicodeString Result;
  177. if (P)
  178. {
  179. Result = Str.SubString(1, P-1);
  180. Str.Delete(1, P);
  181. }
  182. else
  183. {
  184. Result = Str;
  185. Str = L"";
  186. }
  187. if (Trim)
  188. {
  189. Result = Result.TrimRight();
  190. Str = Str.TrimLeft();
  191. }
  192. return Result;
  193. }
  194. //---------------------------------------------------------------------------
  195. UnicodeString CopyToChars(const UnicodeString & Str, int & From, UnicodeString Chs, bool Trim,
  196. wchar_t * Delimiter, bool DoubleDelimiterEscapes)
  197. {
  198. UnicodeString Result;
  199. int P;
  200. for (P = From; P <= Str.Length(); P++)
  201. {
  202. if (IsDelimiter(Chs, Str, P))
  203. {
  204. if (DoubleDelimiterEscapes &&
  205. (P < Str.Length()) &&
  206. IsDelimiter(Chs, Str, P + 1))
  207. {
  208. Result += Str[P];
  209. P++;
  210. }
  211. else
  212. {
  213. break;
  214. }
  215. }
  216. else
  217. {
  218. Result += Str[P];
  219. }
  220. }
  221. if (P <= Str.Length())
  222. {
  223. if (Delimiter != NULL)
  224. {
  225. *Delimiter = Str[P];
  226. }
  227. }
  228. else
  229. {
  230. if (Delimiter != NULL)
  231. {
  232. *Delimiter = L'\0';
  233. }
  234. }
  235. // even if we reached the end, return index, as if there were the delimiter,
  236. // so caller can easily find index of the end of the piece by subtracting
  237. // 2 from From (as long as he did not asked for trimming)
  238. From = P+1;
  239. if (Trim)
  240. {
  241. Result = Result.TrimRight();
  242. while ((From <= Str.Length()) && (Str[From] == L' '))
  243. {
  244. From++;
  245. }
  246. }
  247. return Result;
  248. }
  249. //---------------------------------------------------------------------------
  250. UnicodeString CopyToChar(const UnicodeString & Str, wchar_t Ch, bool Trim)
  251. {
  252. int From = 1;
  253. return CopyToChars(Str, From, UnicodeString(Ch), Trim);
  254. }
  255. //---------------------------------------------------------------------------
  256. UnicodeString DelimitStr(UnicodeString Str, UnicodeString Chars)
  257. {
  258. for (int i = 1; i <= Str.Length(); i++)
  259. {
  260. if (Str.IsDelimiter(Chars, i))
  261. {
  262. Str.Insert(L"\\", i);
  263. i++;
  264. }
  265. }
  266. return Str;
  267. }
  268. //---------------------------------------------------------------------------
  269. UnicodeString ShellDelimitStr(UnicodeString Str, wchar_t Quote)
  270. {
  271. UnicodeString Chars = L"$\\";
  272. if (Quote == L'"')
  273. {
  274. Chars += L"`\"";
  275. }
  276. return DelimitStr(Str, Chars);
  277. }
  278. //---------------------------------------------------------------------------
  279. UnicodeString ExceptionLogString(Exception *E)
  280. {
  281. DebugAssert(E);
  282. if (E->InheritsFrom(__classid(Exception)))
  283. {
  284. UnicodeString Msg;
  285. Msg = FORMAT(L"(%s) %s", (E->ClassName(), E->Message));
  286. if (E->InheritsFrom(__classid(ExtException)))
  287. {
  288. TStrings * MoreMessages = ((ExtException*)E)->MoreMessages;
  289. if (MoreMessages)
  290. {
  291. Msg += L"\n" +
  292. ReplaceStr(MoreMessages->Text, L"\r", L"");
  293. }
  294. }
  295. return Msg;
  296. }
  297. else
  298. {
  299. wchar_t Buffer[1024];
  300. ExceptionErrorMessage(ExceptObject(), ExceptAddr(), Buffer, LENOF(Buffer));
  301. return UnicodeString(Buffer);
  302. }
  303. }
  304. //---------------------------------------------------------------------------
  305. UnicodeString __fastcall MainInstructions(const UnicodeString & S)
  306. {
  307. UnicodeString MainMsgTag = LoadStr(MAIN_MSG_TAG);
  308. return MainMsgTag + S + MainMsgTag;
  309. }
  310. //---------------------------------------------------------------------------
  311. bool __fastcall HasParagraphs(const UnicodeString & S)
  312. {
  313. return (S.Pos(L"\n\n") > 0);
  314. }
  315. //---------------------------------------------------------------------------
  316. UnicodeString __fastcall MainInstructionsFirstParagraph(const UnicodeString & S)
  317. {
  318. // WORKAROUND, we consider it bad practice, the highlighting should better
  319. // be localized (but maybe we change our mind later)
  320. UnicodeString Result;
  321. int Pos = S.Pos(L"\n\n");
  322. // we would not be calling this on single paragraph message
  323. if (ALWAYS_TRUE(Pos > 0))
  324. {
  325. Result =
  326. MainInstructions(S.SubString(1, Pos - 1)) +
  327. S.SubString(Pos, S.Length() - Pos + 1);
  328. }
  329. else
  330. {
  331. Result = MainInstructions(S);
  332. }
  333. return Result;
  334. }
  335. //---------------------------------------------------------------------------
  336. bool ExtractMainInstructions(UnicodeString & S, UnicodeString & MainInstructions)
  337. {
  338. bool Result = false;
  339. UnicodeString MainMsgTag = LoadStr(MAIN_MSG_TAG);
  340. if (StartsStr(MainMsgTag, S))
  341. {
  342. int EndTagPos =
  343. S.SubString(MainMsgTag.Length() + 1, S.Length() - MainMsgTag.Length()).Pos(MainMsgTag);
  344. if (EndTagPos > 0)
  345. {
  346. MainInstructions = S.SubString(MainMsgTag.Length() + 1, EndTagPos - 1);
  347. S.Delete(1, EndTagPos + (2 * MainMsgTag.Length()) - 1);
  348. Result = true;
  349. }
  350. }
  351. DebugAssert(MainInstructions.Pos(MainMsgTag) == 0);
  352. DebugAssert(S.Pos(MainMsgTag) == 0);
  353. return Result;
  354. }
  355. //---------------------------------------------------------------------------
  356. static int FindInteractiveMsgStart(const UnicodeString & S)
  357. {
  358. int Result = 0;
  359. UnicodeString InteractiveMsgTag = LoadStr(INTERACTIVE_MSG_TAG);
  360. if (EndsStr(InteractiveMsgTag, S) &&
  361. (S.Length() >= 2 * InteractiveMsgTag.Length()))
  362. {
  363. Result = S.Length() - 2 * InteractiveMsgTag.Length() + 1;
  364. while ((Result > 0) && (S.SubString(Result, InteractiveMsgTag.Length()) != InteractiveMsgTag))
  365. {
  366. Result--;
  367. }
  368. }
  369. return Result;
  370. }
  371. //---------------------------------------------------------------------------
  372. UnicodeString RemoveMainInstructionsTag(UnicodeString S)
  373. {
  374. UnicodeString MainInstruction;
  375. if (ExtractMainInstructions(S, MainInstruction))
  376. {
  377. S = MainInstruction + S;
  378. }
  379. return S;
  380. }
  381. //---------------------------------------------------------------------------
  382. UnicodeString UnformatMessage(UnicodeString S)
  383. {
  384. S = RemoveMainInstructionsTag(S);
  385. int InteractiveMsgStart = FindInteractiveMsgStart(S);
  386. if (InteractiveMsgStart > 0)
  387. {
  388. S = S.SubString(1, InteractiveMsgStart - 1);
  389. }
  390. return S;
  391. }
  392. //---------------------------------------------------------------------------
  393. UnicodeString RemoveInteractiveMsgTag(UnicodeString S)
  394. {
  395. int InteractiveMsgStart = FindInteractiveMsgStart(S);
  396. if (InteractiveMsgStart > 0)
  397. {
  398. UnicodeString InteractiveMsgTag = LoadStr(INTERACTIVE_MSG_TAG);
  399. S.Delete(InteractiveMsgStart, InteractiveMsgTag.Length());
  400. S.Delete(S.Length() - InteractiveMsgTag.Length() + 1, InteractiveMsgTag.Length());
  401. }
  402. return S;
  403. }
  404. //---------------------------------------------------------------------------
  405. UnicodeString RemoveEmptyLines(const UnicodeString & S)
  406. {
  407. return
  408. ReplaceStr(
  409. ReplaceStr(S.TrimRight(), L"\n\n", L"\n"),
  410. L"\n \n", L"\n");
  411. }
  412. //---------------------------------------------------------------------------
  413. bool IsNumber(const UnicodeString Str)
  414. {
  415. int Value;
  416. return TryStrToInt(Str, Value);
  417. }
  418. //---------------------------------------------------------------------------
  419. UnicodeString __fastcall SystemTemporaryDirectory()
  420. {
  421. UnicodeString TempDir;
  422. TempDir.SetLength(MAX_PATH);
  423. TempDir.SetLength(GetTempPath(MAX_PATH, TempDir.c_str()));
  424. return TempDir;
  425. }
  426. //---------------------------------------------------------------------------
  427. UnicodeString __fastcall GetShellFolderPath(int CSIdl)
  428. {
  429. UnicodeString Result;
  430. wchar_t Path[2 * MAX_PATH + 10] = L"\0";
  431. if (SUCCEEDED(SHGetFolderPath(NULL, CSIdl, NULL, SHGFP_TYPE_CURRENT, Path)))
  432. {
  433. Result = Path;
  434. }
  435. return Result;
  436. }
  437. //---------------------------------------------------------------------------
  438. // Particularly needed when using file name selected by TFilenameEdit,
  439. // as it wraps a path to double-quotes, when there is a space in the path.
  440. UnicodeString __fastcall StripPathQuotes(const UnicodeString Path)
  441. {
  442. if ((Path.Length() >= 2) &&
  443. (Path[1] == L'\"') && (Path[Path.Length()] == L'\"'))
  444. {
  445. return Path.SubString(2, Path.Length() - 2);
  446. }
  447. else
  448. {
  449. return Path;
  450. }
  451. }
  452. //---------------------------------------------------------------------------
  453. UnicodeString __fastcall AddQuotes(UnicodeString Str)
  454. {
  455. if (Str.Pos(L" ") > 0)
  456. {
  457. Str = L"\"" + Str + L"\"";
  458. }
  459. return Str;
  460. }
  461. //---------------------------------------------------------------------------
  462. UnicodeString __fastcall AddPathQuotes(UnicodeString Path)
  463. {
  464. Path = StripPathQuotes(Path);
  465. return AddQuotes(Path);
  466. }
  467. //---------------------------------------------------------------------------
  468. static wchar_t * __fastcall ReplaceChar(
  469. UnicodeString & FileName, wchar_t * InvalidChar, wchar_t InvalidCharsReplacement)
  470. {
  471. int Index = InvalidChar - FileName.c_str() + 1;
  472. if (InvalidCharsReplacement == TokenReplacement)
  473. {
  474. // currently we do not support unicode chars replacement
  475. if (FileName[Index] > 0xFF)
  476. {
  477. EXCEPTION;
  478. }
  479. FileName.Insert(ByteToHex(static_cast<unsigned char>(FileName[Index])), Index + 1);
  480. FileName[Index] = TokenPrefix;
  481. InvalidChar = FileName.c_str() + Index + 2;
  482. }
  483. else
  484. {
  485. FileName[Index] = InvalidCharsReplacement;
  486. InvalidChar = FileName.c_str() + Index;
  487. }
  488. return InvalidChar;
  489. }
  490. //---------------------------------------------------------------------------
  491. UnicodeString __fastcall ValidLocalFileName(UnicodeString FileName)
  492. {
  493. return ValidLocalFileName(FileName, L'_', L"", LocalInvalidChars);
  494. }
  495. //---------------------------------------------------------------------------
  496. UnicodeString __fastcall ValidLocalFileName(
  497. UnicodeString FileName, wchar_t InvalidCharsReplacement,
  498. const UnicodeString & TokenizibleChars, const UnicodeString & LocalInvalidChars)
  499. {
  500. if (InvalidCharsReplacement != NoReplacement)
  501. {
  502. bool ATokenReplacement = (InvalidCharsReplacement == TokenReplacement);
  503. const wchar_t * Chars =
  504. (ATokenReplacement ? TokenizibleChars : LocalInvalidChars).c_str();
  505. wchar_t * InvalidChar = FileName.c_str();
  506. while ((InvalidChar = wcspbrk(InvalidChar, Chars)) != NULL)
  507. {
  508. int Pos = (InvalidChar - FileName.c_str() + 1);
  509. wchar_t Char;
  510. if (ATokenReplacement &&
  511. (*InvalidChar == TokenPrefix) &&
  512. (((FileName.Length() - Pos) <= 1) ||
  513. (((Char = static_cast<wchar_t>(HexToByte(FileName.SubString(Pos + 1, 2)))) == L'\0') ||
  514. (TokenizibleChars.Pos(Char) == 0))))
  515. {
  516. InvalidChar++;
  517. }
  518. else
  519. {
  520. InvalidChar = ReplaceChar(FileName, InvalidChar, InvalidCharsReplacement);
  521. }
  522. }
  523. // Windows trim trailing space or dot, hence we must encode it to preserve it
  524. if (!FileName.IsEmpty() &&
  525. ((FileName[FileName.Length()] == L' ') ||
  526. (FileName[FileName.Length()] == L'.')))
  527. {
  528. ReplaceChar(FileName, FileName.c_str() + FileName.Length() - 1, InvalidCharsReplacement);
  529. }
  530. if (IsReservedName(FileName))
  531. {
  532. int P = FileName.Pos(".");
  533. if (P == 0)
  534. {
  535. P = FileName.Length() + 1;
  536. }
  537. FileName.Insert(L"%00", P);
  538. }
  539. }
  540. return FileName;
  541. }
  542. //---------------------------------------------------------------------------
  543. void __fastcall SplitCommand(UnicodeString Command, UnicodeString &Program,
  544. UnicodeString & Params, UnicodeString & Dir)
  545. {
  546. Command = Command.Trim();
  547. Params = L"";
  548. Dir = L"";
  549. if (!Command.IsEmpty() && (Command[1] == L'\"'))
  550. {
  551. Command.Delete(1, 1);
  552. int P = Command.Pos(L'"');
  553. if (P)
  554. {
  555. Program = Command.SubString(1, P-1).Trim();
  556. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  557. }
  558. else
  559. {
  560. throw Exception(FMTLOAD(INVALID_SHELL_COMMAND, (L"\"" + Command)));
  561. }
  562. }
  563. else
  564. {
  565. int P = Command.Pos(L" ");
  566. if (P)
  567. {
  568. Program = Command.SubString(1, P).Trim();
  569. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  570. }
  571. else
  572. {
  573. Program = Command;
  574. }
  575. }
  576. int B = Program.LastDelimiter(L"\\/");
  577. if (B)
  578. {
  579. Dir = Program.SubString(1, B).Trim();
  580. }
  581. }
  582. //---------------------------------------------------------------------------
  583. UnicodeString __fastcall ExtractProgram(UnicodeString Command)
  584. {
  585. UnicodeString Program;
  586. UnicodeString Params;
  587. UnicodeString Dir;
  588. SplitCommand(Command, Program, Params, Dir);
  589. return Program;
  590. }
  591. //---------------------------------------------------------------------------
  592. UnicodeString __fastcall ExtractProgramName(UnicodeString Command)
  593. {
  594. UnicodeString Name = ExtractFileName(ExtractProgram(Command));
  595. int Dot = Name.LastDelimiter(L".");
  596. if (Dot > 0)
  597. {
  598. Name = Name.SubString(1, Dot - 1);
  599. }
  600. return Name;
  601. }
  602. //---------------------------------------------------------------------------
  603. UnicodeString __fastcall FormatCommand(UnicodeString Program, UnicodeString Params)
  604. {
  605. Program = Program.Trim();
  606. Params = Params.Trim();
  607. if (!Params.IsEmpty()) Params = L" " + Params;
  608. Program = AddQuotes(Program);
  609. return Program + Params;
  610. }
  611. //---------------------------------------------------------------------------
  612. const wchar_t ShellCommandFileNamePattern[] = L"!.!";
  613. //---------------------------------------------------------------------------
  614. void __fastcall ReformatFileNameCommand(UnicodeString & Command)
  615. {
  616. if (!Command.IsEmpty())
  617. {
  618. UnicodeString Program, Params, Dir;
  619. SplitCommand(Command, Program, Params, Dir);
  620. if (Params.Pos(ShellCommandFileNamePattern) == 0)
  621. {
  622. Params = Params + (Params.IsEmpty() ? L"" : L" ") + ShellCommandFileNamePattern;
  623. }
  624. Command = FormatCommand(Program, Params);
  625. }
  626. }
  627. //---------------------------------------------------------------------------
  628. UnicodeString __fastcall ExpandFileNameCommand(const UnicodeString Command,
  629. const UnicodeString FileName)
  630. {
  631. return AnsiReplaceStr(Command, ShellCommandFileNamePattern,
  632. AddPathQuotes(FileName));
  633. }
  634. //---------------------------------------------------------------------------
  635. UnicodeString __fastcall EscapeParam(const UnicodeString & Param)
  636. {
  637. return ReplaceStr(Param, L"\"", L"\"\"");
  638. }
  639. //---------------------------------------------------------------------------
  640. UnicodeString __fastcall EscapePuttyCommandParam(UnicodeString Param)
  641. {
  642. bool Space = false;
  643. for (int i = 1; i <= Param.Length(); i++)
  644. {
  645. switch (Param[i])
  646. {
  647. case L'"':
  648. Param.Insert(L"\\", i);
  649. i++;
  650. break;
  651. case L' ':
  652. Space = true;
  653. break;
  654. case L'\\':
  655. int i2 = i;
  656. while ((i2 <= Param.Length()) && (Param[i2] == L'\\'))
  657. {
  658. i2++;
  659. }
  660. if ((i2 <= Param.Length()) && (Param[i2] == L'"'))
  661. {
  662. while (Param[i] == L'\\')
  663. {
  664. Param.Insert(L"\\", i);
  665. i += 2;
  666. }
  667. i--;
  668. }
  669. break;
  670. }
  671. }
  672. if (Space)
  673. {
  674. Param = L"\"" + Param + L'"';
  675. }
  676. return Param;
  677. }
  678. //---------------------------------------------------------------------------
  679. UnicodeString __fastcall ExpandEnvironmentVariables(const UnicodeString & Str)
  680. {
  681. UnicodeString Buf;
  682. unsigned int Size = 1024;
  683. Buf.SetLength(Size);
  684. Buf.Unique();
  685. unsigned int Len = ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Size);
  686. if (Len > Size)
  687. {
  688. Buf.SetLength(Len);
  689. Buf.Unique();
  690. ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Len);
  691. }
  692. PackStr(Buf);
  693. return Buf;
  694. }
  695. //---------------------------------------------------------------------------
  696. bool __fastcall CompareFileName(const UnicodeString & Path1, const UnicodeString & Path2)
  697. {
  698. UnicodeString ShortPath1 = ExtractShortPathName(Path1);
  699. UnicodeString ShortPath2 = ExtractShortPathName(Path2);
  700. bool Result;
  701. // ExtractShortPathName returns empty string if file does not exist
  702. if (ShortPath1.IsEmpty() || ShortPath2.IsEmpty())
  703. {
  704. Result = AnsiSameText(Path1, Path2);
  705. }
  706. else
  707. {
  708. Result = AnsiSameText(ShortPath1, ShortPath2);
  709. }
  710. return Result;
  711. }
  712. //---------------------------------------------------------------------------
  713. bool __fastcall ComparePaths(const UnicodeString & Path1, const UnicodeString & Path2)
  714. {
  715. // TODO: ExpandUNCFileName
  716. return AnsiSameText(IncludeTrailingBackslash(Path1), IncludeTrailingBackslash(Path2));
  717. }
  718. //---------------------------------------------------------------------------
  719. int __fastcall CompareLogicalText(const UnicodeString & S1, const UnicodeString & S2)
  720. {
  721. return StrCmpLogicalW(S1.c_str(), S2.c_str());
  722. }
  723. //---------------------------------------------------------------------------
  724. bool __fastcall IsReservedName(UnicodeString FileName)
  725. {
  726. int P = FileName.Pos(L".");
  727. int Len = (P > 0) ? P - 1 : FileName.Length();
  728. if ((Len == 3) || (Len == 4))
  729. {
  730. if (P > 0)
  731. {
  732. FileName.SetLength(P - 1);
  733. }
  734. static UnicodeString Reserved[] = {
  735. L"CON", L"PRN", L"AUX", L"NUL",
  736. L"COM1", L"COM2", L"COM3", L"COM4", L"COM5", L"COM6", L"COM7", L"COM8", L"COM9",
  737. L"LPT1", L"LPT2", L"LPT3", L"LPT4", L"LPT5", L"LPT6", L"LPT7", L"LPT8", L"LPT9" };
  738. for (unsigned int Index = 0; Index < LENOF(Reserved); Index++)
  739. {
  740. if (SameText(FileName, Reserved[Index]))
  741. {
  742. return true;
  743. }
  744. }
  745. }
  746. return false;
  747. }
  748. //---------------------------------------------------------------------------
  749. // ApiPath support functions
  750. // Inspired by
  751. // http://stackoverflow.com/questions/18580945/need-clarification-for-converting-paths-into-long-unicode-paths-or-the-ones-star
  752. // This can be reimplemented using PathCchCanonicalizeEx on Windows 8 and later
  753. enum PATH_PREFIX_TYPE
  754. {
  755. PPT_UNKNOWN,
  756. PPT_ABSOLUTE, //Found absolute path that is none of the other types
  757. PPT_UNC, //Found \\server\share\ prefix
  758. PPT_LONG_UNICODE, //Found \\?\ prefix
  759. PPT_LONG_UNICODE_UNC, //Found \\?\UNC\ prefix
  760. };
  761. //---------------------------------------------------------------------------
  762. static int __fastcall PathRootLength(UnicodeString Path)
  763. {
  764. // Correction for PathSkipRoot API
  765. // Replace all /'s with \'s because PathSkipRoot can't handle /'s
  766. UnicodeString Result = ReplaceChar(Path, L'/', L'\\');
  767. // Now call the API
  768. LPCTSTR Buffer = PathSkipRoot(Result.c_str());
  769. return (Buffer != NULL) ? (Buffer - Result.c_str()) : -1;
  770. }
  771. //---------------------------------------------------------------------------
  772. static bool __fastcall PathIsRelative_CorrectedForMicrosoftStupidity(UnicodeString Path)
  773. {
  774. // Correction for PathIsRelative API
  775. // Replace all /'s with \'s because PathIsRelative can't handle /'s
  776. UnicodeString Result = ReplaceChar(Path, L'/', L'\\');
  777. //Now call the API
  778. return PathIsRelative(Result.c_str());
  779. }
  780. //---------------------------------------------------------------------------
  781. static int __fastcall GetOffsetAfterPathRoot(UnicodeString Path, PATH_PREFIX_TYPE & PrefixType)
  782. {
  783. // Checks if 'pPath' begins with the drive, share, prefix, etc
  784. // EXAMPLES:
  785. // Path Return: Points at: PrefixType:
  786. // Relative\Folder\File.txt 0 Relative\Folder\File.txt PPT_UNKNOWN
  787. // \RelativeToRoot\Folder 1 RelativeToRoot\Folder PPT_ABSOLUTE
  788. // C:\Windows\Folder 3 Windows\Folder PPT_ABSOLUTE
  789. // \\server\share\Desktop 15 Desktop PPT_UNC
  790. // \\?\C:\Windows\Folder 7 Windows\Folder PPT_LONG_UNICODE
  791. // \\?\UNC\server\share\Desktop 21 Desktop PPT_LONG_UNICODE_UNC
  792. // RETURN:
  793. // = Index in 'pPath' after the root, or
  794. // = 0 if no root was found
  795. int Result = 0;
  796. PrefixType = PPT_UNKNOWN;
  797. if (!Path.IsEmpty())
  798. {
  799. int Len = Path.Length();
  800. bool WinXPOnly = !IsWinVista();
  801. // The PathSkipRoot() API doesn't work correctly on Windows XP
  802. if (!WinXPOnly)
  803. {
  804. // Works since Vista and up, but still needs correction :)
  805. int RootLength = PathRootLength(Path);
  806. if (RootLength >= 0)
  807. {
  808. Result = RootLength + 1;
  809. }
  810. }
  811. // Now determine the type of prefix
  812. int IndCheckUNC = -1;
  813. if ((Len >= 8) &&
  814. (Path[1] == L'\\' || Path[1] == L'/') &&
  815. (Path[2] == L'\\' || Path[2] == L'/') &&
  816. (Path[3] == L'?') &&
  817. (Path[4] == L'\\' || Path[4] == L'/') &&
  818. (Path[5] == L'U' || Path[5] == L'u') &&
  819. (Path[6] == L'N' || Path[6] == L'n') &&
  820. (Path[7] == L'C' || Path[7] == L'c') &&
  821. (Path[8] == L'\\' || Path[8] == L'/'))
  822. {
  823. // Found \\?\UNC\ prefix
  824. PrefixType = PPT_LONG_UNICODE_UNC;
  825. if (WinXPOnly)
  826. {
  827. //For older OS
  828. Result += 8;
  829. }
  830. //Check for UNC share later
  831. IndCheckUNC = 8;
  832. }
  833. else if ((Len >= 4) &&
  834. (Path[1] == L'\\' || Path[1] == L'/') &&
  835. (Path[2] == L'\\' || Path[2] == L'/') &&
  836. (Path[3] == L'?') &&
  837. (Path[4] == L'\\' || Path[4] == L'/'))
  838. {
  839. // Found \\?\ prefix
  840. PrefixType = PPT_LONG_UNICODE;
  841. if (WinXPOnly)
  842. {
  843. //For older OS
  844. Result += 4;
  845. }
  846. }
  847. else if ((Len >= 2) &&
  848. (Path[1] == L'\\' || Path[1] == L'/') &&
  849. (Path[2] == L'\\' || Path[2] == L'/'))
  850. {
  851. // Check for UNC share later
  852. IndCheckUNC = 2;
  853. }
  854. if (IndCheckUNC >= 0)
  855. {
  856. // Check for UNC, i.e. \\server\share\ part
  857. int Index = IndCheckUNC;
  858. for (int SkipSlashes = 2; SkipSlashes > 0; SkipSlashes--)
  859. {
  860. for(; Index <= Len; Index++)
  861. {
  862. TCHAR z = Path[Index];
  863. if ((z == L'\\') || (z == L'/') || (Index >= Len))
  864. {
  865. Index++;
  866. if (SkipSlashes == 1)
  867. {
  868. if (PrefixType == PPT_UNKNOWN)
  869. {
  870. PrefixType = PPT_UNC;
  871. }
  872. if (WinXPOnly)
  873. {
  874. //For older OS
  875. Result = Index;
  876. }
  877. }
  878. break;
  879. }
  880. }
  881. }
  882. }
  883. if (WinXPOnly)
  884. {
  885. // Only if we didn't determine any other type
  886. if (PrefixType == PPT_UNKNOWN)
  887. {
  888. if (!PathIsRelative_CorrectedForMicrosoftStupidity(Path.SubString(Result, Path.Length() - Result + 1)))
  889. {
  890. PrefixType = PPT_ABSOLUTE;
  891. }
  892. }
  893. // For older OS only
  894. int RootLength = PathRootLength(Path.SubString(Result, Path.Length() - Result + 1));
  895. if (RootLength >= 0)
  896. {
  897. Result = RootLength + 1;
  898. }
  899. }
  900. else
  901. {
  902. // Only if we didn't determine any other type
  903. if (PrefixType == PPT_UNKNOWN)
  904. {
  905. if (!PathIsRelative_CorrectedForMicrosoftStupidity(Path))
  906. {
  907. PrefixType = PPT_ABSOLUTE;
  908. }
  909. }
  910. }
  911. }
  912. return Result;
  913. }
  914. //---------------------------------------------------------------------------
  915. UnicodeString __fastcall MakeUnicodeLargePath(UnicodeString Path)
  916. {
  917. // Convert path from 'into a larger Unicode path, that allows up to 32,767 character length
  918. UnicodeString Result;
  919. if (!Path.IsEmpty())
  920. {
  921. // Determine the type of the existing prefix
  922. PATH_PREFIX_TYPE PrefixType;
  923. GetOffsetAfterPathRoot(Path, PrefixType);
  924. // Assume path to be without change
  925. Result = Path;
  926. switch (PrefixType)
  927. {
  928. case PPT_ABSOLUTE:
  929. {
  930. // First we need to check if its an absolute path relative to the root
  931. bool AddPrefix = true;
  932. if ((Path.Length() >= 1) &&
  933. ((Path[1] == L'\\') || (Path[1] == L'/')))
  934. {
  935. AddPrefix = FALSE;
  936. // Get current root path
  937. UnicodeString CurrentDir = GetCurrentDir();
  938. PATH_PREFIX_TYPE PrefixType2; // unused
  939. int Following = GetOffsetAfterPathRoot(CurrentDir, PrefixType2);
  940. if (Following > 0)
  941. {
  942. AddPrefix = true;
  943. Result = CurrentDir.SubString(1, Following - 1) + Result.SubString(2, Result.Length() - 1);
  944. }
  945. }
  946. if (AddPrefix)
  947. {
  948. // Add \\?\ prefix
  949. Result = L"\\\\?\\" + Result;
  950. }
  951. }
  952. break;
  953. case PPT_UNC:
  954. // First we need to remove the opening slashes for UNC share
  955. if ((Result.Length() >= 2) &&
  956. ((Result[1] == L'\\') || (Result[1] == L'/')) &&
  957. ((Result[2] == L'\\') || (Result[2] == L'/')))
  958. {
  959. Result = Result.SubString(3, Result.Length() - 2);
  960. }
  961. // Add \\?\UNC\ prefix
  962. Result = L"\\\\?\\UNC\\" + Result;
  963. break;
  964. case PPT_LONG_UNICODE:
  965. case PPT_LONG_UNICODE_UNC:
  966. // nothing to do
  967. break;
  968. }
  969. }
  970. return Result;
  971. }
  972. //---------------------------------------------------------------------------
  973. UnicodeString __fastcall ApiPath(UnicodeString Path)
  974. {
  975. if (Path.Length() >= MAX_PATH)
  976. {
  977. if (Configuration != NULL)
  978. {
  979. Configuration->Usage->Inc(L"LongPath");
  980. }
  981. Path = MakeUnicodeLargePath(Path);
  982. }
  983. return Path;
  984. }
  985. //---------------------------------------------------------------------------
  986. UnicodeString __fastcall DisplayableStr(const RawByteString & Str)
  987. {
  988. bool Displayable = true;
  989. int Index = 1;
  990. while ((Index <= Str.Length()) && Displayable)
  991. {
  992. if (((Str[Index] < '\x20') || (static_cast<unsigned char>(Str[Index]) >= static_cast<unsigned char>('\x80'))) &&
  993. (Str[Index] != '\n') && (Str[Index] != '\r') && (Str[Index] != '\t') && (Str[Index] != '\b'))
  994. {
  995. Displayable = false;
  996. }
  997. Index++;
  998. }
  999. UnicodeString Result;
  1000. if (Displayable)
  1001. {
  1002. Result = L"\"";
  1003. for (int Index = 1; Index <= Str.Length(); Index++)
  1004. {
  1005. switch (Str[Index])
  1006. {
  1007. case '\n':
  1008. Result += L"\\n";
  1009. break;
  1010. case '\r':
  1011. Result += L"\\r";
  1012. break;
  1013. case '\t':
  1014. Result += L"\\t";
  1015. break;
  1016. case '\b':
  1017. Result += L"\\b";
  1018. break;
  1019. case '\\':
  1020. Result += L"\\\\";
  1021. break;
  1022. case '"':
  1023. Result += L"\\\"";
  1024. break;
  1025. default:
  1026. Result += wchar_t(Str[Index]);
  1027. break;
  1028. }
  1029. }
  1030. Result += L"\"";
  1031. }
  1032. else
  1033. {
  1034. Result = L"0x" + BytesToHex(Str);
  1035. }
  1036. return Result;
  1037. }
  1038. //---------------------------------------------------------------------------
  1039. UnicodeString __fastcall ByteToHex(unsigned char B, bool UpperCase)
  1040. {
  1041. static wchar_t UpperDigits[] = L"0123456789ABCDEF";
  1042. static wchar_t LowerDigits[] = L"0123456789abcdef";
  1043. const wchar_t * Digits = (UpperCase ? UpperDigits : LowerDigits);
  1044. UnicodeString Result;
  1045. Result.SetLength(2);
  1046. Result[1] = Digits[(B & 0xF0) >> 4];
  1047. Result[2] = Digits[(B & 0x0F) >> 0];
  1048. return Result;
  1049. }
  1050. //---------------------------------------------------------------------------
  1051. UnicodeString __fastcall BytesToHex(const unsigned char * B, size_t Length, bool UpperCase, wchar_t Separator)
  1052. {
  1053. UnicodeString Result;
  1054. for (size_t i = 0; i < Length; i++)
  1055. {
  1056. Result += ByteToHex(B[i], UpperCase);
  1057. if ((Separator != L'\0') && (i < Length - 1))
  1058. {
  1059. Result += Separator;
  1060. }
  1061. }
  1062. return Result;
  1063. }
  1064. //---------------------------------------------------------------------------
  1065. UnicodeString __fastcall BytesToHex(RawByteString Str, bool UpperCase, wchar_t Separator)
  1066. {
  1067. return BytesToHex(reinterpret_cast<const unsigned char *>(Str.c_str()), Str.Length(), UpperCase, Separator);
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. UnicodeString __fastcall CharToHex(wchar_t Ch, bool UpperCase)
  1071. {
  1072. return BytesToHex(reinterpret_cast<const unsigned char *>(&Ch), sizeof(Ch), UpperCase);
  1073. }
  1074. //---------------------------------------------------------------------------
  1075. RawByteString __fastcall HexToBytes(const UnicodeString Hex)
  1076. {
  1077. static UnicodeString Digits = L"0123456789ABCDEF";
  1078. RawByteString Result;
  1079. int L, P1, P2;
  1080. L = Hex.Length();
  1081. if (L % 2 == 0)
  1082. {
  1083. for (int i = 1; i <= Hex.Length(); i += 2)
  1084. {
  1085. P1 = Digits.Pos((wchar_t)toupper(Hex[i]));
  1086. P2 = Digits.Pos((wchar_t)toupper(Hex[i + 1]));
  1087. if (P1 <= 0 || P2 <= 0)
  1088. {
  1089. Result = L"";
  1090. break;
  1091. }
  1092. else
  1093. {
  1094. Result += static_cast<char>((P1 - 1) * 16 + P2 - 1);
  1095. }
  1096. }
  1097. }
  1098. return Result;
  1099. }
  1100. //---------------------------------------------------------------------------
  1101. unsigned char __fastcall HexToByte(const UnicodeString Hex)
  1102. {
  1103. static UnicodeString Digits = L"0123456789ABCDEF";
  1104. DebugAssert(Hex.Length() == 2);
  1105. int P1 = Digits.Pos((wchar_t)toupper(Hex[1]));
  1106. int P2 = Digits.Pos((wchar_t)toupper(Hex[2]));
  1107. return
  1108. static_cast<unsigned char>(((P1 <= 0) || (P2 <= 0)) ? 0 : (((P1 - 1) << 4) + (P2 - 1)));
  1109. }
  1110. //---------------------------------------------------------------------------
  1111. bool __fastcall IsLowerCaseLetter(wchar_t Ch)
  1112. {
  1113. return (Ch >= 'a') && (Ch <= 'z');
  1114. }
  1115. //---------------------------------------------------------------------------
  1116. bool __fastcall IsUpperCaseLetter(wchar_t Ch)
  1117. {
  1118. return (Ch >= 'A') && (Ch <= 'Z');
  1119. }
  1120. //---------------------------------------------------------------------------
  1121. bool __fastcall IsLetter(wchar_t Ch)
  1122. {
  1123. return IsLowerCaseLetter(Ch) || IsUpperCaseLetter(Ch);
  1124. }
  1125. //---------------------------------------------------------------------------
  1126. bool __fastcall IsDigit(wchar_t Ch)
  1127. {
  1128. return (Ch >= '0') && (Ch <= '9');
  1129. }
  1130. //---------------------------------------------------------------------------
  1131. bool __fastcall IsHex(wchar_t Ch)
  1132. {
  1133. return
  1134. IsDigit(Ch) ||
  1135. ((Ch >= 'A') && (Ch <= 'F')) ||
  1136. ((Ch >= 'a') && (Ch <= 'f'));
  1137. }
  1138. //---------------------------------------------------------------------------
  1139. int __fastcall FindCheck(int Result, const UnicodeString & Path)
  1140. {
  1141. if ((Result != ERROR_SUCCESS) &&
  1142. (Result != ERROR_FILE_NOT_FOUND) &&
  1143. (Result != ERROR_NO_MORE_FILES))
  1144. {
  1145. throw EOSExtException(FMTLOAD(FIND_FILE_ERROR, (Path)), Result);
  1146. }
  1147. return Result;
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. int __fastcall FindFirstUnchecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  1151. {
  1152. F.Path = Path;
  1153. return FindFirst(ApiPath(Path), Attr, F);
  1154. }
  1155. //---------------------------------------------------------------------------
  1156. int __fastcall FindFirstChecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  1157. {
  1158. int Result = FindFirstUnchecked(Path, Attr, F);
  1159. return FindCheck(Result, F.Path);
  1160. }
  1161. //---------------------------------------------------------------------------
  1162. // Equivalent to FindNext, just to complement to FindFirstUnchecked
  1163. int __fastcall FindNextUnchecked(TSearchRecChecked & F)
  1164. {
  1165. return FindNext(F);
  1166. }
  1167. //---------------------------------------------------------------------------
  1168. // It can make sense to use FindNextChecked, even if unchecked FindFirst is used.
  1169. // I.e. even if we do not care that FindFirst failed, if FindNext
  1170. // fails after successful FindFirst, it means some terrible problem
  1171. int __fastcall FindNextChecked(TSearchRecChecked & F)
  1172. {
  1173. return FindCheck(FindNextUnchecked(F), F.Path);
  1174. }
  1175. //---------------------------------------------------------------------------
  1176. bool __fastcall FileSearchRec(const UnicodeString FileName, TSearchRec & Rec)
  1177. {
  1178. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1179. bool Result = (FindFirst(ApiPath(FileName), FindAttrs, Rec) == 0);
  1180. if (Result)
  1181. {
  1182. FindClose(Rec);
  1183. }
  1184. return Result;
  1185. }
  1186. //---------------------------------------------------------------------------
  1187. void __fastcall ProcessLocalDirectory(UnicodeString DirName,
  1188. TProcessLocalFileEvent CallBackFunc, void * Param,
  1189. int FindAttrs)
  1190. {
  1191. DebugAssert(CallBackFunc);
  1192. if (FindAttrs < 0)
  1193. {
  1194. FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1195. }
  1196. TSearchRecChecked SearchRec;
  1197. DirName = IncludeTrailingBackslash(DirName);
  1198. if (FindFirstChecked(DirName + L"*.*", FindAttrs, SearchRec) == 0)
  1199. {
  1200. try
  1201. {
  1202. do
  1203. {
  1204. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  1205. {
  1206. CallBackFunc(DirName + SearchRec.Name, SearchRec, Param);
  1207. }
  1208. } while (FindNextChecked(SearchRec) == 0);
  1209. }
  1210. __finally
  1211. {
  1212. FindClose(SearchRec);
  1213. }
  1214. }
  1215. }
  1216. //---------------------------------------------------------------------------
  1217. TDateTime __fastcall EncodeDateVerbose(Word Year, Word Month, Word Day)
  1218. {
  1219. try
  1220. {
  1221. TDateTime DateTime = EncodeDate(Year, Month, Day);
  1222. return DateTime;
  1223. }
  1224. catch (EConvertError & E)
  1225. {
  1226. throw EConvertError(FORMAT(L"%s [%d-%d-%d]", (E.Message, int(Year), int(Month), int(Day))));
  1227. }
  1228. }
  1229. //---------------------------------------------------------------------------
  1230. TDateTime __fastcall EncodeTimeVerbose(Word Hour, Word Min, Word Sec, Word MSec)
  1231. {
  1232. try
  1233. {
  1234. TDateTime DateTime = EncodeTime(Hour, Min, Sec, MSec);
  1235. return DateTime;
  1236. }
  1237. catch (EConvertError & E)
  1238. {
  1239. throw EConvertError(FORMAT(L"%s [%d:%d:%d.%d]", (E.Message, int(Hour), int(Min), int(Sec), int(MSec))));
  1240. }
  1241. }
  1242. //---------------------------------------------------------------------------
  1243. TDateTime __fastcall SystemTimeToDateTimeVerbose(const SYSTEMTIME & SystemTime)
  1244. {
  1245. try
  1246. {
  1247. TDateTime DateTime = SystemTimeToDateTime(SystemTime);
  1248. return DateTime;
  1249. }
  1250. catch (EConvertError & E)
  1251. {
  1252. 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))));
  1253. }
  1254. }
  1255. //---------------------------------------------------------------------------
  1256. struct TDateTimeParams
  1257. {
  1258. TDateTime UnixEpoch;
  1259. double BaseDifference;
  1260. long BaseDifferenceSec;
  1261. // All Current* are actually global, not per-year and
  1262. // are valid for Year 0 (current) only
  1263. double CurrentDaylightDifference;
  1264. long CurrentDaylightDifferenceSec;
  1265. double CurrentDifference;
  1266. long CurrentDifferenceSec;
  1267. double StandardDifference;
  1268. long StandardDifferenceSec;
  1269. double DaylightDifference;
  1270. long DaylightDifferenceSec;
  1271. SYSTEMTIME SystemStandardDate;
  1272. SYSTEMTIME SystemDaylightDate;
  1273. TDateTime StandardDate;
  1274. TDateTime DaylightDate;
  1275. UnicodeString StandardName;
  1276. UnicodeString DaylightName;
  1277. // This is actually global, not per-year
  1278. bool DaylightHack;
  1279. bool HasDST() const
  1280. {
  1281. // On some systems it occurs that StandardDate is unset, while
  1282. // DaylightDate is set. MSDN states that this is invalid and
  1283. // should be treated as if there is no daylight saving.
  1284. // So check both.
  1285. return
  1286. (SystemStandardDate.wMonth != 0) &&
  1287. (SystemDaylightDate.wMonth != 0);
  1288. }
  1289. bool SummerDST() const
  1290. {
  1291. return HasDST() && (DaylightDate < StandardDate);
  1292. }
  1293. };
  1294. typedef std::map<int, TDateTimeParams> TYearlyDateTimeParams;
  1295. static TYearlyDateTimeParams YearlyDateTimeParams;
  1296. static std::unique_ptr<TCriticalSection> DateTimeParamsSection(new TCriticalSection());
  1297. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1298. TDateTime & Result);
  1299. //---------------------------------------------------------------------------
  1300. static unsigned short __fastcall DecodeYear(const TDateTime & DateTime)
  1301. {
  1302. unsigned short Year, Month, Day;
  1303. DecodeDate(DateTime, Year, Month, Day);
  1304. return Year;
  1305. }
  1306. //---------------------------------------------------------------------------
  1307. static const TDateTimeParams * __fastcall GetDateTimeParams(unsigned short Year)
  1308. {
  1309. TGuard Guard(DateTimeParamsSection.get());
  1310. TDateTimeParams * Result;
  1311. TYearlyDateTimeParams::iterator i = YearlyDateTimeParams.find(Year);
  1312. if (i != YearlyDateTimeParams.end())
  1313. {
  1314. Result = &(*i).second;
  1315. }
  1316. else
  1317. {
  1318. // creates new entry as a side effect
  1319. Result = &YearlyDateTimeParams[Year];
  1320. TIME_ZONE_INFORMATION TZI;
  1321. unsigned long GTZI;
  1322. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  1323. typedef BOOL WINAPI (* TGetTimeZoneInformationForYear)(USHORT wYear, PDYNAMIC_TIME_ZONE_INFORMATION pdtzi, LPTIME_ZONE_INFORMATION ptzi);
  1324. TGetTimeZoneInformationForYear GetTimeZoneInformationForYear =
  1325. (TGetTimeZoneInformationForYear)GetProcAddress(Kernel32, "GetTimeZoneInformationForYear");
  1326. if ((Year == 0) || (GetTimeZoneInformationForYear == NULL))
  1327. {
  1328. GTZI = GetTimeZoneInformation(&TZI);
  1329. }
  1330. else
  1331. {
  1332. GetTimeZoneInformationForYear(Year, NULL, &TZI);
  1333. GTZI = TIME_ZONE_ID_UNKNOWN;
  1334. }
  1335. switch (GTZI)
  1336. {
  1337. case TIME_ZONE_ID_UNKNOWN:
  1338. Result->CurrentDaylightDifferenceSec = 0;
  1339. break;
  1340. case TIME_ZONE_ID_STANDARD:
  1341. Result->CurrentDaylightDifferenceSec = TZI.StandardBias;
  1342. break;
  1343. case TIME_ZONE_ID_DAYLIGHT:
  1344. Result->CurrentDaylightDifferenceSec = TZI.DaylightBias;
  1345. break;
  1346. case TIME_ZONE_ID_INVALID:
  1347. default:
  1348. throw Exception(TIMEZONE_ERROR);
  1349. }
  1350. Result->BaseDifferenceSec = TZI.Bias;
  1351. Result->BaseDifference = double(TZI.Bias) / MinsPerDay;
  1352. Result->BaseDifferenceSec *= SecsPerMin;
  1353. Result->CurrentDifferenceSec = TZI.Bias +
  1354. Result->CurrentDaylightDifferenceSec;
  1355. Result->CurrentDifference =
  1356. double(Result->CurrentDifferenceSec) / MinsPerDay;
  1357. Result->CurrentDifferenceSec *= SecsPerMin;
  1358. Result->CurrentDaylightDifference =
  1359. double(Result->CurrentDaylightDifferenceSec) / MinsPerDay;
  1360. Result->CurrentDaylightDifferenceSec *= SecsPerMin;
  1361. Result->DaylightDifferenceSec = TZI.DaylightBias * SecsPerMin;
  1362. Result->DaylightDifference = double(TZI.DaylightBias) / MinsPerDay;
  1363. Result->StandardDifferenceSec = TZI.StandardBias * SecsPerMin;
  1364. Result->StandardDifference = double(TZI.StandardBias) / MinsPerDay;
  1365. Result->SystemStandardDate = TZI.StandardDate;
  1366. Result->SystemDaylightDate = TZI.DaylightDate;
  1367. unsigned short AYear = (Year != 0) ? Year : DecodeYear(Now());
  1368. if (Result->HasDST())
  1369. {
  1370. EncodeDSTMargin(Result->SystemStandardDate, AYear, Result->StandardDate);
  1371. EncodeDSTMargin(Result->SystemDaylightDate, AYear, Result->DaylightDate);
  1372. }
  1373. Result->StandardName = TZI.StandardName;
  1374. Result->DaylightName = TZI.DaylightName;
  1375. Result->DaylightHack = !IsWin7();
  1376. }
  1377. return Result;
  1378. }
  1379. //---------------------------------------------------------------------------
  1380. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1381. TDateTime & Result)
  1382. {
  1383. if (Date.wYear == 0)
  1384. {
  1385. TDateTime Temp = EncodeDateVerbose(Year, Date.wMonth, 1);
  1386. Result = Temp + ((Date.wDayOfWeek - DayOfWeek(Temp) + 8) % 7) +
  1387. (7 * (Date.wDay - 1));
  1388. // Day 5 means, the last occurence of day-of-week in month
  1389. if (Date.wDay == 5)
  1390. {
  1391. unsigned short Month = static_cast<unsigned short>(Date.wMonth + 1);
  1392. if (Month > 12)
  1393. {
  1394. Month = static_cast<unsigned short>(Month - 12);
  1395. Year++;
  1396. }
  1397. if (Result >= EncodeDateVerbose(Year, Month, 1))
  1398. {
  1399. Result -= 7;
  1400. }
  1401. }
  1402. Result += EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond,
  1403. Date.wMilliseconds);
  1404. }
  1405. else
  1406. {
  1407. Result = EncodeDateVerbose(Year, Date.wMonth, Date.wDay) +
  1408. EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond, Date.wMilliseconds);
  1409. }
  1410. }
  1411. //---------------------------------------------------------------------------
  1412. static bool __fastcall IsDateInDST(const TDateTime & DateTime)
  1413. {
  1414. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1415. bool Result;
  1416. // On some systems it occurs that StandardDate is unset, while
  1417. // DaylightDate is set. MSDN states that this is invalid and
  1418. // should be treated as if there is no daylight saving.
  1419. // So check both.
  1420. if (!Params->HasDST())
  1421. {
  1422. Result = false;
  1423. }
  1424. else
  1425. {
  1426. if (Params->SummerDST())
  1427. {
  1428. Result =
  1429. (DateTime >= Params->DaylightDate) &&
  1430. (DateTime < Params->StandardDate);
  1431. }
  1432. else
  1433. {
  1434. Result =
  1435. (DateTime < Params->StandardDate) ||
  1436. (DateTime >= Params->DaylightDate);
  1437. }
  1438. }
  1439. return Result;
  1440. }
  1441. //---------------------------------------------------------------------------
  1442. bool __fastcall UsesDaylightHack()
  1443. {
  1444. return GetDateTimeParams(0)->DaylightHack;
  1445. }
  1446. //---------------------------------------------------------------------------
  1447. TDateTime __fastcall UnixToDateTime(__int64 TimeStamp, TDSTMode DSTMode)
  1448. {
  1449. DebugAssert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1450. TDateTime Result = UnixDateDelta + (double(TimeStamp) / SecsPerDay);
  1451. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(Result));
  1452. if (Params->DaylightHack)
  1453. {
  1454. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1455. {
  1456. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1457. Result -= CurrentParams->CurrentDifference;
  1458. }
  1459. else if (DSTMode == dstmKeep)
  1460. {
  1461. Result -= Params->BaseDifference;
  1462. }
  1463. }
  1464. else
  1465. {
  1466. Result -= Params->BaseDifference;
  1467. }
  1468. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1469. {
  1470. Result -= (IsDateInDST(Result) ?
  1471. Params->DaylightDifference : Params->StandardDifference);
  1472. }
  1473. return Result;
  1474. }
  1475. //---------------------------------------------------------------------------
  1476. __int64 __fastcall Round(double Number)
  1477. {
  1478. double Floor = floor(Number);
  1479. double Ceil = ceil(Number);
  1480. return static_cast<__int64>(((Number - Floor) > (Ceil - Number)) ? Ceil : Floor);
  1481. }
  1482. //---------------------------------------------------------------------------
  1483. bool __fastcall TryRelativeStrToDateTime(UnicodeString S, TDateTime & DateTime)
  1484. {
  1485. S = S.Trim();
  1486. int Index = 1;
  1487. while ((Index <= S.Length()) && IsDigit(S[Index]))
  1488. {
  1489. Index++;
  1490. }
  1491. UnicodeString NumberStr = S.SubString(1, Index - 1);
  1492. int Number;
  1493. bool Result = TryStrToInt(NumberStr, Number);
  1494. if (Result)
  1495. {
  1496. S.Delete(1, Index - 1);
  1497. S = S.Trim().UpperCase();
  1498. DateTime = Now();
  1499. // These may not overlap with ParseSize (K, M and G)
  1500. if (S == "S")
  1501. {
  1502. DateTime = IncSecond(DateTime, -Number);
  1503. }
  1504. else if (S == "N")
  1505. {
  1506. DateTime = IncMinute(DateTime, -Number);
  1507. }
  1508. else if (S == "H")
  1509. {
  1510. DateTime = IncHour(DateTime, -Number);
  1511. }
  1512. else if (S == "D")
  1513. {
  1514. DateTime = IncDay(DateTime, -Number);
  1515. }
  1516. else if (S == "Y")
  1517. {
  1518. DateTime = IncYear(DateTime, -Number);
  1519. }
  1520. else
  1521. {
  1522. Result = false;
  1523. }
  1524. }
  1525. return Result;
  1526. }
  1527. //---------------------------------------------------------------------------
  1528. static __int64 __fastcall DateTimeToUnix(const TDateTime DateTime)
  1529. {
  1530. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1531. DebugAssert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1532. return Round(double(DateTime - UnixDateDelta) * SecsPerDay) +
  1533. CurrentParams->CurrentDifferenceSec;
  1534. }
  1535. //---------------------------------------------------------------------------
  1536. FILETIME __fastcall DateTimeToFileTime(const TDateTime DateTime,
  1537. TDSTMode /*DSTMode*/)
  1538. {
  1539. __int64 UnixTimeStamp = ::DateTimeToUnix(DateTime);
  1540. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1541. if (!Params->DaylightHack)
  1542. {
  1543. // We should probably use reversed code of FileTimeToDateTime here instead of custom implementation
  1544. // We are incrementing and decrementing BaseDifferenceSec because it
  1545. // can actually change between years
  1546. // (as it did in Belarus from GMT+2 to GMT+3 between 2011 and 2012)
  1547. UnixTimeStamp += (IsDateInDST(DateTime) ?
  1548. Params->DaylightDifferenceSec : Params->StandardDifferenceSec) +
  1549. Params->BaseDifferenceSec;
  1550. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1551. UnixTimeStamp -=
  1552. CurrentParams->CurrentDaylightDifferenceSec +
  1553. CurrentParams->BaseDifferenceSec;
  1554. }
  1555. FILETIME Result;
  1556. (*(__int64*)&(Result) = (__int64(UnixTimeStamp) + 11644473600LL) * 10000000LL);
  1557. return Result;
  1558. }
  1559. //---------------------------------------------------------------------------
  1560. TDateTime __fastcall FileTimeToDateTime(const FILETIME & FileTime)
  1561. {
  1562. // duplicated in DirView.pas
  1563. TDateTime Result;
  1564. // The 0xFFF... is sometime seen for invalid timestamps,
  1565. // it would cause failure in SystemTimeToDateTime below
  1566. if (FileTime.dwLowDateTime == std::numeric_limits<DWORD>::max())
  1567. {
  1568. Result = MinDateTime;
  1569. }
  1570. else
  1571. {
  1572. SYSTEMTIME SysTime;
  1573. if (!UsesDaylightHack())
  1574. {
  1575. SYSTEMTIME UniverzalSysTime;
  1576. FileTimeToSystemTime(&FileTime, &UniverzalSysTime);
  1577. SystemTimeToTzSpecificLocalTime(NULL, &UniverzalSysTime, &SysTime);
  1578. }
  1579. else
  1580. {
  1581. FILETIME LocalFileTime;
  1582. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1583. FileTimeToSystemTime(&LocalFileTime, &SysTime);
  1584. }
  1585. Result = SystemTimeToDateTimeVerbose(SysTime);
  1586. }
  1587. return Result;
  1588. }
  1589. //---------------------------------------------------------------------------
  1590. __int64 __fastcall ConvertTimestampToUnix(const FILETIME & FileTime,
  1591. TDSTMode DSTMode)
  1592. {
  1593. __int64 Result = ((*(__int64*)&(FileTime)) / 10000000LL - 11644473600LL);
  1594. if (UsesDaylightHack())
  1595. {
  1596. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1597. {
  1598. FILETIME LocalFileTime;
  1599. SYSTEMTIME SystemTime;
  1600. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1601. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1602. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  1603. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1604. Result += (IsDateInDST(DateTime) ?
  1605. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1606. if (DSTMode == dstmKeep)
  1607. {
  1608. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1609. Result -= CurrentParams->CurrentDaylightDifferenceSec;
  1610. }
  1611. }
  1612. }
  1613. else
  1614. {
  1615. if (DSTMode == dstmWin)
  1616. {
  1617. FILETIME LocalFileTime;
  1618. SYSTEMTIME SystemTime;
  1619. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1620. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1621. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  1622. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1623. Result -= (IsDateInDST(DateTime) ?
  1624. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1625. }
  1626. }
  1627. return Result;
  1628. }
  1629. //---------------------------------------------------------------------------
  1630. TDateTime __fastcall ConvertTimestampToUTC(TDateTime DateTime)
  1631. {
  1632. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1633. DateTime +=
  1634. (IsDateInDST(DateTime) ?
  1635. Params->DaylightDifference : Params->StandardDifference);
  1636. DateTime += Params->BaseDifference;
  1637. if (Params->DaylightHack)
  1638. {
  1639. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1640. DateTime += CurrentParams->CurrentDaylightDifference;
  1641. }
  1642. return DateTime;
  1643. }
  1644. //---------------------------------------------------------------------------
  1645. TDateTime __fastcall ConvertTimestampFromUTC(TDateTime DateTime)
  1646. {
  1647. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1648. DateTime -=
  1649. (IsDateInDST(DateTime) ?
  1650. Params->DaylightDifference : Params->StandardDifference);
  1651. DateTime -= Params->BaseDifference;
  1652. if (Params->DaylightHack)
  1653. {
  1654. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1655. DateTime -= CurrentParams->CurrentDaylightDifference;
  1656. }
  1657. return DateTime;
  1658. }
  1659. //---------------------------------------------------------------------------
  1660. __int64 __fastcall ConvertTimestampToUnixSafe(const FILETIME & FileTime,
  1661. TDSTMode DSTMode)
  1662. {
  1663. __int64 Result;
  1664. if ((FileTime.dwLowDateTime == 0) &&
  1665. (FileTime.dwHighDateTime == 0))
  1666. {
  1667. Result = ::DateTimeToUnix(Now());
  1668. }
  1669. else
  1670. {
  1671. Result = ConvertTimestampToUnix(FileTime, DSTMode);
  1672. }
  1673. return Result;
  1674. }
  1675. //---------------------------------------------------------------------------
  1676. TDateTime __fastcall AdjustDateTimeFromUnix(TDateTime DateTime, TDSTMode DSTMode)
  1677. {
  1678. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1679. if (Params->DaylightHack)
  1680. {
  1681. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1682. {
  1683. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1684. DateTime = DateTime - CurrentParams->CurrentDaylightDifference;
  1685. }
  1686. if (!IsDateInDST(DateTime))
  1687. {
  1688. if (DSTMode == dstmWin)
  1689. {
  1690. DateTime = DateTime - Params->DaylightDifference;
  1691. }
  1692. }
  1693. else
  1694. {
  1695. DateTime = DateTime - Params->StandardDifference;
  1696. }
  1697. }
  1698. else
  1699. {
  1700. if (DSTMode == dstmWin)
  1701. {
  1702. if (IsDateInDST(DateTime))
  1703. {
  1704. DateTime = DateTime + Params->DaylightDifference;
  1705. }
  1706. else
  1707. {
  1708. DateTime = DateTime + Params->StandardDifference;
  1709. }
  1710. }
  1711. }
  1712. return DateTime;
  1713. }
  1714. //---------------------------------------------------------------------------
  1715. UnicodeString __fastcall FixedLenDateTimeFormat(const UnicodeString & Format)
  1716. {
  1717. UnicodeString Result = Format;
  1718. bool AsIs = false;
  1719. int Index = 1;
  1720. while (Index <= Result.Length())
  1721. {
  1722. wchar_t F = Result[Index];
  1723. if ((F == L'\'') || (F == L'\"'))
  1724. {
  1725. AsIs = !AsIs;
  1726. Index++;
  1727. }
  1728. else if (!AsIs && ((F == L'a') || (F == L'A')))
  1729. {
  1730. if (Result.SubString(Index, 5).LowerCase() == L"am/pm")
  1731. {
  1732. Index += 5;
  1733. }
  1734. else if (Result.SubString(Index, 3).LowerCase() == L"a/p")
  1735. {
  1736. Index += 3;
  1737. }
  1738. else if (Result.SubString(Index, 4).LowerCase() == L"ampm")
  1739. {
  1740. Index += 4;
  1741. }
  1742. else
  1743. {
  1744. Index++;
  1745. }
  1746. }
  1747. else
  1748. {
  1749. if (!AsIs && (wcschr(L"dDeEmMhHnNsS", F) != NULL) &&
  1750. ((Index == Result.Length()) || (Result[Index + 1] != F)))
  1751. {
  1752. Result.Insert(F, Index);
  1753. }
  1754. while ((Index <= Result.Length()) && (F == Result[Index]))
  1755. {
  1756. Index++;
  1757. }
  1758. }
  1759. }
  1760. return Result;
  1761. }
  1762. //---------------------------------------------------------------------------
  1763. UnicodeString __fastcall FormatTimeZone(long Sec)
  1764. {
  1765. TTimeSpan Span = TTimeSpan::FromSeconds(Sec);
  1766. UnicodeString Str;
  1767. if ((Span.Seconds == 0) && (Span.Minutes == 0))
  1768. {
  1769. Str = FORMAT(L"%d", (-Span.Hours));
  1770. }
  1771. else if (Span.Seconds == 0)
  1772. {
  1773. Str = FORMAT(L"%d:%2.2d", (-Span.Hours, abs(Span.Minutes)));
  1774. }
  1775. else
  1776. {
  1777. Str = FORMAT(L"%d:%2.2d:%2.2d", (-Span.Hours, abs(Span.Minutes), abs(Span.Seconds)));
  1778. }
  1779. Str = ((Span <= TTimeSpan::Zero) ? L"+" : L"") + Str;
  1780. return Str;
  1781. }
  1782. //---------------------------------------------------------------------------
  1783. UnicodeString __fastcall GetTimeZoneLogString()
  1784. {
  1785. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1786. UnicodeString Result =
  1787. FORMAT(L"Current: GMT%s", (FormatTimeZone(CurrentParams->CurrentDifferenceSec)));
  1788. if (!CurrentParams->HasDST())
  1789. {
  1790. Result += FORMAT(L" (%s), No DST", (CurrentParams->StandardName));
  1791. }
  1792. else
  1793. {
  1794. Result +=
  1795. FORMAT(L", Standard: GMT%s (%s), DST: GMT%s (%s), DST Start: %s, DST End: %s",
  1796. (FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->StandardDifferenceSec),
  1797. CurrentParams->StandardName,
  1798. FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->DaylightDifferenceSec),
  1799. CurrentParams->DaylightName,
  1800. CurrentParams->DaylightDate.DateString(),
  1801. CurrentParams->StandardDate.DateString()));
  1802. }
  1803. return Result;
  1804. }
  1805. //---------------------------------------------------------------------------
  1806. bool __fastcall AdjustClockForDSTEnabled()
  1807. {
  1808. // Windows XP deletes the DisableAutoDaylightTimeSet value when it is off
  1809. // (the later versions set it to DynamicDaylightTimeDisabled to 0)
  1810. bool DynamicDaylightTimeDisabled = false;
  1811. TRegistry * Registry = new TRegistry(KEY_READ);
  1812. try
  1813. {
  1814. Registry->RootKey = HKEY_LOCAL_MACHINE;
  1815. if (Registry->OpenKey(L"SYSTEM", false) &&
  1816. Registry->OpenKey(L"CurrentControlSet", false) &&
  1817. Registry->OpenKey(L"Control", false) &&
  1818. Registry->OpenKey(L"TimeZoneInformation", false))
  1819. {
  1820. if (Registry->ValueExists(L"DynamicDaylightTimeDisabled"))
  1821. {
  1822. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DynamicDaylightTimeDisabled");
  1823. }
  1824. // WORKAROUND
  1825. // Windows XP equivalent
  1826. else if (Registry->ValueExists(L"DisableAutoDaylightTimeSet"))
  1827. {
  1828. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DisableAutoDaylightTimeSet");
  1829. }
  1830. }
  1831. delete Registry;
  1832. }
  1833. catch(...)
  1834. {
  1835. }
  1836. return !DynamicDaylightTimeDisabled;
  1837. }
  1838. //---------------------------------------------------------------------------
  1839. UnicodeString __fastcall StandardDatestamp()
  1840. {
  1841. return FormatDateTime(L"yyyy'-'mm'-'dd", ConvertTimestampToUTC(Now()));
  1842. }
  1843. //---------------------------------------------------------------------------
  1844. UnicodeString __fastcall StandardTimestamp(const TDateTime & DateTime)
  1845. {
  1846. return FormatDateTime(L"yyyy'-'mm'-'dd'T'hh':'nn':'ss'.'zzz'Z'", ConvertTimestampToUTC(DateTime));
  1847. }
  1848. //---------------------------------------------------------------------------
  1849. UnicodeString __fastcall StandardTimestamp()
  1850. {
  1851. return StandardTimestamp(Now());
  1852. }
  1853. //---------------------------------------------------------------------------
  1854. static TDateTime TwoSeconds(0, 0, 2, 0);
  1855. int __fastcall CompareFileTime(TDateTime T1, TDateTime T2)
  1856. {
  1857. // "FAT" time precision
  1858. // (when one time is seconds-precision and other is millisecond-precision,
  1859. // we may have times like 12:00:00.000 and 12:00:01.999, which should
  1860. // be treated the same)
  1861. int Result;
  1862. if (T1 == T2)
  1863. {
  1864. // just optimization
  1865. Result = 0;
  1866. }
  1867. else if ((T1 < T2) && (T2 - T1 >= TwoSeconds))
  1868. {
  1869. Result = -1;
  1870. }
  1871. else if ((T1 > T2) && (T1 - T2 >= TwoSeconds))
  1872. {
  1873. Result = 1;
  1874. }
  1875. else
  1876. {
  1877. Result = 0;
  1878. }
  1879. return Result;
  1880. }
  1881. //---------------------------------------------------------------------------
  1882. int __fastcall TimeToMSec(TDateTime T)
  1883. {
  1884. return int(Round(double(T) * double(MSecsPerDay)));
  1885. }
  1886. //---------------------------------------------------------------------------
  1887. int __fastcall TimeToSeconds(TDateTime T)
  1888. {
  1889. return TimeToMSec(T) / MSecsPerSec;
  1890. }
  1891. //---------------------------------------------------------------------------
  1892. int __fastcall TimeToMinutes(TDateTime T)
  1893. {
  1894. return TimeToSeconds(T) / SecsPerMin;
  1895. }
  1896. //---------------------------------------------------------------------------
  1897. static bool __fastcall DoRecursiveDeleteFile(const UnicodeString FileName, bool ToRecycleBin, UnicodeString & ErrorPath)
  1898. {
  1899. bool Result;
  1900. UnicodeString AErrorPath = FileName;
  1901. if (!ToRecycleBin)
  1902. {
  1903. TSearchRecChecked SearchRec;
  1904. Result = FileSearchRec(FileName, SearchRec);
  1905. if (Result)
  1906. {
  1907. if (FLAGCLEAR(SearchRec.Attr, faDirectory))
  1908. {
  1909. Result = DeleteFile(ApiPath(FileName));
  1910. }
  1911. else
  1912. {
  1913. Result = (FindFirstUnchecked(FileName + L"\\*", faAnyFile, SearchRec) == 0);
  1914. if (Result)
  1915. {
  1916. try
  1917. {
  1918. do
  1919. {
  1920. UnicodeString FileName2 = FileName + L"\\" + SearchRec.Name;
  1921. if (FLAGSET(SearchRec.Attr, faDirectory))
  1922. {
  1923. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  1924. {
  1925. Result = DoRecursiveDeleteFile(FileName2, ALWAYS_FALSE(ToRecycleBin), AErrorPath);
  1926. }
  1927. }
  1928. else
  1929. {
  1930. Result = DeleteFile(ApiPath(FileName2));
  1931. if (!Result)
  1932. {
  1933. AErrorPath = FileName2;
  1934. }
  1935. }
  1936. }
  1937. while (Result && (FindNextUnchecked(SearchRec) == 0));
  1938. }
  1939. __finally
  1940. {
  1941. FindClose(SearchRec);
  1942. }
  1943. if (Result)
  1944. {
  1945. Result = RemoveDir(ApiPath(FileName));
  1946. }
  1947. }
  1948. }
  1949. }
  1950. }
  1951. else
  1952. {
  1953. SHFILEOPSTRUCT Data;
  1954. memset(&Data, 0, sizeof(Data));
  1955. Data.hwnd = NULL;
  1956. Data.wFunc = FO_DELETE;
  1957. // SHFileOperation does not support long paths anyway
  1958. UnicodeString FileList(ApiPath(FileName));
  1959. FileList.SetLength(FileList.Length() + 2);
  1960. FileList[FileList.Length() - 1] = L'\0';
  1961. FileList[FileList.Length()] = L'\0';
  1962. Data.pFrom = FileList.c_str();
  1963. Data.pTo = L"\0\0"; // this will actually give one null more than needed
  1964. Data.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION | FOF_NOCONFIRMMKDIR |
  1965. FOF_NOERRORUI | FOF_SILENT;
  1966. if (ALWAYS_TRUE(ToRecycleBin))
  1967. {
  1968. Data.fFlags |= FOF_ALLOWUNDO;
  1969. }
  1970. int ErrorCode = SHFileOperation(&Data);
  1971. Result = (ErrorCode == 0);
  1972. if (!Result)
  1973. {
  1974. // according to MSDN, SHFileOperation may return following non-Win32
  1975. // error codes
  1976. if (((ErrorCode >= 0x71) && (ErrorCode <= 0x88)) ||
  1977. (ErrorCode == 0xB7) || (ErrorCode == 0x402) || (ErrorCode == 0x10000) ||
  1978. (ErrorCode == 0x10074))
  1979. {
  1980. ErrorCode = 0;
  1981. }
  1982. SetLastError(ErrorCode);
  1983. }
  1984. }
  1985. if (!Result)
  1986. {
  1987. ErrorPath = AErrorPath;
  1988. }
  1989. return Result;
  1990. }
  1991. //---------------------------------------------------------------------------
  1992. bool __fastcall RecursiveDeleteFile(const UnicodeString & FileName, bool ToRecycleBin)
  1993. {
  1994. UnicodeString ErrorPath; // unused
  1995. return DoRecursiveDeleteFile(FileName, ToRecycleBin, ErrorPath);
  1996. }
  1997. //---------------------------------------------------------------------------
  1998. void __fastcall RecursiveDeleteFileChecked(const UnicodeString & FileName, bool ToRecycleBin)
  1999. {
  2000. UnicodeString ErrorPath;
  2001. if (!DoRecursiveDeleteFile(FileName, ToRecycleBin, ErrorPath))
  2002. {
  2003. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (ErrorPath)));
  2004. }
  2005. }
  2006. //---------------------------------------------------------------------------
  2007. void __fastcall DeleteFileChecked(const UnicodeString & FileName)
  2008. {
  2009. if (!DeleteFile(ApiPath(FileName)))
  2010. {
  2011. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  2012. }
  2013. }
  2014. //---------------------------------------------------------------------------
  2015. unsigned int __fastcall CancelAnswer(unsigned int Answers)
  2016. {
  2017. unsigned int Result;
  2018. if ((Answers & qaCancel) != 0)
  2019. {
  2020. Result = qaCancel;
  2021. }
  2022. else if ((Answers & qaNo) != 0)
  2023. {
  2024. Result = qaNo;
  2025. }
  2026. else if ((Answers & qaAbort) != 0)
  2027. {
  2028. Result = qaAbort;
  2029. }
  2030. else if ((Answers & qaOK) != 0)
  2031. {
  2032. Result = qaOK;
  2033. }
  2034. else
  2035. {
  2036. FAIL;
  2037. Result = qaCancel;
  2038. }
  2039. return Result;
  2040. }
  2041. //---------------------------------------------------------------------------
  2042. unsigned int __fastcall AbortAnswer(unsigned int Answers)
  2043. {
  2044. unsigned int Result;
  2045. if (FLAGSET(Answers, qaAbort))
  2046. {
  2047. Result = qaAbort;
  2048. }
  2049. else
  2050. {
  2051. Result = CancelAnswer(Answers);
  2052. }
  2053. return Result;
  2054. }
  2055. //---------------------------------------------------------------------------
  2056. unsigned int __fastcall ContinueAnswer(unsigned int Answers)
  2057. {
  2058. unsigned int Result;
  2059. if (FLAGSET(Answers, qaSkip))
  2060. {
  2061. Result = qaSkip;
  2062. }
  2063. else if (FLAGSET(Answers, qaIgnore))
  2064. {
  2065. Result = qaIgnore;
  2066. }
  2067. else if (FLAGSET(Answers, qaYes))
  2068. {
  2069. Result = qaYes;
  2070. }
  2071. else if (FLAGSET(Answers, qaOK))
  2072. {
  2073. Result = qaOK;
  2074. }
  2075. else if (FLAGSET(Answers, qaRetry))
  2076. {
  2077. Result = qaRetry;
  2078. }
  2079. else
  2080. {
  2081. Result = CancelAnswer(Answers);
  2082. }
  2083. return Result;
  2084. }
  2085. //---------------------------------------------------------------------------
  2086. TLibModule * __fastcall FindModule(void * Instance)
  2087. {
  2088. TLibModule * CurModule;
  2089. CurModule = reinterpret_cast<TLibModule*>(LibModuleList);
  2090. while (CurModule)
  2091. {
  2092. if (CurModule->Instance == (unsigned)Instance)
  2093. {
  2094. break;
  2095. }
  2096. else
  2097. {
  2098. CurModule = CurModule->Next;
  2099. }
  2100. }
  2101. return CurModule;
  2102. }
  2103. //---------------------------------------------------------------------------
  2104. UnicodeString __fastcall LoadStr(int Ident, unsigned int MaxLength)
  2105. {
  2106. TLibModule * MainModule = FindModule(HInstance);
  2107. DebugAssert(MainModule != NULL);
  2108. UnicodeString Result;
  2109. Result.SetLength(MaxLength);
  2110. int Length = LoadString((HINSTANCE)MainModule->ResInstance, Ident, Result.c_str(), MaxLength);
  2111. Result.SetLength(Length);
  2112. return Result;
  2113. }
  2114. //---------------------------------------------------------------------------
  2115. UnicodeString __fastcall LoadStrPart(int Ident, int Part)
  2116. {
  2117. UnicodeString Result;
  2118. UnicodeString Str = LoadStr(Ident);
  2119. while (Part > 0)
  2120. {
  2121. Result = CutToChar(Str, L'|', false);
  2122. Part--;
  2123. }
  2124. return Result;
  2125. }
  2126. //---------------------------------------------------------------------------
  2127. UnicodeString __fastcall DecodeUrlChars(UnicodeString S)
  2128. {
  2129. int i = 1;
  2130. while (i <= S.Length())
  2131. {
  2132. switch (S[i])
  2133. {
  2134. case L'+':
  2135. S[i] = ' ';
  2136. break;
  2137. case L'%':
  2138. {
  2139. UnicodeString Hex;
  2140. while ((i + 2 <= S.Length()) && (S[i] == L'%') &&
  2141. IsHex(S[i + 1]) && IsHex(S[i + 2]))
  2142. {
  2143. Hex += S.SubString(i + 1, 2);
  2144. S.Delete(i, 3);
  2145. }
  2146. if (!Hex.IsEmpty())
  2147. {
  2148. RawByteString Bytes = HexToBytes(Hex);
  2149. UnicodeString Chars(UTF8ToString(Bytes));
  2150. S.Insert(Chars, i);
  2151. i += Chars.Length() - 1;
  2152. }
  2153. }
  2154. break;
  2155. }
  2156. i++;
  2157. }
  2158. return S;
  2159. }
  2160. //---------------------------------------------------------------------------
  2161. UnicodeString __fastcall DoEncodeUrl(UnicodeString S, UnicodeString Chars)
  2162. {
  2163. int i = 1;
  2164. while (i <= S.Length())
  2165. {
  2166. if (Chars.Pos(S[i]) > 0)
  2167. {
  2168. // We decode as UTF-8 so we should encode as UTF-8 too
  2169. UnicodeString H = ByteToHex(AnsiString(UnicodeString(S[i]))[1]);
  2170. S.Insert(H, i + 1);
  2171. S[i] = '%';
  2172. i += H.Length();
  2173. }
  2174. i++;
  2175. }
  2176. return S;
  2177. }
  2178. //---------------------------------------------------------------------------
  2179. // we should probably replace all uses with EncodeUrlString
  2180. UnicodeString __fastcall EncodeUrlChars(UnicodeString S)
  2181. {
  2182. return DoEncodeUrl(S, L" /");
  2183. }
  2184. //---------------------------------------------------------------------------
  2185. UnicodeString __fastcall NonUrlChars()
  2186. {
  2187. UnicodeString S;
  2188. for (unsigned int I = 0; I <= 127; I++)
  2189. {
  2190. wchar_t C = static_cast<wchar_t>(I);
  2191. if (IsLetter(C) ||
  2192. IsDigit(C) ||
  2193. (C == L'_') || (C == L'-') || (C == L'.'))
  2194. {
  2195. // noop
  2196. }
  2197. else
  2198. {
  2199. S += C;
  2200. }
  2201. }
  2202. return S;
  2203. }
  2204. //---------------------------------------------------------------------------
  2205. UnicodeString __fastcall EncodeUrlString(UnicodeString S)
  2206. {
  2207. return DoEncodeUrl(S, NonUrlChars());
  2208. }
  2209. //---------------------------------------------------------------------------
  2210. UnicodeString __fastcall EncodeUrlPath(UnicodeString S)
  2211. {
  2212. UnicodeString Ignore = NonUrlChars();
  2213. int P = Ignore.Pos(L"/");
  2214. if (ALWAYS_TRUE(P > 0))
  2215. {
  2216. Ignore.Delete(P, 1);
  2217. }
  2218. return DoEncodeUrl(S, Ignore);
  2219. }
  2220. //---------------------------------------------------------------------------
  2221. UnicodeString __fastcall AppendUrlParams(UnicodeString AURL, UnicodeString Params)
  2222. {
  2223. // see also TWebHelpSystem::ShowHelp
  2224. const wchar_t FragmentSeparator = L'#';
  2225. UnicodeString URL = CutToChar(AURL, FragmentSeparator, false);
  2226. if (URL.Pos(L"?") == 0)
  2227. {
  2228. URL += L"?";
  2229. }
  2230. else
  2231. {
  2232. URL += L"&";
  2233. }
  2234. URL += Params;
  2235. AddToList(URL, AURL, FragmentSeparator);
  2236. return URL;
  2237. }
  2238. //---------------------------------------------------------------------------
  2239. UnicodeString __fastcall EscapeHotkey(const UnicodeString & Caption)
  2240. {
  2241. return ReplaceStr(Caption, L"&", L"&&");
  2242. }
  2243. //---------------------------------------------------------------------------
  2244. // duplicated in console's Main.cpp
  2245. bool __fastcall CutToken(UnicodeString & Str, UnicodeString & Token,
  2246. UnicodeString * RawToken, UnicodeString * Separator)
  2247. {
  2248. bool Result;
  2249. Token = L"";
  2250. // inspired by Putty's sftp_getcmd() from PSFTP.C
  2251. int Index = 1;
  2252. while ((Index <= Str.Length()) &&
  2253. ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2254. {
  2255. Index++;
  2256. }
  2257. if (Index <= Str.Length())
  2258. {
  2259. bool Quoting = false;
  2260. while (Index <= Str.Length())
  2261. {
  2262. if (!Quoting && ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2263. {
  2264. break;
  2265. }
  2266. // We should escape quotes only within quotes
  2267. // otherwise the "" means " (quote), but it should mean empty string.
  2268. // Or have a special case for bare "".
  2269. else if ((Str[Index] == L'"') && (Index + 1 <= Str.Length()) &&
  2270. (Str[Index + 1] == L'"'))
  2271. {
  2272. Index += 2;
  2273. Token += L'"';
  2274. }
  2275. else if (Str[Index] == L'"')
  2276. {
  2277. Index++;
  2278. Quoting = !Quoting;
  2279. }
  2280. else
  2281. {
  2282. Token += Str[Index];
  2283. Index++;
  2284. }
  2285. }
  2286. if (RawToken != NULL)
  2287. {
  2288. (*RawToken) = Str.SubString(1, Index - 1);
  2289. }
  2290. if (Index <= Str.Length())
  2291. {
  2292. if (Separator != NULL)
  2293. {
  2294. *Separator = Str.SubString(Index, 1);
  2295. }
  2296. Index++;
  2297. }
  2298. else
  2299. {
  2300. if (Separator != NULL)
  2301. {
  2302. *Separator = UnicodeString();
  2303. }
  2304. }
  2305. Str = Str.SubString(Index, Str.Length());
  2306. Result = true;
  2307. }
  2308. else
  2309. {
  2310. Result = false;
  2311. Str = L"";
  2312. }
  2313. return Result;
  2314. }
  2315. //---------------------------------------------------------------------------
  2316. void __fastcall AddToList(UnicodeString & List, const UnicodeString & Value, const UnicodeString & Delimiter)
  2317. {
  2318. if (!Value.IsEmpty())
  2319. {
  2320. if (!List.IsEmpty() &&
  2321. ((List.Length() < Delimiter.Length()) ||
  2322. (List.SubString(List.Length() - Delimiter.Length() + 1, Delimiter.Length()) != Delimiter)))
  2323. {
  2324. List += Delimiter;
  2325. }
  2326. List += Value;
  2327. }
  2328. }
  2329. //---------------------------------------------------------------------------
  2330. bool __fastcall IsWinVista()
  2331. {
  2332. // Vista is 6.0
  2333. // Win XP is 5.1
  2334. // There also 5.2, what is Windows 2003 or Windows XP 64bit
  2335. // (we consider it WinXP for now)
  2336. return CheckWin32Version(6, 0);
  2337. }
  2338. //---------------------------------------------------------------------------
  2339. bool __fastcall IsWin7()
  2340. {
  2341. return CheckWin32Version(6, 1);
  2342. }
  2343. //---------------------------------------------------------------------------
  2344. bool __fastcall IsWin8()
  2345. {
  2346. return CheckWin32Version(6, 2);
  2347. }
  2348. //---------------------------------------------------------------------------
  2349. bool __fastcall IsWin10()
  2350. {
  2351. return CheckWin32Version(10, 0);
  2352. }
  2353. //---------------------------------------------------------------------------
  2354. bool __fastcall IsWine()
  2355. {
  2356. HMODULE NtDll = GetModuleHandle(L"ntdll.dll");
  2357. return
  2358. ALWAYS_TRUE(NtDll != NULL) &&
  2359. (GetProcAddress(NtDll, "wine_get_version") != NULL);
  2360. }
  2361. //---------------------------------------------------------------------------
  2362. LCID __fastcall GetDefaultLCID()
  2363. {
  2364. return GetUserDefaultLCID();
  2365. }
  2366. //---------------------------------------------------------------------------
  2367. static UnicodeString ADefaultEncodingName;
  2368. UnicodeString __fastcall DefaultEncodingName()
  2369. {
  2370. if (ADefaultEncodingName.IsEmpty())
  2371. {
  2372. CPINFOEX Info;
  2373. GetCPInfoEx(CP_ACP, 0, &Info);
  2374. ADefaultEncodingName = Info.CodePageName;
  2375. }
  2376. return ADefaultEncodingName;
  2377. }
  2378. //---------------------------------------------------------------------------
  2379. bool _fastcall GetWindowsProductType(DWORD & Type)
  2380. {
  2381. bool Result;
  2382. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  2383. typedef BOOL WINAPI (* TGetProductInfo)(DWORD, DWORD, DWORD, DWORD, PDWORD);
  2384. TGetProductInfo GetProductInfo =
  2385. (TGetProductInfo)GetProcAddress(Kernel32, "GetProductInfo");
  2386. if (GetProductInfo == NULL)
  2387. {
  2388. Result = false;
  2389. }
  2390. else
  2391. {
  2392. GetProductInfo(Win32MajorVersion, Win32MinorVersion, 0, 0, &Type);
  2393. Result = true;
  2394. }
  2395. return Result;
  2396. }
  2397. //---------------------------------------------------------------------------
  2398. UnicodeString __fastcall WindowsProductName()
  2399. {
  2400. UnicodeString Result;
  2401. TRegistry * Registry = new TRegistry(KEY_READ);
  2402. try
  2403. {
  2404. Registry->RootKey = HKEY_LOCAL_MACHINE;
  2405. if (Registry->OpenKey(L"SOFTWARE", false) &&
  2406. Registry->OpenKey(L"Microsoft", false) &&
  2407. Registry->OpenKey(L"Windows NT", false) &&
  2408. Registry->OpenKey(L"CurrentVersion", false))
  2409. {
  2410. Result = Registry->ReadString(L"ProductName");
  2411. }
  2412. delete Registry;
  2413. }
  2414. catch(...)
  2415. {
  2416. }
  2417. return Result;
  2418. }
  2419. //---------------------------------------------------------------------------
  2420. bool __fastcall IsDirectoryWriteable(const UnicodeString & Path)
  2421. {
  2422. UnicodeString FileName =
  2423. IncludeTrailingPathDelimiter(Path) +
  2424. FORMAT(L"wscp_%s_%d.tmp", (FormatDateTime(L"nnzzz", Now()), int(GetCurrentProcessId())));
  2425. HANDLE Handle = CreateFile(ApiPath(FileName).c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL,
  2426. CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, 0);
  2427. bool Result = (Handle != INVALID_HANDLE_VALUE);
  2428. if (Result)
  2429. {
  2430. CloseHandle(Handle);
  2431. }
  2432. return Result;
  2433. }
  2434. //---------------------------------------------------------------------------
  2435. UnicodeString __fastcall FormatNumber(__int64 Number)
  2436. {
  2437. return FormatFloat(L"#,##0", Number);
  2438. }
  2439. //---------------------------------------------------------------------------
  2440. // simple alternative to FormatBytes
  2441. UnicodeString __fastcall FormatSize(__int64 Size)
  2442. {
  2443. return FormatNumber(Size);
  2444. }
  2445. //---------------------------------------------------------------------------
  2446. UnicodeString __fastcall ExtractFileBaseName(const UnicodeString & Path)
  2447. {
  2448. return ChangeFileExt(ExtractFileName(Path), L"");
  2449. }
  2450. //---------------------------------------------------------------------------
  2451. TStringList * __fastcall TextToStringList(const UnicodeString & Text)
  2452. {
  2453. std::unique_ptr<TStringList> List(new TStringList());
  2454. List->Text = Text;
  2455. return List.release();
  2456. }
  2457. //---------------------------------------------------------------------------
  2458. TStrings * __fastcall CloneStrings(TStrings * Strings)
  2459. {
  2460. std::unique_ptr<TStringList> List(new TStringList());
  2461. List->AddStrings(Strings);
  2462. return List.release();
  2463. }
  2464. //---------------------------------------------------------------------------
  2465. UnicodeString __fastcall TrimVersion(UnicodeString Version)
  2466. {
  2467. while ((Version.Pos(L".") != Version.LastDelimiter(L".")) &&
  2468. (Version.SubString(Version.Length() - 1, 2) == L".0"))
  2469. {
  2470. Version.SetLength(Version.Length() - 2);
  2471. }
  2472. return Version;
  2473. }
  2474. //---------------------------------------------------------------------------
  2475. UnicodeString __fastcall FormatVersion(int MajovVersion, int MinorVersion, int Release)
  2476. {
  2477. return
  2478. TrimVersion(FORMAT(L"%d.%d.%d",
  2479. (MajovVersion, MinorVersion, Release)));
  2480. }
  2481. //---------------------------------------------------------------------------
  2482. TFormatSettings __fastcall GetEngFormatSettings()
  2483. {
  2484. return TFormatSettings::Create((TLocaleID)1033);
  2485. }
  2486. //---------------------------------------------------------------------------
  2487. int __fastcall ParseShortEngMonthName(const UnicodeString & MonthStr)
  2488. {
  2489. TFormatSettings FormatSettings = GetEngFormatSettings();
  2490. return IndexStr(MonthStr, FormatSettings.ShortMonthNames, FormatSettings.ShortMonthNames.Size()) + 1;
  2491. }
  2492. //---------------------------------------------------------------------------
  2493. TStringList * __fastcall CreateSortedStringList(bool CaseSensitive, System::Types::TDuplicates Duplicates)
  2494. {
  2495. TStringList * Result = new TStringList();
  2496. Result->CaseSensitive = CaseSensitive;
  2497. Result->Sorted = true;
  2498. Result->Duplicates = Duplicates;
  2499. return Result;
  2500. }
  2501. //---------------------------------------------------------------------------
  2502. static UnicodeString __fastcall NormalizeIdent(UnicodeString Ident)
  2503. {
  2504. int Index = 1;
  2505. while (Index <= Ident.Length())
  2506. {
  2507. if (Ident[Index] == L'-')
  2508. {
  2509. Ident.Delete(Index, 1);
  2510. }
  2511. else
  2512. {
  2513. Index++;
  2514. }
  2515. }
  2516. return Ident;
  2517. }
  2518. //---------------------------------------------------------------------------
  2519. UnicodeString __fastcall FindIdent(const UnicodeString & Ident, TStrings * Idents)
  2520. {
  2521. UnicodeString NormalizedIdent(NormalizeIdent(Ident));
  2522. for (int Index = 0; Index < Idents->Count; Index++)
  2523. {
  2524. if (SameText(NormalizedIdent, NormalizeIdent(Idents->Strings[Index])))
  2525. {
  2526. return Idents->Strings[Index];
  2527. }
  2528. }
  2529. return Ident;
  2530. }
  2531. //---------------------------------------------------------------------------
  2532. static UnicodeString __fastcall GetTlsErrorStr(int Err)
  2533. {
  2534. char * Buffer = new char[512];
  2535. ERR_error_string(Err, Buffer);
  2536. // not sure about the UTF8
  2537. return UnicodeString(UTF8String(Buffer));
  2538. }
  2539. //---------------------------------------------------------------------------
  2540. static FILE * __fastcall OpenCertificate(const UnicodeString & Path)
  2541. {
  2542. FILE * Result = _wfopen(ApiPath(Path).c_str(), L"rb");
  2543. if (Result == NULL)
  2544. {
  2545. int Error = errno;
  2546. throw EOSExtException(MainInstructions(FMTLOAD(CERTIFICATE_OPEN_ERROR, (Path))), Error);
  2547. }
  2548. return Result;
  2549. }
  2550. //---------------------------------------------------------------------------
  2551. struct TPemPasswordCallbackData
  2552. {
  2553. UnicodeString * Passphrase;
  2554. };
  2555. //---------------------------------------------------------------------------
  2556. static int PemPasswordCallback(char * Buf, int Size, int /*RWFlag*/, void * UserData)
  2557. {
  2558. TPemPasswordCallbackData & Data = *reinterpret_cast<TPemPasswordCallbackData *>(UserData);
  2559. UTF8String UtfPassphrase = UTF8String(*Data.Passphrase);
  2560. strncpy(Buf, UtfPassphrase.c_str(), Size);
  2561. Shred(UtfPassphrase);
  2562. Buf[Size - 1] = '\0';
  2563. return strlen(Buf);
  2564. }
  2565. //---------------------------------------------------------------------------
  2566. static bool __fastcall IsTlsPassphraseError(int Error)
  2567. {
  2568. bool Result =
  2569. ((ERR_GET_LIB(Error) == ERR_LIB_PKCS12) &&
  2570. (ERR_GET_REASON(Error) == PKCS12_R_MAC_VERIFY_FAILURE)) ||
  2571. ((ERR_GET_LIB(Error) == ERR_LIB_PEM) &&
  2572. (ERR_GET_REASON(Error) == PEM_R_BAD_PASSWORD_READ));
  2573. return Result;
  2574. }
  2575. //---------------------------------------------------------------------------
  2576. static void __fastcall ThrowTlsCertificateErrorIgnorePassphraseErrors(const UnicodeString & Path)
  2577. {
  2578. int Error = ERR_get_error();
  2579. if (!IsTlsPassphraseError(Error))
  2580. {
  2581. throw ExtException(MainInstructions(FMTLOAD(CERTIFICATE_READ_ERROR, (Path))), GetTlsErrorStr(Error));
  2582. }
  2583. }
  2584. //---------------------------------------------------------------------------
  2585. void __fastcall ParseCertificate(const UnicodeString & Path,
  2586. const UnicodeString & Passphrase, X509 *& Certificate, EVP_PKEY *& PrivateKey,
  2587. bool & WrongPassphrase)
  2588. {
  2589. FILE * File;
  2590. // Inspired by neon's ne_ssl_clicert_read
  2591. File = OpenCertificate(Path);
  2592. PKCS12 * Pkcs12 = d2i_PKCS12_fp(File, NULL);
  2593. fclose(File);
  2594. if (Pkcs12 != NULL)
  2595. {
  2596. // Not sure about the UTF-8 encoding, but there's no wchar_t API
  2597. bool Result =
  2598. (PKCS12_parse(Pkcs12, UTF8String(Passphrase).c_str(), &PrivateKey, &Certificate, NULL) == 1);
  2599. PKCS12_free(Pkcs12);
  2600. if (!Result)
  2601. {
  2602. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path);
  2603. WrongPassphrase = true;
  2604. }
  2605. }
  2606. else
  2607. {
  2608. ERR_clear_error();
  2609. TPemPasswordCallbackData CallbackUserData;
  2610. // PemPasswordCallback never writes to the .Passphrase
  2611. CallbackUserData.Passphrase = const_cast<UnicodeString *>(&Passphrase);
  2612. File = OpenCertificate(Path);
  2613. PrivateKey = PEM_read_PrivateKey(File, NULL, PemPasswordCallback, &CallbackUserData);
  2614. fclose(File);
  2615. try
  2616. {
  2617. if (PrivateKey == NULL)
  2618. {
  2619. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path);
  2620. WrongPassphrase = true;
  2621. }
  2622. File = OpenCertificate(Path);
  2623. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  2624. fclose(File);
  2625. if (Certificate == NULL)
  2626. {
  2627. int Error = ERR_get_error();
  2628. // unlikely
  2629. if (IsTlsPassphraseError(Error))
  2630. {
  2631. WrongPassphrase = true;
  2632. }
  2633. else
  2634. {
  2635. UnicodeString CertificatePath = ChangeFileExt(Path, L".cer");
  2636. if (!FileExists(CertificatePath))
  2637. {
  2638. CertificatePath = ChangeFileExt(Path, L".crt");
  2639. }
  2640. if (!FileExists(CertificatePath))
  2641. {
  2642. throw Exception(MainInstructions(FMTLOAD(CERTIFICATE_PUBLIC_KEY_NOT_FOUND, (Path))));
  2643. }
  2644. else
  2645. {
  2646. File = OpenCertificate(CertificatePath);
  2647. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  2648. fclose(File);
  2649. if (Certificate == NULL)
  2650. {
  2651. ThrowTlsCertificateErrorIgnorePassphraseErrors(CertificatePath);
  2652. WrongPassphrase = true;
  2653. }
  2654. }
  2655. }
  2656. }
  2657. }
  2658. __finally
  2659. {
  2660. // We loaded private key, but failed to load certificate, discard the certificate
  2661. // (either exception was thrown or WrongPassphrase)
  2662. if ((PrivateKey != NULL) && (Certificate == NULL))
  2663. {
  2664. EVP_PKEY_free(PrivateKey);
  2665. PrivateKey = NULL;
  2666. }
  2667. // Certificate was verified, but passphrase was wrong when loading private key,
  2668. // so discard the certificate
  2669. else if ((Certificate != NULL) && (PrivateKey == NULL))
  2670. {
  2671. X509_free(Certificate);
  2672. Certificate = NULL;
  2673. }
  2674. }
  2675. }
  2676. }
  2677. //---------------------------------------------------------------------------
  2678. void __fastcall CheckCertificate(const UnicodeString & Path)
  2679. {
  2680. X509 * Certificate;
  2681. EVP_PKEY * PrivateKey;
  2682. bool WrongPassphrase;
  2683. ParseCertificate(Path, L"", Certificate, PrivateKey, WrongPassphrase);
  2684. if (PrivateKey != NULL)
  2685. {
  2686. EVP_PKEY_free(PrivateKey);
  2687. }
  2688. if (Certificate != NULL)
  2689. {
  2690. X509_free(Certificate);
  2691. }
  2692. }
  2693. //---------------------------------------------------------------------------
  2694. bool __fastcall IsHttpUrl(const UnicodeString & S)
  2695. {
  2696. return SameText(S.SubString(1, 4), L"http");
  2697. }