Common.cpp 131 KB

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