Common.cpp 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889
  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, bool HasPassphrase)
  2549. {
  2550. int ErrorLib = ERR_GET_LIB(Error);
  2551. int ErrorReason = ERR_GET_REASON(Error);
  2552. bool Result =
  2553. ((ErrorLib == ERR_LIB_PKCS12) &&
  2554. (ErrorReason == PKCS12_R_MAC_VERIFY_FAILURE)) ||
  2555. ((ErrorLib == ERR_LIB_PEM) &&
  2556. (ErrorReason == PEM_R_BAD_PASSWORD_READ)) ||
  2557. (HasPassphrase && (ERR_LIB_EVP == ERR_LIB_EVP) &&
  2558. ((ErrorReason == PEM_R_BAD_DECRYPT) || (ErrorReason == PEM_R_BAD_BASE64_DECODE)));
  2559. return Result;
  2560. }
  2561. //---------------------------------------------------------------------------
  2562. static void __fastcall ThrowTlsCertificateErrorIgnorePassphraseErrors(const UnicodeString & Path, bool HasPassphrase)
  2563. {
  2564. int Error = ERR_get_error();
  2565. if (!IsTlsPassphraseError(Error, HasPassphrase))
  2566. {
  2567. throw ExtException(MainInstructions(FMTLOAD(CERTIFICATE_READ_ERROR, (Path))), GetTlsErrorStr(Error));
  2568. }
  2569. }
  2570. //---------------------------------------------------------------------------
  2571. void __fastcall ParseCertificate(const UnicodeString & Path,
  2572. const UnicodeString & Passphrase, X509 *& Certificate, EVP_PKEY *& PrivateKey,
  2573. bool & WrongPassphrase)
  2574. {
  2575. Certificate = NULL;
  2576. PrivateKey = NULL;
  2577. bool HasPassphrase = !Passphrase.IsEmpty();
  2578. FILE * File;
  2579. // Inspired by neon's ne_ssl_clicert_read
  2580. File = OpenCertificate(Path);
  2581. // openssl pkcs12 -inkey cert.pem -in cert.crt -export -out cert.pfx
  2582. // Binary file
  2583. PKCS12 * Pkcs12 = d2i_PKCS12_fp(File, NULL);
  2584. fclose(File);
  2585. if (Pkcs12 != NULL)
  2586. {
  2587. // Not sure about the UTF-8 encoding, but there's no wchar_t API
  2588. bool Result =
  2589. (PKCS12_parse(Pkcs12, UTF8String(Passphrase).c_str(), &PrivateKey, &Certificate, NULL) == 1);
  2590. PKCS12_free(Pkcs12);
  2591. if (!Result)
  2592. {
  2593. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path, HasPassphrase);
  2594. WrongPassphrase = true;
  2595. }
  2596. }
  2597. else
  2598. {
  2599. ERR_clear_error();
  2600. TPemPasswordCallbackData CallbackUserData;
  2601. // PemPasswordCallback never writes to the .Passphrase
  2602. CallbackUserData.Passphrase = const_cast<UnicodeString *>(&Passphrase);
  2603. File = OpenCertificate(Path);
  2604. // Encrypted:
  2605. // openssl req -x509 -newkey rsa:2048 -keyout cert.pem -out cert.crt
  2606. // -----BEGIN ENCRYPTED PRIVATE KEY-----
  2607. // ...
  2608. // -----END ENCRYPTED PRIVATE KEY-----
  2609. // Not encrypted (add -nodes):
  2610. // -----BEGIN PRIVATE KEY-----
  2611. // ...
  2612. // -----END PRIVATE KEY-----
  2613. // Or (openssl genrsa -out client.key 1024 # used for certificate signing request)
  2614. // -----BEGIN RSA PRIVATE KEY-----
  2615. // ...
  2616. // -----END RSA PRIVATE KEY-----
  2617. PrivateKey = PEM_read_PrivateKey(File, NULL, PemPasswordCallback, &CallbackUserData);
  2618. fclose(File);
  2619. try
  2620. {
  2621. if (PrivateKey == NULL)
  2622. {
  2623. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path, HasPassphrase);
  2624. WrongPassphrase = true;
  2625. }
  2626. File = OpenCertificate(Path);
  2627. // The file can contain both private and public key
  2628. // (basically cert.pem and cert.crt appended one to each other)
  2629. // -----BEGIN ENCRYPTED PRIVATE KEY-----
  2630. // ...
  2631. // -----END ENCRYPTED PRIVATE KEY-----
  2632. // -----BEGIN CERTIFICATE-----
  2633. // ...
  2634. // -----END CERTIFICATE-----
  2635. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  2636. fclose(File);
  2637. if (Certificate == NULL)
  2638. {
  2639. int Error = ERR_get_error();
  2640. // unlikely
  2641. if (IsTlsPassphraseError(Error, HasPassphrase))
  2642. {
  2643. WrongPassphrase = true;
  2644. }
  2645. else
  2646. {
  2647. UnicodeString CertificatePath = ChangeFileExt(Path, L".cer");
  2648. if (!FileExists(CertificatePath))
  2649. {
  2650. CertificatePath = ChangeFileExt(Path, L".crt");
  2651. }
  2652. if (!FileExists(CertificatePath))
  2653. {
  2654. throw Exception(MainInstructions(FMTLOAD(CERTIFICATE_PUBLIC_KEY_NOT_FOUND, (Path))));
  2655. }
  2656. else
  2657. {
  2658. File = OpenCertificate(CertificatePath);
  2659. // -----BEGIN CERTIFICATE-----
  2660. // ...
  2661. // -----END CERTIFICATE-----
  2662. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  2663. fclose(File);
  2664. if (Certificate == NULL)
  2665. {
  2666. int Base64Error = ERR_get_error();
  2667. File = OpenCertificate(CertificatePath);
  2668. // Binary DER-encoded certificate
  2669. // (as above, with BEGIN/END removed, and decoded from Base64 to binary)
  2670. // openssl x509 -in cert.crt -out client.der.crt -outform DER
  2671. Certificate = d2i_X509_fp(File, NULL);
  2672. fclose(File);
  2673. if (Certificate == NULL)
  2674. {
  2675. int DERError = ERR_get_error();
  2676. UnicodeString Message = MainInstructions(FMTLOAD(CERTIFICATE_READ_ERROR, (CertificatePath)));
  2677. UnicodeString MoreMessages =
  2678. FORMAT(L"Base64: %s\nDER: %s", (GetTlsErrorStr(Base64Error), GetTlsErrorStr(DERError)));
  2679. throw ExtException(Message, MoreMessages);
  2680. }
  2681. }
  2682. }
  2683. }
  2684. }
  2685. }
  2686. __finally
  2687. {
  2688. // We loaded private key, but failed to load certificate, discard the certificate
  2689. // (either exception was thrown or WrongPassphrase)
  2690. if ((PrivateKey != NULL) && (Certificate == NULL))
  2691. {
  2692. EVP_PKEY_free(PrivateKey);
  2693. PrivateKey = NULL;
  2694. }
  2695. // Certificate was verified, but passphrase was wrong when loading private key,
  2696. // so discard the certificate
  2697. else if ((Certificate != NULL) && (PrivateKey == NULL))
  2698. {
  2699. X509_free(Certificate);
  2700. Certificate = NULL;
  2701. }
  2702. }
  2703. }
  2704. }
  2705. //---------------------------------------------------------------------------
  2706. void __fastcall CheckCertificate(const UnicodeString & Path)
  2707. {
  2708. X509 * Certificate;
  2709. EVP_PKEY * PrivateKey;
  2710. bool WrongPassphrase;
  2711. ParseCertificate(Path, L"", Certificate, PrivateKey, WrongPassphrase);
  2712. if (PrivateKey != NULL)
  2713. {
  2714. EVP_PKEY_free(PrivateKey);
  2715. }
  2716. if (Certificate != NULL)
  2717. {
  2718. X509_free(Certificate);
  2719. }
  2720. }
  2721. //---------------------------------------------------------------------------
  2722. bool __fastcall IsHttpUrl(const UnicodeString & S)
  2723. {
  2724. return SameText(S.SubString(1, 4), L"http");
  2725. }