Common.cpp 138 KB

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