apprentice.c 65 KB

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