Common.cpp 128 KB

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