Common.cpp 132 KB

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