apprentice.c 69 KB

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