apprentice.c 70 KB

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