Common.cpp 135 KB

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