Common.cpp 125 KB

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