Common.cpp 117 KB

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