apprentice.c 69 KB

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