apprentice.c 72 KB

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