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.68 2014/02/18 11:09:31 kim 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    const char *ftype = NULL;
177
178    if (nb == 0) {
179        def = "empty";
180        type = "application/x-empty";
181        goto simple;
182    } else if (nb == 1) {
183        def = "very short file (no magic)";
184        goto simple;
185    }
186
187    if ((ms->flags & MAGIC_NO_CHECK_ENCODING) == 0) {
188        looks_text = file_encoding(ms, ubuf, nb, &u8buf, &ulen,
189            &code, &code_mime, &ftype);
190    }
191
192#ifdef __EMX__
193    if ((ms->flags & MAGIC_NO_CHECK_APPTYPE) == 0 && inname) {
194        switch (file_os2_apptype(ms, inname, buf, nb)) {
195        case -1:
196            return -1;
197        case 0:
198            break;
199        default:
200            return 1;
201        }
202    }
203#endif
204
205#if PHP_FILEINFO_UNCOMPRESS
206    if ((ms->flags & MAGIC_NO_CHECK_COMPRESS) == 0)
207        if ((m = file_zmagic(ms, stream, inname, ubuf, nb)) != 0) {
208            if ((ms->flags & MAGIC_DEBUG) != 0)
209                (void)fprintf(stderr, "zmagic %d\n", m);
210            goto done_encoding;
211        }
212#endif
213    /* Check if we have a tar file */
214    if ((ms->flags & MAGIC_NO_CHECK_TAR) == 0)
215        if ((m = file_is_tar(ms, ubuf, nb)) != 0) {
216            if ((ms->flags & MAGIC_DEBUG) != 0)
217                (void)fprintf(stderr, "tar %d\n", m);
218            goto done;
219        }
220
221    /* Check if we have a CDF file */
222    if ((ms->flags & MAGIC_NO_CHECK_CDF) == 0) {
223        php_socket_t fd;
224            if (stream && SUCCESS == php_stream_cast(stream, PHP_STREAM_AS_FD, (void **)&fd, 0)) {
225            if ((m = file_trycdf(ms, fd, ubuf, nb)) != 0) {
226                if ((ms->flags & MAGIC_DEBUG) != 0)
227                    (void)fprintf(stderr, "cdf %d\n", m);
228                goto done;
229            }
230        }
231    }
232
233    /* try soft magic tests */
234    if ((ms->flags & MAGIC_NO_CHECK_SOFT) == 0)
235        if ((m = file_softmagic(ms, ubuf, nb, 0, BINTEST,
236            looks_text)) != 0) {
237            if ((ms->flags & MAGIC_DEBUG) != 0)
238                (void)fprintf(stderr, "softmagic %d\n", m);
239#ifdef BUILTIN_ELF
240            if ((ms->flags & MAGIC_NO_CHECK_ELF) == 0 && m == 1 &&
241                nb > 5 && fd != -1) {
242                /*
243                 * We matched something in the file, so this
244                 * *might* be an ELF file, and the file is at
245                 * least 5 bytes long, so if it's an ELF file
246                 * it has at least one byte past the ELF magic
247                 * number - try extracting information from the
248                 * ELF headers that cannot easily * be
249                 * extracted with rules in the magic file.
250                 */
251                if ((m = file_tryelf(ms, fd, ubuf, nb)) != 0)
252                    if ((ms->flags & MAGIC_DEBUG) != 0)
253                        (void)fprintf(stderr,
254                            "elf %d\n", m);
255            }
256#endif
257            goto done;
258        }
259
260    /* try text properties */
261    if ((ms->flags & MAGIC_NO_CHECK_TEXT) == 0) {
262
263        if ((m = file_ascmagic(ms, ubuf, nb, looks_text)) != 0) {
264            if ((ms->flags & MAGIC_DEBUG) != 0)
265                (void)fprintf(stderr, "ascmagic %d\n", m);
266            goto done;
267        }
268
269        /* try to discover text encoding */
270        if ((ms->flags & MAGIC_NO_CHECK_ENCODING) == 0) {
271            if (looks_text == 0)
272                if ((m = file_ascmagic_with_encoding( ms, ubuf,
273                    nb, u8buf, ulen, code, ftype, looks_text))
274                    != 0) {
275                    if ((ms->flags & MAGIC_DEBUG) != 0)
276                        (void)fprintf(stderr,
277                            "ascmagic/enc %d\n", m);
278                    goto done;
279                }
280        }
281    }
282
283simple:
284    /* give up */
285    m = 1;
286    if ((!mime || (mime & MAGIC_MIME_TYPE)) &&
287        file_printf(ms, "%s", mime ? type : def) == -1) {
288        rv = -1;
289    }
290 done:
291    if ((ms->flags & MAGIC_MIME_ENCODING) != 0) {
292        if (ms->flags & MAGIC_MIME_TYPE)
293            if (file_printf(ms, "; charset=") == -1)
294                rv = -1;
295        if (file_printf(ms, "%s", code_mime) == -1)
296            rv = -1;
297    }
298 done_encoding:
299    free(u8buf);
300    if (rv)
301        return rv;
302
303    return m;
304}
305
306protected int
307file_reset(struct magic_set *ms)
308{
309    if (ms->mlist[0] == NULL) {
310        file_error(ms, 0, "no magic files loaded");
311        return -1;
312    }
313    if (ms->o.buf) {
314        efree(ms->o.buf);
315        ms->o.buf = NULL;
316    }
317    if (ms->o.pbuf) {
318        efree(ms->o.pbuf);
319        ms->o.pbuf = NULL;
320    }
321    ms->event_flags &= ~EVENT_HAD_ERR;
322    ms->error = -1;
323    return 0;
324}
325
326#define OCTALIFY(n, o)  \
327    /*LINTED*/ \
328    (void)(*(n)++ = '\\', \
329    *(n)++ = (((uint32_t)*(o) >> 6) & 3) + '0', \
330    *(n)++ = (((uint32_t)*(o) >> 3) & 7) + '0', \
331    *(n)++ = (((uint32_t)*(o) >> 0) & 7) + '0', \
332    (o)++)
333
334protected const char *
335file_getbuffer(struct magic_set *ms)
336{
337    char *op, *np;
338    size_t psize, len;
339
340    if (ms->event_flags & EVENT_HAD_ERR)
341        return NULL;
342
343    if (ms->flags & MAGIC_RAW)
344        return ms->o.buf;
345
346    if (ms->o.buf == NULL)
347        return NULL;
348
349    /* * 4 is for octal representation, + 1 is for NUL */
350    len = strlen(ms->o.buf);
351    if (len > (SIZE_MAX - 1) / 4) {
352        return NULL;
353    }
354    psize = len * 4 + 1;
355    if ((ms->o.pbuf = CAST(char *, erealloc(ms->o.pbuf, psize))) == NULL) {
356        file_oomem(ms, psize);
357        return NULL;
358    }
359
360#if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
361    {
362        mbstate_t state;
363        wchar_t nextchar;
364        int mb_conv = 1;
365        size_t bytesconsumed;
366        char *eop;
367        (void)memset(&state, 0, sizeof(mbstate_t));
368
369        np = ms->o.pbuf;
370        op = ms->o.buf;
371        eop = op + len;
372
373        while (op < eop) {
374            bytesconsumed = mbrtowc(&nextchar, op,
375                (size_t)(eop - op), &state);
376            if (bytesconsumed == (size_t)(-1) ||
377                bytesconsumed == (size_t)(-2)) {
378                mb_conv = 0;
379                break;
380            }
381
382            if (iswprint(nextchar)) {
383                (void)memcpy(np, op, bytesconsumed);
384                op += bytesconsumed;
385                np += bytesconsumed;
386            } else {
387                while (bytesconsumed-- > 0)
388                    OCTALIFY(np, op);
389            }
390        }
391        *np = '\0';
392
393        /* Parsing succeeded as a multi-byte sequence */
394        if (mb_conv != 0)
395            return ms->o.pbuf;
396    }
397#endif
398
399    for (np = ms->o.pbuf, op = ms->o.buf; *op;) {
400        if (isprint((unsigned char)*op)) {
401            *np++ = *op++;
402        } else {
403            OCTALIFY(np, op);
404        }
405    }
406    *np = '\0';
407    return ms->o.pbuf;
408}
409
410protected int
411file_check_mem(struct magic_set *ms, unsigned int level)
412{
413    size_t len;
414
415    if (level >= ms->c.len) {
416        len = (ms->c.len += 20) * sizeof(*ms->c.li);
417        ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ?
418            emalloc(len) :
419            erealloc(ms->c.li, len));
420        if (ms->c.li == NULL) {
421            file_oomem(ms, len);
422            return -1;
423        }
424    }
425    ms->c.li[level].got_match = 0;
426#ifdef ENABLE_CONDITIONALS
427    ms->c.li[level].last_match = 0;
428    ms->c.li[level].last_cond = COND_NONE;
429#endif /* ENABLE_CONDITIONALS */
430    return 0;
431}
432
433protected size_t
434file_printedlen(const struct magic_set *ms)
435{
436    return ms->o.buf == NULL ? 0 : strlen(ms->o.buf);
437}
438
439file_replace(struct magic_set *ms, const char *pat, const char *rep)
440{
441    zval patt;
442    int opts = 0;
443    pcre_cache_entry *pce;
444    zend_string *res;
445    zval repl;
446    int  rep_cnt = 0;
447
448    (void)setlocale(LC_CTYPE, "C");
449
450    opts |= PCRE_MULTILINE;
451    convert_libmagic_pattern(&patt, pat, strlen(pat), opts);
452    if ((pce = pcre_get_compiled_regex_cache(Z_STR(patt))) == NULL) {
453        zval_ptr_dtor(&patt);
454        rep_cnt = -1;
455        goto out;
456    }
457    zval_ptr_dtor(&patt);
458
459    ZVAL_STRING(&repl, rep);
460    res = php_pcre_replace_impl(pce, ms->o.buf, strlen(ms->o.buf), &repl, 0, -1, &rep_cnt);
461
462    zval_ptr_dtor(&repl);
463    if (NULL == res) {
464        rep_cnt = -1;
465        goto out;
466    }
467
468    strncpy(ms->o.buf, res->val, res->len);
469    ms->o.buf[res->len] = '\0';
470
471    zend_string_release(res);
472
473out:
474    (void)setlocale(LC_CTYPE, "");
475    return rep_cnt;
476}
477