apprentice.c 70 KB

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