Coverage Report

Created: 2023-09-25 07:18

/src/file/src/funcs.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) Christos Zoulas 2003.
3
 * All Rights Reserved.
4
 *
5
 * Redistribution and use in source and binary forms, with or without
6
 * modification, are permitted provided that the following conditions
7
 * are met:
8
 * 1. Redistributions of source code must retain the above copyright
9
 *    notice immediately at the beginning of the file, without modification,
10
 *    this list of conditions, and the following disclaimer.
11
 * 2. Redistributions in binary form must reproduce the above copyright
12
 *    notice, this list of conditions and the following disclaimer in the
13
 *    documentation and/or other materials provided with the distribution.
14
 *
15
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
19
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25
 * SUCH DAMAGE.
26
 */
27
#include "file.h"
28
29
#ifndef lint
30
FILE_RCSID("@(#)$File: funcs.c,v 1.142 2023/07/30 14:41:14 christos Exp $")
31
#endif  /* lint */
32
33
#include "magic.h"
34
#include <assert.h>
35
#include <stdarg.h>
36
#include <stdlib.h>
37
#include <string.h>
38
#include <ctype.h>
39
#ifdef HAVE_UNISTD_H
40
#include <unistd.h> /* for pipe2() */
41
#endif
42
#if defined(HAVE_WCHAR_H)
43
#include <wchar.h>
44
#endif
45
#if defined(HAVE_WCTYPE_H)
46
#include <wctype.h>
47
#endif
48
#include <limits.h>
49
50
#ifndef SIZE_MAX
51
#define SIZE_MAX  ((size_t)~0)
52
#endif
53
54
file_protected char *
55
file_copystr(char *buf, size_t blen, size_t width, const char *str)
56
0
{
57
0
  if (blen == 0)
58
0
    return buf;
59
0
  if (width >= blen)
60
0
    width = blen - 1;
61
0
  memcpy(buf, str, width);
62
0
  buf[width] = '\0';
63
0
  return buf;
64
0
}
65
66
file_private void
67
file_clearbuf(struct magic_set *ms)
68
7.58k
{
69
7.58k
  free(ms->o.buf);
70
7.58k
  ms->o.buf = NULL;
71
7.58k
  ms->o.blen = 0;
72
7.58k
}
73
74
file_private int
75
file_checkfield(char *msg, size_t mlen, const char *what, const char **pp)
76
122k
{
77
122k
  const char *p = *pp;
78
122k
  int fw = 0;
79
80
128k
  while (*p && isdigit((unsigned char)*p))
81
5.86k
    fw = fw * 10 + (*p++ - '0');
82
83
122k
  *pp = p;
84
85
122k
  if (fw < 1024)
86
122k
    return 1;
87
0
  if (msg)
88
0
    snprintf(msg, mlen, "field %s too large: %d", what, fw);
89
90
0
  return 0;
91
122k
}
92
93
file_protected int
94
file_checkfmt(char *msg, size_t mlen, const char *fmt)
95
276k
{
96
276k
  const char *p;
97
1.93M
  for (p = fmt; *p; p++) {
98
1.66M
    if (*p != '%')
99
1.54M
      continue;
100
120k
    if (*++p == '%')
101
0
      continue;
102
    // Skip uninteresting.
103
127k
    while (strchr("#0.'+- ", *p) != NULL)
104
6.95k
      p++;
105
120k
    if (*p == '*') {
106
0
      if (msg)
107
0
        snprintf(msg, mlen, "* not allowed in format");
108
0
      return -1;
109
0
    }
110
111
120k
    if (!file_checkfield(msg, mlen, "width", &p))
112
0
      return -1;
113
114
120k
    if (*p == '.') {
115
1.92k
      p++;
116
1.92k
      if (!file_checkfield(msg, mlen, "precision", &p))
117
0
        return -1;
118
1.92k
    }
119
120
120k
    if (!isalpha((unsigned char)*p)) {
121
0
      if (msg)
122
0
        snprintf(msg, mlen, "bad format char: %c", *p);
123
0
      return -1;
124
0
    }
125
120k
  }
126
276k
  return 0;
127
276k
}
128
129
/*
130
 * Like printf, only we append to a buffer.
131
 */
132
file_protected int
133
file_vprintf(struct magic_set *ms, const char *fmt, va_list ap)
134
288k
{
135
288k
  int len;
136
288k
  char *buf, *newstr;
137
288k
  char tbuf[1024];
138
139
288k
  if (ms->event_flags & EVENT_HAD_ERR)
140
11.8k
    return 0;
141
142
276k
  if (file_checkfmt(tbuf, sizeof(tbuf), fmt)) {
143
0
    file_clearbuf(ms);
144
0
    file_error(ms, 0, "Bad magic format `%s' (%s)", fmt, tbuf);
145
0
    return -1;
146
0
  }
147
148
276k
  len = vasprintf(&buf, fmt, ap);
149
276k
  if (len < 0 || (size_t)len > 1024 || len + ms->o.blen > 1024 * 1024) {
150
95
    size_t blen = ms->o.blen;
151
95
    free(buf);
152
95
    file_clearbuf(ms);
153
95
    file_error(ms, 0, "Output buffer space exceeded %d+%"
154
95
        SIZE_T_FORMAT "u", len, blen);
155
95
    return -1;
156
95
  }
157
158
276k
  if (ms->o.buf != NULL) {
159
251k
    len = asprintf(&newstr, "%s%s", ms->o.buf, buf);
160
251k
    free(buf);
161
251k
    if (len < 0)
162
0
      goto out;
163
251k
    free(ms->o.buf);
164
251k
    buf = newstr;
165
251k
  }
166
276k
  ms->o.buf = buf;
167
276k
  ms->o.blen = len;
168
276k
  return 0;
169
0
out:
170
0
  file_clearbuf(ms);
171
0
  file_error(ms, errno, "vasprintf failed");
172
0
  return -1;
173
276k
}
174
175
file_protected int
176
file_printf(struct magic_set *ms, const char *fmt, ...)
177
288k
{
178
288k
  int rv;
179
288k
  va_list ap;
180
181
288k
  va_start(ap, fmt);
182
288k
  rv = file_vprintf(ms, fmt, ap);
183
288k
  va_end(ap);
184
288k
  return rv;
185
288k
}
186
187
/*
188
 * error - print best error message possible
189
 */
190
/*VARARGS*/
191
__attribute__((__format__(__printf__, 3, 0)))
192
file_private void
193
file_error_core(struct magic_set *ms, int error, const char *f, va_list va,
194
    size_t lineno)
195
848
{
196
  /* Only the first error is ok */
197
848
  if (ms->event_flags & EVENT_HAD_ERR)
198
663
    return;
199
185
  if (lineno != 0) {
200
0
    file_clearbuf(ms);
201
0
    (void)file_printf(ms, "line %" SIZE_T_FORMAT "u:", lineno);
202
0
  }
203
185
  if (ms->o.buf && *ms->o.buf)
204
4
    (void)file_printf(ms, " ");
205
185
  (void)file_vprintf(ms, f, va);
206
185
  if (error > 0)
207
0
    (void)file_printf(ms, " (%s)", strerror(error));
208
185
  ms->event_flags |= EVENT_HAD_ERR;
209
185
  ms->error = error;
210
185
}
211
212
/*VARARGS*/
213
file_protected void
214
file_error(struct magic_set *ms, int error, const char *f, ...)
215
848
{
216
848
  va_list va;
217
848
  va_start(va, f);
218
848
  file_error_core(ms, error, f, va, 0);
219
848
  va_end(va);
220
848
}
221
222
/*
223
 * Print an error with magic line number.
224
 */
225
/*VARARGS*/
226
file_protected void
227
file_magerror(struct magic_set *ms, const char *f, ...)
228
0
{
229
0
  va_list va;
230
0
  va_start(va, f);
231
0
  file_error_core(ms, 0, f, va, ms->line);
232
0
  va_end(va);
233
0
}
234
235
file_protected void
236
file_oomem(struct magic_set *ms, size_t len)
237
0
{
238
0
  file_error(ms, errno, "cannot allocate %" SIZE_T_FORMAT "u bytes",
239
0
      len);
240
0
}
241
242
file_protected void
243
file_badseek(struct magic_set *ms)
244
0
{
245
0
  file_error(ms, errno, "error seeking");
246
0
}
247
248
file_protected void
249
file_badread(struct magic_set *ms)
250
0
{
251
0
  file_error(ms, errno, "error reading");
252
0
}
253
254
#ifndef COMPILE_ONLY
255
77.2k
#define FILE_SEPARATOR "\n- "
256
257
file_protected int
258
file_separator(struct magic_set *ms)
259
46.3k
{
260
46.3k
  return file_printf(ms, FILE_SEPARATOR);
261
46.3k
}
262
263
static void
264
trim_separator(struct magic_set *ms)
265
10.2k
{
266
10.2k
  size_t l;
267
268
10.2k
  if (ms->o.buf == NULL)
269
0
    return;
270
271
10.2k
  l = strlen(ms->o.buf);
272
10.2k
  if (l < sizeof(FILE_SEPARATOR))
273
0
    return;
274
275
10.2k
  l -= sizeof(FILE_SEPARATOR) - 1;
276
10.2k
  if (strcmp(ms->o.buf + l, FILE_SEPARATOR) != 0)
277
10.2k
    return;
278
279
0
  ms->o.buf[l] = '\0';
280
0
}
281
282
static int
283
checkdone(struct magic_set *ms, int *rv)
284
9.24k
{
285
9.24k
  if ((ms->flags & MAGIC_CONTINUE) == 0)
286
0
    return 1;
287
9.24k
  if (file_separator(ms) == -1)
288
0
    *rv = -1;
289
9.24k
  return 0;
290
9.24k
}
291
292
file_protected int
293
file_default(struct magic_set *ms, size_t nb)
294
8.12k
{
295
8.12k
  if (ms->flags & MAGIC_MIME) {
296
0
    if ((ms->flags & MAGIC_MIME_TYPE) &&
297
0
        file_printf(ms, "application/%s",
298
0
      nb ? "octet-stream" : "x-empty") == -1)
299
0
      return -1;
300
0
    return 1;
301
0
  }
302
8.12k
  if (ms->flags & MAGIC_APPLE) {
303
0
    if (file_printf(ms, "UNKNUNKN") == -1)
304
0
      return -1;
305
0
    return 1;
306
0
  }
307
8.12k
  if (ms->flags & MAGIC_EXTENSION) {
308
0
    if (file_printf(ms, "???") == -1)
309
0
      return -1;
310
0
    return 1;
311
0
  }
312
8.12k
  return 0;
313
8.12k
}
314
315
/*
316
 * The magic detection functions return:
317
 *   1: found
318
 *   0: not found
319
 *  -1: error
320
 */
321
/*ARGSUSED*/
322
file_protected int
323
file_buffer(struct magic_set *ms, int fd, struct stat *st,
324
    const char *inname __attribute__ ((__unused__)),
325
    const void *buf, size_t nb)
326
12.7k
{
327
12.7k
  int m = 0, rv = 0, looks_text = 0;
328
12.7k
  const char *code = NULL;
329
12.7k
  const char *code_mime = "binary";
330
12.7k
  const char *def = "data";
331
12.7k
  const char *ftype = NULL;
332
12.7k
  char *rbuf = NULL;
333
12.7k
  struct buffer b;
334
335
12.7k
  buffer_init(&b, fd, st, buf, nb);
336
12.7k
  ms->mode = b.st.st_mode;
337
338
12.7k
  if (nb == 0) {
339
15
    def = "empty";
340
15
    goto simple;
341
12.7k
  } else if (nb == 1) {
342
4
    def = "very short file (no magic)";
343
4
    goto simple;
344
4
  }
345
346
12.7k
  if ((ms->flags & MAGIC_NO_CHECK_ENCODING) == 0) {
347
12.7k
    looks_text = file_encoding(ms, &b, NULL, 0,
348
12.7k
        &code, &code_mime, &ftype);
349
12.7k
  }
350
351
#ifdef __EMX__
352
  if ((ms->flags & MAGIC_NO_CHECK_APPTYPE) == 0 && inname) {
353
    m = file_os2_apptype(ms, inname, &b);
354
    if ((ms->flags & MAGIC_DEBUG) != 0)
355
      (void)fprintf(stderr, "[try os2_apptype %d]\n", m);
356
    switch (m) {
357
    case -1:
358
      return -1;
359
    case 0:
360
      break;
361
    default:
362
      return 1;
363
    }
364
  }
365
#endif
366
12.7k
#if HAVE_FORK
367
  /* try compression stuff */
368
12.7k
  if ((ms->flags & MAGIC_NO_CHECK_COMPRESS) == 0) {
369
12.7k
    m = file_zmagic(ms, &b, inname);
370
12.7k
    if ((ms->flags & MAGIC_DEBUG) != 0)
371
0
      (void)fprintf(stderr, "[try zmagic %d]\n", m);
372
12.7k
    if (m) {
373
2.47k
      goto done_encoding;
374
2.47k
    }
375
12.7k
  }
376
10.2k
#endif
377
  /* Check if we have a tar file */
378
10.2k
  if ((ms->flags & MAGIC_NO_CHECK_TAR) == 0) {
379
10.2k
    m = file_is_tar(ms, &b);
380
10.2k
    if ((ms->flags & MAGIC_DEBUG) != 0)
381
0
      (void)fprintf(stderr, "[try tar %d]\n", m);
382
10.2k
    if (m) {
383
16
      if (checkdone(ms, &rv))
384
0
        goto done;
385
16
    }
386
10.2k
  }
387
388
  /* Check if we have a JSON file */
389
10.2k
  if ((ms->flags & MAGIC_NO_CHECK_JSON) == 0) {
390
10.2k
    m = file_is_json(ms, &b);
391
10.2k
    if ((ms->flags & MAGIC_DEBUG) != 0)
392
0
      (void)fprintf(stderr, "[try json %d]\n", m);
393
10.2k
    if (m) {
394
38
      if (checkdone(ms, &rv))
395
0
        goto done;
396
38
    }
397
10.2k
  }
398
399
  /* Check if we have a CSV file */
400
10.2k
  if ((ms->flags & MAGIC_NO_CHECK_CSV) == 0) {
401
10.2k
    m = file_is_csv(ms, &b, looks_text, code);
402
10.2k
    if ((ms->flags & MAGIC_DEBUG) != 0)
403
0
      (void)fprintf(stderr, "[try csv %d]\n", m);
404
10.2k
    if (m) {
405
8
      if (checkdone(ms, &rv))
406
0
        goto done;
407
8
    }
408
10.2k
  }
409
410
  /* Check if we have a SIMH tape file */
411
10.2k
  if ((ms->flags & MAGIC_NO_CHECK_SIMH) == 0) {
412
10.2k
    m = file_is_simh(ms, &b);
413
10.2k
    if ((ms->flags & MAGIC_DEBUG) != 0)
414
0
      (void)fprintf(stderr, "[try simh %d]\n", m);
415
10.2k
    if (m) {
416
34
      if (checkdone(ms, &rv))
417
0
        goto done;
418
34
    }
419
10.2k
  }
420
421
  /* Check if we have a CDF file */
422
10.2k
  if ((ms->flags & MAGIC_NO_CHECK_CDF) == 0) {
423
10.2k
    m = file_trycdf(ms, &b);
424
10.2k
    if ((ms->flags & MAGIC_DEBUG) != 0)
425
0
      (void)fprintf(stderr, "[try cdf %d]\n", m);
426
10.2k
    if (m) {
427
1.86k
      if (checkdone(ms, &rv))
428
0
        goto done;
429
1.86k
    }
430
10.2k
  }
431
10.2k
#ifdef BUILTIN_ELF
432
10.2k
  if ((ms->flags & MAGIC_NO_CHECK_ELF) == 0 && nb > 5 && fd != -1) {
433
0
    file_pushbuf_t *pb;
434
    /*
435
     * We matched something in the file, so this
436
     * *might* be an ELF file, and the file is at
437
     * least 5 bytes long, so if it's an ELF file
438
     * it has at least one byte past the ELF magic
439
     * number - try extracting information from the
440
     * ELF headers that cannot easily be  extracted
441
     * with rules in the magic file. We we don't
442
     * print the information yet.
443
     */
444
0
    if ((pb = file_push_buffer(ms)) == NULL)
445
0
      return -1;
446
447
0
    rv = file_tryelf(ms, &b);
448
0
    rbuf = file_pop_buffer(ms, pb);
449
0
    if (rv == -1) {
450
0
      free(rbuf);
451
0
      rbuf = NULL;
452
0
    }
453
0
    if ((ms->flags & MAGIC_DEBUG) != 0)
454
0
      (void)fprintf(stderr, "[try elf %d]\n", m);
455
0
  }
456
10.2k
#endif
457
458
  /* try soft magic tests */
459
10.2k
  if ((ms->flags & MAGIC_NO_CHECK_SOFT) == 0) {
460
10.2k
    m = file_softmagic(ms, &b, NULL, NULL, BINTEST, looks_text);
461
10.2k
    if ((ms->flags & MAGIC_DEBUG) != 0)
462
0
      (void)fprintf(stderr, "[try softmagic %d]\n", m);
463
10.2k
    if (m == 1 && rbuf) {
464
0
      if (file_printf(ms, "%s", rbuf) == -1)
465
0
        goto done;
466
0
    }
467
10.2k
    if (m) {
468
7.28k
      if (checkdone(ms, &rv))
469
0
        goto done;
470
7.28k
    }
471
10.2k
  }
472
473
  /* try text properties */
474
10.2k
  if ((ms->flags & MAGIC_NO_CHECK_TEXT) == 0) {
475
476
10.2k
    m = file_ascmagic(ms, &b, looks_text);
477
10.2k
    if ((ms->flags & MAGIC_DEBUG) != 0)
478
0
      (void)fprintf(stderr, "[try ascmagic %d]\n", m);
479
10.2k
    if (m) {
480
2.15k
      goto done;
481
2.15k
    }
482
10.2k
  }
483
484
8.12k
simple:
485
  /* give up */
486
8.12k
  if (m == 0) {
487
8.12k
    m = 1;
488
8.12k
    rv = file_default(ms, nb);
489
8.12k
    if (rv == 0)
490
8.12k
      if (file_printf(ms, "%s", def) == -1)
491
0
        rv = -1;
492
8.12k
  }
493
10.2k
 done:
494
10.2k
  trim_separator(ms);
495
10.2k
  if ((ms->flags & MAGIC_MIME_ENCODING) != 0) {
496
0
    if (ms->flags & MAGIC_MIME_TYPE)
497
0
      if (file_printf(ms, "; charset=") == -1)
498
0
        rv = -1;
499
0
    if (file_printf(ms, "%s", code_mime) == -1)
500
0
      rv = -1;
501
0
  }
502
10.2k
#if HAVE_FORK
503
12.7k
 done_encoding:
504
12.7k
#endif
505
12.7k
  free(rbuf);
506
12.7k
  buffer_fini(&b);
507
12.7k
  if (rv)
508
0
    return rv;
509
510
12.7k
  return m;
511
12.7k
}
512
#endif
513
514
file_protected int
515
file_reset(struct magic_set *ms, int checkloaded)
516
7.48k
{
517
7.48k
  if (checkloaded && ms->mlist[0] == NULL) {
518
0
    file_error(ms, 0, "no magic files loaded");
519
0
    return -1;
520
0
  }
521
7.48k
  file_clearbuf(ms);
522
7.48k
  if (ms->o.pbuf) {
523
7.30k
    free(ms->o.pbuf);
524
7.30k
    ms->o.pbuf = NULL;
525
7.30k
  }
526
7.48k
  ms->event_flags &= ~EVENT_HAD_ERR;
527
7.48k
  ms->error = -1;
528
7.48k
  return 0;
529
7.48k
}
530
531
#define OCTALIFY(n, o)  \
532
  /*LINTED*/ \
533
31.4k
  (void)(*(n)++ = '\\', \
534
31.4k
  *(n)++ = ((CAST(uint32_t, *(o)) >> 6) & 3) + '0', \
535
31.4k
  *(n)++ = ((CAST(uint32_t, *(o)) >> 3) & 7) + '0', \
536
31.4k
  *(n)++ = ((CAST(uint32_t, *(o)) >> 0) & 7) + '0', \
537
31.4k
  (o)++)
538
539
file_protected const char *
540
file_getbuffer(struct magic_set *ms)
541
7.46k
{
542
7.46k
  char *pbuf, *op, *np;
543
7.46k
  size_t psize, len;
544
545
7.46k
  if (ms->event_flags & EVENT_HAD_ERR)
546
168
    return NULL;
547
548
7.30k
  if (ms->flags & MAGIC_RAW)
549
0
    return ms->o.buf;
550
551
7.30k
  if (ms->o.buf == NULL)
552
0
    return NULL;
553
554
  /* * 4 is for octal representation, + 1 is for NUL */
555
7.30k
  len = strlen(ms->o.buf);
556
7.30k
  if (len > (SIZE_MAX - 1) / 4) {
557
0
    file_oomem(ms, len);
558
0
    return NULL;
559
0
  }
560
7.30k
  psize = len * 4 + 1;
561
7.30k
  if ((pbuf = CAST(char *, realloc(ms->o.pbuf, psize))) == NULL) {
562
0
    file_oomem(ms, psize);
563
0
    return NULL;
564
0
  }
565
7.30k
  ms->o.pbuf = pbuf;
566
567
7.30k
#if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
568
7.30k
  {
569
7.30k
    mbstate_t state;
570
7.30k
    wchar_t nextchar;
571
7.30k
    int mb_conv = 1;
572
7.30k
    size_t bytesconsumed;
573
7.30k
    char *eop;
574
7.30k
    (void)memset(&state, 0, sizeof(mbstate_t));
575
576
7.30k
    np = ms->o.pbuf;
577
7.30k
    op = ms->o.buf;
578
7.30k
    eop = op + len;
579
580
1.46M
    while (op < eop) {
581
1.45M
      bytesconsumed = mbrtowc(&nextchar, op,
582
1.45M
          CAST(size_t, eop - op), &state);
583
1.45M
      if (bytesconsumed == CAST(size_t, -1) ||
584
1.45M
          bytesconsumed == CAST(size_t, -2)) {
585
27
        mb_conv = 0;
586
27
        break;
587
27
      }
588
589
1.45M
      if (iswprint(nextchar)) {
590
1.42M
        (void)memcpy(np, op, bytesconsumed);
591
1.42M
        op += bytesconsumed;
592
1.42M
        np += bytesconsumed;
593
1.42M
      } else {
594
61.1k
        while (bytesconsumed-- > 0)
595
30.5k
          OCTALIFY(np, op);
596
30.5k
      }
597
1.45M
    }
598
7.30k
    *np = '\0';
599
600
    /* Parsing succeeded as a multi-byte sequence */
601
7.30k
    if (mb_conv != 0)
602
7.27k
      return ms->o.pbuf;
603
7.30k
  }
604
27
#endif
605
606
23.1k
  for (np = ms->o.pbuf, op = ms->o.buf; *op;) {
607
23.1k
    if (isprint(CAST(unsigned char, *op))) {
608
22.2k
      *np++ = *op++;
609
22.2k
    } else {
610
853
      OCTALIFY(np, op);
611
853
    }
612
23.1k
  }
613
27
  *np = '\0';
614
27
  return ms->o.pbuf;
615
7.30k
}
616
617
file_protected int
618
file_check_mem(struct magic_set *ms, unsigned int level)
619
700k
{
620
700k
  size_t len;
621
622
700k
  if (level >= ms->c.len) {
623
1
    len = (ms->c.len = 20 + level) * sizeof(*ms->c.li);
624
1
    ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ?
625
1
        malloc(len) :
626
1
        realloc(ms->c.li, len));
627
1
    if (ms->c.li == NULL) {
628
0
      file_oomem(ms, len);
629
0
      return -1;
630
0
    }
631
1
  }
632
700k
  ms->c.li[level].got_match = 0;
633
700k
#ifdef ENABLE_CONDITIONALS
634
700k
  ms->c.li[level].last_match = 0;
635
700k
  ms->c.li[level].last_cond = COND_NONE;
636
700k
#endif /* ENABLE_CONDITIONALS */
637
700k
  return 0;
638
700k
}
639
640
file_protected size_t
641
file_printedlen(const struct magic_set *ms)
642
2.15k
{
643
2.15k
  return ms->o.blen;
644
2.15k
}
645
646
file_protected int
647
file_replace(struct magic_set *ms, const char *pat, const char *rep)
648
1.37k
{
649
1.37k
  file_regex_t rx;
650
1.37k
  int rc, rv = -1;
651
652
1.37k
  rc = file_regcomp(ms, &rx, pat, REG_EXTENDED);
653
1.37k
  if (rc == 0) {
654
1.37k
    regmatch_t rm;
655
1.37k
    int nm = 0;
656
1.45k
    while (file_regexec(ms, &rx, ms->o.buf, 1, &rm, 0) == 0) {
657
88
      ms->o.buf[rm.rm_so] = '\0';
658
88
      if (file_printf(ms, "%s%s", rep,
659
88
          rm.rm_eo != 0 ? ms->o.buf + rm.rm_eo : "") == -1)
660
0
        goto out;
661
88
      nm++;
662
88
    }
663
1.37k
    rv = nm;
664
1.37k
  }
665
1.37k
out:
666
1.37k
  file_regfree(&rx);
667
1.37k
  return rv;
668
1.37k
}
669
670
file_private int
671
check_regex(struct magic_set *ms, const char *pat)
672
26.2k
{
673
26.2k
  char sbuf[512];
674
26.2k
  unsigned char oc = '\0';
675
26.2k
  const char *p;
676
26.2k
  unsigned long l;
677
678
317k
  for (p = pat; *p; p++) {
679
290k
    unsigned char c = *p;
680
    // Avoid repetition
681
290k
    if (c == oc && strchr("?*+{", c) != NULL) {
682
0
      size_t len = strlen(pat);
683
0
      file_magwarn(ms,
684
0
          "repetition-operator operand `%c' "
685
0
          "invalid in regex `%s'", c,
686
0
          file_printable(ms, sbuf, sizeof(sbuf), pat, len));
687
0
      return -1;
688
0
    }
689
290k
    if (c == '{') {
690
65
      char *ep, *eep;
691
65
      errno = 0;
692
65
      l = strtoul(p + 1, &ep, 10);
693
65
      if (ep != p + 1 && l > 1000)
694
0
        goto bounds;
695
696
65
      if (*ep == ',') {
697
27
        l = strtoul(ep + 1, &eep, 10);
698
27
        if (eep != ep + 1 && l > 1000)
699
0
          goto bounds;
700
27
      }
701
65
    }
702
290k
    oc = c;
703
290k
    if (isprint(c) || isspace(c) || c == '\b'
704
290k
        || c == 0x8a) // XXX: apple magic fixme
705
290k
      continue;
706
0
    size_t len = strlen(pat);
707
0
    file_magwarn(ms,
708
0
        "non-ascii characters in regex \\%#o `%s'",
709
0
        c, file_printable(ms, sbuf, sizeof(sbuf), pat, len));
710
0
    return -1;
711
290k
  }
712
26.2k
  return 0;
713
0
bounds:
714
0
  file_magwarn(ms, "bounds too large %ld in regex `%s'", l, pat);
715
0
  return -1;
716
26.2k
}
717
718
file_protected int
719
file_regcomp(struct magic_set *ms file_locale_used, file_regex_t *rx,
720
    const char *pat, int flags)
721
26.2k
{
722
26.2k
  if (check_regex(ms, pat) == -1)
723
0
    return -1;
724
725
26.2k
#ifdef USE_C_LOCALE
726
26.2k
  locale_t old = uselocale(ms->c_lc_ctype);
727
26.2k
  assert(old != NULL);
728
#else
729
  char old[1024];
730
  strlcpy(old, setlocale(LC_CTYPE, NULL), sizeof(old));
731
  (void)setlocale(LC_CTYPE, "C");
732
#endif
733
26.2k
  int rc;
734
26.2k
  rc = regcomp(rx, pat, flags);
735
736
26.2k
#ifdef USE_C_LOCALE
737
26.2k
  uselocale(old);
738
#else
739
  (void)setlocale(LC_CTYPE, old);
740
#endif
741
26.2k
  if (rc > 0 && (ms->flags & MAGIC_CHECK)) {
742
0
    char errmsg[512], buf[512];
743
744
0
    (void)regerror(rc, rx, errmsg, sizeof(errmsg));
745
0
    file_magerror(ms, "regex error %d for `%s', (%s)", rc, 
746
0
        file_printable(ms, buf, sizeof(buf), pat, strlen(pat)),
747
0
        errmsg);
748
0
  }
749
26.2k
  return rc;
750
26.2k
}
751
752
/*ARGSUSED*/
753
file_protected int
754
file_regexec(struct magic_set *ms file_locale_used, file_regex_t *rx,
755
    const char *str, size_t nmatch, regmatch_t* pmatch, int eflags)
756
240k
{
757
240k
#ifdef USE_C_LOCALE
758
240k
  locale_t old = uselocale(ms->c_lc_ctype);
759
240k
  assert(old != NULL);
760
#else
761
  char old[1024];
762
  strlcpy(old, setlocale(LC_CTYPE, NULL), sizeof(old));
763
  (void)setlocale(LC_CTYPE, "C");
764
#endif
765
240k
  int rc;
766
  /* XXX: force initialization because glibc does not always do this */
767
240k
  if (nmatch != 0)
768
215k
    memset(pmatch, 0, nmatch * sizeof(*pmatch));
769
240k
  rc = regexec(rx, str, nmatch, pmatch, eflags);
770
240k
#ifdef USE_C_LOCALE
771
240k
  uselocale(old);
772
#else
773
  (void)setlocale(LC_CTYPE, old);
774
#endif
775
240k
  return rc;
776
240k
}
777
778
file_protected void
779
file_regfree(file_regex_t *rx)
780
26.0k
{
781
26.0k
  regfree(rx);
782
26.0k
}
783
784
file_protected file_pushbuf_t *
785
file_push_buffer(struct magic_set *ms)
786
21.2k
{
787
21.2k
  file_pushbuf_t *pb;
788
789
21.2k
  if (ms->event_flags & EVENT_HAD_ERR)
790
1.15k
    return NULL;
791
792
20.0k
  if ((pb = (CAST(file_pushbuf_t *, malloc(sizeof(*pb))))) == NULL)
793
0
    return NULL;
794
795
20.0k
  pb->buf = ms->o.buf;
796
20.0k
  pb->blen = ms->o.blen;
797
20.0k
  pb->offset = ms->offset;
798
799
20.0k
  ms->o.buf = NULL;
800
20.0k
  ms->o.blen = 0;
801
20.0k
  ms->offset = 0;
802
803
20.0k
  return pb;
804
20.0k
}
805
806
file_protected char *
807
file_pop_buffer(struct magic_set *ms, file_pushbuf_t *pb)
808
20.0k
{
809
20.0k
  char *rbuf;
810
811
20.0k
  if (ms->event_flags & EVENT_HAD_ERR) {
812
1.27k
    free(pb->buf);
813
1.27k
    free(pb);
814
1.27k
    return NULL;
815
1.27k
  }
816
817
18.7k
  rbuf = ms->o.buf;
818
819
18.7k
  ms->o.buf = pb->buf;
820
18.7k
  ms->o.blen = pb->blen;
821
18.7k
  ms->offset = pb->offset;
822
823
18.7k
  free(pb);
824
18.7k
  return rbuf;
825
20.0k
}
826
827
/*
828
 * convert string to ascii printable format.
829
 */
830
file_protected char *
831
file_printable(struct magic_set *ms, char *buf, size_t bufsiz,
832
    const char *str, size_t slen)
833
38.2k
{
834
38.2k
  char *ptr, *eptr = buf + bufsiz - 1;
835
38.2k
  const unsigned char *s = RCAST(const unsigned char *, str);
836
38.2k
  const unsigned char *es = s + slen;
837
838
235k
  for (ptr = buf;  ptr < eptr && s < es && *s; s++) {
839
196k
    if ((ms->flags & MAGIC_RAW) != 0 || isprint(*s)) {
840
115k
      *ptr++ = *s;
841
115k
      continue;
842
115k
    }
843
81.3k
    if (ptr >= eptr - 3)
844
67
      break;
845
81.2k
    *ptr++ = '\\';
846
81.2k
    *ptr++ = ((CAST(unsigned int, *s) >> 6) & 7) + '0';
847
81.2k
    *ptr++ = ((CAST(unsigned int, *s) >> 3) & 7) + '0';
848
81.2k
    *ptr++ = ((CAST(unsigned int, *s) >> 0) & 7) + '0';
849
81.2k
  }
850
38.2k
  *ptr = '\0';
851
38.2k
  return buf;
852
38.2k
}
853
854
struct guid {
855
  uint32_t data1;
856
  uint16_t data2;
857
  uint16_t data3;
858
  uint8_t data4[8];
859
};
860
861
file_protected int
862
file_parse_guid(const char *s, uint64_t *guid)
863
0
{
864
0
  struct guid *g = CAST(struct guid *, CAST(void *, guid));
865
0
#ifndef WIN32
866
0
  return sscanf(s,
867
0
      "%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx",
868
0
      &g->data1, &g->data2, &g->data3, &g->data4[0], &g->data4[1],
869
0
      &g->data4[2], &g->data4[3], &g->data4[4], &g->data4[5],
870
0
      &g->data4[6], &g->data4[7]) == 11 ? 0 : -1;
871
#else
872
  /* MS-Windows runtime doesn't support %hhx, except under
873
     non-default __USE_MINGW_ANSI_STDIO.  */
874
  uint16_t data16[8];
875
  int rv = sscanf(s, "%8x-%4hx-%4hx-%2hx%2hx-%2hx%2hx%2hx%2hx%2hx%2hx",
876
      &g->data1, &g->data2, &g->data3, &data16[0], &data16[1],
877
      &data16[2], &data16[3], &data16[4], &data16[5],
878
      &data16[6], &data16[7]) == 11 ? 0 : -1;
879
  int i;
880
  for (i = 0; i < 8; i++)
881
      g->data4[i] = data16[i];
882
  return rv;
883
#endif
884
0
}
885
886
file_protected int
887
file_print_guid(char *str, size_t len, const uint64_t *guid)
888
313
{
889
313
  const struct guid *g = CAST(const struct guid *,
890
313
      CAST(const void *, guid));
891
892
313
#ifndef WIN32
893
313
  return snprintf(str, len, "%.8X-%.4hX-%.4hX-%.2hhX%.2hhX-"
894
313
      "%.2hhX%.2hhX%.2hhX%.2hhX%.2hhX%.2hhX",
895
313
      g->data1, g->data2, g->data3, g->data4[0], g->data4[1],
896
313
      g->data4[2], g->data4[3], g->data4[4], g->data4[5],
897
313
      g->data4[6], g->data4[7]);
898
#else
899
  return snprintf(str, len, "%.8X-%.4hX-%.4hX-%.2hX%.2hX-"
900
      "%.2hX%.2hX%.2hX%.2hX%.2hX%.2hX",
901
      g->data1, g->data2, g->data3, g->data4[0], g->data4[1],
902
      g->data4[2], g->data4[3], g->data4[4], g->data4[5],
903
      g->data4[6], g->data4[7]);
904
#endif
905
313
}
906
907
file_protected int
908
file_pipe_closexec(int *fds)
909
8.13k
{
910
#ifdef __MINGW32__
911
  return 0;
912
#elif defined(HAVE_PIPE2)
913
8.13k
  return pipe2(fds, O_CLOEXEC);
914
#else
915
  if (pipe(fds) == -1)
916
    return -1;
917
# ifdef F_SETFD
918
  (void)fcntl(fds[0], F_SETFD, FD_CLOEXEC);
919
  (void)fcntl(fds[1], F_SETFD, FD_CLOEXEC);
920
# endif
921
  return 0;
922
#endif
923
8.13k
}
924
925
file_protected int
926
8.13k
file_clear_closexec(int fd) {
927
8.13k
#ifdef F_SETFD
928
8.13k
  return fcntl(fd, F_SETFD, 0);
929
#else
930
  return 0;
931
#endif
932
8.13k
}
933
934
file_protected char *
935
file_strtrim(char *str)
936
290
{
937
290
  char *last;
938
939
290
  while (isspace(CAST(unsigned char, *str)))
940
346
    str++;
941
290
  last = str;
942
2.91k
  while (*last)
943
2.62k
    last++;
944
290
  --last;
945
290
  while (isspace(CAST(unsigned char, *last)))
946
557
    last--;
947
290
  *++last = '\0';
948
290
  return str;
949
290
}