Common.cpp 119 KB

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