Common.cpp 119 KB

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