Common.cpp 137 KB

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