Common.cpp 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839
  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 (DebugAlwaysTrue(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 -= DSTDifferenceForTime(Result);
  1471. }
  1472. return Result;
  1473. }
  1474. //---------------------------------------------------------------------------
  1475. __int64 __fastcall Round(double Number)
  1476. {
  1477. double Floor = floor(Number);
  1478. double Ceil = ceil(Number);
  1479. return static_cast<__int64>(((Number - Floor) > (Ceil - Number)) ? Ceil : Floor);
  1480. }
  1481. //---------------------------------------------------------------------------
  1482. bool __fastcall TryRelativeStrToDateTime(UnicodeString S, TDateTime & DateTime)
  1483. {
  1484. S = S.Trim();
  1485. int Index = 1;
  1486. while ((Index <= S.Length()) && IsDigit(S[Index]))
  1487. {
  1488. Index++;
  1489. }
  1490. UnicodeString NumberStr = S.SubString(1, Index - 1);
  1491. int Number;
  1492. bool Result = TryStrToInt(NumberStr, Number);
  1493. if (Result)
  1494. {
  1495. S.Delete(1, Index - 1);
  1496. S = S.Trim().UpperCase();
  1497. DateTime = Now();
  1498. // These may not overlap with ParseSize (K, M and G)
  1499. if (S == "S")
  1500. {
  1501. DateTime = IncSecond(DateTime, -Number);
  1502. }
  1503. else if (S == "N")
  1504. {
  1505. DateTime = IncMinute(DateTime, -Number);
  1506. }
  1507. else if (S == "H")
  1508. {
  1509. DateTime = IncHour(DateTime, -Number);
  1510. }
  1511. else if (S == "D")
  1512. {
  1513. DateTime = IncDay(DateTime, -Number);
  1514. }
  1515. else if (S == "Y")
  1516. {
  1517. DateTime = IncYear(DateTime, -Number);
  1518. }
  1519. else
  1520. {
  1521. Result = false;
  1522. }
  1523. }
  1524. return Result;
  1525. }
  1526. //---------------------------------------------------------------------------
  1527. static __int64 __fastcall DateTimeToUnix(const TDateTime DateTime)
  1528. {
  1529. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1530. DebugAssert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1531. return Round(double(DateTime - UnixDateDelta) * SecsPerDay) +
  1532. CurrentParams->CurrentDifferenceSec;
  1533. }
  1534. //---------------------------------------------------------------------------
  1535. FILETIME __fastcall DateTimeToFileTime(const TDateTime DateTime,
  1536. TDSTMode /*DSTMode*/)
  1537. {
  1538. __int64 UnixTimeStamp = ::DateTimeToUnix(DateTime);
  1539. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1540. if (!Params->DaylightHack)
  1541. {
  1542. // We should probably use reversed code of FileTimeToDateTime here instead of custom implementation
  1543. // We are incrementing and decrementing BaseDifferenceSec because it
  1544. // can actually change between years
  1545. // (as it did in Belarus from GMT+2 to GMT+3 between 2011 and 2012)
  1546. UnixTimeStamp += (IsDateInDST(DateTime) ?
  1547. Params->DaylightDifferenceSec : Params->StandardDifferenceSec) +
  1548. Params->BaseDifferenceSec;
  1549. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1550. UnixTimeStamp -=
  1551. CurrentParams->CurrentDaylightDifferenceSec +
  1552. CurrentParams->BaseDifferenceSec;
  1553. }
  1554. FILETIME Result;
  1555. (*(__int64*)&(Result) = (__int64(UnixTimeStamp) + 11644473600LL) * 10000000LL);
  1556. return Result;
  1557. }
  1558. //---------------------------------------------------------------------------
  1559. TDateTime __fastcall FileTimeToDateTime(const FILETIME & FileTime)
  1560. {
  1561. // duplicated in DirView.pas
  1562. TDateTime Result;
  1563. // The 0xFFF... is sometime seen for invalid timestamps,
  1564. // it would cause failure in SystemTimeToDateTime below
  1565. if (FileTime.dwLowDateTime == std::numeric_limits<DWORD>::max())
  1566. {
  1567. Result = MinDateTime;
  1568. }
  1569. else
  1570. {
  1571. SYSTEMTIME SysTime;
  1572. if (!UsesDaylightHack())
  1573. {
  1574. SYSTEMTIME UniverzalSysTime;
  1575. FileTimeToSystemTime(&FileTime, &UniverzalSysTime);
  1576. SystemTimeToTzSpecificLocalTime(NULL, &UniverzalSysTime, &SysTime);
  1577. }
  1578. else
  1579. {
  1580. FILETIME LocalFileTime;
  1581. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1582. FileTimeToSystemTime(&LocalFileTime, &SysTime);
  1583. }
  1584. Result = SystemTimeToDateTimeVerbose(SysTime);
  1585. }
  1586. return Result;
  1587. }
  1588. //---------------------------------------------------------------------------
  1589. __int64 __fastcall ConvertTimestampToUnix(const FILETIME & FileTime,
  1590. TDSTMode DSTMode)
  1591. {
  1592. __int64 Result = ((*(__int64*)&(FileTime)) / 10000000LL - 11644473600LL);
  1593. if (UsesDaylightHack())
  1594. {
  1595. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1596. {
  1597. FILETIME LocalFileTime;
  1598. SYSTEMTIME SystemTime;
  1599. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1600. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1601. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  1602. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1603. Result += (IsDateInDST(DateTime) ?
  1604. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1605. if (DSTMode == dstmKeep)
  1606. {
  1607. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1608. Result -= CurrentParams->CurrentDaylightDifferenceSec;
  1609. }
  1610. }
  1611. }
  1612. else
  1613. {
  1614. if (DSTMode == dstmWin)
  1615. {
  1616. FILETIME LocalFileTime;
  1617. SYSTEMTIME SystemTime;
  1618. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1619. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1620. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  1621. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1622. Result -= (IsDateInDST(DateTime) ?
  1623. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1624. }
  1625. }
  1626. return Result;
  1627. }
  1628. //---------------------------------------------------------------------------
  1629. TDateTime __fastcall ConvertTimestampToUTC(TDateTime DateTime)
  1630. {
  1631. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1632. DateTime += DSTDifferenceForTime(DateTime);
  1633. DateTime += Params->BaseDifference;
  1634. if (Params->DaylightHack)
  1635. {
  1636. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1637. DateTime += CurrentParams->CurrentDaylightDifference;
  1638. }
  1639. return DateTime;
  1640. }
  1641. //---------------------------------------------------------------------------
  1642. TDateTime __fastcall ConvertTimestampFromUTC(TDateTime DateTime)
  1643. {
  1644. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1645. DateTime -= DSTDifferenceForTime(DateTime);
  1646. DateTime -= Params->BaseDifference;
  1647. if (Params->DaylightHack)
  1648. {
  1649. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1650. DateTime -= CurrentParams->CurrentDaylightDifference;
  1651. }
  1652. return DateTime;
  1653. }
  1654. //---------------------------------------------------------------------------
  1655. __int64 __fastcall ConvertTimestampToUnixSafe(const FILETIME & FileTime,
  1656. TDSTMode DSTMode)
  1657. {
  1658. __int64 Result;
  1659. if ((FileTime.dwLowDateTime == 0) &&
  1660. (FileTime.dwHighDateTime == 0))
  1661. {
  1662. Result = ::DateTimeToUnix(Now());
  1663. }
  1664. else
  1665. {
  1666. Result = ConvertTimestampToUnix(FileTime, DSTMode);
  1667. }
  1668. return Result;
  1669. }
  1670. //---------------------------------------------------------------------------
  1671. double __fastcall DSTDifferenceForTime(TDateTime DateTime)
  1672. {
  1673. double Result;
  1674. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1675. if (IsDateInDST(DateTime))
  1676. {
  1677. Result = Params->DaylightDifference;
  1678. }
  1679. else
  1680. {
  1681. Result = Params->StandardDifference;
  1682. }
  1683. return Result;
  1684. }
  1685. //---------------------------------------------------------------------------
  1686. TDateTime __fastcall AdjustDateTimeFromUnix(TDateTime DateTime, TDSTMode DSTMode)
  1687. {
  1688. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1689. if (Params->DaylightHack)
  1690. {
  1691. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1692. {
  1693. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1694. DateTime = DateTime - CurrentParams->CurrentDaylightDifference;
  1695. }
  1696. if (!IsDateInDST(DateTime))
  1697. {
  1698. if (DSTMode == dstmWin)
  1699. {
  1700. DateTime = DateTime - Params->DaylightDifference;
  1701. }
  1702. }
  1703. else
  1704. {
  1705. DateTime = DateTime - Params->StandardDifference;
  1706. }
  1707. }
  1708. else
  1709. {
  1710. if (DSTMode == dstmWin)
  1711. {
  1712. DateTime = DateTime + DSTDifferenceForTime(DateTime);
  1713. }
  1714. }
  1715. return DateTime;
  1716. }
  1717. //---------------------------------------------------------------------------
  1718. UnicodeString __fastcall FixedLenDateTimeFormat(const UnicodeString & Format)
  1719. {
  1720. UnicodeString Result = Format;
  1721. bool AsIs = false;
  1722. int Index = 1;
  1723. while (Index <= Result.Length())
  1724. {
  1725. wchar_t F = Result[Index];
  1726. if ((F == L'\'') || (F == L'\"'))
  1727. {
  1728. AsIs = !AsIs;
  1729. Index++;
  1730. }
  1731. else if (!AsIs && ((F == L'a') || (F == L'A')))
  1732. {
  1733. if (Result.SubString(Index, 5).LowerCase() == L"am/pm")
  1734. {
  1735. Index += 5;
  1736. }
  1737. else if (Result.SubString(Index, 3).LowerCase() == L"a/p")
  1738. {
  1739. Index += 3;
  1740. }
  1741. else if (Result.SubString(Index, 4).LowerCase() == L"ampm")
  1742. {
  1743. Index += 4;
  1744. }
  1745. else
  1746. {
  1747. Index++;
  1748. }
  1749. }
  1750. else
  1751. {
  1752. if (!AsIs && (wcschr(L"dDeEmMhHnNsS", F) != NULL) &&
  1753. ((Index == Result.Length()) || (Result[Index + 1] != F)))
  1754. {
  1755. Result.Insert(F, Index);
  1756. }
  1757. while ((Index <= Result.Length()) && (F == Result[Index]))
  1758. {
  1759. Index++;
  1760. }
  1761. }
  1762. }
  1763. return Result;
  1764. }
  1765. //---------------------------------------------------------------------------
  1766. UnicodeString __fastcall FormatTimeZone(long Sec)
  1767. {
  1768. TTimeSpan Span = TTimeSpan::FromSeconds(Sec);
  1769. UnicodeString Str;
  1770. if ((Span.Seconds == 0) && (Span.Minutes == 0))
  1771. {
  1772. Str = FORMAT(L"%d", (-Span.Hours));
  1773. }
  1774. else if (Span.Seconds == 0)
  1775. {
  1776. Str = FORMAT(L"%d:%2.2d", (-Span.Hours, abs(Span.Minutes)));
  1777. }
  1778. else
  1779. {
  1780. Str = FORMAT(L"%d:%2.2d:%2.2d", (-Span.Hours, abs(Span.Minutes), abs(Span.Seconds)));
  1781. }
  1782. Str = ((Span <= TTimeSpan::Zero) ? L"+" : L"") + Str;
  1783. return Str;
  1784. }
  1785. //---------------------------------------------------------------------------
  1786. UnicodeString __fastcall GetTimeZoneLogString()
  1787. {
  1788. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1789. UnicodeString Result =
  1790. FORMAT(L"Current: GMT%s", (FormatTimeZone(CurrentParams->CurrentDifferenceSec)));
  1791. if (!CurrentParams->HasDST())
  1792. {
  1793. Result += FORMAT(L" (%s), No DST", (CurrentParams->StandardName));
  1794. }
  1795. else
  1796. {
  1797. Result +=
  1798. FORMAT(L", Standard: GMT%s (%s), DST: GMT%s (%s), DST Start: %s, DST End: %s",
  1799. (FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->StandardDifferenceSec),
  1800. CurrentParams->StandardName,
  1801. FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->DaylightDifferenceSec),
  1802. CurrentParams->DaylightName,
  1803. CurrentParams->DaylightDate.DateString(),
  1804. CurrentParams->StandardDate.DateString()));
  1805. }
  1806. return Result;
  1807. }
  1808. //---------------------------------------------------------------------------
  1809. bool __fastcall AdjustClockForDSTEnabled()
  1810. {
  1811. // Windows XP deletes the DisableAutoDaylightTimeSet value when it is off
  1812. // (the later versions set it to DynamicDaylightTimeDisabled to 0)
  1813. bool DynamicDaylightTimeDisabled = false;
  1814. TRegistry * Registry = new TRegistry(KEY_READ);
  1815. try
  1816. {
  1817. Registry->RootKey = HKEY_LOCAL_MACHINE;
  1818. if (Registry->OpenKey(L"SYSTEM", false) &&
  1819. Registry->OpenKey(L"CurrentControlSet", false) &&
  1820. Registry->OpenKey(L"Control", false) &&
  1821. Registry->OpenKey(L"TimeZoneInformation", false))
  1822. {
  1823. if (Registry->ValueExists(L"DynamicDaylightTimeDisabled"))
  1824. {
  1825. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DynamicDaylightTimeDisabled");
  1826. }
  1827. // WORKAROUND
  1828. // Windows XP equivalent
  1829. else if (Registry->ValueExists(L"DisableAutoDaylightTimeSet"))
  1830. {
  1831. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DisableAutoDaylightTimeSet");
  1832. }
  1833. }
  1834. delete Registry;
  1835. }
  1836. catch(...)
  1837. {
  1838. }
  1839. return !DynamicDaylightTimeDisabled;
  1840. }
  1841. //---------------------------------------------------------------------------
  1842. UnicodeString __fastcall StandardDatestamp()
  1843. {
  1844. return FormatDateTime(L"yyyy'-'mm'-'dd", ConvertTimestampToUTC(Now()));
  1845. }
  1846. //---------------------------------------------------------------------------
  1847. UnicodeString __fastcall StandardTimestamp(const TDateTime & DateTime)
  1848. {
  1849. return FormatDateTime(L"yyyy'-'mm'-'dd'T'hh':'nn':'ss'.'zzz'Z'", ConvertTimestampToUTC(DateTime));
  1850. }
  1851. //---------------------------------------------------------------------------
  1852. UnicodeString __fastcall StandardTimestamp()
  1853. {
  1854. return StandardTimestamp(Now());
  1855. }
  1856. //---------------------------------------------------------------------------
  1857. static TDateTime TwoSeconds(0, 0, 2, 0);
  1858. int __fastcall CompareFileTime(TDateTime T1, TDateTime T2)
  1859. {
  1860. // "FAT" time precision
  1861. // (when one time is seconds-precision and other is millisecond-precision,
  1862. // we may have times like 12:00:00.000 and 12:00:01.999, which should
  1863. // be treated the same)
  1864. int Result;
  1865. if (T1 == T2)
  1866. {
  1867. // just optimization
  1868. Result = 0;
  1869. }
  1870. else if ((T1 < T2) && (T2 - T1 >= TwoSeconds))
  1871. {
  1872. Result = -1;
  1873. }
  1874. else if ((T1 > T2) && (T1 - T2 >= TwoSeconds))
  1875. {
  1876. Result = 1;
  1877. }
  1878. else
  1879. {
  1880. Result = 0;
  1881. }
  1882. return Result;
  1883. }
  1884. //---------------------------------------------------------------------------
  1885. int __fastcall TimeToMSec(TDateTime T)
  1886. {
  1887. return int(Round(double(T) * double(MSecsPerDay)));
  1888. }
  1889. //---------------------------------------------------------------------------
  1890. int __fastcall TimeToSeconds(TDateTime T)
  1891. {
  1892. return TimeToMSec(T) / MSecsPerSec;
  1893. }
  1894. //---------------------------------------------------------------------------
  1895. int __fastcall TimeToMinutes(TDateTime T)
  1896. {
  1897. return TimeToSeconds(T) / SecsPerMin;
  1898. }
  1899. //---------------------------------------------------------------------------
  1900. static bool __fastcall DoRecursiveDeleteFile(const UnicodeString FileName, bool ToRecycleBin, UnicodeString & ErrorPath)
  1901. {
  1902. bool Result;
  1903. UnicodeString AErrorPath = FileName;
  1904. if (!ToRecycleBin)
  1905. {
  1906. TSearchRecChecked SearchRec;
  1907. Result = FileSearchRec(FileName, SearchRec);
  1908. if (Result)
  1909. {
  1910. if (FLAGCLEAR(SearchRec.Attr, faDirectory))
  1911. {
  1912. Result = DeleteFile(ApiPath(FileName));
  1913. }
  1914. else
  1915. {
  1916. Result = (FindFirstUnchecked(FileName + L"\\*", faAnyFile, SearchRec) == 0);
  1917. if (Result)
  1918. {
  1919. try
  1920. {
  1921. do
  1922. {
  1923. UnicodeString FileName2 = FileName + L"\\" + SearchRec.Name;
  1924. if (FLAGSET(SearchRec.Attr, faDirectory))
  1925. {
  1926. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  1927. {
  1928. Result = DoRecursiveDeleteFile(FileName2, DebugAlwaysFalse(ToRecycleBin), AErrorPath);
  1929. }
  1930. }
  1931. else
  1932. {
  1933. Result = DeleteFile(ApiPath(FileName2));
  1934. if (!Result)
  1935. {
  1936. AErrorPath = FileName2;
  1937. }
  1938. }
  1939. }
  1940. while (Result && (FindNextUnchecked(SearchRec) == 0));
  1941. }
  1942. __finally
  1943. {
  1944. FindClose(SearchRec);
  1945. }
  1946. if (Result)
  1947. {
  1948. Result = RemoveDir(ApiPath(FileName));
  1949. }
  1950. }
  1951. }
  1952. }
  1953. }
  1954. else
  1955. {
  1956. SHFILEOPSTRUCT Data;
  1957. memset(&Data, 0, sizeof(Data));
  1958. Data.hwnd = NULL;
  1959. Data.wFunc = FO_DELETE;
  1960. // SHFileOperation does not support long paths anyway
  1961. UnicodeString FileList(ApiPath(FileName));
  1962. FileList.SetLength(FileList.Length() + 2);
  1963. FileList[FileList.Length() - 1] = L'\0';
  1964. FileList[FileList.Length()] = L'\0';
  1965. Data.pFrom = FileList.c_str();
  1966. Data.pTo = L"\0\0"; // this will actually give one null more than needed
  1967. Data.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION | FOF_NOCONFIRMMKDIR |
  1968. FOF_NOERRORUI | FOF_SILENT;
  1969. if (DebugAlwaysTrue(ToRecycleBin))
  1970. {
  1971. Data.fFlags |= FOF_ALLOWUNDO;
  1972. }
  1973. int ErrorCode = SHFileOperation(&Data);
  1974. Result = (ErrorCode == 0);
  1975. if (!Result)
  1976. {
  1977. // according to MSDN, SHFileOperation may return following non-Win32
  1978. // error codes
  1979. if (((ErrorCode >= 0x71) && (ErrorCode <= 0x88)) ||
  1980. (ErrorCode == 0xB7) || (ErrorCode == 0x402) || (ErrorCode == 0x10000) ||
  1981. (ErrorCode == 0x10074))
  1982. {
  1983. ErrorCode = 0;
  1984. }
  1985. SetLastError(ErrorCode);
  1986. }
  1987. }
  1988. if (!Result)
  1989. {
  1990. ErrorPath = AErrorPath;
  1991. }
  1992. return Result;
  1993. }
  1994. //---------------------------------------------------------------------------
  1995. bool __fastcall RecursiveDeleteFile(const UnicodeString & FileName, bool ToRecycleBin)
  1996. {
  1997. UnicodeString ErrorPath; // unused
  1998. return DoRecursiveDeleteFile(FileName, ToRecycleBin, ErrorPath);
  1999. }
  2000. //---------------------------------------------------------------------------
  2001. void __fastcall RecursiveDeleteFileChecked(const UnicodeString & FileName, bool ToRecycleBin)
  2002. {
  2003. UnicodeString ErrorPath;
  2004. if (!DoRecursiveDeleteFile(FileName, ToRecycleBin, ErrorPath))
  2005. {
  2006. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (ErrorPath)));
  2007. }
  2008. }
  2009. //---------------------------------------------------------------------------
  2010. void __fastcall DeleteFileChecked(const UnicodeString & FileName)
  2011. {
  2012. if (!DeleteFile(ApiPath(FileName)))
  2013. {
  2014. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  2015. }
  2016. }
  2017. //---------------------------------------------------------------------------
  2018. unsigned int __fastcall CancelAnswer(unsigned int Answers)
  2019. {
  2020. unsigned int Result;
  2021. if ((Answers & qaCancel) != 0)
  2022. {
  2023. Result = qaCancel;
  2024. }
  2025. else if ((Answers & qaNo) != 0)
  2026. {
  2027. Result = qaNo;
  2028. }
  2029. else if ((Answers & qaAbort) != 0)
  2030. {
  2031. Result = qaAbort;
  2032. }
  2033. else if ((Answers & qaOK) != 0)
  2034. {
  2035. Result = qaOK;
  2036. }
  2037. else
  2038. {
  2039. DebugFail();
  2040. Result = qaCancel;
  2041. }
  2042. return Result;
  2043. }
  2044. //---------------------------------------------------------------------------
  2045. unsigned int __fastcall AbortAnswer(unsigned int Answers)
  2046. {
  2047. unsigned int Result;
  2048. if (FLAGSET(Answers, qaAbort))
  2049. {
  2050. Result = qaAbort;
  2051. }
  2052. else
  2053. {
  2054. Result = CancelAnswer(Answers);
  2055. }
  2056. return Result;
  2057. }
  2058. //---------------------------------------------------------------------------
  2059. unsigned int __fastcall ContinueAnswer(unsigned int Answers)
  2060. {
  2061. unsigned int Result;
  2062. if (FLAGSET(Answers, qaSkip))
  2063. {
  2064. Result = qaSkip;
  2065. }
  2066. else if (FLAGSET(Answers, qaIgnore))
  2067. {
  2068. Result = qaIgnore;
  2069. }
  2070. else if (FLAGSET(Answers, qaYes))
  2071. {
  2072. Result = qaYes;
  2073. }
  2074. else if (FLAGSET(Answers, qaOK))
  2075. {
  2076. Result = qaOK;
  2077. }
  2078. else if (FLAGSET(Answers, qaRetry))
  2079. {
  2080. Result = qaRetry;
  2081. }
  2082. else
  2083. {
  2084. Result = CancelAnswer(Answers);
  2085. }
  2086. return Result;
  2087. }
  2088. //---------------------------------------------------------------------------
  2089. TLibModule * __fastcall FindModule(void * Instance)
  2090. {
  2091. TLibModule * CurModule;
  2092. CurModule = reinterpret_cast<TLibModule*>(LibModuleList);
  2093. while (CurModule)
  2094. {
  2095. if (CurModule->Instance == (unsigned)Instance)
  2096. {
  2097. break;
  2098. }
  2099. else
  2100. {
  2101. CurModule = CurModule->Next;
  2102. }
  2103. }
  2104. return CurModule;
  2105. }
  2106. //---------------------------------------------------------------------------
  2107. UnicodeString __fastcall LoadStr(int Ident, unsigned int MaxLength)
  2108. {
  2109. TLibModule * MainModule = FindModule(HInstance);
  2110. DebugAssert(MainModule != NULL);
  2111. UnicodeString Result;
  2112. Result.SetLength(MaxLength);
  2113. int Length = LoadString((HINSTANCE)MainModule->ResInstance, Ident, Result.c_str(), MaxLength);
  2114. Result.SetLength(Length);
  2115. return Result;
  2116. }
  2117. //---------------------------------------------------------------------------
  2118. UnicodeString __fastcall LoadStrPart(int Ident, int Part)
  2119. {
  2120. UnicodeString Result;
  2121. UnicodeString Str = LoadStr(Ident);
  2122. while (Part > 0)
  2123. {
  2124. Result = CutToChar(Str, L'|', false);
  2125. Part--;
  2126. }
  2127. return Result;
  2128. }
  2129. //---------------------------------------------------------------------------
  2130. UnicodeString __fastcall DecodeUrlChars(UnicodeString S)
  2131. {
  2132. int i = 1;
  2133. while (i <= S.Length())
  2134. {
  2135. switch (S[i])
  2136. {
  2137. case L'+':
  2138. S[i] = ' ';
  2139. break;
  2140. case L'%':
  2141. {
  2142. UnicodeString Hex;
  2143. while ((i + 2 <= S.Length()) && (S[i] == L'%') &&
  2144. IsHex(S[i + 1]) && IsHex(S[i + 2]))
  2145. {
  2146. Hex += S.SubString(i + 1, 2);
  2147. S.Delete(i, 3);
  2148. }
  2149. if (!Hex.IsEmpty())
  2150. {
  2151. RawByteString Bytes = HexToBytes(Hex);
  2152. UnicodeString Chars(UTF8ToString(Bytes));
  2153. S.Insert(Chars, i);
  2154. i += Chars.Length() - 1;
  2155. }
  2156. }
  2157. break;
  2158. }
  2159. i++;
  2160. }
  2161. return S;
  2162. }
  2163. //---------------------------------------------------------------------------
  2164. UnicodeString __fastcall DoEncodeUrl(UnicodeString S, bool EncodeSlash)
  2165. {
  2166. int Index = 1;
  2167. while (Index <= S.Length())
  2168. {
  2169. wchar_t C = S[Index];
  2170. if (IsLetter(C) ||
  2171. IsDigit(C) ||
  2172. (C == L'_') || (C == L'-') || (C == L'.') ||
  2173. ((C == L'/') && !EncodeSlash))
  2174. {
  2175. Index++;
  2176. }
  2177. else
  2178. {
  2179. UTF8String UtfS(S.SubString(Index, 1));
  2180. UnicodeString H;
  2181. for (int Index2 = 1; Index2 <= UtfS.Length(); Index2++)
  2182. {
  2183. H += L"%" + ByteToHex(static_cast<unsigned char>(UtfS[Index2]));
  2184. }
  2185. S.Delete(Index, 1);
  2186. S.Insert(H, Index);
  2187. Index += H.Length();
  2188. }
  2189. }
  2190. return S;
  2191. }
  2192. //---------------------------------------------------------------------------
  2193. UnicodeString __fastcall EncodeUrlString(UnicodeString S)
  2194. {
  2195. return DoEncodeUrl(S, true);
  2196. }
  2197. //---------------------------------------------------------------------------
  2198. UnicodeString __fastcall EncodeUrlPath(UnicodeString S)
  2199. {
  2200. return DoEncodeUrl(S, false);
  2201. }
  2202. //---------------------------------------------------------------------------
  2203. UnicodeString __fastcall AppendUrlParams(UnicodeString AURL, UnicodeString Params)
  2204. {
  2205. // see also TWebHelpSystem::ShowHelp
  2206. const wchar_t FragmentSeparator = L'#';
  2207. UnicodeString URL = CutToChar(AURL, FragmentSeparator, false);
  2208. if (URL.Pos(L"?") == 0)
  2209. {
  2210. URL += L"?";
  2211. }
  2212. else
  2213. {
  2214. URL += L"&";
  2215. }
  2216. URL += Params;
  2217. AddToList(URL, AURL, FragmentSeparator);
  2218. return URL;
  2219. }
  2220. //---------------------------------------------------------------------------
  2221. UnicodeString __fastcall EscapeHotkey(const UnicodeString & Caption)
  2222. {
  2223. return ReplaceStr(Caption, L"&", L"&&");
  2224. }
  2225. //---------------------------------------------------------------------------
  2226. // duplicated in console's Main.cpp
  2227. bool __fastcall CutToken(UnicodeString & Str, UnicodeString & Token,
  2228. UnicodeString * RawToken, UnicodeString * Separator)
  2229. {
  2230. bool Result;
  2231. Token = L"";
  2232. // inspired by Putty's sftp_getcmd() from PSFTP.C
  2233. int Index = 1;
  2234. while ((Index <= Str.Length()) &&
  2235. ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2236. {
  2237. Index++;
  2238. }
  2239. if (Index <= Str.Length())
  2240. {
  2241. bool Quoting = false;
  2242. while (Index <= Str.Length())
  2243. {
  2244. if (!Quoting && ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2245. {
  2246. break;
  2247. }
  2248. // We should escape quotes only within quotes
  2249. // otherwise the "" means " (quote), but it should mean empty string.
  2250. // Or have a special case for bare "".
  2251. else if ((Str[Index] == L'"') && (Index + 1 <= Str.Length()) &&
  2252. (Str[Index + 1] == L'"'))
  2253. {
  2254. Index += 2;
  2255. Token += L'"';
  2256. }
  2257. else if (Str[Index] == L'"')
  2258. {
  2259. Index++;
  2260. Quoting = !Quoting;
  2261. }
  2262. else
  2263. {
  2264. Token += Str[Index];
  2265. Index++;
  2266. }
  2267. }
  2268. if (RawToken != NULL)
  2269. {
  2270. (*RawToken) = Str.SubString(1, Index - 1);
  2271. }
  2272. if (Index <= Str.Length())
  2273. {
  2274. if (Separator != NULL)
  2275. {
  2276. *Separator = Str.SubString(Index, 1);
  2277. }
  2278. Index++;
  2279. }
  2280. else
  2281. {
  2282. if (Separator != NULL)
  2283. {
  2284. *Separator = UnicodeString();
  2285. }
  2286. }
  2287. Str = Str.SubString(Index, Str.Length());
  2288. Result = true;
  2289. }
  2290. else
  2291. {
  2292. Result = false;
  2293. Str = L"";
  2294. }
  2295. return Result;
  2296. }
  2297. //---------------------------------------------------------------------------
  2298. void __fastcall AddToList(UnicodeString & List, const UnicodeString & Value, const UnicodeString & Delimiter)
  2299. {
  2300. if (!Value.IsEmpty())
  2301. {
  2302. if (!List.IsEmpty() &&
  2303. ((List.Length() < Delimiter.Length()) ||
  2304. (List.SubString(List.Length() - Delimiter.Length() + 1, Delimiter.Length()) != Delimiter)))
  2305. {
  2306. List += Delimiter;
  2307. }
  2308. List += Value;
  2309. }
  2310. }
  2311. //---------------------------------------------------------------------------
  2312. bool __fastcall IsWinVista()
  2313. {
  2314. // Vista is 6.0
  2315. // Win XP is 5.1
  2316. // There also 5.2, what is Windows 2003 or Windows XP 64bit
  2317. // (we consider it WinXP for now)
  2318. return CheckWin32Version(6, 0);
  2319. }
  2320. //---------------------------------------------------------------------------
  2321. bool __fastcall IsWin7()
  2322. {
  2323. return CheckWin32Version(6, 1);
  2324. }
  2325. //---------------------------------------------------------------------------
  2326. bool __fastcall IsWin8()
  2327. {
  2328. return CheckWin32Version(6, 2);
  2329. }
  2330. //---------------------------------------------------------------------------
  2331. bool __fastcall IsWin10()
  2332. {
  2333. return CheckWin32Version(10, 0);
  2334. }
  2335. //---------------------------------------------------------------------------
  2336. bool __fastcall IsWine()
  2337. {
  2338. HMODULE NtDll = GetModuleHandle(L"ntdll.dll");
  2339. return
  2340. DebugAlwaysTrue(NtDll != NULL) &&
  2341. (GetProcAddress(NtDll, "wine_get_version") != NULL);
  2342. }
  2343. //---------------------------------------------------------------------------
  2344. LCID __fastcall GetDefaultLCID()
  2345. {
  2346. return GetUserDefaultLCID();
  2347. }
  2348. //---------------------------------------------------------------------------
  2349. static UnicodeString ADefaultEncodingName;
  2350. UnicodeString __fastcall DefaultEncodingName()
  2351. {
  2352. if (ADefaultEncodingName.IsEmpty())
  2353. {
  2354. CPINFOEX Info;
  2355. GetCPInfoEx(CP_ACP, 0, &Info);
  2356. ADefaultEncodingName = Info.CodePageName;
  2357. }
  2358. return ADefaultEncodingName;
  2359. }
  2360. //---------------------------------------------------------------------------
  2361. bool _fastcall GetWindowsProductType(DWORD & Type)
  2362. {
  2363. bool Result;
  2364. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  2365. typedef BOOL WINAPI (* TGetProductInfo)(DWORD, DWORD, DWORD, DWORD, PDWORD);
  2366. TGetProductInfo GetProductInfo =
  2367. (TGetProductInfo)GetProcAddress(Kernel32, "GetProductInfo");
  2368. if (GetProductInfo == NULL)
  2369. {
  2370. Result = false;
  2371. }
  2372. else
  2373. {
  2374. GetProductInfo(Win32MajorVersion, Win32MinorVersion, 0, 0, &Type);
  2375. Result = true;
  2376. }
  2377. return Result;
  2378. }
  2379. //---------------------------------------------------------------------------
  2380. UnicodeString __fastcall WindowsProductName()
  2381. {
  2382. UnicodeString Result;
  2383. TRegistry * Registry = new TRegistry(KEY_READ);
  2384. try
  2385. {
  2386. Registry->RootKey = HKEY_LOCAL_MACHINE;
  2387. if (Registry->OpenKey(L"SOFTWARE", false) &&
  2388. Registry->OpenKey(L"Microsoft", false) &&
  2389. Registry->OpenKey(L"Windows NT", false) &&
  2390. Registry->OpenKey(L"CurrentVersion", false))
  2391. {
  2392. Result = Registry->ReadString(L"ProductName");
  2393. }
  2394. delete Registry;
  2395. }
  2396. catch(...)
  2397. {
  2398. }
  2399. return Result;
  2400. }
  2401. //---------------------------------------------------------------------------
  2402. bool __fastcall IsDirectoryWriteable(const UnicodeString & Path)
  2403. {
  2404. UnicodeString FileName =
  2405. IncludeTrailingPathDelimiter(Path) +
  2406. FORMAT(L"wscp_%s_%d.tmp", (FormatDateTime(L"nnzzz", Now()), int(GetCurrentProcessId())));
  2407. HANDLE Handle = CreateFile(ApiPath(FileName).c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL,
  2408. CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, 0);
  2409. bool Result = (Handle != INVALID_HANDLE_VALUE);
  2410. if (Result)
  2411. {
  2412. CloseHandle(Handle);
  2413. }
  2414. return Result;
  2415. }
  2416. //---------------------------------------------------------------------------
  2417. UnicodeString __fastcall FormatNumber(__int64 Number)
  2418. {
  2419. return FormatFloat(L"#,##0", Number);
  2420. }
  2421. //---------------------------------------------------------------------------
  2422. // simple alternative to FormatBytes
  2423. UnicodeString __fastcall FormatSize(__int64 Size)
  2424. {
  2425. return FormatNumber(Size);
  2426. }
  2427. //---------------------------------------------------------------------------
  2428. UnicodeString __fastcall ExtractFileBaseName(const UnicodeString & Path)
  2429. {
  2430. return ChangeFileExt(ExtractFileName(Path), L"");
  2431. }
  2432. //---------------------------------------------------------------------------
  2433. TStringList * __fastcall TextToStringList(const UnicodeString & Text)
  2434. {
  2435. std::unique_ptr<TStringList> List(new TStringList());
  2436. List->Text = Text;
  2437. return List.release();
  2438. }
  2439. //---------------------------------------------------------------------------
  2440. TStrings * __fastcall CloneStrings(TStrings * Strings)
  2441. {
  2442. std::unique_ptr<TStringList> List(new TStringList());
  2443. List->AddStrings(Strings);
  2444. return List.release();
  2445. }
  2446. //---------------------------------------------------------------------------
  2447. UnicodeString __fastcall TrimVersion(UnicodeString Version)
  2448. {
  2449. while ((Version.Pos(L".") != Version.LastDelimiter(L".")) &&
  2450. (Version.SubString(Version.Length() - 1, 2) == L".0"))
  2451. {
  2452. Version.SetLength(Version.Length() - 2);
  2453. }
  2454. return Version;
  2455. }
  2456. //---------------------------------------------------------------------------
  2457. UnicodeString __fastcall FormatVersion(int MajovVersion, int MinorVersion, int Release)
  2458. {
  2459. return
  2460. TrimVersion(FORMAT(L"%d.%d.%d",
  2461. (MajovVersion, MinorVersion, Release)));
  2462. }
  2463. //---------------------------------------------------------------------------
  2464. TFormatSettings __fastcall GetEngFormatSettings()
  2465. {
  2466. return TFormatSettings::Create((TLocaleID)1033);
  2467. }
  2468. //---------------------------------------------------------------------------
  2469. int __fastcall ParseShortEngMonthName(const UnicodeString & MonthStr)
  2470. {
  2471. TFormatSettings FormatSettings = GetEngFormatSettings();
  2472. return IndexStr(MonthStr, FormatSettings.ShortMonthNames, FormatSettings.ShortMonthNames.Size()) + 1;
  2473. }
  2474. //---------------------------------------------------------------------------
  2475. TStringList * __fastcall CreateSortedStringList(bool CaseSensitive, System::Types::TDuplicates Duplicates)
  2476. {
  2477. TStringList * Result = new TStringList();
  2478. Result->CaseSensitive = CaseSensitive;
  2479. Result->Sorted = true;
  2480. Result->Duplicates = Duplicates;
  2481. return Result;
  2482. }
  2483. //---------------------------------------------------------------------------
  2484. static UnicodeString __fastcall NormalizeIdent(UnicodeString Ident)
  2485. {
  2486. int Index = 1;
  2487. while (Index <= Ident.Length())
  2488. {
  2489. if (Ident[Index] == L'-')
  2490. {
  2491. Ident.Delete(Index, 1);
  2492. }
  2493. else
  2494. {
  2495. Index++;
  2496. }
  2497. }
  2498. return Ident;
  2499. }
  2500. //---------------------------------------------------------------------------
  2501. UnicodeString __fastcall FindIdent(const UnicodeString & Ident, TStrings * Idents)
  2502. {
  2503. UnicodeString NormalizedIdent(NormalizeIdent(Ident));
  2504. for (int Index = 0; Index < Idents->Count; Index++)
  2505. {
  2506. if (SameText(NormalizedIdent, NormalizeIdent(Idents->Strings[Index])))
  2507. {
  2508. return Idents->Strings[Index];
  2509. }
  2510. }
  2511. return Ident;
  2512. }
  2513. //---------------------------------------------------------------------------
  2514. static UnicodeString __fastcall GetTlsErrorStr(int Err)
  2515. {
  2516. char * Buffer = new char[512];
  2517. ERR_error_string(Err, Buffer);
  2518. // not sure about the UTF8
  2519. return UnicodeString(UTF8String(Buffer));
  2520. }
  2521. //---------------------------------------------------------------------------
  2522. static FILE * __fastcall OpenCertificate(const UnicodeString & Path)
  2523. {
  2524. FILE * Result = _wfopen(ApiPath(Path).c_str(), L"rb");
  2525. if (Result == NULL)
  2526. {
  2527. int Error = errno;
  2528. throw EOSExtException(MainInstructions(FMTLOAD(CERTIFICATE_OPEN_ERROR, (Path))), Error);
  2529. }
  2530. return Result;
  2531. }
  2532. //---------------------------------------------------------------------------
  2533. struct TPemPasswordCallbackData
  2534. {
  2535. UnicodeString * Passphrase;
  2536. };
  2537. //---------------------------------------------------------------------------
  2538. static int PemPasswordCallback(char * Buf, int Size, int /*RWFlag*/, void * UserData)
  2539. {
  2540. TPemPasswordCallbackData & Data = *reinterpret_cast<TPemPasswordCallbackData *>(UserData);
  2541. UTF8String UtfPassphrase = UTF8String(*Data.Passphrase);
  2542. strncpy(Buf, UtfPassphrase.c_str(), Size);
  2543. Shred(UtfPassphrase);
  2544. Buf[Size - 1] = '\0';
  2545. return strlen(Buf);
  2546. }
  2547. //---------------------------------------------------------------------------
  2548. static bool __fastcall IsTlsPassphraseError(int Error)
  2549. {
  2550. bool Result =
  2551. ((ERR_GET_LIB(Error) == ERR_LIB_PKCS12) &&
  2552. (ERR_GET_REASON(Error) == PKCS12_R_MAC_VERIFY_FAILURE)) ||
  2553. ((ERR_GET_LIB(Error) == ERR_LIB_PEM) &&
  2554. (ERR_GET_REASON(Error) == PEM_R_BAD_PASSWORD_READ));
  2555. return Result;
  2556. }
  2557. //---------------------------------------------------------------------------
  2558. static void __fastcall ThrowTlsCertificateErrorIgnorePassphraseErrors(const UnicodeString & Path)
  2559. {
  2560. int Error = ERR_get_error();
  2561. if (!IsTlsPassphraseError(Error))
  2562. {
  2563. throw ExtException(MainInstructions(FMTLOAD(CERTIFICATE_READ_ERROR, (Path))), GetTlsErrorStr(Error));
  2564. }
  2565. }
  2566. //---------------------------------------------------------------------------
  2567. void __fastcall ParseCertificate(const UnicodeString & Path,
  2568. const UnicodeString & Passphrase, X509 *& Certificate, EVP_PKEY *& PrivateKey,
  2569. bool & WrongPassphrase)
  2570. {
  2571. Certificate = NULL;
  2572. PrivateKey = NULL;
  2573. FILE * File;
  2574. // Inspired by neon's ne_ssl_clicert_read
  2575. File = OpenCertificate(Path);
  2576. PKCS12 * Pkcs12 = d2i_PKCS12_fp(File, NULL);
  2577. fclose(File);
  2578. if (Pkcs12 != NULL)
  2579. {
  2580. // Not sure about the UTF-8 encoding, but there's no wchar_t API
  2581. bool Result =
  2582. (PKCS12_parse(Pkcs12, UTF8String(Passphrase).c_str(), &PrivateKey, &Certificate, NULL) == 1);
  2583. PKCS12_free(Pkcs12);
  2584. if (!Result)
  2585. {
  2586. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path);
  2587. WrongPassphrase = true;
  2588. }
  2589. }
  2590. else
  2591. {
  2592. ERR_clear_error();
  2593. TPemPasswordCallbackData CallbackUserData;
  2594. // PemPasswordCallback never writes to the .Passphrase
  2595. CallbackUserData.Passphrase = const_cast<UnicodeString *>(&Passphrase);
  2596. File = OpenCertificate(Path);
  2597. PrivateKey = PEM_read_PrivateKey(File, NULL, PemPasswordCallback, &CallbackUserData);
  2598. fclose(File);
  2599. try
  2600. {
  2601. if (PrivateKey == NULL)
  2602. {
  2603. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path);
  2604. WrongPassphrase = true;
  2605. }
  2606. File = OpenCertificate(Path);
  2607. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  2608. fclose(File);
  2609. if (Certificate == NULL)
  2610. {
  2611. int Error = ERR_get_error();
  2612. // unlikely
  2613. if (IsTlsPassphraseError(Error))
  2614. {
  2615. WrongPassphrase = true;
  2616. }
  2617. else
  2618. {
  2619. UnicodeString CertificatePath = ChangeFileExt(Path, L".cer");
  2620. if (!FileExists(CertificatePath))
  2621. {
  2622. CertificatePath = ChangeFileExt(Path, L".crt");
  2623. }
  2624. if (!FileExists(CertificatePath))
  2625. {
  2626. throw Exception(MainInstructions(FMTLOAD(CERTIFICATE_PUBLIC_KEY_NOT_FOUND, (Path))));
  2627. }
  2628. else
  2629. {
  2630. File = OpenCertificate(CertificatePath);
  2631. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  2632. fclose(File);
  2633. if (Certificate == NULL)
  2634. {
  2635. ThrowTlsCertificateErrorIgnorePassphraseErrors(CertificatePath);
  2636. WrongPassphrase = true;
  2637. }
  2638. }
  2639. }
  2640. }
  2641. }
  2642. __finally
  2643. {
  2644. // We loaded private key, but failed to load certificate, discard the certificate
  2645. // (either exception was thrown or WrongPassphrase)
  2646. if ((PrivateKey != NULL) && (Certificate == NULL))
  2647. {
  2648. EVP_PKEY_free(PrivateKey);
  2649. PrivateKey = NULL;
  2650. }
  2651. // Certificate was verified, but passphrase was wrong when loading private key,
  2652. // so discard the certificate
  2653. else if ((Certificate != NULL) && (PrivateKey == NULL))
  2654. {
  2655. X509_free(Certificate);
  2656. Certificate = NULL;
  2657. }
  2658. }
  2659. }
  2660. }
  2661. //---------------------------------------------------------------------------
  2662. void __fastcall CheckCertificate(const UnicodeString & Path)
  2663. {
  2664. X509 * Certificate;
  2665. EVP_PKEY * PrivateKey;
  2666. bool WrongPassphrase;
  2667. ParseCertificate(Path, L"", Certificate, PrivateKey, WrongPassphrase);
  2668. if (PrivateKey != NULL)
  2669. {
  2670. EVP_PKEY_free(PrivateKey);
  2671. }
  2672. if (Certificate != NULL)
  2673. {
  2674. X509_free(Certificate);
  2675. }
  2676. }
  2677. //---------------------------------------------------------------------------
  2678. bool __fastcall IsHttpUrl(const UnicodeString & S)
  2679. {
  2680. return SameText(S.SubString(1, 4), L"http");
  2681. }