Common.cpp 124 KB

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