Common.cpp 107 KB

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