apprentice.c 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439
  1. /*
  2. * Copyright (c) Ian F. Darwin 1986-1995.
  3. * Software written by Ian F. Darwin and others;
  4. * maintained 1995-present by Christos Zoulas and others.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice immediately at the beginning of the file, without modification,
  11. * this list of conditions, and the following disclaimer.
  12. * 2. Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  17. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  19. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
  20. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  22. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  23. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  24. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  25. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  26. * SUCH DAMAGE.
  27. */
  28. /*
  29. * apprentice - make one pass through /etc/magic, learning its secrets.
  30. */
  31. #include "php.h"
  32. #include "file.h"
  33. #ifndef lint
  34. FILE_RCSID("@(#)$File: apprentice.c,v 1.270 2018/02/21 21:26:48 christos Exp $")
  35. #endif /* lint */
  36. #include "magic.h"
  37. #include "patchlevel.h"
  38. #include <stdlib.h>
  39. #if defined(__hpux) && !defined(HAVE_STRTOULL)
  40. #if SIZEOF_LONG == 8
  41. # define strtoull strtoul
  42. #else
  43. # define strtoull __strtoull
  44. #endif
  45. #endif
  46. #ifdef PHP_WIN32
  47. #include "win32/unistd.h"
  48. #define strtoull _strtoui64
  49. #else
  50. #include <unistd.h>
  51. #endif
  52. #include <string.h>
  53. #include <assert.h>
  54. #include <ctype.h>
  55. #include <fcntl.h>
  56. #ifndef SSIZE_MAX
  57. #define MAXMAGIC_SIZE ((ssize_t)0x7fffffff)
  58. #else
  59. #define MAXMAGIC_SIZE SSIZE_MAX
  60. #endif
  61. #define EATAB {while (isascii((unsigned char) *l) && \
  62. isspace((unsigned char) *l)) ++l;}
  63. #define LOWCASE(l) (isupper((unsigned char) (l)) ? \
  64. tolower((unsigned char) (l)) : (l))
  65. /*
  66. * Work around a bug in headers on Digital Unix.
  67. * At least confirmed for: OSF1 V4.0 878
  68. */
  69. #if defined(__osf__) && defined(__DECC)
  70. #ifdef MAP_FAILED
  71. #undef MAP_FAILED
  72. #endif
  73. #endif
  74. #ifndef offsetof
  75. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  76. #endif
  77. #ifndef MAP_FAILED
  78. #define MAP_FAILED (void *) -1
  79. #endif
  80. #ifndef MAP_FILE
  81. #define MAP_FILE 0
  82. #endif
  83. #define ALLOC_CHUNK (size_t)10
  84. #define ALLOC_INCR (size_t)200
  85. #define MAP_TYPE_USER 0
  86. #define MAP_TYPE_MALLOC 1
  87. #define MAP_TYPE_MMAP 2
  88. struct magic_entry {
  89. struct magic *mp;
  90. uint32_t cont_count;
  91. uint32_t max_count;
  92. };
  93. struct magic_entry_set {
  94. struct magic_entry *me;
  95. uint32_t count;
  96. uint32_t max;
  97. };
  98. struct magic_map {
  99. void *p;
  100. size_t len;
  101. int type;
  102. struct magic *magic[MAGIC_SETS];
  103. uint32_t nmagic[MAGIC_SETS];
  104. };
  105. int file_formats[FILE_NAMES_SIZE];
  106. const size_t file_nformats = FILE_NAMES_SIZE;
  107. const char *file_names[FILE_NAMES_SIZE];
  108. const size_t file_nnames = FILE_NAMES_SIZE;
  109. private int getvalue(struct magic_set *ms, struct magic *, const char **, int);
  110. private int hextoint(int);
  111. private const char *getstr(struct magic_set *, struct magic *, const char *,
  112. int);
  113. private int parse(struct magic_set *, struct magic_entry *, const char *,
  114. size_t, int);
  115. private void eatsize(const char **);
  116. private int apprentice_1(struct magic_set *, const char *, int);
  117. private size_t apprentice_magic_strength(const struct magic *);
  118. private int apprentice_sort(const void *, const void *);
  119. private void apprentice_list(struct mlist *, int );
  120. private struct magic_map *apprentice_load(struct magic_set *,
  121. const char *, int);
  122. private struct mlist *mlist_alloc(void);
  123. private void mlist_free(struct mlist *);
  124. private void byteswap(struct magic *, uint32_t);
  125. private void bs1(struct magic *);
  126. private uint16_t swap2(uint16_t);
  127. private uint32_t swap4(uint32_t);
  128. private uint64_t swap8(uint64_t);
  129. private char *mkdbname(struct magic_set *, const char *, int);
  130. private struct magic_map *apprentice_buf(struct magic_set *, struct magic *,
  131. size_t);
  132. private struct magic_map *apprentice_map(struct magic_set *, const char *);
  133. private int check_buffer(struct magic_set *, struct magic_map *, const char *);
  134. private void apprentice_unmap(struct magic_map *);
  135. private int apprentice_compile(struct magic_set *, struct magic_map *,
  136. const char *);
  137. private int check_format_type(const char *, int, const char **);
  138. private int check_format(struct magic_set *, struct magic *);
  139. private int get_op(char);
  140. private int parse_mime(struct magic_set *, struct magic_entry *, const char *);
  141. private int parse_strength(struct magic_set *, struct magic_entry *, const char *);
  142. private int parse_apple(struct magic_set *, struct magic_entry *, const char *);
  143. private int parse_ext(struct magic_set *, struct magic_entry *, const char *);
  144. private size_t magicsize = sizeof(struct magic);
  145. private const char usg_hdr[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
  146. private struct {
  147. const char *name;
  148. size_t len;
  149. int (*fun)(struct magic_set *, struct magic_entry *, const char *);
  150. } bang[] = {
  151. #define DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name }
  152. DECLARE_FIELD(mime),
  153. DECLARE_FIELD(apple),
  154. DECLARE_FIELD(ext),
  155. DECLARE_FIELD(strength),
  156. #undef DECLARE_FIELD
  157. { NULL, 0, NULL }
  158. };
  159. #include "../data_file.c"
  160. struct type_tbl_s {
  161. const char name[16];
  162. const size_t len;
  163. const int type;
  164. const int format;
  165. };
  166. /*
  167. * XXX - the actual Single UNIX Specification says that "long" means "long",
  168. * as in the C data type, but we treat it as meaning "4-byte integer".
  169. * Given that the OS X version of file 5.04 did the same, I guess that passes
  170. * the actual test; having "long" be dependent on how big a "long" is on
  171. * the machine running "file" is silly.
  172. */
  173. static const struct type_tbl_s type_tbl[] = {
  174. # define XX(s) s, (sizeof(s) - 1)
  175. # define XX_NULL "", 0
  176. { XX("invalid"), FILE_INVALID, FILE_FMT_NONE },
  177. { XX("byte"), FILE_BYTE, FILE_FMT_NUM },
  178. { XX("short"), FILE_SHORT, FILE_FMT_NUM },
  179. { XX("default"), FILE_DEFAULT, FILE_FMT_NONE },
  180. { XX("long"), FILE_LONG, FILE_FMT_NUM },
  181. { XX("string"), FILE_STRING, FILE_FMT_STR },
  182. { XX("date"), FILE_DATE, FILE_FMT_STR },
  183. { XX("beshort"), FILE_BESHORT, FILE_FMT_NUM },
  184. { XX("belong"), FILE_BELONG, FILE_FMT_NUM },
  185. { XX("bedate"), FILE_BEDATE, FILE_FMT_STR },
  186. { XX("leshort"), FILE_LESHORT, FILE_FMT_NUM },
  187. { XX("lelong"), FILE_LELONG, FILE_FMT_NUM },
  188. { XX("ledate"), FILE_LEDATE, FILE_FMT_STR },
  189. { XX("pstring"), FILE_PSTRING, FILE_FMT_STR },
  190. { XX("ldate"), FILE_LDATE, FILE_FMT_STR },
  191. { XX("beldate"), FILE_BELDATE, FILE_FMT_STR },
  192. { XX("leldate"), FILE_LELDATE, FILE_FMT_STR },
  193. { XX("regex"), FILE_REGEX, FILE_FMT_STR },
  194. { XX("bestring16"), FILE_BESTRING16, FILE_FMT_STR },
  195. { XX("lestring16"), FILE_LESTRING16, FILE_FMT_STR },
  196. { XX("search"), FILE_SEARCH, FILE_FMT_STR },
  197. { XX("medate"), FILE_MEDATE, FILE_FMT_STR },
  198. { XX("meldate"), FILE_MELDATE, FILE_FMT_STR },
  199. { XX("melong"), FILE_MELONG, FILE_FMT_NUM },
  200. { XX("quad"), FILE_QUAD, FILE_FMT_QUAD },
  201. { XX("lequad"), FILE_LEQUAD, FILE_FMT_QUAD },
  202. { XX("bequad"), FILE_BEQUAD, FILE_FMT_QUAD },
  203. { XX("qdate"), FILE_QDATE, FILE_FMT_STR },
  204. { XX("leqdate"), FILE_LEQDATE, FILE_FMT_STR },
  205. { XX("beqdate"), FILE_BEQDATE, FILE_FMT_STR },
  206. { XX("qldate"), FILE_QLDATE, FILE_FMT_STR },
  207. { XX("leqldate"), FILE_LEQLDATE, FILE_FMT_STR },
  208. { XX("beqldate"), FILE_BEQLDATE, FILE_FMT_STR },
  209. { XX("float"), FILE_FLOAT, FILE_FMT_FLOAT },
  210. { XX("befloat"), FILE_BEFLOAT, FILE_FMT_FLOAT },
  211. { XX("lefloat"), FILE_LEFLOAT, FILE_FMT_FLOAT },
  212. { XX("double"), FILE_DOUBLE, FILE_FMT_DOUBLE },
  213. { XX("bedouble"), FILE_BEDOUBLE, FILE_FMT_DOUBLE },
  214. { XX("ledouble"), FILE_LEDOUBLE, FILE_FMT_DOUBLE },
  215. { XX("leid3"), FILE_LEID3, FILE_FMT_NUM },
  216. { XX("beid3"), FILE_BEID3, FILE_FMT_NUM },
  217. { XX("indirect"), FILE_INDIRECT, FILE_FMT_NUM },
  218. { XX("qwdate"), FILE_QWDATE, FILE_FMT_STR },
  219. { XX("leqwdate"), FILE_LEQWDATE, FILE_FMT_STR },
  220. { XX("beqwdate"), FILE_BEQWDATE, FILE_FMT_STR },
  221. { XX("name"), FILE_NAME, FILE_FMT_NONE },
  222. { XX("use"), FILE_USE, FILE_FMT_NONE },
  223. { XX("clear"), FILE_CLEAR, FILE_FMT_NONE },
  224. { XX("der"), FILE_DER, FILE_FMT_STR },
  225. { XX_NULL, FILE_INVALID, FILE_FMT_NONE },
  226. };
  227. /*
  228. * These are not types, and cannot be preceded by "u" to make them
  229. * unsigned.
  230. */
  231. static const struct type_tbl_s special_tbl[] = {
  232. { XX("der"), FILE_DER, FILE_FMT_STR },
  233. { XX("name"), FILE_NAME, FILE_FMT_STR },
  234. { XX("use"), FILE_USE, FILE_FMT_STR },
  235. { XX_NULL, FILE_INVALID, FILE_FMT_NONE },
  236. };
  237. # undef XX
  238. # undef XX_NULL
  239. private int
  240. get_type(const struct type_tbl_s *tbl, const char *l, const char **t)
  241. {
  242. const struct type_tbl_s *p;
  243. for (p = tbl; p->len; p++) {
  244. if (strncmp(l, p->name, p->len) == 0) {
  245. if (t)
  246. *t = l + p->len;
  247. break;
  248. }
  249. }
  250. return p->type;
  251. }
  252. private int
  253. get_standard_integer_type(const char *l, const char **t)
  254. {
  255. int type;
  256. if (isalpha((unsigned char)l[1])) {
  257. switch (l[1]) {
  258. case 'C':
  259. /* "dC" and "uC" */
  260. type = FILE_BYTE;
  261. break;
  262. case 'S':
  263. /* "dS" and "uS" */
  264. type = FILE_SHORT;
  265. break;
  266. case 'I':
  267. case 'L':
  268. /*
  269. * "dI", "dL", "uI", and "uL".
  270. *
  271. * XXX - the actual Single UNIX Specification says
  272. * that "L" means "long", as in the C data type,
  273. * but we treat it as meaning "4-byte integer".
  274. * Given that the OS X version of file 5.04 did
  275. * the same, I guess that passes the actual SUS
  276. * validation suite; having "dL" be dependent on
  277. * how big a "long" is on the machine running
  278. * "file" is silly.
  279. */
  280. type = FILE_LONG;
  281. break;
  282. case 'Q':
  283. /* "dQ" and "uQ" */
  284. type = FILE_QUAD;
  285. break;
  286. default:
  287. /* "d{anything else}", "u{anything else}" */
  288. return FILE_INVALID;
  289. }
  290. l += 2;
  291. } else if (isdigit((unsigned char)l[1])) {
  292. /*
  293. * "d{num}" and "u{num}"; we only support {num} values
  294. * of 1, 2, 4, and 8 - the Single UNIX Specification
  295. * doesn't say anything about whether arbitrary
  296. * values should be supported, but both the Solaris 10
  297. * and OS X Mountain Lion versions of file passed the
  298. * Single UNIX Specification validation suite, and
  299. * neither of them support values bigger than 8 or
  300. * non-power-of-2 values.
  301. */
  302. if (isdigit((unsigned char)l[2])) {
  303. /* Multi-digit, so > 9 */
  304. return FILE_INVALID;
  305. }
  306. switch (l[1]) {
  307. case '1':
  308. type = FILE_BYTE;
  309. break;
  310. case '2':
  311. type = FILE_SHORT;
  312. break;
  313. case '4':
  314. type = FILE_LONG;
  315. break;
  316. case '8':
  317. type = FILE_QUAD;
  318. break;
  319. default:
  320. /* XXX - what about 3, 5, 6, or 7? */
  321. return FILE_INVALID;
  322. }
  323. l += 2;
  324. } else {
  325. /*
  326. * "d" or "u" by itself.
  327. */
  328. type = FILE_LONG;
  329. ++l;
  330. }
  331. if (t)
  332. *t = l;
  333. return type;
  334. }
  335. private void
  336. init_file_tables(void)
  337. {
  338. static int done = 0;
  339. const struct type_tbl_s *p;
  340. if (done)
  341. return;
  342. done++;
  343. for (p = type_tbl; p->len; p++) {
  344. assert(p->type < FILE_NAMES_SIZE);
  345. file_names[p->type] = p->name;
  346. file_formats[p->type] = p->format;
  347. }
  348. assert(p - type_tbl == FILE_NAMES_SIZE);
  349. }
  350. private int
  351. add_mlist(struct mlist *mlp, struct magic_map *map, size_t idx)
  352. {
  353. struct mlist *ml;
  354. mlp->map = NULL;
  355. if ((ml = CAST(struct mlist *, emalloc(sizeof(*ml)))) == NULL)
  356. return -1;
  357. ml->map = idx == 0 ? map : NULL;
  358. ml->magic = map->magic[idx];
  359. ml->nmagic = map->nmagic[idx];
  360. mlp->prev->next = ml;
  361. ml->prev = mlp->prev;
  362. ml->next = mlp;
  363. mlp->prev = ml;
  364. return 0;
  365. }
  366. /*
  367. * Handle one file or directory.
  368. */
  369. private int
  370. apprentice_1(struct magic_set *ms, const char *fn, int action)
  371. {
  372. struct magic_map *map;
  373. struct mlist *ml;
  374. size_t i;
  375. if (magicsize != FILE_MAGICSIZE) {
  376. file_error(ms, 0, "magic element size %lu != %lu",
  377. (unsigned long)sizeof(*map->magic[0]),
  378. (unsigned long)FILE_MAGICSIZE);
  379. return -1;
  380. }
  381. if (action == FILE_COMPILE) {
  382. map = apprentice_load(ms, fn, action);
  383. if (map == NULL)
  384. return -1;
  385. return apprentice_compile(ms, map, fn);
  386. }
  387. map = apprentice_map(ms, fn);
  388. if (map == (struct magic_map *)-1)
  389. return -1;
  390. if (map == NULL) {
  391. if (fn) {
  392. if (ms->flags & MAGIC_CHECK)
  393. file_magwarn(ms, "using regular magic file `%s'", fn);
  394. map = apprentice_load(ms, fn, action);
  395. }
  396. if (map == NULL)
  397. return -1;
  398. }
  399. for (i = 0; i < MAGIC_SETS; i++) {
  400. if (add_mlist(ms->mlist[i], map, i) == -1) {
  401. file_oomem(ms, sizeof(*ml));
  402. return -1;
  403. }
  404. }
  405. if (action == FILE_LIST) {
  406. for (i = 0; i < MAGIC_SETS; i++) {
  407. printf("Set %" SIZE_T_FORMAT "u:\nBinary patterns:\n",
  408. i);
  409. apprentice_list(ms->mlist[i], BINTEST);
  410. printf("Text patterns:\n");
  411. apprentice_list(ms->mlist[i], TEXTTEST);
  412. }
  413. }
  414. return 0;
  415. }
  416. protected void
  417. file_ms_free(struct magic_set *ms)
  418. {
  419. size_t i;
  420. if (ms == NULL)
  421. return;
  422. for (i = 0; i < MAGIC_SETS; i++)
  423. mlist_free(ms->mlist[i]);
  424. if (ms->o.pbuf) {
  425. efree(ms->o.pbuf);
  426. }
  427. if (ms->o.buf) {
  428. efree(ms->o.buf);
  429. }
  430. if (ms->c.li) {
  431. efree(ms->c.li);
  432. }
  433. efree(ms);
  434. }
  435. protected struct magic_set *
  436. file_ms_alloc(int flags)
  437. {
  438. struct magic_set *ms;
  439. size_t i, len;
  440. if ((ms = CAST(struct magic_set *, ecalloc((size_t)1,
  441. sizeof(struct magic_set)))) == NULL)
  442. return NULL;
  443. if (magic_setflags(ms, flags) == -1) {
  444. errno = EINVAL;
  445. goto free;
  446. }
  447. ms->o.buf = ms->o.pbuf = NULL;
  448. len = (ms->c.len = 10) * sizeof(*ms->c.li);
  449. if ((ms->c.li = CAST(struct level_info *, emalloc(len))) == NULL)
  450. goto free;
  451. ms->event_flags = 0;
  452. ms->error = -1;
  453. for (i = 0; i < MAGIC_SETS; i++)
  454. ms->mlist[i] = NULL;
  455. ms->file = "unknown";
  456. ms->line = 0;
  457. ms->indir_max = FILE_INDIR_MAX;
  458. ms->name_max = FILE_NAME_MAX;
  459. ms->elf_shnum_max = FILE_ELF_SHNUM_MAX;
  460. ms->elf_phnum_max = FILE_ELF_PHNUM_MAX;
  461. ms->elf_notes_max = FILE_ELF_NOTES_MAX;
  462. ms->regex_max = FILE_REGEX_MAX;
  463. ms->bytes_max = FILE_BYTES_MAX;
  464. return ms;
  465. free:
  466. efree(ms);
  467. return NULL;
  468. }
  469. private void
  470. apprentice_unmap(struct magic_map *map)
  471. {
  472. if (map == NULL)
  473. return;
  474. if (map->p != php_magic_database) {
  475. if (map->p == NULL) {
  476. int j;
  477. for (j = 0; j < MAGIC_SETS; j++) {
  478. if (map->magic[j]) {
  479. efree(map->magic[j]);
  480. }
  481. }
  482. } else {
  483. efree(map->p);
  484. }
  485. }
  486. efree(map);
  487. }
  488. private struct mlist *
  489. mlist_alloc(void)
  490. {
  491. struct mlist *mlist;
  492. if ((mlist = CAST(struct mlist *, ecalloc(1, sizeof(*mlist)))) == NULL) {
  493. return NULL;
  494. }
  495. mlist->next = mlist->prev = mlist;
  496. return mlist;
  497. }
  498. private void
  499. mlist_free(struct mlist *mlist)
  500. {
  501. struct mlist *ml, *next;
  502. if (mlist == NULL)
  503. return;
  504. ml = mlist->next;
  505. for (ml = mlist->next; (next = ml->next) != NULL; ml = next) {
  506. if (ml->map)
  507. apprentice_unmap(CAST(struct magic_map *, ml->map));
  508. efree(ml);
  509. if (ml == mlist)
  510. break;
  511. }
  512. }
  513. /* const char *fn: list of magic files and directories */
  514. protected int
  515. file_apprentice(struct magic_set *ms, const char *fn, int action)
  516. {
  517. char *p, *mfn;
  518. int fileerr, errs = -1;
  519. size_t i;
  520. if (ms->mlist[0] != NULL)
  521. (void)file_reset(ms, 0);
  522. /* XXX disabling default magic loading so the compiled in data is used */
  523. #if 0
  524. if ((fn = magic_getpath(fn, action)) == NULL)
  525. return -1;
  526. #endif
  527. init_file_tables();
  528. if (fn == NULL)
  529. fn = getenv("MAGIC");
  530. if (fn == NULL) {
  531. for (i = 0; i < MAGIC_SETS; i++) {
  532. mlist_free(ms->mlist[i]);
  533. if ((ms->mlist[i] = mlist_alloc()) == NULL) {
  534. file_oomem(ms, sizeof(*ms->mlist[i]));
  535. return -1;
  536. }
  537. }
  538. return apprentice_1(ms, fn, action);
  539. }
  540. if ((mfn = estrdup(fn)) == NULL) {
  541. file_oomem(ms, strlen(fn));
  542. return -1;
  543. }
  544. for (i = 0; i < MAGIC_SETS; i++) {
  545. mlist_free(ms->mlist[i]);
  546. if ((ms->mlist[i] = mlist_alloc()) == NULL) {
  547. file_oomem(ms, sizeof(*ms->mlist[i]));
  548. while (i-- > 0) {
  549. mlist_free(ms->mlist[i]);
  550. ms->mlist[i] = NULL;
  551. }
  552. efree(mfn);
  553. return -1;
  554. }
  555. }
  556. fn = mfn;
  557. while (fn) {
  558. p = strchr(fn, PATHSEP);
  559. if (p)
  560. *p++ = '\0';
  561. if (*fn == '\0')
  562. break;
  563. fileerr = apprentice_1(ms, fn, action);
  564. errs = MAX(errs, fileerr);
  565. fn = p;
  566. }
  567. efree(mfn);
  568. if (errs == -1) {
  569. for (i = 0; i < MAGIC_SETS; i++) {
  570. mlist_free(ms->mlist[i]);
  571. ms->mlist[i] = NULL;
  572. }
  573. file_error(ms, 0, "could not find any valid magic files!");
  574. return -1;
  575. }
  576. #if 0
  577. /*
  578. * Always leave the database loaded
  579. */
  580. if (action == FILE_LOAD)
  581. return 0;
  582. for (i = 0; i < MAGIC_SETS; i++) {
  583. mlist_free(ms->mlist[i]);
  584. ms->mlist[i] = NULL;
  585. }
  586. #endif
  587. switch (action) {
  588. case FILE_LOAD:
  589. case FILE_COMPILE:
  590. case FILE_CHECK:
  591. case FILE_LIST:
  592. return 0;
  593. default:
  594. file_error(ms, 0, "Invalid action %d", action);
  595. return -1;
  596. }
  597. }
  598. /*
  599. * Compute the real length of a magic expression, for the purposes
  600. * of determining how "strong" a magic expression is (approximating
  601. * how specific its matches are):
  602. * - magic characters count 0 unless escaped.
  603. * - [] expressions count 1
  604. * - {} expressions count 0
  605. * - regular characters or escaped magic characters count 1
  606. * - 0 length expressions count as one
  607. */
  608. private size_t
  609. nonmagic(const char *str)
  610. {
  611. const char *p;
  612. size_t rv = 0;
  613. for (p = str; *p; p++)
  614. switch (*p) {
  615. case '\\': /* Escaped anything counts 1 */
  616. if (!*++p)
  617. p--;
  618. rv++;
  619. continue;
  620. case '?': /* Magic characters count 0 */
  621. case '*':
  622. case '.':
  623. case '+':
  624. case '^':
  625. case '$':
  626. continue;
  627. case '[': /* Bracketed expressions count 1 the ']' */
  628. while (*p && *p != ']')
  629. p++;
  630. p--;
  631. continue;
  632. case '{': /* Braced expressions count 0 */
  633. while (*p && *p != '}')
  634. p++;
  635. if (!*p)
  636. p--;
  637. continue;
  638. default: /* Anything else counts 1 */
  639. rv++;
  640. continue;
  641. }
  642. return rv == 0 ? 1 : rv; /* Return at least 1 */
  643. }
  644. private size_t
  645. typesize(int type)
  646. {
  647. switch (type) {
  648. case FILE_BYTE:
  649. return 1;
  650. case FILE_SHORT:
  651. case FILE_LESHORT:
  652. case FILE_BESHORT:
  653. return 2;
  654. case FILE_LONG:
  655. case FILE_LELONG:
  656. case FILE_BELONG:
  657. case FILE_MELONG:
  658. return 4;
  659. case FILE_DATE:
  660. case FILE_LEDATE:
  661. case FILE_BEDATE:
  662. case FILE_MEDATE:
  663. case FILE_LDATE:
  664. case FILE_LELDATE:
  665. case FILE_BELDATE:
  666. case FILE_MELDATE:
  667. case FILE_FLOAT:
  668. case FILE_BEFLOAT:
  669. case FILE_LEFLOAT:
  670. return 4;
  671. case FILE_QUAD:
  672. case FILE_BEQUAD:
  673. case FILE_LEQUAD:
  674. case FILE_QDATE:
  675. case FILE_LEQDATE:
  676. case FILE_BEQDATE:
  677. case FILE_QLDATE:
  678. case FILE_LEQLDATE:
  679. case FILE_BEQLDATE:
  680. case FILE_QWDATE:
  681. case FILE_LEQWDATE:
  682. case FILE_BEQWDATE:
  683. case FILE_DOUBLE:
  684. case FILE_BEDOUBLE:
  685. case FILE_LEDOUBLE:
  686. return 8;
  687. default:
  688. return (size_t)~0;
  689. }
  690. }
  691. /*
  692. * Get weight of this magic entry, for sorting purposes.
  693. */
  694. private size_t
  695. apprentice_magic_strength(const struct magic *m)
  696. {
  697. #define MULT 10
  698. size_t ts, v, val = 2 * MULT; /* baseline strength */
  699. switch (m->type) {
  700. case FILE_DEFAULT: /* make sure this sorts last */
  701. if (m->factor_op != FILE_FACTOR_OP_NONE)
  702. abort();
  703. return 0;
  704. case FILE_BYTE:
  705. case FILE_SHORT:
  706. case FILE_LESHORT:
  707. case FILE_BESHORT:
  708. case FILE_LONG:
  709. case FILE_LELONG:
  710. case FILE_BELONG:
  711. case FILE_MELONG:
  712. case FILE_DATE:
  713. case FILE_LEDATE:
  714. case FILE_BEDATE:
  715. case FILE_MEDATE:
  716. case FILE_LDATE:
  717. case FILE_LELDATE:
  718. case FILE_BELDATE:
  719. case FILE_MELDATE:
  720. case FILE_FLOAT:
  721. case FILE_BEFLOAT:
  722. case FILE_LEFLOAT:
  723. case FILE_QUAD:
  724. case FILE_BEQUAD:
  725. case FILE_LEQUAD:
  726. case FILE_QDATE:
  727. case FILE_LEQDATE:
  728. case FILE_BEQDATE:
  729. case FILE_QLDATE:
  730. case FILE_LEQLDATE:
  731. case FILE_BEQLDATE:
  732. case FILE_QWDATE:
  733. case FILE_LEQWDATE:
  734. case FILE_BEQWDATE:
  735. case FILE_DOUBLE:
  736. case FILE_BEDOUBLE:
  737. case FILE_LEDOUBLE:
  738. ts = typesize(m->type);
  739. if (ts == (size_t)~0)
  740. abort();
  741. val += ts * MULT;
  742. break;
  743. case FILE_PSTRING:
  744. case FILE_STRING:
  745. val += m->vallen * MULT;
  746. break;
  747. case FILE_BESTRING16:
  748. case FILE_LESTRING16:
  749. val += m->vallen * MULT / 2;
  750. break;
  751. case FILE_SEARCH:
  752. val += m->vallen * MAX(MULT / m->vallen, 1);
  753. break;
  754. case FILE_REGEX:
  755. v = nonmagic(m->value.s);
  756. val += v * MAX(MULT / v, 1);
  757. break;
  758. case FILE_INDIRECT:
  759. case FILE_NAME:
  760. case FILE_USE:
  761. break;
  762. case FILE_DER:
  763. val += MULT;
  764. break;
  765. default:
  766. (void)fprintf(stderr, "Bad type %d\n", m->type);
  767. abort();
  768. }
  769. switch (m->reln) {
  770. case 'x': /* matches anything penalize */
  771. case '!': /* matches almost anything penalize */
  772. val = 0;
  773. break;
  774. case '=': /* Exact match, prefer */
  775. val += MULT;
  776. break;
  777. case '>':
  778. case '<': /* comparison match reduce strength */
  779. val -= 2 * MULT;
  780. break;
  781. case '^':
  782. case '&': /* masking bits, we could count them too */
  783. val -= MULT;
  784. break;
  785. default:
  786. (void)fprintf(stderr, "Bad relation %c\n", m->reln);
  787. abort();
  788. }
  789. if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */
  790. val = 1;
  791. switch (m->factor_op) {
  792. case FILE_FACTOR_OP_NONE:
  793. break;
  794. case FILE_FACTOR_OP_PLUS:
  795. val += m->factor;
  796. break;
  797. case FILE_FACTOR_OP_MINUS:
  798. val -= m->factor;
  799. break;
  800. case FILE_FACTOR_OP_TIMES:
  801. val *= m->factor;
  802. break;
  803. case FILE_FACTOR_OP_DIV:
  804. val /= m->factor;
  805. break;
  806. default:
  807. abort();
  808. }
  809. /*
  810. * Magic entries with no description get a bonus because they depend
  811. * on subsequent magic entries to print something.
  812. */
  813. if (m->desc[0] == '\0')
  814. val++;
  815. return val;
  816. }
  817. /*
  818. * Sort callback for sorting entries by "strength" (basically length)
  819. */
  820. private int
  821. apprentice_sort(const void *a, const void *b)
  822. {
  823. const struct magic_entry *ma = CAST(const struct magic_entry *, a);
  824. const struct magic_entry *mb = CAST(const struct magic_entry *, b);
  825. size_t sa = apprentice_magic_strength(ma->mp);
  826. size_t sb = apprentice_magic_strength(mb->mp);
  827. if (sa == sb)
  828. return 0;
  829. else if (sa > sb)
  830. return -1;
  831. else
  832. return 1;
  833. }
  834. /*
  835. * Shows sorted patterns list in the order which is used for the matching
  836. */
  837. private void
  838. apprentice_list(struct mlist *mlist, int mode)
  839. {
  840. uint32_t magindex = 0;
  841. struct mlist *ml;
  842. for (ml = mlist->next; ml != mlist; ml = ml->next) {
  843. for (magindex = 0; magindex < ml->nmagic; magindex++) {
  844. struct magic *m = &ml->magic[magindex];
  845. if ((m->flag & mode) != mode) {
  846. /* Skip sub-tests */
  847. while (magindex + 1 < ml->nmagic &&
  848. ml->magic[magindex + 1].cont_level != 0)
  849. ++magindex;
  850. continue; /* Skip to next top-level test*/
  851. }
  852. /*
  853. * Try to iterate over the tree until we find item with
  854. * description/mimetype.
  855. */
  856. while (magindex + 1 < ml->nmagic &&
  857. ml->magic[magindex + 1].cont_level != 0 &&
  858. *ml->magic[magindex].desc == '\0' &&
  859. *ml->magic[magindex].mimetype == '\0')
  860. magindex++;
  861. printf("Strength = %3" SIZE_T_FORMAT "u@%u: %s [%s]\n",
  862. apprentice_magic_strength(m),
  863. ml->magic[magindex].lineno,
  864. ml->magic[magindex].desc,
  865. ml->magic[magindex].mimetype);
  866. }
  867. }
  868. }
  869. private void
  870. set_test_type(struct magic *mstart, struct magic *m)
  871. {
  872. switch (m->type) {
  873. case FILE_BYTE:
  874. case FILE_SHORT:
  875. case FILE_LONG:
  876. case FILE_DATE:
  877. case FILE_BESHORT:
  878. case FILE_BELONG:
  879. case FILE_BEDATE:
  880. case FILE_LESHORT:
  881. case FILE_LELONG:
  882. case FILE_LEDATE:
  883. case FILE_LDATE:
  884. case FILE_BELDATE:
  885. case FILE_LELDATE:
  886. case FILE_MEDATE:
  887. case FILE_MELDATE:
  888. case FILE_MELONG:
  889. case FILE_QUAD:
  890. case FILE_LEQUAD:
  891. case FILE_BEQUAD:
  892. case FILE_QDATE:
  893. case FILE_LEQDATE:
  894. case FILE_BEQDATE:
  895. case FILE_QLDATE:
  896. case FILE_LEQLDATE:
  897. case FILE_BEQLDATE:
  898. case FILE_QWDATE:
  899. case FILE_LEQWDATE:
  900. case FILE_BEQWDATE:
  901. case FILE_FLOAT:
  902. case FILE_BEFLOAT:
  903. case FILE_LEFLOAT:
  904. case FILE_DOUBLE:
  905. case FILE_BEDOUBLE:
  906. case FILE_LEDOUBLE:
  907. case FILE_DER:
  908. mstart->flag |= BINTEST;
  909. break;
  910. case FILE_STRING:
  911. case FILE_PSTRING:
  912. case FILE_BESTRING16:
  913. case FILE_LESTRING16:
  914. /* Allow text overrides */
  915. if (mstart->str_flags & STRING_TEXTTEST)
  916. mstart->flag |= TEXTTEST;
  917. else
  918. mstart->flag |= BINTEST;
  919. break;
  920. case FILE_REGEX:
  921. case FILE_SEARCH:
  922. /* Check for override */
  923. if (mstart->str_flags & STRING_BINTEST)
  924. mstart->flag |= BINTEST;
  925. if (mstart->str_flags & STRING_TEXTTEST)
  926. mstart->flag |= TEXTTEST;
  927. if (mstart->flag & (TEXTTEST|BINTEST))
  928. break;
  929. /* binary test if pattern is not text */
  930. if (file_looks_utf8(m->value.us, (size_t)m->vallen, NULL,
  931. NULL) <= 0)
  932. mstart->flag |= BINTEST;
  933. else
  934. mstart->flag |= TEXTTEST;
  935. break;
  936. case FILE_DEFAULT:
  937. /* can't deduce anything; we shouldn't see this at the
  938. top level anyway */
  939. break;
  940. case FILE_INVALID:
  941. default:
  942. /* invalid search type, but no need to complain here */
  943. break;
  944. }
  945. }
  946. private int
  947. addentry(struct magic_set *ms, struct magic_entry *me,
  948. struct magic_entry_set *mset)
  949. {
  950. size_t i = me->mp->type == FILE_NAME ? 1 : 0;
  951. if (mset[i].count == mset[i].max) {
  952. struct magic_entry *mp;
  953. mset[i].max += ALLOC_INCR;
  954. if ((mp = CAST(struct magic_entry *,
  955. erealloc(mset[i].me, sizeof(*mp) * mset[i].max))) ==
  956. NULL) {
  957. file_oomem(ms, sizeof(*mp) * mset[i].max);
  958. return -1;
  959. }
  960. (void)memset(&mp[mset[i].count], 0, sizeof(*mp) *
  961. ALLOC_INCR);
  962. mset[i].me = mp;
  963. }
  964. mset[i].me[mset[i].count++] = *me;
  965. memset(me, 0, sizeof(*me));
  966. return 0;
  967. }
  968. /*
  969. * Load and parse one file.
  970. */
  971. private void
  972. load_1(struct magic_set *ms, int action, const char *fn, int *errs,
  973. struct magic_entry_set *mset)
  974. {
  975. char buffer[BUFSIZ + 1];
  976. char *line = NULL;
  977. size_t len;
  978. size_t lineno = 0;
  979. struct magic_entry me;
  980. php_stream *stream;
  981. ms->file = fn;
  982. stream = php_stream_open_wrapper((char *)fn, "rb", REPORT_ERRORS, NULL);
  983. if (stream == NULL) {
  984. if (errno != ENOENT)
  985. file_error(ms, errno, "cannot read magic file `%s'",
  986. fn);
  987. (*errs)++;
  988. return;
  989. }
  990. memset(&me, 0, sizeof(me));
  991. /* read and parse this file */
  992. for (ms->line = 1; (line = php_stream_get_line(stream, buffer , BUFSIZ, &len)) != NULL; ms->line++) {
  993. if (len == 0) /* null line, garbage, etc */
  994. continue;
  995. if (line[len - 1] == '\n') {
  996. lineno++;
  997. line[len - 1] = '\0'; /* delete newline */
  998. }
  999. switch (line[0]) {
  1000. case '\0': /* empty, do not parse */
  1001. case '#': /* comment, do not parse */
  1002. continue;
  1003. case '!':
  1004. if (line[1] == ':') {
  1005. size_t i;
  1006. for (i = 0; bang[i].name != NULL; i++) {
  1007. if ((size_t)(len - 2) > bang[i].len &&
  1008. memcmp(bang[i].name, line + 2,
  1009. bang[i].len) == 0)
  1010. break;
  1011. }
  1012. if (bang[i].name == NULL) {
  1013. file_error(ms, 0,
  1014. "Unknown !: entry `%s'", line);
  1015. (*errs)++;
  1016. continue;
  1017. }
  1018. if (me.mp == NULL) {
  1019. file_error(ms, 0,
  1020. "No current entry for :!%s type",
  1021. bang[i].name);
  1022. (*errs)++;
  1023. continue;
  1024. }
  1025. if ((*bang[i].fun)(ms, &me,
  1026. line + bang[i].len + 2) != 0) {
  1027. (*errs)++;
  1028. continue;
  1029. }
  1030. continue;
  1031. }
  1032. /*FALLTHROUGH*/
  1033. default:
  1034. again:
  1035. switch (parse(ms, &me, line, lineno, action)) {
  1036. case 0:
  1037. continue;
  1038. case 1:
  1039. (void)addentry(ms, &me, mset);
  1040. goto again;
  1041. default:
  1042. (*errs)++;
  1043. break;
  1044. }
  1045. }
  1046. }
  1047. if (me.mp)
  1048. (void)addentry(ms, &me, mset);
  1049. efree(line);
  1050. php_stream_close(stream);
  1051. }
  1052. /*
  1053. * parse a file or directory of files
  1054. * const char *fn: name of magic file or directory
  1055. */
  1056. private int
  1057. cmpstrp(const void *p1, const void *p2)
  1058. {
  1059. return strcmp(*(char *const *)p1, *(char *const *)p2);
  1060. }
  1061. private uint32_t
  1062. set_text_binary(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
  1063. uint32_t starttest)
  1064. {
  1065. static const char text[] = "text";
  1066. static const char binary[] = "binary";
  1067. static const size_t len = sizeof(text);
  1068. uint32_t i = starttest;
  1069. do {
  1070. set_test_type(me[starttest].mp, me[i].mp);
  1071. if ((ms->flags & MAGIC_DEBUG) == 0)
  1072. continue;
  1073. (void)fprintf(stderr, "%s%s%s: %s\n",
  1074. me[i].mp->mimetype,
  1075. me[i].mp->mimetype[0] == '\0' ? "" : "; ",
  1076. me[i].mp->desc[0] ? me[i].mp->desc : "(no description)",
  1077. me[i].mp->flag & BINTEST ? binary : text);
  1078. if (me[i].mp->flag & BINTEST) {
  1079. char *p = strstr(me[i].mp->desc, text);
  1080. if (p && (p == me[i].mp->desc ||
  1081. isspace((unsigned char)p[-1])) &&
  1082. (p + len - me[i].mp->desc == MAXstring
  1083. || (p[len] == '\0' ||
  1084. isspace((unsigned char)p[len]))))
  1085. (void)fprintf(stderr, "*** Possible "
  1086. "binary test for text type\n");
  1087. }
  1088. } while (++i < nme && me[i].mp->cont_level != 0);
  1089. return i;
  1090. }
  1091. private void
  1092. set_last_default(struct magic_set *ms, struct magic_entry *me, uint32_t nme)
  1093. {
  1094. uint32_t i;
  1095. for (i = 0; i < nme; i++) {
  1096. if (me[i].mp->cont_level == 0 &&
  1097. me[i].mp->type == FILE_DEFAULT) {
  1098. while (++i < nme)
  1099. if (me[i].mp->cont_level == 0)
  1100. break;
  1101. if (i != nme) {
  1102. /* XXX - Ugh! */
  1103. ms->line = me[i].mp->lineno;
  1104. file_magwarn(ms,
  1105. "level 0 \"default\" did not sort last");
  1106. }
  1107. return;
  1108. }
  1109. }
  1110. }
  1111. private int
  1112. coalesce_entries(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
  1113. struct magic **ma, uint32_t *nma)
  1114. {
  1115. uint32_t i, mentrycount = 0;
  1116. size_t slen;
  1117. for (i = 0; i < nme; i++)
  1118. mentrycount += me[i].cont_count;
  1119. slen = sizeof(**ma) * mentrycount;
  1120. if ((*ma = CAST(struct magic *, emalloc(slen))) == NULL) {
  1121. file_oomem(ms, slen);
  1122. return -1;
  1123. }
  1124. mentrycount = 0;
  1125. for (i = 0; i < nme; i++) {
  1126. (void)memcpy(*ma + mentrycount, me[i].mp,
  1127. me[i].cont_count * sizeof(**ma));
  1128. mentrycount += me[i].cont_count;
  1129. }
  1130. *nma = mentrycount;
  1131. return 0;
  1132. }
  1133. private void
  1134. magic_entry_free(struct magic_entry *me, uint32_t nme)
  1135. {
  1136. uint32_t i;
  1137. if (me == NULL)
  1138. return;
  1139. for (i = 0; i < nme; i++)
  1140. efree(me[i].mp);
  1141. efree(me);
  1142. }
  1143. private struct magic_map *
  1144. apprentice_load(struct magic_set *ms, const char *fn, int action)
  1145. {
  1146. int errs = 0;
  1147. uint32_t i, j;
  1148. size_t files = 0, maxfiles = 0;
  1149. char **filearr = NULL;
  1150. zend_stat_t st;
  1151. struct magic_map *map;
  1152. struct magic_entry_set mset[MAGIC_SETS];
  1153. php_stream *dir;
  1154. php_stream_dirent d;
  1155. memset(mset, 0, sizeof(mset));
  1156. ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
  1157. if ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL)
  1158. {
  1159. file_oomem(ms, sizeof(*map));
  1160. return NULL;
  1161. }
  1162. map->type = MAP_TYPE_MALLOC;
  1163. /* print silly verbose header for USG compat. */
  1164. if (action == FILE_CHECK)
  1165. (void)fprintf(stderr, "%s\n", usg_hdr);
  1166. /* load directory or file */
  1167. /* FIXME: Read file names and sort them to prevent
  1168. non-determinism. See Debian bug #488562. */
  1169. if (php_sys_stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
  1170. int mflen;
  1171. char mfn[MAXPATHLEN];
  1172. dir = php_stream_opendir((char *)fn, REPORT_ERRORS, NULL);
  1173. if (!dir) {
  1174. errs++;
  1175. goto out;
  1176. }
  1177. while (php_stream_readdir(dir, &d)) {
  1178. if ((mflen = snprintf(mfn, sizeof(mfn), "%s/%s", fn, d.d_name)) < 0) {
  1179. file_oomem(ms,
  1180. strlen(fn) + strlen(d.d_name) + 2);
  1181. errs++;
  1182. php_stream_closedir(dir);
  1183. goto out;
  1184. }
  1185. if (zend_stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {
  1186. continue;
  1187. }
  1188. if (files >= maxfiles) {
  1189. size_t mlen;
  1190. maxfiles = (maxfiles + 1) * 2;
  1191. mlen = maxfiles * sizeof(*filearr);
  1192. if ((filearr = CAST(char **,
  1193. erealloc(filearr, mlen))) == NULL) {
  1194. file_oomem(ms, mlen);
  1195. php_stream_closedir(dir);
  1196. errs++;
  1197. goto out;
  1198. }
  1199. }
  1200. filearr[files++] = estrndup(mfn, (mflen > sizeof(mfn) - 1)? sizeof(mfn) - 1: mflen);
  1201. }
  1202. php_stream_closedir(dir);
  1203. qsort(filearr, files, sizeof(*filearr), cmpstrp);
  1204. for (i = 0; i < files; i++) {
  1205. load_1(ms, action, filearr[i], &errs, mset);
  1206. efree(filearr[i]);
  1207. }
  1208. efree(filearr);
  1209. } else
  1210. load_1(ms, action, fn, &errs, mset);
  1211. if (errs)
  1212. goto out;
  1213. for (j = 0; j < MAGIC_SETS; j++) {
  1214. /* Set types of tests */
  1215. for (i = 0; i < mset[j].count; ) {
  1216. if (mset[j].me[i].mp->cont_level != 0) {
  1217. i++;
  1218. continue;
  1219. }
  1220. i = set_text_binary(ms, mset[j].me, mset[j].count, i);
  1221. }
  1222. if (mset[j].me)
  1223. qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),
  1224. apprentice_sort);
  1225. /*
  1226. * Make sure that any level 0 "default" line is last
  1227. * (if one exists).
  1228. */
  1229. set_last_default(ms, mset[j].me, mset[j].count);
  1230. /* coalesce per file arrays into a single one */
  1231. if (coalesce_entries(ms, mset[j].me, mset[j].count,
  1232. &map->magic[j], &map->nmagic[j]) == -1) {
  1233. errs++;
  1234. goto out;
  1235. }
  1236. }
  1237. out:
  1238. for (j = 0; j < MAGIC_SETS; j++)
  1239. magic_entry_free(mset[j].me, mset[j].count);
  1240. if (errs) {
  1241. apprentice_unmap(map);
  1242. return NULL;
  1243. }
  1244. return map;
  1245. }
  1246. /*
  1247. * extend the sign bit if the comparison is to be signed
  1248. */
  1249. protected uint64_t
  1250. file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
  1251. {
  1252. if (!(m->flag & UNSIGNED)) {
  1253. switch(m->type) {
  1254. /*
  1255. * Do not remove the casts below. They are
  1256. * vital. When later compared with the data,
  1257. * the sign extension must have happened.
  1258. */
  1259. case FILE_BYTE:
  1260. v = (signed char) v;
  1261. break;
  1262. case FILE_SHORT:
  1263. case FILE_BESHORT:
  1264. case FILE_LESHORT:
  1265. v = (short) v;
  1266. break;
  1267. case FILE_DATE:
  1268. case FILE_BEDATE:
  1269. case FILE_LEDATE:
  1270. case FILE_MEDATE:
  1271. case FILE_LDATE:
  1272. case FILE_BELDATE:
  1273. case FILE_LELDATE:
  1274. case FILE_MELDATE:
  1275. case FILE_LONG:
  1276. case FILE_BELONG:
  1277. case FILE_LELONG:
  1278. case FILE_MELONG:
  1279. case FILE_FLOAT:
  1280. case FILE_BEFLOAT:
  1281. case FILE_LEFLOAT:
  1282. v = (int32_t) v;
  1283. break;
  1284. case FILE_QUAD:
  1285. case FILE_BEQUAD:
  1286. case FILE_LEQUAD:
  1287. case FILE_QDATE:
  1288. case FILE_QLDATE:
  1289. case FILE_QWDATE:
  1290. case FILE_BEQDATE:
  1291. case FILE_BEQLDATE:
  1292. case FILE_BEQWDATE:
  1293. case FILE_LEQDATE:
  1294. case FILE_LEQLDATE:
  1295. case FILE_LEQWDATE:
  1296. case FILE_DOUBLE:
  1297. case FILE_BEDOUBLE:
  1298. case FILE_LEDOUBLE:
  1299. v = (int64_t) v;
  1300. break;
  1301. case FILE_STRING:
  1302. case FILE_PSTRING:
  1303. case FILE_BESTRING16:
  1304. case FILE_LESTRING16:
  1305. case FILE_REGEX:
  1306. case FILE_SEARCH:
  1307. case FILE_DEFAULT:
  1308. case FILE_INDIRECT:
  1309. case FILE_NAME:
  1310. case FILE_USE:
  1311. case FILE_CLEAR:
  1312. case FILE_DER:
  1313. break;
  1314. default:
  1315. if (ms->flags & MAGIC_CHECK)
  1316. file_magwarn(ms, "cannot happen: m->type=%d\n",
  1317. m->type);
  1318. return ~0U;
  1319. }
  1320. }
  1321. return v;
  1322. }
  1323. private int
  1324. string_modifier_check(struct magic_set *ms, struct magic *m)
  1325. {
  1326. if ((ms->flags & MAGIC_CHECK) == 0)
  1327. return 0;
  1328. if ((m->type != FILE_REGEX || (m->str_flags & REGEX_LINE_COUNT) == 0) &&
  1329. (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0)) {
  1330. file_magwarn(ms,
  1331. "'/BHhLl' modifiers are only allowed for pascal strings\n");
  1332. return -1;
  1333. }
  1334. switch (m->type) {
  1335. case FILE_BESTRING16:
  1336. case FILE_LESTRING16:
  1337. if (m->str_flags != 0) {
  1338. file_magwarn(ms,
  1339. "no modifiers allowed for 16-bit strings\n");
  1340. return -1;
  1341. }
  1342. break;
  1343. case FILE_STRING:
  1344. case FILE_PSTRING:
  1345. if ((m->str_flags & REGEX_OFFSET_START) != 0) {
  1346. file_magwarn(ms,
  1347. "'/%c' only allowed on regex and search\n",
  1348. CHAR_REGEX_OFFSET_START);
  1349. return -1;
  1350. }
  1351. break;
  1352. case FILE_SEARCH:
  1353. if (m->str_range == 0) {
  1354. file_magwarn(ms,
  1355. "missing range; defaulting to %d\n",
  1356. STRING_DEFAULT_RANGE);
  1357. m->str_range = STRING_DEFAULT_RANGE;
  1358. return -1;
  1359. }
  1360. break;
  1361. case FILE_REGEX:
  1362. if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
  1363. file_magwarn(ms, "'/%c' not allowed on regex\n",
  1364. CHAR_COMPACT_WHITESPACE);
  1365. return -1;
  1366. }
  1367. if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
  1368. file_magwarn(ms, "'/%c' not allowed on regex\n",
  1369. CHAR_COMPACT_OPTIONAL_WHITESPACE);
  1370. return -1;
  1371. }
  1372. break;
  1373. default:
  1374. file_magwarn(ms, "coding error: m->type=%d\n",
  1375. m->type);
  1376. return -1;
  1377. }
  1378. return 0;
  1379. }
  1380. private int
  1381. get_op(char c)
  1382. {
  1383. switch (c) {
  1384. case '&':
  1385. return FILE_OPAND;
  1386. case '|':
  1387. return FILE_OPOR;
  1388. case '^':
  1389. return FILE_OPXOR;
  1390. case '+':
  1391. return FILE_OPADD;
  1392. case '-':
  1393. return FILE_OPMINUS;
  1394. case '*':
  1395. return FILE_OPMULTIPLY;
  1396. case '/':
  1397. return FILE_OPDIVIDE;
  1398. case '%':
  1399. return FILE_OPMODULO;
  1400. default:
  1401. return -1;
  1402. }
  1403. }
  1404. #ifdef ENABLE_CONDITIONALS
  1405. private int
  1406. get_cond(const char *l, const char **t)
  1407. {
  1408. static const struct cond_tbl_s {
  1409. char name[8];
  1410. size_t len;
  1411. int cond;
  1412. } cond_tbl[] = {
  1413. { "if", 2, COND_IF },
  1414. { "elif", 4, COND_ELIF },
  1415. { "else", 4, COND_ELSE },
  1416. { "", 0, COND_NONE },
  1417. };
  1418. const struct cond_tbl_s *p;
  1419. for (p = cond_tbl; p->len; p++) {
  1420. if (strncmp(l, p->name, p->len) == 0 &&
  1421. isspace((unsigned char)l[p->len])) {
  1422. if (t)
  1423. *t = l + p->len;
  1424. break;
  1425. }
  1426. }
  1427. return p->cond;
  1428. }
  1429. private int
  1430. check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
  1431. {
  1432. int last_cond;
  1433. last_cond = ms->c.li[cont_level].last_cond;
  1434. switch (cond) {
  1435. case COND_IF:
  1436. if (last_cond != COND_NONE && last_cond != COND_ELIF) {
  1437. if (ms->flags & MAGIC_CHECK)
  1438. file_magwarn(ms, "syntax error: `if'");
  1439. return -1;
  1440. }
  1441. last_cond = COND_IF;
  1442. break;
  1443. case COND_ELIF:
  1444. if (last_cond != COND_IF && last_cond != COND_ELIF) {
  1445. if (ms->flags & MAGIC_CHECK)
  1446. file_magwarn(ms, "syntax error: `elif'");
  1447. return -1;
  1448. }
  1449. last_cond = COND_ELIF;
  1450. break;
  1451. case COND_ELSE:
  1452. if (last_cond != COND_IF && last_cond != COND_ELIF) {
  1453. if (ms->flags & MAGIC_CHECK)
  1454. file_magwarn(ms, "syntax error: `else'");
  1455. return -1;
  1456. }
  1457. last_cond = COND_NONE;
  1458. break;
  1459. case COND_NONE:
  1460. last_cond = COND_NONE;
  1461. break;
  1462. }
  1463. ms->c.li[cont_level].last_cond = last_cond;
  1464. return 0;
  1465. }
  1466. #endif /* ENABLE_CONDITIONALS */
  1467. private int
  1468. parse_indirect_modifier(struct magic_set *ms, struct magic *m, const char **lp)
  1469. {
  1470. const char *l = *lp;
  1471. while (!isspace((unsigned char)*++l))
  1472. switch (*l) {
  1473. case CHAR_INDIRECT_RELATIVE:
  1474. m->str_flags |= INDIRECT_RELATIVE;
  1475. break;
  1476. default:
  1477. if (ms->flags & MAGIC_CHECK)
  1478. file_magwarn(ms, "indirect modifier `%c' "
  1479. "invalid", *l);
  1480. *lp = l;
  1481. return -1;
  1482. }
  1483. *lp = l;
  1484. return 0;
  1485. }
  1486. private void
  1487. parse_op_modifier(struct magic_set *ms, struct magic *m, const char **lp,
  1488. int op)
  1489. {
  1490. const char *l = *lp;
  1491. char *t;
  1492. uint64_t val;
  1493. ++l;
  1494. m->mask_op |= op;
  1495. val = (uint64_t)strtoull(l, &t, 0);
  1496. l = t;
  1497. m->num_mask = file_signextend(ms, m, val);
  1498. eatsize(&l);
  1499. *lp = l;
  1500. }
  1501. private int
  1502. parse_string_modifier(struct magic_set *ms, struct magic *m, const char **lp)
  1503. {
  1504. const char *l = *lp;
  1505. char *t;
  1506. int have_range = 0;
  1507. while (!isspace((unsigned char)*++l)) {
  1508. switch (*l) {
  1509. case '0': case '1': case '2':
  1510. case '3': case '4': case '5':
  1511. case '6': case '7': case '8':
  1512. case '9':
  1513. if (have_range && (ms->flags & MAGIC_CHECK))
  1514. file_magwarn(ms, "multiple ranges");
  1515. have_range = 1;
  1516. m->str_range = CAST(uint32_t, strtoul(l, &t, 0));
  1517. if (m->str_range == 0)
  1518. file_magwarn(ms, "zero range");
  1519. l = t - 1;
  1520. break;
  1521. case CHAR_COMPACT_WHITESPACE:
  1522. m->str_flags |= STRING_COMPACT_WHITESPACE;
  1523. break;
  1524. case CHAR_COMPACT_OPTIONAL_WHITESPACE:
  1525. m->str_flags |= STRING_COMPACT_OPTIONAL_WHITESPACE;
  1526. break;
  1527. case CHAR_IGNORE_LOWERCASE:
  1528. m->str_flags |= STRING_IGNORE_LOWERCASE;
  1529. break;
  1530. case CHAR_IGNORE_UPPERCASE:
  1531. m->str_flags |= STRING_IGNORE_UPPERCASE;
  1532. break;
  1533. case CHAR_REGEX_OFFSET_START:
  1534. m->str_flags |= REGEX_OFFSET_START;
  1535. break;
  1536. case CHAR_BINTEST:
  1537. m->str_flags |= STRING_BINTEST;
  1538. break;
  1539. case CHAR_TEXTTEST:
  1540. m->str_flags |= STRING_TEXTTEST;
  1541. break;
  1542. case CHAR_TRIM:
  1543. m->str_flags |= STRING_TRIM;
  1544. break;
  1545. case CHAR_PSTRING_1_LE:
  1546. #define SET_LENGTH(a) m->str_flags = (m->str_flags & ~PSTRING_LEN) | (a)
  1547. if (m->type != FILE_PSTRING)
  1548. goto bad;
  1549. SET_LENGTH(PSTRING_1_LE);
  1550. break;
  1551. case CHAR_PSTRING_2_BE:
  1552. if (m->type != FILE_PSTRING)
  1553. goto bad;
  1554. SET_LENGTH(PSTRING_2_BE);
  1555. break;
  1556. case CHAR_PSTRING_2_LE:
  1557. if (m->type != FILE_PSTRING)
  1558. goto bad;
  1559. SET_LENGTH(PSTRING_2_LE);
  1560. break;
  1561. case CHAR_PSTRING_4_BE:
  1562. if (m->type != FILE_PSTRING)
  1563. goto bad;
  1564. SET_LENGTH(PSTRING_4_BE);
  1565. break;
  1566. case CHAR_PSTRING_4_LE:
  1567. switch (m->type) {
  1568. case FILE_PSTRING:
  1569. case FILE_REGEX:
  1570. break;
  1571. default:
  1572. goto bad;
  1573. }
  1574. SET_LENGTH(PSTRING_4_LE);
  1575. break;
  1576. case CHAR_PSTRING_LENGTH_INCLUDES_ITSELF:
  1577. if (m->type != FILE_PSTRING)
  1578. goto bad;
  1579. m->str_flags |= PSTRING_LENGTH_INCLUDES_ITSELF;
  1580. break;
  1581. default:
  1582. bad:
  1583. if (ms->flags & MAGIC_CHECK)
  1584. file_magwarn(ms, "string modifier `%c' "
  1585. "invalid", *l);
  1586. goto out;
  1587. }
  1588. /* allow multiple '/' for readability */
  1589. if (l[1] == '/' && !isspace((unsigned char)l[2]))
  1590. l++;
  1591. }
  1592. if (string_modifier_check(ms, m) == -1)
  1593. goto out;
  1594. *lp = l;
  1595. return 0;
  1596. out:
  1597. *lp = l;
  1598. return -1;
  1599. }
  1600. /*
  1601. * parse one line from magic file, put into magic[index++] if valid
  1602. */
  1603. private int
  1604. parse(struct magic_set *ms, struct magic_entry *me, const char *line,
  1605. size_t lineno, int action)
  1606. {
  1607. #ifdef ENABLE_CONDITIONALS
  1608. static uint32_t last_cont_level = 0;
  1609. #endif
  1610. size_t i;
  1611. struct magic *m;
  1612. const char *l = line;
  1613. char *t;
  1614. int op;
  1615. uint32_t cont_level;
  1616. int32_t diff;
  1617. cont_level = 0;
  1618. /*
  1619. * Parse the offset.
  1620. */
  1621. while (*l == '>') {
  1622. ++l; /* step over */
  1623. cont_level++;
  1624. }
  1625. #ifdef ENABLE_CONDITIONALS
  1626. if (cont_level == 0 || cont_level > last_cont_level)
  1627. if (file_check_mem(ms, cont_level) == -1)
  1628. return -1;
  1629. last_cont_level = cont_level;
  1630. #endif
  1631. if (cont_level != 0) {
  1632. if (me->mp == NULL) {
  1633. file_magerror(ms, "No current entry for continuation");
  1634. return -1;
  1635. }
  1636. if (me->cont_count == 0) {
  1637. file_magerror(ms, "Continuations present with 0 count");
  1638. return -1;
  1639. }
  1640. m = &me->mp[me->cont_count - 1];
  1641. diff = (int32_t)cont_level - (int32_t)m->cont_level;
  1642. if (diff > 1)
  1643. file_magwarn(ms, "New continuation level %u is more "
  1644. "than one larger than current level %u", cont_level,
  1645. m->cont_level);
  1646. if (me->cont_count == me->max_count) {
  1647. struct magic *nm;
  1648. size_t cnt = me->max_count + ALLOC_CHUNK;
  1649. if ((nm = CAST(struct magic *, erealloc(me->mp,
  1650. sizeof(*nm) * cnt))) == NULL) {
  1651. file_oomem(ms, sizeof(*nm) * cnt);
  1652. return -1;
  1653. }
  1654. me->mp = m = nm;
  1655. me->max_count = CAST(uint32_t, cnt);
  1656. }
  1657. m = &me->mp[me->cont_count++];
  1658. (void)memset(m, 0, sizeof(*m));
  1659. m->cont_level = cont_level;
  1660. } else {
  1661. static const size_t len = sizeof(*m) * ALLOC_CHUNK;
  1662. if (me->mp != NULL)
  1663. return 1;
  1664. if ((m = CAST(struct magic *, emalloc(len))) == NULL) {
  1665. file_oomem(ms, len);
  1666. return -1;
  1667. }
  1668. me->mp = m;
  1669. me->max_count = ALLOC_CHUNK;
  1670. (void)memset(m, 0, sizeof(*m));
  1671. m->factor_op = FILE_FACTOR_OP_NONE;
  1672. m->cont_level = 0;
  1673. me->cont_count = 1;
  1674. }
  1675. m->lineno = CAST(uint32_t, lineno);
  1676. if (*l == '&') { /* m->cont_level == 0 checked below. */
  1677. ++l; /* step over */
  1678. m->flag |= OFFADD;
  1679. }
  1680. if (*l == '(') {
  1681. ++l; /* step over */
  1682. m->flag |= INDIR;
  1683. if (m->flag & OFFADD)
  1684. m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
  1685. if (*l == '&') { /* m->cont_level == 0 checked below */
  1686. ++l; /* step over */
  1687. m->flag |= OFFADD;
  1688. }
  1689. }
  1690. /* Indirect offsets are not valid at level 0. */
  1691. if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD))) {
  1692. if (ms->flags & MAGIC_CHECK)
  1693. file_magwarn(ms, "relative offset at level 0");
  1694. return -1;
  1695. }
  1696. /* get offset, then skip over it */
  1697. m->offset = (int32_t)strtol(l, &t, 0);
  1698. if (l == t) {
  1699. if (ms->flags & MAGIC_CHECK)
  1700. file_magwarn(ms, "offset `%s' invalid", l);
  1701. return -1;
  1702. }
  1703. l = t;
  1704. if (m->flag & INDIR) {
  1705. m->in_type = FILE_LONG;
  1706. m->in_offset = 0;
  1707. m->in_op = 0;
  1708. /*
  1709. * read [.,lbs][+-]nnnnn)
  1710. */
  1711. if (*l == '.' || *l == ',') {
  1712. if (*l == ',')
  1713. m->in_op |= FILE_OPSIGNED;
  1714. l++;
  1715. switch (*l) {
  1716. case 'l':
  1717. m->in_type = FILE_LELONG;
  1718. break;
  1719. case 'L':
  1720. m->in_type = FILE_BELONG;
  1721. break;
  1722. case 'm':
  1723. m->in_type = FILE_MELONG;
  1724. break;
  1725. case 'h':
  1726. case 's':
  1727. m->in_type = FILE_LESHORT;
  1728. break;
  1729. case 'H':
  1730. case 'S':
  1731. m->in_type = FILE_BESHORT;
  1732. break;
  1733. case 'c':
  1734. case 'b':
  1735. case 'C':
  1736. case 'B':
  1737. m->in_type = FILE_BYTE;
  1738. break;
  1739. case 'e':
  1740. case 'f':
  1741. case 'g':
  1742. m->in_type = FILE_LEDOUBLE;
  1743. break;
  1744. case 'E':
  1745. case 'F':
  1746. case 'G':
  1747. m->in_type = FILE_BEDOUBLE;
  1748. break;
  1749. case 'i':
  1750. m->in_type = FILE_LEID3;
  1751. break;
  1752. case 'I':
  1753. m->in_type = FILE_BEID3;
  1754. break;
  1755. default:
  1756. if (ms->flags & MAGIC_CHECK)
  1757. file_magwarn(ms,
  1758. "indirect offset type `%c' invalid",
  1759. *l);
  1760. return -1;
  1761. }
  1762. l++;
  1763. }
  1764. if (*l == '~') {
  1765. m->in_op |= FILE_OPINVERSE;
  1766. l++;
  1767. }
  1768. if ((op = get_op(*l)) != -1) {
  1769. m->in_op |= op;
  1770. l++;
  1771. }
  1772. if (*l == '(') {
  1773. m->in_op |= FILE_OPINDIRECT;
  1774. l++;
  1775. }
  1776. if (isdigit((unsigned char)*l) || *l == '-') {
  1777. m->in_offset = (int32_t)strtol(l, &t, 0);
  1778. if (l == t) {
  1779. if (ms->flags & MAGIC_CHECK)
  1780. file_magwarn(ms,
  1781. "in_offset `%s' invalid", l);
  1782. return -1;
  1783. }
  1784. l = t;
  1785. }
  1786. if (*l++ != ')' ||
  1787. ((m->in_op & FILE_OPINDIRECT) && *l++ != ')')) {
  1788. if (ms->flags & MAGIC_CHECK)
  1789. file_magwarn(ms,
  1790. "missing ')' in indirect offset");
  1791. return -1;
  1792. }
  1793. }
  1794. EATAB;
  1795. #ifdef ENABLE_CONDITIONALS
  1796. m->cond = get_cond(l, &l);
  1797. if (check_cond(ms, m->cond, cont_level) == -1)
  1798. return -1;
  1799. EATAB;
  1800. #endif
  1801. /*
  1802. * Parse the type.
  1803. */
  1804. if (*l == 'u') {
  1805. /*
  1806. * Try it as a keyword type prefixed by "u"; match what
  1807. * follows the "u". If that fails, try it as an SUS
  1808. * integer type.
  1809. */
  1810. m->type = get_type(type_tbl, l + 1, &l);
  1811. if (m->type == FILE_INVALID) {
  1812. /*
  1813. * Not a keyword type; parse it as an SUS type,
  1814. * 'u' possibly followed by a number or C/S/L.
  1815. */
  1816. m->type = get_standard_integer_type(l, &l);
  1817. }
  1818. /* It's unsigned. */
  1819. if (m->type != FILE_INVALID)
  1820. m->flag |= UNSIGNED;
  1821. } else {
  1822. /*
  1823. * Try it as a keyword type. If that fails, try it as
  1824. * an SUS integer type if it begins with "d" or as an
  1825. * SUS string type if it begins with "s". In any case,
  1826. * it's not unsigned.
  1827. */
  1828. m->type = get_type(type_tbl, l, &l);
  1829. if (m->type == FILE_INVALID) {
  1830. /*
  1831. * Not a keyword type; parse it as an SUS type,
  1832. * either 'd' possibly followed by a number or
  1833. * C/S/L, or just 's'.
  1834. */
  1835. if (*l == 'd')
  1836. m->type = get_standard_integer_type(l, &l);
  1837. else if (*l == 's' && !isalpha((unsigned char)l[1])) {
  1838. m->type = FILE_STRING;
  1839. ++l;
  1840. }
  1841. }
  1842. }
  1843. if (m->type == FILE_INVALID) {
  1844. /* Not found - try it as a special keyword. */
  1845. m->type = get_type(special_tbl, l, &l);
  1846. }
  1847. if (m->type == FILE_INVALID) {
  1848. if (ms->flags & MAGIC_CHECK)
  1849. file_magwarn(ms, "type `%s' invalid", l);
  1850. return -1;
  1851. }
  1852. /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
  1853. /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
  1854. m->mask_op = 0;
  1855. if (*l == '~') {
  1856. if (!IS_LIBMAGIC_STRING(m->type))
  1857. m->mask_op |= FILE_OPINVERSE;
  1858. else if (ms->flags & MAGIC_CHECK)
  1859. file_magwarn(ms, "'~' invalid for string types");
  1860. ++l;
  1861. }
  1862. m->str_range = 0;
  1863. m->str_flags = m->type == FILE_PSTRING ? PSTRING_1_LE : 0;
  1864. if ((op = get_op(*l)) != -1) {
  1865. if (IS_LIBMAGIC_STRING(m->type)) {
  1866. int r;
  1867. if (op != FILE_OPDIVIDE) {
  1868. if (ms->flags & MAGIC_CHECK)
  1869. file_magwarn(ms,
  1870. "invalid string/indirect op: "
  1871. "`%c'", *t);
  1872. return -1;
  1873. }
  1874. if (m->type == FILE_INDIRECT)
  1875. r = parse_indirect_modifier(ms, m, &l);
  1876. else
  1877. r = parse_string_modifier(ms, m, &l);
  1878. if (r == -1)
  1879. return -1;
  1880. } else
  1881. parse_op_modifier(ms, m, &l, op);
  1882. }
  1883. /*
  1884. * We used to set mask to all 1's here, instead let's just not do
  1885. * anything if mask = 0 (unless you have a better idea)
  1886. */
  1887. EATAB;
  1888. switch (*l) {
  1889. case '>':
  1890. case '<':
  1891. m->reln = *l;
  1892. ++l;
  1893. if (*l == '=') {
  1894. if (ms->flags & MAGIC_CHECK) {
  1895. file_magwarn(ms, "%c= not supported",
  1896. m->reln);
  1897. return -1;
  1898. }
  1899. ++l;
  1900. }
  1901. break;
  1902. /* Old-style anding: "0 byte &0x80 dynamically linked" */
  1903. case '&':
  1904. case '^':
  1905. case '=':
  1906. m->reln = *l;
  1907. ++l;
  1908. if (*l == '=') {
  1909. /* HP compat: ignore &= etc. */
  1910. ++l;
  1911. }
  1912. break;
  1913. case '!':
  1914. m->reln = *l;
  1915. ++l;
  1916. break;
  1917. default:
  1918. m->reln = '='; /* the default relation */
  1919. if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
  1920. isspace((unsigned char)l[1])) || !l[1])) {
  1921. m->reln = *l;
  1922. ++l;
  1923. }
  1924. break;
  1925. }
  1926. /*
  1927. * Grab the value part, except for an 'x' reln.
  1928. */
  1929. if (m->reln != 'x' && getvalue(ms, m, &l, action))
  1930. return -1;
  1931. /*
  1932. * TODO finish this macro and start using it!
  1933. * #define offsetcheck {if (offset > ms->bytes_max -1)
  1934. * magwarn("offset too big"); }
  1935. */
  1936. /*
  1937. * Now get last part - the description
  1938. */
  1939. EATAB;
  1940. if (l[0] == '\b') {
  1941. ++l;
  1942. m->flag |= NOSPACE;
  1943. } else if ((l[0] == '\\') && (l[1] == 'b')) {
  1944. ++l;
  1945. ++l;
  1946. m->flag |= NOSPACE;
  1947. }
  1948. for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
  1949. continue;
  1950. if (i == sizeof(m->desc)) {
  1951. m->desc[sizeof(m->desc) - 1] = '\0';
  1952. if (ms->flags & MAGIC_CHECK)
  1953. file_magwarn(ms, "description `%s' truncated", m->desc);
  1954. }
  1955. /*
  1956. * We only do this check while compiling, or if any of the magic
  1957. * files were not compiled.
  1958. */
  1959. if (ms->flags & MAGIC_CHECK) {
  1960. if (check_format(ms, m) == -1)
  1961. return -1;
  1962. }
  1963. m->mimetype[0] = '\0'; /* initialise MIME type to none */
  1964. return 0;
  1965. }
  1966. /*
  1967. * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
  1968. * if valid
  1969. */
  1970. private int
  1971. parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line)
  1972. {
  1973. const char *l = line;
  1974. char *el;
  1975. unsigned long factor;
  1976. struct magic *m = &me->mp[0];
  1977. if (m->factor_op != FILE_FACTOR_OP_NONE) {
  1978. file_magwarn(ms,
  1979. "Current entry already has a strength type: %c %d",
  1980. m->factor_op, m->factor);
  1981. return -1;
  1982. }
  1983. if (m->type == FILE_NAME) {
  1984. file_magwarn(ms, "%s: Strength setting is not supported in "
  1985. "\"name\" magic entries", m->value.s);
  1986. return -1;
  1987. }
  1988. EATAB;
  1989. switch (*l) {
  1990. case FILE_FACTOR_OP_NONE:
  1991. case FILE_FACTOR_OP_PLUS:
  1992. case FILE_FACTOR_OP_MINUS:
  1993. case FILE_FACTOR_OP_TIMES:
  1994. case FILE_FACTOR_OP_DIV:
  1995. m->factor_op = *l++;
  1996. break;
  1997. default:
  1998. file_magwarn(ms, "Unknown factor op `%c'", *l);
  1999. return -1;
  2000. }
  2001. EATAB;
  2002. factor = strtoul(l, &el, 0);
  2003. if (factor > 255) {
  2004. file_magwarn(ms, "Too large factor `%lu'", factor);
  2005. goto out;
  2006. }
  2007. if (*el && !isspace((unsigned char)*el)) {
  2008. file_magwarn(ms, "Bad factor `%s'", l);
  2009. goto out;
  2010. }
  2011. m->factor = (uint8_t)factor;
  2012. if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) {
  2013. file_magwarn(ms, "Cannot have factor op `%c' and factor %u",
  2014. m->factor_op, m->factor);
  2015. goto out;
  2016. }
  2017. return 0;
  2018. out:
  2019. m->factor_op = FILE_FACTOR_OP_NONE;
  2020. m->factor = 0;
  2021. return -1;
  2022. }
  2023. private int
  2024. goodchar(unsigned char x, const char *extra)
  2025. {
  2026. return (isascii(x) && isalnum(x)) || strchr(extra, x);
  2027. }
  2028. private int
  2029. parse_extra(struct magic_set *ms, struct magic_entry *me, const char *line,
  2030. zend_off_t off, size_t len, const char *name, const char *extra, int nt)
  2031. {
  2032. size_t i;
  2033. const char *l = line;
  2034. struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
  2035. char *buf = CAST(char *, CAST(void *, m)) + off;
  2036. if (buf[0] != '\0') {
  2037. len = nt ? strlen(buf) : len;
  2038. file_magwarn(ms, "Current entry already has a %s type "
  2039. "`%.*s', new type `%s'", name, (int)len, buf, l);
  2040. return -1;
  2041. }
  2042. if (*m->desc == '\0') {
  2043. file_magwarn(ms, "Current entry does not yet have a "
  2044. "description for adding a %s type", name);
  2045. return -1;
  2046. }
  2047. EATAB;
  2048. for (i = 0; *l && i < len && goodchar(*l, extra); buf[i++] = *l++)
  2049. continue;
  2050. if (i == len && *l) {
  2051. if (nt)
  2052. buf[len - 1] = '\0';
  2053. if (ms->flags & MAGIC_CHECK)
  2054. file_magwarn(ms, "%s type `%s' truncated %"
  2055. SIZE_T_FORMAT "u", name, line, i);
  2056. } else {
  2057. if (!isspace((unsigned char)*l) && !goodchar(*l, extra))
  2058. file_magwarn(ms, "%s type `%s' has bad char '%c'",
  2059. name, line, *l);
  2060. if (nt)
  2061. buf[i] = '\0';
  2062. }
  2063. if (i > 0)
  2064. return 0;
  2065. file_magerror(ms, "Bad magic entry '%s'", line);
  2066. return -1;
  2067. }
  2068. /*
  2069. * Parse an Apple CREATOR/TYPE annotation from magic file and put it into
  2070. * magic[index - 1]
  2071. */
  2072. private int
  2073. parse_apple(struct magic_set *ms, struct magic_entry *me, const char *line)
  2074. {
  2075. struct magic *m = &me->mp[0];
  2076. return parse_extra(ms, me, line,
  2077. CAST(off_t, offsetof(struct magic, apple)),
  2078. sizeof(m->apple), "APPLE", "!+-./?", 0);
  2079. }
  2080. /*
  2081. * Parse a comma-separated list of extensions
  2082. */
  2083. private int
  2084. parse_ext(struct magic_set *ms, struct magic_entry *me, const char *line)
  2085. {
  2086. struct magic *m = &me->mp[0];
  2087. return parse_extra(ms, me, line,
  2088. CAST(off_t, offsetof(struct magic, ext)),
  2089. sizeof(m->ext), "EXTENSION", ",!+-/@?_$", 0);
  2090. }
  2091. /*
  2092. * parse a MIME annotation line from magic file, put into magic[index - 1]
  2093. * if valid
  2094. */
  2095. private int
  2096. parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line)
  2097. {
  2098. struct magic *m = &me->mp[0];
  2099. return parse_extra(ms, me, line,
  2100. CAST(zend_off_t, offsetof(struct magic, mimetype)),
  2101. sizeof(m->mimetype), "MIME", "+-/.$?:{}", 1);
  2102. }
  2103. private int
  2104. check_format_type(const char *ptr, int type, const char **estr)
  2105. {
  2106. int quad = 0, h;
  2107. size_t len, cnt;
  2108. if (*ptr == '\0') {
  2109. /* Missing format string; bad */
  2110. *estr = "missing format spec";
  2111. return -1;
  2112. }
  2113. switch (file_formats[type]) {
  2114. case FILE_FMT_QUAD:
  2115. quad = 1;
  2116. /*FALLTHROUGH*/
  2117. case FILE_FMT_NUM:
  2118. if (quad == 0) {
  2119. switch (type) {
  2120. case FILE_BYTE:
  2121. h = 2;
  2122. break;
  2123. case FILE_SHORT:
  2124. case FILE_BESHORT:
  2125. case FILE_LESHORT:
  2126. h = 1;
  2127. break;
  2128. case FILE_LONG:
  2129. case FILE_BELONG:
  2130. case FILE_LELONG:
  2131. case FILE_MELONG:
  2132. case FILE_LEID3:
  2133. case FILE_BEID3:
  2134. case FILE_INDIRECT:
  2135. h = 0;
  2136. break;
  2137. default:
  2138. abort();
  2139. }
  2140. } else
  2141. h = 0;
  2142. if (*ptr == '-')
  2143. ptr++;
  2144. if (*ptr == '.')
  2145. ptr++;
  2146. if (*ptr == '#')
  2147. ptr++;
  2148. #define CHECKLEN() do { \
  2149. for (len = cnt = 0; isdigit((unsigned char)*ptr); ptr++, cnt++) \
  2150. len = len * 10 + (*ptr - '0'); \
  2151. if (cnt > 5 || len > 1024) \
  2152. goto toolong; \
  2153. } while (/*CONSTCOND*/0)
  2154. CHECKLEN();
  2155. if (*ptr == '.')
  2156. ptr++;
  2157. CHECKLEN();
  2158. if (quad) {
  2159. if (*ptr++ != 'l')
  2160. goto invalid;
  2161. if (*ptr++ != 'l')
  2162. goto invalid;
  2163. }
  2164. switch (*ptr++) {
  2165. #ifdef STRICT_FORMAT /* "long" formats are int formats for us */
  2166. /* so don't accept the 'l' modifier */
  2167. case 'l':
  2168. switch (*ptr++) {
  2169. case 'i':
  2170. case 'd':
  2171. case 'u':
  2172. case 'o':
  2173. case 'x':
  2174. case 'X':
  2175. if (h == 0)
  2176. return 0;
  2177. /*FALLTHROUGH*/
  2178. default:
  2179. goto invalid;
  2180. }
  2181. /*
  2182. * Don't accept h and hh modifiers. They make writing
  2183. * magic entries more complicated, for very little benefit
  2184. */
  2185. case 'h':
  2186. if (h-- <= 0)
  2187. goto invalid;
  2188. switch (*ptr++) {
  2189. case 'h':
  2190. if (h-- <= 0)
  2191. goto invalid;
  2192. switch (*ptr++) {
  2193. case 'i':
  2194. case 'd':
  2195. case 'u':
  2196. case 'o':
  2197. case 'x':
  2198. case 'X':
  2199. return 0;
  2200. default:
  2201. goto invalid;
  2202. }
  2203. case 'i':
  2204. case 'd':
  2205. case 'u':
  2206. case 'o':
  2207. case 'x':
  2208. case 'X':
  2209. if (h == 0)
  2210. return 0;
  2211. /*FALLTHROUGH*/
  2212. default:
  2213. goto invalid;
  2214. }
  2215. #endif
  2216. case 'c':
  2217. if (h == 2)
  2218. return 0;
  2219. goto invalid;
  2220. case 'i':
  2221. case 'd':
  2222. case 'u':
  2223. case 'o':
  2224. case 'x':
  2225. case 'X':
  2226. #ifdef STRICT_FORMAT
  2227. if (h == 0)
  2228. return 0;
  2229. /*FALLTHROUGH*/
  2230. #else
  2231. return 0;
  2232. #endif
  2233. default:
  2234. goto invalid;
  2235. }
  2236. case FILE_FMT_FLOAT:
  2237. case FILE_FMT_DOUBLE:
  2238. if (*ptr == '-')
  2239. ptr++;
  2240. if (*ptr == '.')
  2241. ptr++;
  2242. CHECKLEN();
  2243. if (*ptr == '.')
  2244. ptr++;
  2245. CHECKLEN();
  2246. switch (*ptr++) {
  2247. case 'e':
  2248. case 'E':
  2249. case 'f':
  2250. case 'F':
  2251. case 'g':
  2252. case 'G':
  2253. return 0;
  2254. default:
  2255. goto invalid;
  2256. }
  2257. case FILE_FMT_STR:
  2258. if (*ptr == '-')
  2259. ptr++;
  2260. while (isdigit((unsigned char )*ptr))
  2261. ptr++;
  2262. if (*ptr == '.') {
  2263. ptr++;
  2264. while (isdigit((unsigned char )*ptr))
  2265. ptr++;
  2266. }
  2267. switch (*ptr++) {
  2268. case 's':
  2269. return 0;
  2270. default:
  2271. goto invalid;
  2272. }
  2273. default:
  2274. /* internal error */
  2275. abort();
  2276. }
  2277. invalid:
  2278. *estr = "not valid";
  2279. toolong:
  2280. *estr = "too long";
  2281. return -1;
  2282. }
  2283. /*
  2284. * Check that the optional printf format in description matches
  2285. * the type of the magic.
  2286. */
  2287. private int
  2288. check_format(struct magic_set *ms, struct magic *m)
  2289. {
  2290. char *ptr;
  2291. const char *estr;
  2292. for (ptr = m->desc; *ptr; ptr++)
  2293. if (*ptr == '%')
  2294. break;
  2295. if (*ptr == '\0') {
  2296. /* No format string; ok */
  2297. return 1;
  2298. }
  2299. assert(file_nformats == file_nnames);
  2300. if (m->type >= file_nformats) {
  2301. file_magwarn(ms, "Internal error inconsistency between "
  2302. "m->type and format strings");
  2303. return -1;
  2304. }
  2305. if (file_formats[m->type] == FILE_FMT_NONE) {
  2306. file_magwarn(ms, "No format string for `%s' with description "
  2307. "`%s'", m->desc, file_names[m->type]);
  2308. return -1;
  2309. }
  2310. ptr++;
  2311. if (check_format_type(ptr, m->type, &estr) == -1) {
  2312. /*
  2313. * TODO: this error message is unhelpful if the format
  2314. * string is not one character long
  2315. */
  2316. file_magwarn(ms, "Printf format is %s for type "
  2317. "`%s' in description `%s'", estr,
  2318. file_names[m->type], m->desc);
  2319. return -1;
  2320. }
  2321. for (; *ptr; ptr++) {
  2322. if (*ptr == '%') {
  2323. file_magwarn(ms,
  2324. "Too many format strings (should have at most one) "
  2325. "for `%s' with description `%s'",
  2326. file_names[m->type], m->desc);
  2327. return -1;
  2328. }
  2329. }
  2330. return 0;
  2331. }
  2332. /*
  2333. * Read a numeric value from a pointer, into the value union of a magic
  2334. * pointer, according to the magic type. Update the string pointer to point
  2335. * just after the number read. Return 0 for success, non-zero for failure.
  2336. */
  2337. private int
  2338. getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
  2339. {
  2340. char *ep;
  2341. uint64_t ull;
  2342. switch (m->type) {
  2343. case FILE_BESTRING16:
  2344. case FILE_LESTRING16:
  2345. case FILE_STRING:
  2346. case FILE_PSTRING:
  2347. case FILE_REGEX:
  2348. case FILE_SEARCH:
  2349. case FILE_NAME:
  2350. case FILE_USE:
  2351. case FILE_DER:
  2352. *p = getstr(ms, m, *p, action == FILE_COMPILE);
  2353. if (*p == NULL) {
  2354. if (ms->flags & MAGIC_CHECK)
  2355. file_magwarn(ms, "cannot get string from `%s'",
  2356. m->value.s);
  2357. return -1;
  2358. }
  2359. if (m->type == FILE_REGEX) {
  2360. zval pattern;
  2361. int options = 0;
  2362. pcre_cache_entry *pce;
  2363. convert_libmagic_pattern(&pattern, m->value.s, strlen(m->value.s), options);
  2364. if ((pce = pcre_get_compiled_regex_cache(Z_STR(pattern))) == NULL) {
  2365. zval_dtor(&pattern);
  2366. return -1;
  2367. }
  2368. zval_dtor(&pattern);
  2369. return 0;
  2370. }
  2371. return 0;
  2372. default:
  2373. if (m->reln == 'x')
  2374. return 0;
  2375. break;
  2376. }
  2377. switch (m->type) {
  2378. case FILE_FLOAT:
  2379. case FILE_BEFLOAT:
  2380. case FILE_LEFLOAT:
  2381. errno = 0;
  2382. #ifdef HAVE_STRTOF
  2383. m->value.f = strtof(*p, &ep);
  2384. #else
  2385. m->value.f = (float)strtod(*p, &ep);
  2386. #endif
  2387. if (errno == 0)
  2388. *p = ep;
  2389. return 0;
  2390. case FILE_DOUBLE:
  2391. case FILE_BEDOUBLE:
  2392. case FILE_LEDOUBLE:
  2393. errno = 0;
  2394. m->value.d = strtod(*p, &ep);
  2395. if (errno == 0)
  2396. *p = ep;
  2397. return 0;
  2398. default:
  2399. errno = 0;
  2400. ull = (uint64_t)strtoull(*p, &ep, 0);
  2401. m->value.q = file_signextend(ms, m, ull);
  2402. if (*p == ep) {
  2403. file_magwarn(ms, "Unparseable number `%s'", *p);
  2404. } else {
  2405. size_t ts = typesize(m->type);
  2406. uint64_t x;
  2407. const char *q;
  2408. if (ts == (size_t)~0) {
  2409. file_magwarn(ms,
  2410. "Expected numeric type got `%s'",
  2411. type_tbl[m->type].name);
  2412. }
  2413. for (q = *p; isspace((unsigned char)*q); q++)
  2414. continue;
  2415. if (*q == '-')
  2416. ull = -(int64_t)ull;
  2417. switch (ts) {
  2418. case 1:
  2419. x = (uint64_t)(ull & ~0xffULL);
  2420. break;
  2421. case 2:
  2422. x = (uint64_t)(ull & ~0xffffULL);
  2423. break;
  2424. case 4:
  2425. x = (uint64_t)(ull & ~0xffffffffULL);
  2426. break;
  2427. case 8:
  2428. x = 0;
  2429. break;
  2430. default:
  2431. abort();
  2432. }
  2433. if (x) {
  2434. file_magwarn(ms, "Overflow for numeric"
  2435. " type `%s' value %#" PRIx64,
  2436. type_tbl[m->type].name, ull);
  2437. }
  2438. }
  2439. if (errno == 0) {
  2440. *p = ep;
  2441. eatsize(p);
  2442. }
  2443. return 0;
  2444. }
  2445. }
  2446. /*
  2447. * Convert a string containing C character escapes. Stop at an unescaped
  2448. * space or tab.
  2449. * Copy the converted version to "m->value.s", and the length in m->vallen.
  2450. * Return updated scan pointer as function result. Warn if set.
  2451. */
  2452. private const char *
  2453. getstr(struct magic_set *ms, struct magic *m, const char *s, int warn)
  2454. {
  2455. const char *origs = s;
  2456. char *p = m->value.s;
  2457. size_t plen = sizeof(m->value.s);
  2458. char *origp = p;
  2459. char *pmax = p + plen - 1;
  2460. int c;
  2461. int val;
  2462. while ((c = *s++) != '\0') {
  2463. if (isspace((unsigned char) c))
  2464. break;
  2465. if (p >= pmax) {
  2466. file_error(ms, 0, "string too long: `%s'", origs);
  2467. return NULL;
  2468. }
  2469. if (c == '\\') {
  2470. switch(c = *s++) {
  2471. case '\0':
  2472. if (warn)
  2473. file_magwarn(ms, "incomplete escape");
  2474. s--;
  2475. goto out;
  2476. case '\t':
  2477. if (warn) {
  2478. file_magwarn(ms,
  2479. "escaped tab found, use \\t instead");
  2480. warn = 0; /* already did */
  2481. }
  2482. /*FALLTHROUGH*/
  2483. default:
  2484. if (warn) {
  2485. if (isprint((unsigned char)c)) {
  2486. /* Allow escaping of
  2487. * ``relations'' */
  2488. if (strchr("<>&^=!", c) == NULL
  2489. && (m->type != FILE_REGEX ||
  2490. strchr("[]().*?^$|{}", c)
  2491. == NULL)) {
  2492. file_magwarn(ms, "no "
  2493. "need to escape "
  2494. "`%c'", c);
  2495. }
  2496. } else {
  2497. file_magwarn(ms,
  2498. "unknown escape sequence: "
  2499. "\\%03o", c);
  2500. }
  2501. }
  2502. /*FALLTHROUGH*/
  2503. /* space, perhaps force people to use \040? */
  2504. case ' ':
  2505. #if 0
  2506. /*
  2507. * Other things people escape, but shouldn't need to,
  2508. * so we disallow them
  2509. */
  2510. case '\'':
  2511. case '"':
  2512. case '?':
  2513. #endif
  2514. /* Relations */
  2515. case '>':
  2516. case '<':
  2517. case '&':
  2518. case '^':
  2519. case '=':
  2520. case '!':
  2521. /* and baskslash itself */
  2522. case '\\':
  2523. *p++ = (char) c;
  2524. break;
  2525. case 'a':
  2526. *p++ = '\a';
  2527. break;
  2528. case 'b':
  2529. *p++ = '\b';
  2530. break;
  2531. case 'f':
  2532. *p++ = '\f';
  2533. break;
  2534. case 'n':
  2535. *p++ = '\n';
  2536. break;
  2537. case 'r':
  2538. *p++ = '\r';
  2539. break;
  2540. case 't':
  2541. *p++ = '\t';
  2542. break;
  2543. case 'v':
  2544. *p++ = '\v';
  2545. break;
  2546. /* \ and up to 3 octal digits */
  2547. case '0':
  2548. case '1':
  2549. case '2':
  2550. case '3':
  2551. case '4':
  2552. case '5':
  2553. case '6':
  2554. case '7':
  2555. val = c - '0';
  2556. c = *s++; /* try for 2 */
  2557. if (c >= '0' && c <= '7') {
  2558. val = (val << 3) | (c - '0');
  2559. c = *s++; /* try for 3 */
  2560. if (c >= '0' && c <= '7')
  2561. val = (val << 3) | (c-'0');
  2562. else
  2563. --s;
  2564. }
  2565. else
  2566. --s;
  2567. *p++ = (char)val;
  2568. break;
  2569. /* \x and up to 2 hex digits */
  2570. case 'x':
  2571. val = 'x'; /* Default if no digits */
  2572. c = hextoint(*s++); /* Get next char */
  2573. if (c >= 0) {
  2574. val = c;
  2575. c = hextoint(*s++);
  2576. if (c >= 0)
  2577. val = (val << 4) + c;
  2578. else
  2579. --s;
  2580. } else
  2581. --s;
  2582. *p++ = (char)val;
  2583. break;
  2584. }
  2585. } else
  2586. *p++ = (char)c;
  2587. }
  2588. --s;
  2589. out:
  2590. *p = '\0';
  2591. m->vallen = CAST(unsigned char, (p - origp));
  2592. if (m->type == FILE_PSTRING)
  2593. m->vallen += (unsigned char)file_pstring_length_size(m);
  2594. return s;
  2595. }
  2596. /* Single hex char to int; -1 if not a hex char. */
  2597. private int
  2598. hextoint(int c)
  2599. {
  2600. if (!isascii((unsigned char) c))
  2601. return -1;
  2602. if (isdigit((unsigned char) c))
  2603. return c - '0';
  2604. if ((c >= 'a') && (c <= 'f'))
  2605. return c + 10 - 'a';
  2606. if (( c>= 'A') && (c <= 'F'))
  2607. return c + 10 - 'A';
  2608. return -1;
  2609. }
  2610. /*
  2611. * Print a string containing C character escapes.
  2612. */
  2613. protected void
  2614. file_showstr(FILE *fp, const char *s, size_t len)
  2615. {
  2616. char c;
  2617. for (;;) {
  2618. if (len == ~0U) {
  2619. c = *s++;
  2620. if (c == '\0')
  2621. break;
  2622. }
  2623. else {
  2624. if (len-- == 0)
  2625. break;
  2626. c = *s++;
  2627. }
  2628. if (c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */
  2629. (void) fputc(c, fp);
  2630. else {
  2631. (void) fputc('\\', fp);
  2632. switch (c) {
  2633. case '\a':
  2634. (void) fputc('a', fp);
  2635. break;
  2636. case '\b':
  2637. (void) fputc('b', fp);
  2638. break;
  2639. case '\f':
  2640. (void) fputc('f', fp);
  2641. break;
  2642. case '\n':
  2643. (void) fputc('n', fp);
  2644. break;
  2645. case '\r':
  2646. (void) fputc('r', fp);
  2647. break;
  2648. case '\t':
  2649. (void) fputc('t', fp);
  2650. break;
  2651. case '\v':
  2652. (void) fputc('v', fp);
  2653. break;
  2654. default:
  2655. (void) fprintf(fp, "%.3o", c & 0377);
  2656. break;
  2657. }
  2658. }
  2659. }
  2660. }
  2661. /*
  2662. * eatsize(): Eat the size spec from a number [eg. 10UL]
  2663. */
  2664. private void
  2665. eatsize(const char **p)
  2666. {
  2667. const char *l = *p;
  2668. if (LOWCASE(*l) == 'u')
  2669. l++;
  2670. switch (LOWCASE(*l)) {
  2671. case 'l': /* long */
  2672. case 's': /* short */
  2673. case 'h': /* short */
  2674. case 'b': /* char/byte */
  2675. case 'c': /* char/byte */
  2676. l++;
  2677. /*FALLTHROUGH*/
  2678. default:
  2679. break;
  2680. }
  2681. *p = l;
  2682. }
  2683. /*
  2684. * handle a buffer containing a compiled file.
  2685. */
  2686. private struct magic_map *
  2687. apprentice_buf(struct magic_set *ms, struct magic *buf, size_t len)
  2688. {
  2689. struct magic_map *map;
  2690. if ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL) {
  2691. file_oomem(ms, sizeof(*map));
  2692. return NULL;
  2693. }
  2694. map->len = len;
  2695. map->p = buf;
  2696. map->type = MAP_TYPE_USER;
  2697. if (check_buffer(ms, map, "buffer") != 0) {
  2698. apprentice_unmap(map);
  2699. return NULL;
  2700. }
  2701. return map;
  2702. }
  2703. /*
  2704. * handle a compiled file.
  2705. */
  2706. private struct magic_map *
  2707. apprentice_map(struct magic_set *ms, const char *fn)
  2708. {
  2709. uint32_t *ptr;
  2710. uint32_t version, entries, nentries;
  2711. int needsbyteswap;
  2712. char *dbname = NULL;
  2713. struct magic_map *map;
  2714. size_t i;
  2715. php_stream *stream = NULL;
  2716. php_stream_statbuf st;
  2717. if ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL) {
  2718. file_oomem(ms, sizeof(*map));
  2719. return NULL;
  2720. }
  2721. if (fn == NULL) {
  2722. map->p = (void *)&php_magic_database;
  2723. goto internal_loaded;
  2724. }
  2725. #ifdef PHP_WIN32
  2726. /* Don't bother on windows with php_stream_open_wrapper,
  2727. return to give apprentice_load() a chance. */
  2728. if (php_stream_stat_path_ex((char *)fn, 0, &st, NULL) == SUCCESS) {
  2729. if (st.sb.st_mode & S_IFDIR) {
  2730. return NULL;
  2731. }
  2732. }
  2733. #endif
  2734. dbname = mkdbname(ms, fn, 0);
  2735. if (dbname == NULL)
  2736. goto error;
  2737. stream = php_stream_open_wrapper((char *)fn, "rb", REPORT_ERRORS, NULL);
  2738. if (!stream) {
  2739. goto error;
  2740. }
  2741. if (php_stream_stat(stream, &st) < 0) {
  2742. file_error(ms, errno, "cannot stat `%s'", dbname);
  2743. goto error;
  2744. }
  2745. if (st.sb.st_size < 8 || st.sb.st_size > MAXMAGIC_SIZE) {
  2746. file_error(ms, 0, "file `%s' is too %s", dbname,
  2747. st.sb.st_size < 8 ? "small" : "large");
  2748. goto error;
  2749. }
  2750. map->len = (size_t)st.sb.st_size;
  2751. if ((map->p = CAST(void *, emalloc(map->len))) == NULL) {
  2752. file_oomem(ms, map->len);
  2753. goto error;
  2754. }
  2755. if (php_stream_read(stream, map->p, (size_t)st.sb.st_size) != (size_t)st.sb.st_size) {
  2756. file_badread(ms);
  2757. goto error;
  2758. }
  2759. map->len = 0;
  2760. #define RET 1
  2761. php_stream_close(stream);
  2762. stream = NULL;
  2763. internal_loaded:
  2764. ptr = (uint32_t *)(void *)map->p;
  2765. if (*ptr != MAGICNO) {
  2766. if (swap4(*ptr) != MAGICNO) {
  2767. file_error(ms, 0, "bad magic in `%s'", dbname);
  2768. goto error;
  2769. }
  2770. needsbyteswap = 1;
  2771. } else
  2772. needsbyteswap = 0;
  2773. if (needsbyteswap)
  2774. version = swap4(ptr[1]);
  2775. else
  2776. version = ptr[1];
  2777. if (version != VERSIONNO) {
  2778. file_error(ms, 0, "File %d.%d supports only version %d magic "
  2779. "files. `%s' is version %d", FILE_VERSION_MAJOR, patchlevel,
  2780. VERSIONNO, dbname, version);
  2781. goto error;
  2782. }
  2783. /* php_magic_database is a const, performing writes will segfault. This is for big-endian
  2784. machines only, PPC and Sparc specifically. Consider static variable or MINIT in
  2785. future. */
  2786. if (needsbyteswap && fn == NULL) {
  2787. map->p = emalloc(sizeof(php_magic_database));
  2788. map->p = memcpy(map->p, php_magic_database, sizeof(php_magic_database));
  2789. }
  2790. if (NULL != fn) {
  2791. nentries = (uint32_t)(st.sb.st_size / sizeof(struct magic));
  2792. entries = (uint32_t)(st.sb.st_size / sizeof(struct magic));
  2793. if ((zend_off_t)(entries * sizeof(struct magic)) != st.sb.st_size) {
  2794. file_error(ms, 0, "Size of `%s' %llu is not a multiple of %zu",
  2795. dbname, (unsigned long long)st.sb.st_size,
  2796. sizeof(struct magic));
  2797. goto error;
  2798. }
  2799. }
  2800. map->magic[0] = CAST(struct magic *, map->p) + 1;
  2801. nentries = 0;
  2802. for (i = 0; i < MAGIC_SETS; i++) {
  2803. if (needsbyteswap)
  2804. map->nmagic[i] = swap4(ptr[i + 2]);
  2805. else
  2806. map->nmagic[i] = ptr[i + 2];
  2807. if (i != MAGIC_SETS - 1)
  2808. map->magic[i + 1] = map->magic[i] + map->nmagic[i];
  2809. nentries += map->nmagic[i];
  2810. }
  2811. if (NULL != fn && entries != nentries + 1) {
  2812. file_error(ms, 0, "Inconsistent entries in `%s' %u != %u",
  2813. dbname, entries, nentries + 1);
  2814. goto error;
  2815. }
  2816. if (needsbyteswap)
  2817. for (i = 0; i < MAGIC_SETS; i++)
  2818. byteswap(map->magic[i], map->nmagic[i]);
  2819. if (dbname) {
  2820. efree(dbname);
  2821. }
  2822. return map;
  2823. error:
  2824. if (stream) {
  2825. php_stream_close(stream);
  2826. }
  2827. apprentice_unmap(map);
  2828. if (dbname) {
  2829. efree(dbname);
  2830. }
  2831. return NULL;
  2832. }
  2833. private int
  2834. check_buffer(struct magic_set *ms, struct magic_map *map, const char *dbname)
  2835. {
  2836. uint32_t *ptr;
  2837. uint32_t entries, nentries;
  2838. uint32_t version;
  2839. int i, needsbyteswap;
  2840. ptr = CAST(uint32_t *, map->p);
  2841. if (*ptr != MAGICNO) {
  2842. if (swap4(*ptr) != MAGICNO) {
  2843. file_error(ms, 0, "bad magic in `%s'", dbname);
  2844. return -1;
  2845. }
  2846. needsbyteswap = 1;
  2847. } else
  2848. needsbyteswap = 0;
  2849. if (needsbyteswap)
  2850. version = swap4(ptr[1]);
  2851. else
  2852. version = ptr[1];
  2853. if (version != VERSIONNO) {
  2854. file_error(ms, 0, "File %s supports only version %d magic "
  2855. "files. `%s' is version %d", FILE_VERSION_MAJOR,
  2856. VERSIONNO, dbname, version);
  2857. return -1;
  2858. }
  2859. entries = (uint32_t)(map->len / sizeof(struct magic));
  2860. if ((entries * sizeof(struct magic)) != map->len) {
  2861. file_error(ms, 0, "Size of `%s' %" SIZE_T_FORMAT "u is not "
  2862. "a multiple of %" SIZE_T_FORMAT "u",
  2863. dbname, map->len, sizeof(struct magic));
  2864. return -1;
  2865. }
  2866. map->magic[0] = CAST(struct magic *, map->p) + 1;
  2867. nentries = 0;
  2868. for (i = 0; i < MAGIC_SETS; i++) {
  2869. if (needsbyteswap)
  2870. map->nmagic[i] = swap4(ptr[i + 2]);
  2871. else
  2872. map->nmagic[i] = ptr[i + 2];
  2873. if (i != MAGIC_SETS - 1)
  2874. map->magic[i + 1] = map->magic[i] + map->nmagic[i];
  2875. nentries += map->nmagic[i];
  2876. }
  2877. if (entries != nentries + 1) {
  2878. file_error(ms, 0, "Inconsistent entries in `%s' %u != %u",
  2879. dbname, entries, nentries + 1);
  2880. return -1;
  2881. }
  2882. if (needsbyteswap)
  2883. for (i = 0; i < MAGIC_SETS; i++)
  2884. byteswap(map->magic[i], map->nmagic[i]);
  2885. return 0;
  2886. }
  2887. /*
  2888. * handle an mmaped file.
  2889. */
  2890. private int
  2891. apprentice_compile(struct magic_set *ms, struct magic_map *map, const char *fn)
  2892. {
  2893. static const size_t nm = sizeof(*map->nmagic) * MAGIC_SETS;
  2894. static const size_t m = sizeof(**map->magic);
  2895. size_t len;
  2896. char *dbname;
  2897. int rv = -1;
  2898. uint32_t i;
  2899. union {
  2900. struct magic m;
  2901. uint32_t h[2 + MAGIC_SETS];
  2902. } hdr;
  2903. php_stream *stream;
  2904. dbname = mkdbname(ms, fn, 1);
  2905. if (dbname == NULL)
  2906. goto out;
  2907. /* wb+ == O_WRONLY|O_CREAT|O_TRUNC|O_BINARY */
  2908. stream = php_stream_open_wrapper((char *)fn, "wb+", REPORT_ERRORS, NULL);
  2909. if (!stream) {
  2910. file_error(ms, errno, "cannot open `%s'", dbname);
  2911. goto out;
  2912. }
  2913. memset(&hdr, 0, sizeof(hdr));
  2914. hdr.h[0] = MAGICNO;
  2915. hdr.h[1] = VERSIONNO;
  2916. memcpy(hdr.h + 2, map->nmagic, nm);
  2917. if (php_stream_write(stream,(const char *)&hdr, sizeof(hdr)) != (ssize_t)sizeof(hdr)) {
  2918. file_error(ms, errno, "error writing `%s'", dbname);
  2919. goto out;
  2920. }
  2921. for (i = 0; i < MAGIC_SETS; i++) {
  2922. len = m * map->nmagic[i];
  2923. if (php_stream_write(stream, (const char *)map->magic[i], len) != (ssize_t)len) {
  2924. file_error(ms, errno, "error writing `%s'", dbname);
  2925. goto out;
  2926. }
  2927. }
  2928. if (stream) {
  2929. php_stream_close(stream);
  2930. }
  2931. rv = 0;
  2932. out:
  2933. efree(dbname);
  2934. return rv;
  2935. }
  2936. private const char ext[] = ".mgc";
  2937. /*
  2938. * make a dbname
  2939. */
  2940. private char *
  2941. mkdbname(struct magic_set *ms, const char *fn, int strip)
  2942. {
  2943. const char *p, *q;
  2944. char *buf;
  2945. if (strip) {
  2946. if ((p = strrchr(fn, '/')) != NULL)
  2947. fn = ++p;
  2948. }
  2949. for (q = fn; *q; q++)
  2950. continue;
  2951. /* Look for .mgc */
  2952. for (p = ext + sizeof(ext) - 1; p >= ext && q >= fn; p--, q--)
  2953. if (*p != *q)
  2954. break;
  2955. /* Did not find .mgc, restore q */
  2956. if (p >= ext)
  2957. while (*q)
  2958. q++;
  2959. q++;
  2960. /* Compatibility with old code that looked in .mime */
  2961. if (ms->flags & MAGIC_MIME) {
  2962. spprintf(&buf, MAXPATHLEN, "%.*s.mime%s", (int)(q - fn), fn, ext);
  2963. #ifdef PHP_WIN32
  2964. if (VCWD_ACCESS(buf, R_OK) == 0) {
  2965. #else
  2966. if (VCWD_ACCESS(buf, R_OK) != -1) {
  2967. #endif
  2968. ms->flags &= MAGIC_MIME_TYPE;
  2969. return buf;
  2970. }
  2971. efree(buf);
  2972. }
  2973. spprintf(&buf, MAXPATHLEN, "%.*s%s", (int)(q - fn), fn, ext);
  2974. /* Compatibility with old code that looked in .mime */
  2975. if (strstr(fn, ".mime") != NULL)
  2976. ms->flags &= MAGIC_MIME_TYPE;
  2977. return buf;
  2978. }
  2979. /*
  2980. * Byteswap an mmap'ed file if needed
  2981. */
  2982. private void
  2983. byteswap(struct magic *magic, uint32_t nmagic)
  2984. {
  2985. uint32_t i;
  2986. for (i = 0; i < nmagic; i++)
  2987. bs1(&magic[i]);
  2988. }
  2989. /*
  2990. * swap a short
  2991. */
  2992. private uint16_t
  2993. swap2(uint16_t sv)
  2994. {
  2995. uint16_t rv;
  2996. uint8_t *s = (uint8_t *)(void *)&sv;
  2997. uint8_t *d = (uint8_t *)(void *)&rv;
  2998. d[0] = s[1];
  2999. d[1] = s[0];
  3000. return rv;
  3001. }
  3002. /*
  3003. * swap an int
  3004. */
  3005. private uint32_t
  3006. swap4(uint32_t sv)
  3007. {
  3008. uint32_t rv;
  3009. uint8_t *s = (uint8_t *)(void *)&sv;
  3010. uint8_t *d = (uint8_t *)(void *)&rv;
  3011. d[0] = s[3];
  3012. d[1] = s[2];
  3013. d[2] = s[1];
  3014. d[3] = s[0];
  3015. return rv;
  3016. }
  3017. /*
  3018. * swap a quad
  3019. */
  3020. private uint64_t
  3021. swap8(uint64_t sv)
  3022. {
  3023. uint64_t rv;
  3024. uint8_t *s = (uint8_t *)(void *)&sv;
  3025. uint8_t *d = (uint8_t *)(void *)&rv;
  3026. #if 0
  3027. d[0] = s[3];
  3028. d[1] = s[2];
  3029. d[2] = s[1];
  3030. d[3] = s[0];
  3031. d[4] = s[7];
  3032. d[5] = s[6];
  3033. d[6] = s[5];
  3034. d[7] = s[4];
  3035. #else
  3036. d[0] = s[7];
  3037. d[1] = s[6];
  3038. d[2] = s[5];
  3039. d[3] = s[4];
  3040. d[4] = s[3];
  3041. d[5] = s[2];
  3042. d[6] = s[1];
  3043. d[7] = s[0];
  3044. #endif
  3045. return rv;
  3046. }
  3047. /*
  3048. * byteswap a single magic entry
  3049. */
  3050. private void
  3051. bs1(struct magic *m)
  3052. {
  3053. m->cont_level = swap2(m->cont_level);
  3054. m->offset = swap4((int32_t)m->offset);
  3055. m->in_offset = swap4((uint32_t)m->in_offset);
  3056. m->lineno = swap4((uint32_t)m->lineno);
  3057. if (IS_LIBMAGIC_STRING(m->type)) {
  3058. m->str_range = swap4(m->str_range);
  3059. m->str_flags = swap4(m->str_flags);
  3060. }
  3061. else {
  3062. m->value.q = swap8(m->value.q);
  3063. m->num_mask = swap8(m->num_mask);
  3064. }
  3065. }
  3066. protected size_t
  3067. file_pstring_length_size(const struct magic *m)
  3068. {
  3069. switch (m->str_flags & PSTRING_LEN) {
  3070. case PSTRING_1_LE:
  3071. return 1;
  3072. case PSTRING_2_LE:
  3073. case PSTRING_2_BE:
  3074. return 2;
  3075. case PSTRING_4_LE:
  3076. case PSTRING_4_BE:
  3077. return 4;
  3078. default:
  3079. abort(); /* Impossible */
  3080. return 1;
  3081. }
  3082. }
  3083. protected size_t
  3084. file_pstring_get_length(const struct magic *m, const char *ss)
  3085. {
  3086. size_t len = 0;
  3087. const unsigned char *s = (const unsigned char *)ss;
  3088. unsigned int s3, s2, s1, s0;
  3089. switch (m->str_flags & PSTRING_LEN) {
  3090. case PSTRING_1_LE:
  3091. len = *s;
  3092. break;
  3093. case PSTRING_2_LE:
  3094. s0 = s[0];
  3095. s1 = s[1];
  3096. len = (s1 << 8) | s0;
  3097. break;
  3098. case PSTRING_2_BE:
  3099. s0 = s[0];
  3100. s1 = s[1];
  3101. len = (s0 << 8) | s1;
  3102. break;
  3103. case PSTRING_4_LE:
  3104. s0 = s[0];
  3105. s1 = s[1];
  3106. s2 = s[2];
  3107. s3 = s[3];
  3108. len = (s3 << 24) | (s2 << 16) | (s1 << 8) | s0;
  3109. break;
  3110. case PSTRING_4_BE:
  3111. s0 = s[0];
  3112. s1 = s[1];
  3113. s2 = s[2];
  3114. s3 = s[3];
  3115. len = (s0 << 24) | (s1 << 16) | (s2 << 8) | s3;
  3116. break;
  3117. default:
  3118. abort(); /* Impossible */
  3119. }
  3120. if (m->str_flags & PSTRING_LENGTH_INCLUDES_ITSELF)
  3121. len -= file_pstring_length_size(m);
  3122. return len;
  3123. }
  3124. protected int
  3125. file_magicfind(struct magic_set *ms, const char *name, struct mlist *v)
  3126. {
  3127. uint32_t i, j;
  3128. struct mlist *mlist, *ml;
  3129. mlist = ms->mlist[1];
  3130. for (ml = mlist->next; ml != mlist; ml = ml->next) {
  3131. struct magic *ma = ml->magic;
  3132. uint32_t nma = ml->nmagic;
  3133. for (i = 0; i < nma; i++) {
  3134. if (ma[i].type != FILE_NAME)
  3135. continue;
  3136. if (strcmp(ma[i].value.s, name) == 0) {
  3137. v->magic = &ma[i];
  3138. for (j = i + 1; j < nma; j++)
  3139. if (ma[j].cont_level == 0)
  3140. break;
  3141. v->nmagic = j - i;
  3142. return 0;
  3143. }
  3144. }
  3145. }
  3146. return -1;
  3147. }