Common.cpp 137 KB

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