Common.cpp 118 KB

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