Common.cpp 124 KB

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