1
0

Common.cpp 133 KB

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