forked from Velocidex/go-yara
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_apprentice.c
3509 lines (3218 loc) · 73.8 KB
/
file_apprentice.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Ian F. Darwin 1986-1995.
* Software written by Ian F. Darwin and others;
* maintained 1995-present by Christos Zoulas and others.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* apprentice - make one pass through /etc/magic, learning its secrets.
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: apprentice.c,v 1.297 2020/05/09 18:57:15 christos Exp $")
#endif /* lint */
#include "file_magic.h"
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <stddef.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <fcntl.h>
#ifdef QUICK
#include <sys/mman.h>
#endif
#include <dirent.h>
#include <limits.h>
#define EATAB {while (isascii(CAST(unsigned char, *l)) && \
isspace(CAST(unsigned char, *l))) ++l;}
#define LOWCASE(l) (isupper(CAST(unsigned char, l)) ? \
tolower(CAST(unsigned char, l)) : (l))
/*
* Work around a bug in headers on Digital Unix.
* At least confirmed for: OSF1 V4.0 878
*/
#if defined(__osf__) && defined(__DECC)
#ifdef MAP_FAILED
#undef MAP_FAILED
#endif
#endif
#ifndef MAP_FAILED
#define MAP_FAILED (void *) -1
#endif
#ifndef MAP_FILE
#define MAP_FILE 0
#endif
#define ALLOC_CHUNK CAST(size_t, 10)
#define ALLOC_INCR CAST(size_t, 200)
#define MAP_TYPE_USER 0
#define MAP_TYPE_MALLOC 1
#define MAP_TYPE_MMAP 2
struct magic_entry {
struct magic *mp;
uint32_t cont_count;
uint32_t max_count;
};
struct magic_entry_set {
struct magic_entry *me;
uint32_t count;
uint32_t max;
};
struct magic_map {
void *p;
size_t len;
int type;
struct magic *magic[MAGIC_SETS];
uint32_t nmagic[MAGIC_SETS];
};
int file_formats[FILE_NAMES_SIZE];
const size_t file_nformats = FILE_NAMES_SIZE;
const char *file_names[FILE_NAMES_SIZE];
const size_t file_nnames = FILE_NAMES_SIZE;
private int getvalue(struct magic_set *ms, struct magic *, const char **, int);
private int hextoint(int);
private const char *getstr(struct magic_set *, struct magic *, const char *,
int);
private int parse(struct magic_set *, struct magic_entry *, const char *,
size_t, int);
private void eatsize(const char **);
private int apprentice_1(struct magic_set *, const char *, int);
private size_t apprentice_magic_strength(const struct magic *);
private int apprentice_sort(const void *, const void *);
private void apprentice_list(struct mlist *, int );
private struct magic_map *apprentice_load(struct magic_set *,
const char *, int);
private struct mlist *mlist_alloc(void);
private void mlist_free_all(struct magic_set *);
private void mlist_free(struct mlist *);
private void byteswap(struct magic *, uint32_t);
private void bs1(struct magic *);
private uint16_t swap2(uint16_t);
private uint32_t swap4(uint32_t);
private uint64_t swap8(uint64_t);
private char *mkdbname(struct magic_set *, const char *, int);
private struct magic_map *apprentice_buf(struct magic_set *, struct magic *,
size_t);
private struct magic_map *apprentice_map(struct magic_set *, const char *);
private int check_buffer(struct magic_set *, struct magic_map *, const char *);
private void apprentice_unmap(struct magic_map *);
private int apprentice_compile(struct magic_set *, struct magic_map *,
const char *);
private int check_format_type(const char *, int, const char **);
private int check_format(struct magic_set *, struct magic *);
private int get_op(char);
private int parse_mime(struct magic_set *, struct magic_entry *, const char *,
size_t);
private int parse_strength(struct magic_set *, struct magic_entry *,
const char *, size_t);
private int parse_apple(struct magic_set *, struct magic_entry *, const char *,
size_t);
private int parse_ext(struct magic_set *, struct magic_entry *, const char *,
size_t);
private size_t magicsize = sizeof(struct magic);
private const char usg_hdr[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
private struct {
const char *name;
size_t len;
int (*fun)(struct magic_set *, struct magic_entry *, const char *,
size_t);
} bang[] = {
#define DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name }
DECLARE_FIELD(mime),
DECLARE_FIELD(apple),
DECLARE_FIELD(ext),
DECLARE_FIELD(strength),
#undef DECLARE_FIELD
{ NULL, 0, NULL }
};
#ifdef COMPILE_ONLY
int main(int, char *[]);
int
main(int argc, char *argv[])
{
int ret;
struct magic_set *ms;
char *progname;
if ((progname = strrchr(argv[0], '/')) != NULL)
progname++;
else
progname = argv[0];
if (argc != 2) {
(void)fprintf(stderr, "Usage: %s file\n", progname);
return 1;
}
if ((ms = magic_open(MAGIC_CHECK)) == NULL) {
(void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
return 1;
}
ret = magic_compile(ms, argv[1]) == -1 ? 1 : 0;
if (ret == 1)
(void)fprintf(stderr, "%s: %s\n", progname, magic_error(ms));
magic_close(ms);
return ret;
}
#endif /* COMPILE_ONLY */
struct type_tbl_s {
const char name[16];
const size_t len;
const int type;
const int format;
};
/*
* XXX - the actual Single UNIX Specification says that "long" means "long",
* as in the C data type, but we treat it as meaning "4-byte integer".
* Given that the OS X version of file 5.04 did the same, I guess that passes
* the actual test; having "long" be dependent on how big a "long" is on
* the machine running "file" is silly.
*/
static const struct type_tbl_s type_tbl[] = {
# define XX(s) s, (sizeof(s) - 1)
# define XX_NULL "", 0
{ XX("invalid"), FILE_INVALID, FILE_FMT_NONE },
{ XX("byte"), FILE_BYTE, FILE_FMT_NUM },
{ XX("short"), FILE_SHORT, FILE_FMT_NUM },
{ XX("default"), FILE_DEFAULT, FILE_FMT_NONE },
{ XX("long"), FILE_LONG, FILE_FMT_NUM },
{ XX("string"), FILE_STRING, FILE_FMT_STR },
{ XX("date"), FILE_DATE, FILE_FMT_STR },
{ XX("beshort"), FILE_BESHORT, FILE_FMT_NUM },
{ XX("belong"), FILE_BELONG, FILE_FMT_NUM },
{ XX("bedate"), FILE_BEDATE, FILE_FMT_STR },
{ XX("leshort"), FILE_LESHORT, FILE_FMT_NUM },
{ XX("lelong"), FILE_LELONG, FILE_FMT_NUM },
{ XX("ledate"), FILE_LEDATE, FILE_FMT_STR },
{ XX("pstring"), FILE_PSTRING, FILE_FMT_STR },
{ XX("ldate"), FILE_LDATE, FILE_FMT_STR },
{ XX("beldate"), FILE_BELDATE, FILE_FMT_STR },
{ XX("leldate"), FILE_LELDATE, FILE_FMT_STR },
{ XX("regex"), FILE_REGEX, FILE_FMT_STR },
{ XX("bestring16"), FILE_BESTRING16, FILE_FMT_STR },
{ XX("lestring16"), FILE_LESTRING16, FILE_FMT_STR },
{ XX("search"), FILE_SEARCH, FILE_FMT_STR },
{ XX("medate"), FILE_MEDATE, FILE_FMT_STR },
{ XX("meldate"), FILE_MELDATE, FILE_FMT_STR },
{ XX("melong"), FILE_MELONG, FILE_FMT_NUM },
{ XX("quad"), FILE_QUAD, FILE_FMT_QUAD },
{ XX("lequad"), FILE_LEQUAD, FILE_FMT_QUAD },
{ XX("bequad"), FILE_BEQUAD, FILE_FMT_QUAD },
{ XX("qdate"), FILE_QDATE, FILE_FMT_STR },
{ XX("leqdate"), FILE_LEQDATE, FILE_FMT_STR },
{ XX("beqdate"), FILE_BEQDATE, FILE_FMT_STR },
{ XX("qldate"), FILE_QLDATE, FILE_FMT_STR },
{ XX("leqldate"), FILE_LEQLDATE, FILE_FMT_STR },
{ XX("beqldate"), FILE_BEQLDATE, FILE_FMT_STR },
{ XX("float"), FILE_FLOAT, FILE_FMT_FLOAT },
{ XX("befloat"), FILE_BEFLOAT, FILE_FMT_FLOAT },
{ XX("lefloat"), FILE_LEFLOAT, FILE_FMT_FLOAT },
{ XX("double"), FILE_DOUBLE, FILE_FMT_DOUBLE },
{ XX("bedouble"), FILE_BEDOUBLE, FILE_FMT_DOUBLE },
{ XX("ledouble"), FILE_LEDOUBLE, FILE_FMT_DOUBLE },
{ XX("leid3"), FILE_LEID3, FILE_FMT_NUM },
{ XX("beid3"), FILE_BEID3, FILE_FMT_NUM },
{ XX("indirect"), FILE_INDIRECT, FILE_FMT_NUM },
{ XX("qwdate"), FILE_QWDATE, FILE_FMT_STR },
{ XX("leqwdate"), FILE_LEQWDATE, FILE_FMT_STR },
{ XX("beqwdate"), FILE_BEQWDATE, FILE_FMT_STR },
{ XX("name"), FILE_NAME, FILE_FMT_NONE },
{ XX("use"), FILE_USE, FILE_FMT_NONE },
{ XX("clear"), FILE_CLEAR, FILE_FMT_NONE },
{ XX("der"), FILE_DER, FILE_FMT_STR },
{ XX("guid"), FILE_GUID, FILE_FMT_STR },
{ XX("offset"), FILE_OFFSET, FILE_FMT_QUAD },
{ XX_NULL, FILE_INVALID, FILE_FMT_NONE },
};
/*
* These are not types, and cannot be preceded by "u" to make them
* unsigned.
*/
static const struct type_tbl_s special_tbl[] = {
{ XX("der"), FILE_DER, FILE_FMT_STR },
{ XX("name"), FILE_NAME, FILE_FMT_STR },
{ XX("use"), FILE_USE, FILE_FMT_STR },
{ XX_NULL, FILE_INVALID, FILE_FMT_NONE },
};
# undef XX
# undef XX_NULL
private int
get_type(const struct type_tbl_s *tbl, const char *l, const char **t)
{
const struct type_tbl_s *p;
for (p = tbl; p->len; p++) {
if (strncmp(l, p->name, p->len) == 0) {
if (t)
*t = l + p->len;
break;
}
}
return p->type;
}
private off_t
maxoff_t(void) {
if (/*CONSTCOND*/sizeof(off_t) == sizeof(int))
return CAST(off_t, INT_MAX);
if (/*CONSTCOND*/sizeof(off_t) == sizeof(long))
return CAST(off_t, LONG_MAX);
return 0x7fffffff;
}
private int
get_standard_integer_type(const char *l, const char **t)
{
int type;
if (isalpha(CAST(unsigned char, l[1]))) {
switch (l[1]) {
case 'C':
/* "dC" and "uC" */
type = FILE_BYTE;
break;
case 'S':
/* "dS" and "uS" */
type = FILE_SHORT;
break;
case 'I':
case 'L':
/*
* "dI", "dL", "uI", and "uL".
*
* XXX - the actual Single UNIX Specification says
* that "L" means "long", as in the C data type,
* but we treat it as meaning "4-byte integer".
* Given that the OS X version of file 5.04 did
* the same, I guess that passes the actual SUS
* validation suite; having "dL" be dependent on
* how big a "long" is on the machine running
* "file" is silly.
*/
type = FILE_LONG;
break;
case 'Q':
/* "dQ" and "uQ" */
type = FILE_QUAD;
break;
default:
/* "d{anything else}", "u{anything else}" */
return FILE_INVALID;
}
l += 2;
} else if (isdigit(CAST(unsigned char, l[1]))) {
/*
* "d{num}" and "u{num}"; we only support {num} values
* of 1, 2, 4, and 8 - the Single UNIX Specification
* doesn't say anything about whether arbitrary
* values should be supported, but both the Solaris 10
* and OS X Mountain Lion versions of file passed the
* Single UNIX Specification validation suite, and
* neither of them support values bigger than 8 or
* non-power-of-2 values.
*/
if (isdigit(CAST(unsigned char, l[2]))) {
/* Multi-digit, so > 9 */
return FILE_INVALID;
}
switch (l[1]) {
case '1':
type = FILE_BYTE;
break;
case '2':
type = FILE_SHORT;
break;
case '4':
type = FILE_LONG;
break;
case '8':
type = FILE_QUAD;
break;
default:
/* XXX - what about 3, 5, 6, or 7? */
return FILE_INVALID;
}
l += 2;
} else {
/*
* "d" or "u" by itself.
*/
type = FILE_LONG;
++l;
}
if (t)
*t = l;
return type;
}
private void
init_file_tables(void)
{
static int done = 0;
const struct type_tbl_s *p;
if (done)
return;
done++;
for (p = type_tbl; p->len; p++) {
assert(p->type < FILE_NAMES_SIZE);
file_names[p->type] = p->name;
file_formats[p->type] = p->format;
}
assert(p - type_tbl == FILE_NAMES_SIZE);
}
private int
add_mlist(struct mlist *mlp, struct magic_map *map, size_t idx)
{
struct mlist *ml;
mlp->map = NULL;
if ((ml = CAST(struct mlist *, malloc(sizeof(*ml)))) == NULL)
return -1;
ml->map = idx == 0 ? map : NULL;
ml->magic = map->magic[idx];
ml->nmagic = map->nmagic[idx];
mlp->prev->next = ml;
ml->prev = mlp->prev;
ml->next = mlp;
mlp->prev = ml;
return 0;
}
/*
* Handle one file or directory.
*/
private int
apprentice_1(struct magic_set *ms, const char *fn, int action)
{
struct magic_map *map;
#ifndef COMPILE_ONLY
struct mlist *ml;
size_t i;
#endif
if (magicsize != FILE_MAGICSIZE) {
file_error(ms, 0, "magic element size %lu != %lu",
CAST(unsigned long, sizeof(*map->magic[0])),
CAST(unsigned long, FILE_MAGICSIZE));
return -1;
}
if (action == FILE_COMPILE) {
map = apprentice_load(ms, fn, action);
if (map == NULL)
return -1;
return apprentice_compile(ms, map, fn);
}
#ifndef COMPILE_ONLY
map = apprentice_map(ms, fn);
if (map == NULL) {
if (ms->flags & MAGIC_CHECK)
file_magwarn(ms, "using regular magic file `%s'", fn);
map = apprentice_load(ms, fn, action);
if (map == NULL)
return -1;
}
for (i = 0; i < MAGIC_SETS; i++) {
if (add_mlist(ms->mlist[i], map, i) == -1) {
/* failed to add to any list, free explicitly */
if (i == 0)
apprentice_unmap(map);
else
mlist_free_all(ms);
file_oomem(ms, sizeof(*ml));
return -1;
}
}
if (action == FILE_LIST) {
for (i = 0; i < MAGIC_SETS; i++) {
printf("Set %zu:\nBinary patterns:\n",
i);
apprentice_list(ms->mlist[i], BINTEST);
printf("Text patterns:\n");
apprentice_list(ms->mlist[i], TEXTTEST);
}
}
return 0;
#else
return 0;
#endif /* COMPILE_ONLY */
}
protected void
file_ms_free(struct magic_set *ms)
{
size_t i;
if (ms == NULL)
return;
for (i = 0; i < MAGIC_SETS; i++)
mlist_free(ms->mlist[i]);
free(ms->o.pbuf);
free(ms->o.buf);
free(ms->c.li);
free(ms);
}
protected struct magic_set *
file_ms_alloc(int flags)
{
struct magic_set *ms;
size_t i, len;
if ((ms = CAST(struct magic_set *, calloc(CAST(size_t, 1u),
sizeof(struct magic_set)))) == NULL)
return NULL;
if (magic_setflags(ms, flags) == -1) {
errno = EINVAL;
goto free;
}
ms->o.buf = ms->o.pbuf = NULL;
ms->o.blen = 0;
len = (ms->c.len = 10) * sizeof(*ms->c.li);
if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL)
goto free;
ms->event_flags = 0;
ms->error = -1;
for (i = 0; i < MAGIC_SETS; i++)
ms->mlist[i] = NULL;
ms->file = "unknown";
ms->line = 0;
ms->indir_max = FILE_INDIR_MAX;
ms->name_max = FILE_NAME_MAX;
ms->elf_shnum_max = FILE_ELF_SHNUM_MAX;
ms->elf_phnum_max = FILE_ELF_PHNUM_MAX;
ms->elf_notes_max = FILE_ELF_NOTES_MAX;
ms->regex_max = FILE_REGEX_MAX;
ms->bytes_max = FILE_BYTES_MAX;
return ms;
free:
free(ms);
return NULL;
}
private void
apprentice_unmap(struct magic_map *map)
{
size_t i;
if (map == NULL)
return;
switch (map->type) {
case MAP_TYPE_USER:
break;
case MAP_TYPE_MALLOC:
for (i = 0; i < MAGIC_SETS; i++) {
void *b = map->magic[i];
void *p = map->p;
if (CAST(char *, b) >= CAST(char *, p) &&
CAST(char *, b) <= CAST(char *, p) + map->len)
continue;
free(map->magic[i]);
}
free(map->p);
break;
#ifdef QUICK
case MAP_TYPE_MMAP:
if (map->p && map->p != MAP_FAILED)
(void)munmap(map->p, map->len);
break;
#endif
default:
abort();
}
free(map);
}
private struct mlist *
mlist_alloc(void)
{
struct mlist *mlist;
if ((mlist = CAST(struct mlist *, calloc(1, sizeof(*mlist)))) == NULL) {
return NULL;
}
mlist->next = mlist->prev = mlist;
return mlist;
}
private void
mlist_free_all(struct magic_set *ms)
{
size_t i;
for (i = 0; i < MAGIC_SETS; i++) {
mlist_free(ms->mlist[i]);
ms->mlist[i] = NULL;
}
}
private void
mlist_free_one(struct mlist *ml)
{
if (ml->map)
apprentice_unmap(CAST(struct magic_map *, ml->map));
free(ml);
}
private void
mlist_free(struct mlist *mlist)
{
struct mlist *ml, *next;
if (mlist == NULL)
return;
for (ml = mlist->next; ml != mlist;) {
next = ml->next;
mlist_free_one(ml);
ml = next;
}
mlist_free_one(mlist);
}
#ifndef COMPILE_ONLY
/* void **bufs: an array of compiled magic files */
protected int
buffer_apprentice(struct magic_set *ms, struct magic **bufs,
size_t *sizes, size_t nbufs)
{
size_t i, j;
struct mlist *ml;
struct magic_map *map;
if (nbufs == 0)
return -1;
(void)file_reset(ms, 0);
init_file_tables();
for (i = 0; i < MAGIC_SETS; i++) {
mlist_free(ms->mlist[i]);
if ((ms->mlist[i] = mlist_alloc()) == NULL) {
file_oomem(ms, sizeof(*ms->mlist[i]));
goto fail;
}
}
for (i = 0; i < nbufs; i++) {
map = apprentice_buf(ms, bufs[i], sizes[i]);
if (map == NULL)
goto fail;
for (j = 0; j < MAGIC_SETS; j++) {
if (add_mlist(ms->mlist[j], map, j) == -1) {
file_oomem(ms, sizeof(*ml));
goto fail;
}
}
}
return 0;
fail:
mlist_free_all(ms);
return -1;
}
#endif
/* const char *fn: list of magic files and directories */
protected int
file_apprentice(struct magic_set *ms, const char *fn, int action)
{
char *p, *mfn;
int fileerr, errs = -1;
size_t i, j;
(void)file_reset(ms, 0);
if ((fn = magic_getpath(fn, action)) == NULL)
return -1;
init_file_tables();
if ((mfn = strdup(fn)) == NULL) {
file_oomem(ms, strlen(fn));
return -1;
}
for (i = 0; i < MAGIC_SETS; i++) {
mlist_free(ms->mlist[i]);
if ((ms->mlist[i] = mlist_alloc()) == NULL) {
file_oomem(ms, sizeof(*ms->mlist[i]));
for (j = 0; j < i; j++) {
mlist_free(ms->mlist[j]);
ms->mlist[j] = NULL;
}
free(mfn);
return -1;
}
}
fn = mfn;
while (fn) {
p = strchr(fn, PATHSEP);
if (p)
*p++ = '\0';
if (*fn == '\0')
break;
fileerr = apprentice_1(ms, fn, action);
errs = MAX(errs, fileerr);
fn = p;
}
free(mfn);
if (errs == -1) {
for (i = 0; i < MAGIC_SETS; i++) {
mlist_free(ms->mlist[i]);
ms->mlist[i] = NULL;
}
file_error(ms, 0, "could not find any valid magic files!");
return -1;
}
#if 0
/*
* Always leave the database loaded
*/
if (action == FILE_LOAD)
return 0;
for (i = 0; i < MAGIC_SETS; i++) {
mlist_free(ms->mlist[i]);
ms->mlist[i] = NULL;
}
#endif
switch (action) {
case FILE_LOAD:
case FILE_COMPILE:
case FILE_CHECK:
case FILE_LIST:
return 0;
default:
file_error(ms, 0, "Invalid action %d", action);
return -1;
}
}
/*
* Compute the real length of a magic expression, for the purposes
* of determining how "strong" a magic expression is (approximating
* how specific its matches are):
* - magic characters count 0 unless escaped.
* - [] expressions count 1
* - {} expressions count 0
* - regular characters or escaped magic characters count 1
* - 0 length expressions count as one
*/
private size_t
nonmagic(const char *str)
{
const char *p;
size_t rv = 0;
for (p = str; *p; p++)
switch (*p) {
case '\\': /* Escaped anything counts 1 */
if (!*++p)
p--;
rv++;
continue;
case '?': /* Magic characters count 0 */
case '*':
case '.':
case '+':
case '^':
case '$':
continue;
case '[': /* Bracketed expressions count 1 the ']' */
while (*p && *p != ']')
p++;
p--;
continue;
case '{': /* Braced expressions count 0 */
while (*p && *p != '}')
p++;
if (!*p)
p--;
continue;
default: /* Anything else counts 1 */
rv++;
continue;
}
return rv == 0 ? 1 : rv; /* Return at least 1 */
}
private size_t
typesize(int type)
{
switch (type) {
case FILE_BYTE:
return 1;
case FILE_SHORT:
case FILE_LESHORT:
case FILE_BESHORT:
return 2;
case FILE_LONG:
case FILE_LELONG:
case FILE_BELONG:
case FILE_MELONG:
return 4;
case FILE_DATE:
case FILE_LEDATE:
case FILE_BEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_LELDATE:
case FILE_BELDATE:
case FILE_MELDATE:
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
return 4;
case FILE_QUAD:
case FILE_BEQUAD:
case FILE_LEQUAD:
case FILE_QDATE:
case FILE_LEQDATE:
case FILE_BEQDATE:
case FILE_QLDATE:
case FILE_LEQLDATE:
case FILE_BEQLDATE:
case FILE_QWDATE:
case FILE_LEQWDATE:
case FILE_BEQWDATE:
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
case FILE_OFFSET:
return 8;
case FILE_GUID:
return 16;
default:
return FILE_BADSIZE;
}
}
/*
* Get weight of this magic entry, for sorting purposes.
*/
private size_t
apprentice_magic_strength(const struct magic *m)
{
#define MULT 10U
size_t ts, v;
ssize_t val = 2 * MULT; /* baseline strength */
switch (m->type) {
case FILE_DEFAULT: /* make sure this sorts last */
if (m->factor_op != FILE_FACTOR_OP_NONE)
abort();
return 0;
case FILE_BYTE:
case FILE_SHORT:
case FILE_LESHORT:
case FILE_BESHORT:
case FILE_LONG:
case FILE_LELONG:
case FILE_BELONG:
case FILE_MELONG:
case FILE_DATE:
case FILE_LEDATE:
case FILE_BEDATE:
case FILE_MEDATE:
case FILE_LDATE:
case FILE_LELDATE:
case FILE_BELDATE:
case FILE_MELDATE:
case FILE_FLOAT:
case FILE_BEFLOAT:
case FILE_LEFLOAT:
case FILE_QUAD:
case FILE_BEQUAD:
case FILE_LEQUAD:
case FILE_QDATE:
case FILE_LEQDATE:
case FILE_BEQDATE:
case FILE_QLDATE:
case FILE_LEQLDATE:
case FILE_BEQLDATE:
case FILE_QWDATE:
case FILE_LEQWDATE:
case FILE_BEQWDATE:
case FILE_DOUBLE:
case FILE_BEDOUBLE:
case FILE_LEDOUBLE:
case FILE_GUID:
case FILE_OFFSET:
ts = typesize(m->type);
if (ts == FILE_BADSIZE)
abort();
val += ts * MULT;
break;
case FILE_PSTRING:
case FILE_STRING:
val += m->vallen * MULT;
break;
case FILE_BESTRING16:
case FILE_LESTRING16:
val += m->vallen * MULT / 2;
break;
case FILE_SEARCH:
if (m->vallen == 0)
break;
val += m->vallen * MAX(MULT / m->vallen, 1);
break;
case FILE_REGEX:
v = nonmagic(m->value.s);
val += v * MAX(MULT / v, 1);
break;
case FILE_INDIRECT:
case FILE_NAME:
case FILE_USE:
break;
case FILE_DER:
val += MULT;
break;
default:
(void)fprintf(stderr, "Bad type %d\n", m->type);
abort();
}
switch (m->reln) {
case 'x': /* matches anything penalize */
case '!': /* matches almost anything penalize */
val = 0;
break;
case '=': /* Exact match, prefer */
val += MULT;
break;
case '>':
case '<': /* comparison match reduce strength */
val -= 2 * MULT;
break;
case '^':
case '&': /* masking bits, we could count them too */
val -= MULT;
break;
default:
(void)fprintf(stderr, "Bad relation %c\n", m->reln);
abort();
}
switch (m->factor_op) {
case FILE_FACTOR_OP_NONE:
break;
case FILE_FACTOR_OP_PLUS:
val += m->factor;
break;
case FILE_FACTOR_OP_MINUS:
val -= m->factor;
break;
case FILE_FACTOR_OP_TIMES:
val *= m->factor;
break;
case FILE_FACTOR_OP_DIV:
val /= m->factor;
break;
default:
abort();
}