Common.cpp 136 KB

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