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
30FILE_RCSID("@(#)$File: funcs.c,v 1.79 2014/12/16 20:52:49 christos Exp $")
31#endif  /* lint */
32
33#include "magic.h"
34#include <stdarg.h>
35#include <stdlib.h>
36#include <string.h>
37#include <ctype.h>
38#if defined(HAVE_WCHAR_H)
39#include <wchar.h>
40#endif
41#if defined(HAVE_WCTYPE_H)
42#include <wctype.h>
43#endif
44#if defined(HAVE_LOCALE_H)
45#include <locale.h>
46#endif
47
48#ifndef SIZE_MAX
49#define SIZE_MAX    ((size_t)~0)
50#endif
51
52#include "php.h"
53#include "main/php_network.h"
54
55#ifndef PREG_OFFSET_CAPTURE
56# define PREG_OFFSET_CAPTURE                 (1<<8)
57#endif
58
59extern public void convert_libmagic_pattern(zval *pattern, char *val, int len, int options);
60
61protected int
62file_printf(struct magic_set *ms, const char *fmt, ...)
63{
64    int rv;
65    va_list ap;
66    int len;
67    char *buf = NULL, *newstr;
68
69    va_start(ap, fmt);
70    len = vspprintf(&buf, 0, fmt, ap);
71    va_end(ap);
72
73    if (ms->o.buf != NULL) {
74        len = spprintf(&newstr, 0, "%s%s", ms->o.buf, (buf ? buf : ""));
75        if (buf) {
76            efree(buf);
77        }
78        efree(ms->o.buf);
79        ms->o.buf = newstr;
80    } else {
81        ms->o.buf = buf;
82    }
83    return 0;
84}
85
86/*
87 * error - print best error message possible
88 */
89/*VARARGS*/
90private void
91file_error_core(struct magic_set *ms, int error, const char *f, va_list va,
92    size_t lineno)
93{
94    char *buf = NULL;
95
96    /* Only the first error is ok */
97    if (ms->event_flags & EVENT_HAD_ERR)
98        return;
99    if (lineno != 0) {
100        efree(ms->o.buf);
101        ms->o.buf = NULL;
102        file_printf(ms, "line %" SIZE_T_FORMAT "u: ", lineno);
103    }
104
105    vspprintf(&buf, 0, f, va);
106    va_end(va);
107
108    if (error > 0) {
109        file_printf(ms, "%s (%s)", (*buf ? buf : ""), strerror(error));
110    } else if (*buf) {
111        file_printf(ms, "%s", buf);
112    }
113
114    if (buf) {
115        efree(buf);
116    }
117
118    ms->event_flags |= EVENT_HAD_ERR;
119    ms->error = error;
120}
121
122/*VARARGS*/
123protected void
124file_error(struct magic_set *ms, int error, const char *f, ...)
125{
126    va_list va;
127    va_start(va, f);
128    file_error_core(ms, error, f, va, 0);
129    va_end(va);
130}
131
132/*
133 * Print an error with magic line number.
134 */
135/*VARARGS*/
136protected void
137file_magerror(struct magic_set *ms, const char *f, ...)
138{
139    va_list va;
140    va_start(va, f);
141    file_error_core(ms, 0, f, va, ms->line);
142    va_end(va);
143}
144
145protected void
146file_oomem(struct magic_set *ms, size_t len)
147{
148    file_error(ms, errno, "cannot allocate %" SIZE_T_FORMAT "u bytes",
149        len);
150}
151
152protected void
153file_badseek(struct magic_set *ms)
154{
155    file_error(ms, errno, "error seeking");
156}
157
158protected void
159file_badread(struct magic_set *ms)
160{
161    file_error(ms, errno, "error reading");
162}
163
164protected int
165file_buffer(struct magic_set *ms, php_stream *stream, const char *inname, const void *buf,
166    size_t nb)
167{
168    int m = 0, rv = 0, looks_text = 0;
169    int mime = ms->flags & MAGIC_MIME;
170    const unsigned char *ubuf = CAST(const unsigned char *, buf);
171    unichar *u8buf = NULL;
172    size_t ulen;
173    const char *code = NULL;
174    const char *code_mime = "binary";
175    const char *type = "application/octet-stream";
176    const char *def = "data";
177    const char *ftype = NULL;
178
179    if (nb == 0) {
180        def = "empty";
181        type = "application/x-empty";
182        goto simple;
183    } else if (nb == 1) {
184        def = "very short file (no magic)";
185        goto simple;
186    }
187
188    if ((ms->flags & MAGIC_NO_CHECK_ENCODING) == 0) {
189        looks_text = file_encoding(ms, ubuf, nb, &u8buf, &ulen,
190            &code, &code_mime, &ftype);
191    }
192
193#ifdef __EMX__
194    if ((ms->flags & MAGIC_NO_CHECK_APPTYPE) == 0 && inname) {
195        switch (file_os2_apptype(ms, inname, buf, nb)) {
196        case -1:
197            return -1;
198        case 0:
199            break;
200        default:
201            return 1;
202        }
203    }
204#endif
205
206#if PHP_FILEINFO_UNCOMPRESS
207    if ((ms->flags & MAGIC_NO_CHECK_COMPRESS) == 0)
208        if ((m = file_zmagic(ms, stream, inname, ubuf, nb)) != 0) {
209            if ((ms->flags & MAGIC_DEBUG) != 0)
210                (void)fprintf(stderr, "zmagic %d\n", m);
211            goto done_encoding;
212        }
213#endif
214    /* Check if we have a tar file */
215    if ((ms->flags & MAGIC_NO_CHECK_TAR) == 0)
216        if ((m = file_is_tar(ms, ubuf, nb)) != 0) {
217            if ((ms->flags & MAGIC_DEBUG) != 0)
218                (void)fprintf(stderr, "tar %d\n", m);
219            goto done;
220        }
221
222    /* Check if we have a CDF file */
223    if ((ms->flags & MAGIC_NO_CHECK_CDF) == 0) {
224        php_socket_t fd;
225            if (stream && SUCCESS == php_stream_cast(stream, PHP_STREAM_AS_FD, (void **)&fd, 0)) {
226            if ((m = file_trycdf(ms, fd, ubuf, nb)) != 0) {
227                if ((ms->flags & MAGIC_DEBUG) != 0)
228                    (void)fprintf(stderr, "cdf %d\n", m);
229                goto done;
230            }
231        }
232    }
233
234    /* try soft magic tests */
235    if ((ms->flags & MAGIC_NO_CHECK_SOFT) == 0)
236        if ((m = file_softmagic(ms, ubuf, nb, 0, NULL, BINTEST,
237            looks_text)) != 0) {
238            if ((ms->flags & MAGIC_DEBUG) != 0)
239                (void)fprintf(stderr, "softmagic %d\n", m);
240#ifdef BUILTIN_ELF
241            if ((ms->flags & MAGIC_NO_CHECK_ELF) == 0 && m == 1 &&
242                nb > 5 && fd != -1) {
243                /*
244                 * We matched something in the file, so this
245                 * *might* be an ELF file, and the file is at
246                 * least 5 bytes long, so if it's an ELF file
247                 * it has at least one byte past the ELF magic
248                 * number - try extracting information from the
249                 * ELF headers that cannot easily * be
250                 * extracted with rules in the magic file.
251                 */
252                if ((m = file_tryelf(ms, fd, ubuf, nb)) != 0)
253                    if ((ms->flags & MAGIC_DEBUG) != 0)
254                        (void)fprintf(stderr,
255                            "elf %d\n", m);
256            }
257#endif
258            goto done;
259        }
260
261    /* try text properties */
262    if ((ms->flags & MAGIC_NO_CHECK_TEXT) == 0) {
263
264        if ((m = file_ascmagic(ms, ubuf, nb, looks_text)) != 0) {
265            if ((ms->flags & MAGIC_DEBUG) != 0)
266                (void)fprintf(stderr, "ascmagic %d\n", m);
267            goto done;
268        }
269    }
270
271simple:
272    /* give up */
273    m = 1;
274    if ((!mime || (mime & MAGIC_MIME_TYPE)) &&
275        file_printf(ms, "%s", mime ? type : def) == -1) {
276        rv = -1;
277    }
278 done:
279    if ((ms->flags & MAGIC_MIME_ENCODING) != 0) {
280        if (ms->flags & MAGIC_MIME_TYPE)
281            if (file_printf(ms, "; charset=") == -1)
282                rv = -1;
283        if (file_printf(ms, "%s", code_mime) == -1)
284            rv = -1;
285    }
286 done_encoding:
287    free(u8buf);
288    if (rv)
289        return rv;
290
291    return m;
292}
293
294protected int
295file_reset(struct magic_set *ms)
296{
297    if (ms->mlist[0] == NULL) {
298        file_error(ms, 0, "no magic files loaded");
299        return -1;
300    }
301    if (ms->o.buf) {
302        efree(ms->o.buf);
303        ms->o.buf = NULL;
304    }
305    if (ms->o.pbuf) {
306        efree(ms->o.pbuf);
307        ms->o.pbuf = NULL;
308    }
309    ms->event_flags &= ~EVENT_HAD_ERR;
310    ms->error = -1;
311    return 0;
312}
313
314#define OCTALIFY(n, o)  \
315    /*LINTED*/ \
316    (void)(*(n)++ = '\\', \
317    *(n)++ = (((uint32_t)*(o) >> 6) & 3) + '0', \
318    *(n)++ = (((uint32_t)*(o) >> 3) & 7) + '0', \
319    *(n)++ = (((uint32_t)*(o) >> 0) & 7) + '0', \
320    (o)++)
321
322protected const char *
323file_getbuffer(struct magic_set *ms)
324{
325    char *op, *np;
326    size_t psize, len;
327
328    if (ms->event_flags & EVENT_HAD_ERR)
329        return NULL;
330
331    if (ms->flags & MAGIC_RAW)
332        return ms->o.buf;
333
334    if (ms->o.buf == NULL)
335        return NULL;
336
337    /* * 4 is for octal representation, + 1 is for NUL */
338    len = strlen(ms->o.buf);
339    if (len > (SIZE_MAX - 1) / 4) {
340        file_oomem(ms, len);
341        return NULL;
342    }
343    psize = len * 4 + 1;
344    if ((ms->o.pbuf = CAST(char *, erealloc(ms->o.pbuf, psize))) == NULL) {
345        file_oomem(ms, psize);
346        return NULL;
347    }
348
349#if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
350    {
351        mbstate_t state;
352        wchar_t nextchar;
353        int mb_conv = 1;
354        size_t bytesconsumed;
355        char *eop;
356        (void)memset(&state, 0, sizeof(mbstate_t));
357
358        np = ms->o.pbuf;
359        op = ms->o.buf;
360        eop = op + len;
361
362        while (op < eop) {
363            bytesconsumed = mbrtowc(&nextchar, op,
364                (size_t)(eop - op), &state);
365            if (bytesconsumed == (size_t)(-1) ||
366                bytesconsumed == (size_t)(-2)) {
367                mb_conv = 0;
368                break;
369            }
370
371            if (iswprint(nextchar)) {
372                (void)memcpy(np, op, bytesconsumed);
373                op += bytesconsumed;
374                np += bytesconsumed;
375            } else {
376                while (bytesconsumed-- > 0)
377                    OCTALIFY(np, op);
378            }
379        }
380        *np = '\0';
381
382        /* Parsing succeeded as a multi-byte sequence */
383        if (mb_conv != 0)
384            return ms->o.pbuf;
385    }
386#endif
387
388    for (np = ms->o.pbuf, op = ms->o.buf; *op;) {
389        if (isprint((unsigned char)*op)) {
390            *np++ = *op++;
391        } else {
392            OCTALIFY(np, op);
393        }
394    }
395    *np = '\0';
396    return ms->o.pbuf;
397}
398
399protected int
400file_check_mem(struct magic_set *ms, unsigned int level)
401{
402    size_t len;
403
404    if (level >= ms->c.len) {
405        len = (ms->c.len += 20) * sizeof(*ms->c.li);
406        ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ?
407            emalloc(len) :
408            erealloc(ms->c.li, len));
409        if (ms->c.li == NULL) {
410            file_oomem(ms, len);
411            return -1;
412        }
413    }
414    ms->c.li[level].got_match = 0;
415#ifdef ENABLE_CONDITIONALS
416    ms->c.li[level].last_match = 0;
417    ms->c.li[level].last_cond = COND_NONE;
418#endif /* ENABLE_CONDITIONALS */
419    return 0;
420}
421
422protected size_t
423file_printedlen(const struct magic_set *ms)
424{
425    return ms->o.buf == NULL ? 0 : strlen(ms->o.buf);
426}
427
428protected int
429file_replace(struct magic_set *ms, const char *pat, const char *rep)
430{
431    zval patt;
432    int opts = 0;
433    pcre_cache_entry *pce;
434    zend_string *res;
435    zval repl;
436    int  rep_cnt = 0;
437
438    (void)setlocale(LC_CTYPE, "C");
439
440    opts |= PCRE_MULTILINE;
441    convert_libmagic_pattern(&patt, pat, strlen(pat), opts);
442    if ((pce = pcre_get_compiled_regex_cache(Z_STR(patt))) == NULL) {
443        zval_ptr_dtor(&patt);
444        rep_cnt = -1;
445        goto out;
446    }
447    zval_ptr_dtor(&patt);
448
449    ZVAL_STRING(&repl, rep);
450    res = php_pcre_replace_impl(pce, NULL, ms->o.buf, strlen(ms->o.buf), &repl, 0, -1, &rep_cnt);
451
452    zval_ptr_dtor(&repl);
453    if (NULL == res) {
454        rep_cnt = -1;
455        goto out;
456    }
457
458    strncpy(ms->o.buf, res->val, res->len);
459    ms->o.buf[res->len] = '\0';
460
461    zend_string_release(res);
462
463out:
464    (void)setlocale(LC_CTYPE, "");
465    return rep_cnt;
466}
467
468protected file_pushbuf_t *
469file_push_buffer(struct magic_set *ms)
470{
471    file_pushbuf_t *pb;
472
473    if (ms->event_flags & EVENT_HAD_ERR)
474        return NULL;
475
476    if ((pb = (CAST(file_pushbuf_t *, emalloc(sizeof(*pb))))) == NULL)
477        return NULL;
478
479    pb->buf = ms->o.buf;
480    pb->offset = ms->offset;
481
482    ms->o.buf = NULL;
483    ms->offset = 0;
484
485    return pb;
486}
487
488protected char *
489file_pop_buffer(struct magic_set *ms, file_pushbuf_t *pb)
490{
491    char *rbuf;
492
493    if (ms->event_flags & EVENT_HAD_ERR) {
494        efree(pb->buf);
495        efree(pb);
496        return NULL;
497    }
498
499    rbuf = ms->o.buf;
500
501    ms->o.buf = pb->buf;
502    ms->offset = pb->offset;
503
504    efree(pb);
505    return rbuf;
506}
507
508/*
509 * convert string to ascii printable format.
510 */
511protected char *
512file_printable(char *buf, size_t bufsiz, const char *str)
513{
514    char *ptr, *eptr;
515    const unsigned char *s = (const unsigned char *)str;
516
517    for (ptr = buf, eptr = ptr + bufsiz - 1; ptr < eptr && *s; s++) {
518        if (isprint(*s)) {
519            *ptr++ = *s;
520            continue;
521        }
522        if (ptr >= eptr - 3)
523            break;
524        *ptr++ = '\\';
525        *ptr++ = ((*s >> 6) & 7) + '0';
526        *ptr++ = ((*s >> 3) & 7) + '0';
527        *ptr++ = ((*s >> 0) & 7) + '0';
528    }
529    *ptr = '\0';
530    return buf;
531}
532
533