Common.cpp 137 KB

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