Common.cpp 127 KB

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