apprentice.c 80 KB

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