Common.cpp 121 KB

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