apprentice.c 67 KB

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