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.67 2014/02/12 23:20:53 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) -1)
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    va_list ap;
65    int len;
66    char *buf = NULL, *newstr;
67
68    va_start(ap, fmt);
69    len = vspprintf(&buf, 0, fmt, ap);
70    va_end(ap);
71
72    if (ms->o.buf != NULL) {
73        len = spprintf(&newstr, 0, "%s%s", ms->o.buf, (buf ? buf : ""));
74        if (buf) {
75            efree(buf);
76        }
77        efree(ms->o.buf);
78        ms->o.buf = newstr;
79    } else {
80        ms->o.buf = buf;
81    }
82    return 0;
83}
84
85/*
86 * error - print best error message possible
87 */
88/*VARARGS*/
89private void
90file_error_core(struct magic_set *ms, int error, const char *f, va_list va,
91    size_t lineno)
92{
93    char *buf = NULL;
94
95    /* Only the first error is ok */
96    if (ms->event_flags & EVENT_HAD_ERR)
97        return;
98    if (lineno != 0) {
99        efree(ms->o.buf);
100        ms->o.buf = NULL;
101        file_printf(ms, "line %" SIZE_T_FORMAT "u: ", lineno);
102    }
103
104    vspprintf(&buf, 0, f, va);
105    va_end(va);
106
107    if (error > 0) {
108        file_printf(ms, "%s (%s)", (*buf ? buf : ""), strerror(error));
109    } else if (*buf) {
110        file_printf(ms, "%s", buf);
111    }
112
113    if (buf) {
114        efree(buf);
115    }
116
117    ms->event_flags |= EVENT_HAD_ERR;
118    ms->error = error;
119}
120
121/*VARARGS*/
122protected void
123file_error(struct magic_set *ms, int error, const char *f, ...)
124{
125    va_list va;
126    va_start(va, f);
127    file_error_core(ms, error, f, va, 0);
128    va_end(va);
129}
130
131/*
132 * Print an error with magic line number.
133 */
134/*VARARGS*/
135protected void
136file_magerror(struct magic_set *ms, const char *f, ...)
137{
138    va_list va;
139    va_start(va, f);
140    file_error_core(ms, 0, f, va, ms->line);
141    va_end(va);
142}
143
144protected void
145file_oomem(struct magic_set *ms, size_t len)
146{
147    file_error(ms, errno, "cannot allocate %" SIZE_T_FORMAT "u bytes",
148        len);
149}
150
151protected void
152file_badseek(struct magic_set *ms)
153{
154    file_error(ms, errno, "error seeking");
155}
156
157protected void
158file_badread(struct magic_set *ms)
159{
160    file_error(ms, errno, "error reading");
161}
162
163protected int
164file_buffer(struct magic_set *ms, php_stream *stream, const char *inname, const void *buf,
165    size_t nb)
166{
167    int m = 0, rv = 0, looks_text = 0;
168    int mime = ms->flags & MAGIC_MIME;
169    const unsigned char *ubuf = CAST(const unsigned char *, buf);
170    unichar *u8buf = NULL;
171    size_t ulen;
172    const char *code = NULL;
173    const char *code_mime = "binary";
174    const char *type = "application/octet-stream";
175    const char *def = "data";
176
177
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, &type);
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        TSRMLS_FETCH();
226        if (stream && SUCCESS == php_stream_cast(stream, PHP_STREAM_AS_FD, (void **)&fd, 0)) {
227            if ((m = file_trycdf(ms, fd, ubuf, nb)) != 0) {
228                if ((ms->flags & MAGIC_DEBUG) != 0)
229                    (void)fprintf(stderr, "cdf %d\n", m);
230                goto done;
231            }
232        }
233    }
234
235    /* try soft magic tests */
236    if ((ms->flags & MAGIC_NO_CHECK_SOFT) == 0)
237        if ((m = file_softmagic(ms, ubuf, nb, 0, BINTEST,
238            looks_text)) != 0) {
239            if ((ms->flags & MAGIC_DEBUG) != 0)
240                (void)fprintf(stderr, "softmagic %d\n", m);
241#ifdef BUILTIN_ELF
242            if ((ms->flags & MAGIC_NO_CHECK_ELF) == 0 && m == 1 &&
243                nb > 5 && fd != -1) {
244                /*
245                 * We matched something in the file, so this
246                 * *might* be an ELF file, and the file is at
247                 * least 5 bytes long, so if it's an ELF file
248                 * it has at least one byte past the ELF magic
249                 * number - try extracting information from the
250                 * ELF headers that cannot easily * be
251                 * extracted with rules in the magic file.
252                 */
253                if ((m = file_tryelf(ms, fd, ubuf, nb)) != 0)
254                    if ((ms->flags & MAGIC_DEBUG) != 0)
255                        (void)fprintf(stderr,
256                            "elf %d\n", m);
257            }
258#endif
259            goto done;
260        }
261
262    /* try text properties */
263    if ((ms->flags & MAGIC_NO_CHECK_TEXT) == 0) {
264
265        if ((m = file_ascmagic(ms, ubuf, nb, looks_text)) != 0) {
266            if ((ms->flags & MAGIC_DEBUG) != 0)
267                (void)fprintf(stderr, "ascmagic %d\n", m);
268            goto done;
269        }
270
271        /* try to discover text encoding */
272        if ((ms->flags & MAGIC_NO_CHECK_ENCODING) == 0) {
273            if (looks_text == 0)
274                if ((m = file_ascmagic_with_encoding( ms, ubuf,
275                    nb, u8buf, ulen, code, type, looks_text))
276                    != 0) {
277                    if ((ms->flags & MAGIC_DEBUG) != 0)
278                        (void)fprintf(stderr,
279                            "ascmagic/enc %d\n", m);
280                    goto done;
281                }
282        }
283    }
284
285simple:
286    /* give up */
287    m = 1;
288    if ((!mime || (mime & MAGIC_MIME_TYPE)) &&
289        file_printf(ms, "%s", mime ? type : def) == -1) {
290        rv = -1;
291    }
292 done:
293    if ((ms->flags & MAGIC_MIME_ENCODING) != 0) {
294        if (ms->flags & MAGIC_MIME_TYPE)
295            if (file_printf(ms, "; charset=") == -1)
296                rv = -1;
297        if (file_printf(ms, "%s", code_mime) == -1)
298            rv = -1;
299    }
300 done_encoding:
301    free(u8buf);
302    if (rv)
303        return rv;
304
305    return m;
306}
307
308protected int
309file_reset(struct magic_set *ms)
310{
311    if (ms->mlist[0] == NULL) {
312        file_error(ms, 0, "no magic files loaded");
313        return -1;
314    }
315    if (ms->o.buf) {
316        efree(ms->o.buf);
317        ms->o.buf = NULL;
318    }
319    if (ms->o.pbuf) {
320        efree(ms->o.pbuf);
321        ms->o.pbuf = NULL;
322    }
323    ms->event_flags &= ~EVENT_HAD_ERR;
324    ms->error = -1;
325    return 0;
326}
327
328#define OCTALIFY(n, o)  \
329    /*LINTED*/ \
330    (void)(*(n)++ = '\\', \
331    *(n)++ = (((uint32_t)*(o) >> 6) & 3) + '0', \
332    *(n)++ = (((uint32_t)*(o) >> 3) & 7) + '0', \
333    *(n)++ = (((uint32_t)*(o) >> 0) & 7) + '0', \
334    (o)++)
335
336protected const char *
337file_getbuffer(struct magic_set *ms)
338{
339    char *op, *np;
340    size_t psize, len;
341
342    if (ms->event_flags & EVENT_HAD_ERR)
343        return NULL;
344
345    if (ms->flags & MAGIC_RAW)
346        return ms->o.buf;
347
348    if (ms->o.buf == NULL)
349        return NULL;
350
351    /* * 4 is for octal representation, + 1 is for NUL */
352    len = strlen(ms->o.buf);
353    if (len > (SIZE_MAX - 1) / 4) {
354        return NULL;
355    }
356    psize = len * 4 + 1;
357    if ((ms->o.pbuf = CAST(char *, erealloc(ms->o.pbuf, psize))) == NULL) {
358        file_oomem(ms, psize);
359        return NULL;
360    }
361
362#if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
363    {
364        mbstate_t state;
365        wchar_t nextchar;
366        int mb_conv = 1;
367        size_t bytesconsumed;
368        char *eop;
369        (void)memset(&state, 0, sizeof(mbstate_t));
370
371        np = ms->o.pbuf;
372        op = ms->o.buf;
373        eop = op + len;
374
375        while (op < eop) {
376            bytesconsumed = mbrtowc(&nextchar, op,
377                (size_t)(eop - op), &state);
378            if (bytesconsumed == (size_t)(-1) ||
379                bytesconsumed == (size_t)(-2)) {
380                mb_conv = 0;
381                break;
382            }
383
384            if (iswprint(nextchar)) {
385                (void)memcpy(np, op, bytesconsumed);
386                op += bytesconsumed;
387                np += bytesconsumed;
388            } else {
389                while (bytesconsumed-- > 0)
390                    OCTALIFY(np, op);
391            }
392        }
393        *np = '\0';
394
395        /* Parsing succeeded as a multi-byte sequence */
396        if (mb_conv != 0)
397            return ms->o.pbuf;
398    }
399#endif
400
401    for (np = ms->o.pbuf, op = ms->o.buf; *op;) {
402        if (isprint((unsigned char)*op)) {
403            *np++ = *op++;
404        } else {
405            OCTALIFY(np, op);
406        }
407    }
408    *np = '\0';
409    return ms->o.pbuf;
410}
411
412protected int
413file_check_mem(struct magic_set *ms, unsigned int level)
414{
415    size_t len;
416
417    if (level >= ms->c.len) {
418        len = (ms->c.len += 20) * sizeof(*ms->c.li);
419        ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ?
420            emalloc(len) :
421            erealloc(ms->c.li, len));
422        if (ms->c.li == NULL) {
423            file_oomem(ms, len);
424            return -1;
425        }
426    }
427    ms->c.li[level].got_match = 0;
428#ifdef ENABLE_CONDITIONALS
429    ms->c.li[level].last_match = 0;
430    ms->c.li[level].last_cond = COND_NONE;
431#endif /* ENABLE_CONDITIONALS */
432    return 0;
433}
434
435protected size_t
436file_printedlen(const struct magic_set *ms)
437{
438    return ms->o.buf == NULL ? 0 : strlen(ms->o.buf);
439}
440
441file_replace(struct magic_set *ms, const char *pat, const char *rep)
442{
443    zval patt;
444    int opts = 0;
445    pcre_cache_entry *pce;
446    zend_string *res;
447    zval repl;
448    int  rep_cnt = 0;
449    TSRMLS_FETCH();
450
451    (void)setlocale(LC_CTYPE, "C");
452
453    opts |= PCRE_MULTILINE;
454    convert_libmagic_pattern(&patt, pat, strlen(pat), opts);
455    if ((pce = pcre_get_compiled_regex_cache(Z_STR(patt) TSRMLS_CC)) == NULL) {
456        zval_ptr_dtor(&patt);
457        rep_cnt = -1;
458        goto out;
459    }
460    zval_ptr_dtor(&patt);
461
462    ZVAL_STRING(&repl, rep);
463    res = php_pcre_replace_impl(pce, ms->o.buf, strlen(ms->o.buf), &repl, 0, -1, &rep_cnt TSRMLS_CC);
464
465    zval_ptr_dtor(&repl);
466    if (NULL == res) {
467        rep_cnt = -1;
468        goto out;
469    }
470
471    strncpy(ms->o.buf, res->val, res->len);
472    ms->o.buf[res->len] = '\0';
473
474    zend_string_release(res);
475
476out:
477    (void)setlocale(LC_CTYPE, "");
478    return rep_cnt;
479}
480