Common.cpp 106 KB

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