home *** CD-ROM | disk | FTP | other *** search
/ PC Online 1999 April / PCO0499.ISO / filesbbs / os2 / apach134.arj / APACH134.ZIP / src / modules / standard / mod_mime_magic.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-01-01  |  61.9 KB  |  2,469 lines

  1. /* ====================================================================
  2.  * Copyright (c) 1995-1999 The Apache Group.  All rights reserved.
  3.  *
  4.  * Redistribution and use in source and binary forms, with or without
  5.  * modification, are permitted provided that the following conditions
  6.  * are met:
  7.  *
  8.  * 1. Redistributions of source code must retain the above copyright
  9.  *    notice, this list of conditions and the following disclaimer.
  10.  *
  11.  * 2. Redistributions in binary form must reproduce the above copyright
  12.  *    notice, this list of conditions and the following disclaimer in
  13.  *    the documentation and/or other materials provided with the
  14.  *    distribution.
  15.  *
  16.  * 3. All advertising materials mentioning features or use of this
  17.  *    software must display the following acknowledgment:
  18.  *    "This product includes software developed by the Apache Group
  19.  *    for use in the Apache HTTP server project (http://www.apache.org/)."
  20.  *
  21.  * 4. The names "Apache Server" and "Apache Group" must not be used to
  22.  *    endorse or promote products derived from this software without
  23.  *    prior written permission. For written permission, please contact
  24.  *    apache@apache.org.
  25.  *
  26.  * 5. Products derived from this software may not be called "Apache"
  27.  *    nor may "Apache" appear in their names without prior written
  28.  *    permission of the Apache Group.
  29.  *
  30.  * 6. Redistributions of any form whatsoever must retain the following
  31.  *    acknowledgment:
  32.  *    "This product includes software developed by the Apache Group
  33.  *    for use in the Apache HTTP server project (http://www.apache.org/)."
  34.  *
  35.  * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
  36.  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  37.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  38.  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE APACHE GROUP OR
  39.  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  41.  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  42.  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  43.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  44.  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  45.  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  46.  * OF THE POSSIBILITY OF SUCH DAMAGE.
  47.  * ====================================================================
  48.  *
  49.  * This software consists of voluntary contributions made by many
  50.  * individuals on behalf of the Apache Group and was originally based
  51.  * on public domain software written at the National Center for
  52.  * Supercomputing Applications, University of Illinois, Urbana-Champaign.
  53.  * For more information on the Apache Group and the Apache HTTP server
  54.  * project, please see <http://www.apache.org/>.
  55.  *
  56.  */
  57.  
  58. /*
  59.  * mod_mime_magic: MIME type lookup via file magic numbers
  60.  * Copyright (c) 1996-1997 Cisco Systems, Inc.
  61.  *
  62.  * This software was submitted by Cisco Systems to the Apache Group in July
  63.  * 1997.  Future revisions and derivatives of this source code must
  64.  * acknowledge Cisco Systems as the original contributor of this module.
  65.  * All other licensing and usage conditions are those of the Apache Group.
  66.  *
  67.  * Some of this code is derived from the free version of the file command
  68.  * originally posted to comp.sources.unix.  Copyright info for that program
  69.  * is included below as required.
  70.  * ---------------------------------------------------------------------------
  71.  * - Copyright (c) Ian F. Darwin, 1987. Written by Ian F. Darwin.
  72.  *
  73.  * This software is not subject to any license of the American Telephone and
  74.  * Telegraph Company or of the Regents of the University of California.
  75.  *
  76.  * Permission is granted to anyone to use this software for any purpose on any
  77.  * computer system, and to alter it and redistribute it freely, subject to
  78.  * the following restrictions:
  79.  *
  80.  * 1. The author is not responsible for the consequences of use of this
  81.  * software, no matter how awful, even if they arise from flaws in it.
  82.  *
  83.  * 2. The origin of this software must not be misrepresented, either by
  84.  * explicit claim or by omission.  Since few users ever read sources, credits
  85.  * must appear in the documentation.
  86.  *
  87.  * 3. Altered versions must be plainly marked as such, and must not be
  88.  * misrepresented as being the original software.  Since few users ever read
  89.  * sources, credits must appear in the documentation.
  90.  *
  91.  * 4. This notice may not be removed or altered.
  92.  * -------------------------------------------------------------------------
  93.  *
  94.  * For compliance with Mr Darwin's terms: this has been very significantly
  95.  * modified from the free "file" command.
  96.  * - all-in-one file for compilation convenience when moving from one
  97.  *   version of Apache to the next.
  98.  * - Memory allocation is done through the Apache API's pool structure.
  99.  * - All functions have had necessary Apache API request or server
  100.  *   structures passed to them where necessary to call other Apache API
  101.  *   routines.  (i.e. usually for logging, files, or memory allocation in
  102.  *   itself or a called function.)
  103.  * - struct magic has been converted from an array to a single-ended linked
  104.  *   list because it only grows one record at a time, it's only accessed
  105.  *   sequentially, and the Apache API has no equivalent of realloc().
  106.  * - Functions have been changed to get their parameters from the server
  107.  *   configuration instead of globals.  (It should be reentrant now but has
  108.  *   not been tested in a threaded environment.)
  109.  * - Places where it used to print results to stdout now saves them in a
  110.  *   list where they're used to set the MIME type in the Apache request
  111.  *   record.
  112.  * - Command-line flags have been removed since they will never be used here.
  113.  *
  114.  * Ian Kluft <ikluft@cisco.com>
  115.  * Engineering Information Framework
  116.  * Central Engineering
  117.  * Cisco Systems, Inc.
  118.  * San Jose, CA, USA
  119.  *
  120.  * Initial installation          July/August 1996
  121.  * Misc bug fixes                May 1997
  122.  * Submission to Apache Group    July 1997
  123.  *
  124.  */
  125.  
  126. #include "httpd.h"
  127. #include "http_config.h"
  128. #include "http_request.h"
  129. #include "http_core.h"
  130. #include "http_log.h"
  131. #include "http_protocol.h"
  132.  
  133. #include <utime.h>
  134.  
  135.  
  136. /*
  137.  * data structures and related constants
  138.  */
  139.  
  140. #define MODNAME        "mod_mime_magic"
  141. #define MIME_MAGIC_DEBUG        0
  142.  
  143. #define MIME_BINARY_UNKNOWN    "application/octet-stream"
  144. #define MIME_TEXT_UNKNOWN    "text/plain"
  145.  
  146. #define MAXMIMESTRING        256
  147.  
  148. /* HOWMANY must be at least 4096 to make gzip -dcq work */
  149. #define HOWMANY    4096
  150. /* SMALL_HOWMANY limits how much work we do to figure out text files */
  151. #define SMALL_HOWMANY 1024
  152. #define MAXDESC    50        /* max leng of text description */
  153. #define MAXstring 64        /* max leng of "string" types */
  154.  
  155. struct magic {
  156.     struct magic *next;        /* link to next entry */
  157.     int lineno;            /* line number from magic file */
  158.  
  159.     short flag;
  160. #define INDIR    1        /* if '>(...)' appears,  */
  161. #define    UNSIGNED 2        /* comparison is unsigned */
  162.     short cont_level;        /* level of ">" */
  163.     struct {
  164.     char type;        /* byte short long */
  165.     long offset;        /* offset from indirection */
  166.     } in;
  167.     long offset;        /* offset to magic number */
  168.     unsigned char reln;        /* relation (0=eq, '>'=gt, etc) */
  169.     char type;            /* int, short, long or string. */
  170.     char vallen;        /* length of string value, if any */
  171. #define BYTE    1
  172. #define SHORT    2
  173. #define LONG    4
  174. #define STRING    5
  175. #define DATE    6
  176. #define BESHORT    7
  177. #define BELONG    8
  178. #define BEDATE    9
  179. #define LESHORT    10
  180. #define LELONG    11
  181. #define LEDATE    12
  182.     union VALUETYPE {
  183.     unsigned char b;
  184.     unsigned short h;
  185.     unsigned long l;
  186.     char s[MAXstring];
  187.     unsigned char hs[2];    /* 2 bytes of a fixed-endian "short" */
  188.     unsigned char hl[4];    /* 2 bytes of a fixed-endian "long" */
  189.     } value;            /* either number or string */
  190.     unsigned long mask;        /* mask before comparison with value */
  191.     char nospflag;        /* supress space character */
  192.  
  193.     /* NOTE: this string is suspected of overrunning - find it! */
  194.     char desc[MAXDESC];        /* description */
  195. };
  196.  
  197. /*
  198.  * data structures for tar file recognition
  199.  * --------------------------------------------------------------------------
  200.  * Header file for public domain tar (tape archive) program.
  201.  *
  202.  * @(#)tar.h 1.20 86/10/29    Public Domain. Created 25 August 1985 by John
  203.  * Gilmore, ihnp4!hoptoad!gnu.
  204.  *
  205.  * Header block on tape.
  206.  *
  207.  * I'm going to use traditional DP naming conventions here. A "block" is a big
  208.  * chunk of stuff that we do I/O on. A "record" is a piece of info that we
  209.  * care about. Typically many "record"s fit into a "block".
  210.  */
  211. #define RECORDSIZE    512
  212. #define NAMSIZ    100
  213. #define TUNMLEN    32
  214. #define TGNMLEN    32
  215.  
  216. union record {
  217.     char charptr[RECORDSIZE];
  218.     struct header {
  219.     char name[NAMSIZ];
  220.     char mode[8];
  221.     char uid[8];
  222.     char gid[8];
  223.     char size[12];
  224.     char mtime[12];
  225.     char chksum[8];
  226.     char linkflag;
  227.     char linkname[NAMSIZ];
  228.     char magic[8];
  229.     char uname[TUNMLEN];
  230.     char gname[TGNMLEN];
  231.     char devmajor[8];
  232.     char devminor[8];
  233.     } header;
  234. };
  235.  
  236. /* The magic field is filled with this if uname and gname are valid. */
  237. #define    TMAGIC        "ustar  "    /* 7 chars and a null */
  238.  
  239. /*
  240.  * file-function prototypes
  241.  */
  242. static int ascmagic(request_rec *, unsigned char *, int);
  243. static int is_tar(unsigned char *, int);
  244. static int softmagic(request_rec *, unsigned char *, int);
  245. static void tryit(request_rec *, unsigned char *, int);
  246. static int zmagic(request_rec *, unsigned char *, int);
  247.  
  248. static int getvalue(server_rec *, struct magic *, char **);
  249. static int hextoint(int);
  250. static char *getstr(server_rec *, char *, char *, int, int *);
  251. static int parse(server_rec *, pool *p, char *, int);
  252.  
  253. static int match(request_rec *, unsigned char *, int);
  254. static int mget(request_rec *, union VALUETYPE *, unsigned char *,
  255.         struct magic *, int);
  256. static int mcheck(request_rec *, union VALUETYPE *, struct magic *);
  257. static void mprint(request_rec *, union VALUETYPE *, struct magic *);
  258.  
  259. static int uncompress(request_rec *, int, const unsigned char *,
  260.               unsigned char **, int);
  261. static long from_oct(int, char *);
  262. static int fsmagic(request_rec *r, const char *fn);
  263.  
  264. /*
  265.  * includes for ASCII substring recognition formerly "names.h" in file
  266.  * command
  267.  *
  268.  * Original notes: names and types used by ascmagic in file(1). These tokens are
  269.  * here because they can appear anywhere in the first HOWMANY bytes, while
  270.  * tokens in /etc/magic must appear at fixed offsets into the file. Don't
  271.  * make HOWMANY too high unless you have a very fast CPU.
  272.  */
  273.  
  274. /* these types are used to index the table 'types': keep em in sync! */
  275. /* HTML inserted in first because this is a web server module now */
  276. #define L_HTML    0        /* HTML */
  277. #define L_C       1        /* first and foremost on UNIX */
  278. #define L_FORT    2        /* the oldest one */
  279. #define L_MAKE    3        /* Makefiles */
  280. #define L_PLI     4        /* PL/1 */
  281. #define L_MACH    5        /* some kinda assembler */
  282. #define L_ENG     6        /* English */
  283. #define L_PAS     7        /* Pascal */
  284. #define L_MAIL    8        /* Electronic mail */
  285. #define L_NEWS    9        /* Usenet Netnews */
  286.  
  287. static char *types[] =
  288. {
  289.     "text/html",        /* HTML */
  290.     "text/plain",        /* "c program text", */
  291.     "text/plain",        /* "fortran program text", */
  292.     "text/plain",        /* "make commands text", */
  293.     "text/plain",        /* "pl/1 program text", */
  294.     "text/plain",        /* "assembler program text", */
  295.     "text/plain",        /* "English text", */
  296.     "text/plain",        /* "pascal program text", */
  297.     "message/rfc822",        /* "mail text", */
  298.     "message/news",        /* "news text", */
  299.     "application/binary",    /* "can't happen error on names.h/types", */
  300.     0
  301. };
  302.  
  303. static struct names {
  304.     char *name;
  305.     short type;
  306. } names[] = {
  307.  
  308.     /* These must be sorted by eye for optimal hit rate */
  309.     /* Add to this list only after substantial meditation */
  310.     {
  311.     "<html>", L_HTML
  312.     },
  313.     {
  314.     "<HTML>", L_HTML
  315.     },
  316.     {
  317.     "<head>", L_HTML
  318.     },
  319.     {
  320.     "<HEAD>", L_HTML
  321.     },
  322.     {
  323.     "<title>", L_HTML
  324.     },
  325.     {
  326.     "<TITLE>", L_HTML
  327.     },
  328.     {
  329.     "<h1>", L_HTML
  330.     },
  331.     {
  332.     "<H1>", L_HTML
  333.     },
  334.     {
  335.     "<!--", L_HTML
  336.     },
  337.     {
  338.     "<!DOCTYPE HTML", L_HTML
  339.     },
  340.     {
  341.     "/*", L_C
  342.     },                /* must precede "The", "the", etc. */
  343.     {
  344.     "#include", L_C
  345.     },
  346.     {
  347.     "char", L_C
  348.     },
  349.     {
  350.     "The", L_ENG
  351.     },
  352.     {
  353.     "the", L_ENG
  354.     },
  355.     {
  356.     "double", L_C
  357.     },
  358.     {
  359.     "extern", L_C
  360.     },
  361.     {
  362.     "float", L_C
  363.     },
  364.     {
  365.     "real", L_C
  366.     },
  367.     {
  368.     "struct", L_C
  369.     },
  370.     {
  371.     "union", L_C
  372.     },
  373.     {
  374.     "CFLAGS", L_MAKE
  375.     },
  376.     {
  377.     "LDFLAGS", L_MAKE
  378.     },
  379.     {
  380.     "all:", L_MAKE
  381.     },
  382.     {
  383.     ".PRECIOUS", L_MAKE
  384.     },
  385.     /*
  386.      * Too many files of text have these words in them.  Find another way to
  387.      * recognize Fortrash.
  388.      */
  389. #ifdef    NOTDEF
  390.     {
  391.     "subroutine", L_FORT
  392.     },
  393.     {
  394.     "function", L_FORT
  395.     },
  396.     {
  397.     "block", L_FORT
  398.     },
  399.     {
  400.     "common", L_FORT
  401.     },
  402.     {
  403.     "dimension", L_FORT
  404.     },
  405.     {
  406.     "integer", L_FORT
  407.     },
  408.     {
  409.     "data", L_FORT
  410.     },
  411. #endif /* NOTDEF */
  412.     {
  413.     ".ascii", L_MACH
  414.     },
  415.     {
  416.     ".asciiz", L_MACH
  417.     },
  418.     {
  419.     ".byte", L_MACH
  420.     },
  421.     {
  422.     ".even", L_MACH
  423.     },
  424.     {
  425.     ".globl", L_MACH
  426.     },
  427.     {
  428.     "clr", L_MACH
  429.     },
  430.     {
  431.     "(input,", L_PAS
  432.     },
  433.     {
  434.     "dcl", L_PLI
  435.     },
  436.     {
  437.     "Received:", L_MAIL
  438.     },
  439.     {
  440.     ">From", L_MAIL
  441.     },
  442.     {
  443.     "Return-Path:", L_MAIL
  444.     },
  445.     {
  446.     "Cc:", L_MAIL
  447.     },
  448.     {
  449.     "Newsgroups:", L_NEWS
  450.     },
  451.     {
  452.     "Path:", L_NEWS
  453.     },
  454.     {
  455.     "Organization:", L_NEWS
  456.     },
  457.     {
  458.     NULL, 0
  459.     }
  460. };
  461.  
  462. #define NNAMES ((sizeof(names)/sizeof(struct names)) - 1)
  463.  
  464. /*
  465.  * Result String List (RSL)
  466.  *
  467.  * The file(1) command prints its output.  Instead, we store the various
  468.  * "printed" strings in a list (allocating memory as we go) and concatenate
  469.  * them at the end when we finally know how much space they'll need.
  470.  */
  471.  
  472. typedef struct magic_rsl_s {
  473.     char *str;            /* string, possibly a fragment */
  474.     struct magic_rsl_s *next;    /* pointer to next fragment */
  475. } magic_rsl;
  476.  
  477. /*
  478.  * Apache module configuration structures
  479.  */
  480.  
  481. /* per-server info */
  482. typedef struct {
  483.     char *magicfile;        /* where magic be found */
  484.     struct magic *magic;    /* head of magic config list */
  485.     struct magic *last;
  486. } magic_server_config_rec;
  487.  
  488. /* per-request info */
  489. typedef struct {
  490.     magic_rsl *head;        /* result string list */
  491.     magic_rsl *tail;
  492.     unsigned suf_recursion;    /* recursion depth in suffix check */
  493. } magic_req_rec;
  494.  
  495. /*
  496.  * configuration functions - called by Apache API routines
  497.  */
  498.  
  499. module mime_magic_module;
  500.  
  501. static void *create_magic_server_config(pool *p, server_rec *d)
  502. {
  503.     /* allocate the config - use pcalloc because it needs to be zeroed */
  504.     return ap_pcalloc(p, sizeof(magic_server_config_rec));
  505. }
  506.  
  507. static void *merge_magic_server_config(pool *p, void *basev, void *addv)
  508. {
  509.     magic_server_config_rec *base = (magic_server_config_rec *) basev;
  510.     magic_server_config_rec *add = (magic_server_config_rec *) addv;
  511.     magic_server_config_rec *new = (magic_server_config_rec *)
  512.                 ap_palloc(p, sizeof(magic_server_config_rec));
  513.  
  514.     new->magicfile = add->magicfile ? add->magicfile : base->magicfile;
  515.     new->magic = NULL;
  516.     new->last = NULL;
  517.     return new;
  518. }
  519.  
  520. static const char *set_magicfile(cmd_parms *cmd, char *d, char *arg)
  521. {
  522.     magic_server_config_rec *conf = (magic_server_config_rec *)
  523.     ap_get_module_config(cmd->server->module_config,
  524.               &mime_magic_module);
  525.  
  526.     if (!conf) {
  527.     return MODNAME ": server structure not allocated";
  528.     }
  529.     conf->magicfile = arg;
  530.     return NULL;
  531. }
  532.  
  533. /*
  534.  * configuration file commands - exported to Apache API
  535.  */
  536.  
  537. static const command_rec mime_magic_cmds[] =
  538. {
  539.     {"MimeMagicFile", set_magicfile, NULL, RSRC_CONF, TAKE1,
  540.      "Path to MIME Magic file (in file(1) format)"},
  541.     {NULL}
  542. };
  543.  
  544. /*
  545.  * RSL (result string list) processing routines
  546.  *
  547.  * These collect strings that would have been printed in fragments by file(1)
  548.  * into a list of magic_rsl structures with the strings. When complete,
  549.  * they're concatenated together to become the MIME content and encoding
  550.  * types.
  551.  *
  552.  * return value conventions for these functions: functions which return int:
  553.  * failure = -1, other = result functions which return pointers: failure = 0,
  554.  * other = result
  555.  */
  556.  
  557. /* allocate a per-request structure and put it in the request record */
  558. static magic_req_rec *magic_set_config(request_rec *r)
  559. {
  560.     magic_req_rec *req_dat = (magic_req_rec *) ap_palloc(r->pool,
  561.                               sizeof(magic_req_rec));
  562.  
  563.     req_dat->head = req_dat->tail = (magic_rsl *) NULL;
  564.     ap_set_module_config(r->request_config, &mime_magic_module, req_dat);
  565.     return req_dat;
  566. }
  567.  
  568. /* add a string to the result string list for this request */
  569. /* it is the responsibility of the caller to allocate "str" */
  570. static int magic_rsl_add(request_rec *r, char *str)
  571. {
  572.     magic_req_rec *req_dat = (magic_req_rec *)
  573.             ap_get_module_config(r->request_config, &mime_magic_module);
  574.     magic_rsl *rsl;
  575.  
  576.     /* make sure we have a list to put it in */
  577.     if (!req_dat) {
  578.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, r,
  579.             MODNAME ": request config should not be NULL");
  580.     if (!(req_dat = magic_set_config(r))) {
  581.         /* failure */
  582.         return -1;
  583.     }
  584.     }
  585.  
  586.     /* allocate the list entry */
  587.     rsl = (magic_rsl *) ap_palloc(r->pool, sizeof(magic_rsl));
  588.  
  589.     /* fill it */
  590.     rsl->str = str;
  591.     rsl->next = (magic_rsl *) NULL;
  592.  
  593.     /* append to the list */
  594.     if (req_dat->head && req_dat->tail) {
  595.     req_dat->tail->next = rsl;
  596.     req_dat->tail = rsl;
  597.     }
  598.     else {
  599.     req_dat->head = req_dat->tail = rsl;
  600.     }
  601.  
  602.     /* success */
  603.     return 0;
  604. }
  605.  
  606. /* RSL hook for puts-type functions */
  607. static int magic_rsl_puts(request_rec *r, char *str)
  608. {
  609.     return magic_rsl_add(r, str);
  610. }
  611.  
  612. /* RSL hook for printf-type functions */
  613. static int magic_rsl_printf(request_rec *r, char *str,...)
  614. {
  615.     va_list ap;
  616.  
  617.     char buf[MAXMIMESTRING];
  618.  
  619.     /* assemble the string into the buffer */
  620.     va_start(ap, str);
  621.     ap_vsnprintf(buf, sizeof(buf), str, ap);
  622.     va_end(ap);
  623.  
  624.     /* add the buffer to the list */
  625.     return magic_rsl_add(r, strdup(buf));
  626. }
  627.  
  628. /* RSL hook for putchar-type functions */
  629. static int magic_rsl_putchar(request_rec *r, char c)
  630. {
  631.     char str[2];
  632.  
  633.     /* high overhead for 1 char - just hope they don't do this much */
  634.     str[0] = c;
  635.     str[1] = '\0';
  636.     return magic_rsl_add(r, str);
  637. }
  638.  
  639. /* allocate and copy a contiguous string from a result string list */
  640. static char *rsl_strdup(request_rec *r, int start_frag, int start_pos, int len)
  641. {
  642.     char *result;        /* return value */
  643.     int cur_frag,        /* current fragment number/counter */
  644.         cur_pos,        /* current position within fragment */
  645.         res_pos;        /* position in result string */
  646.     magic_rsl *frag;        /* list-traversal pointer */
  647.     magic_req_rec *req_dat = (magic_req_rec *)
  648.             ap_get_module_config(r->request_config, &mime_magic_module);
  649.  
  650.     /* allocate the result string */
  651.     result = (char *) ap_palloc(r->pool, len + 1);
  652.  
  653.     /* loop through and collect the string */
  654.     res_pos = 0;
  655.     for (frag = req_dat->head, cur_frag = 0;
  656.      frag->next;
  657.      frag = frag->next, cur_frag++) {
  658.     /* loop to the first fragment */
  659.     if (cur_frag < start_frag)
  660.         continue;
  661.  
  662.     /* loop through and collect chars */
  663.     for (cur_pos = (cur_frag == start_frag) ? start_pos : 0;
  664.          frag->str[cur_pos];
  665.          cur_pos++) {
  666.         if (cur_frag >= start_frag
  667.         && cur_pos >= start_pos
  668.         && res_pos <= len) {
  669.         result[res_pos++] = frag->str[cur_pos];
  670.         if (res_pos > len) {
  671.             break;
  672.         }
  673.         }
  674.     }
  675.     }
  676.  
  677.     /* clean up and return */
  678.     result[res_pos] = 0;
  679. #if MIME_MAGIC_DEBUG
  680.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  681.          MODNAME ": rsl_strdup() %d chars: %s", res_pos - 1, result);
  682. #endif
  683.     return result;
  684. }
  685.  
  686. /* states for the state-machine algorithm in magic_rsl_to_request() */
  687. typedef enum {
  688.     rsl_leading_space, rsl_type, rsl_subtype, rsl_separator, rsl_encoding
  689. } rsl_states;
  690.  
  691. /* process the RSL and set the MIME info in the request record */
  692. static int magic_rsl_to_request(request_rec *r)
  693. {
  694.     int cur_frag,        /* current fragment number/counter */
  695.         cur_pos,        /* current position within fragment */
  696.         type_frag,        /* content type starting point: fragment */
  697.         type_pos,        /* content type starting point: position */
  698.         type_len,        /* content type length */
  699.         encoding_frag,        /* content encoding starting point: fragment */
  700.         encoding_pos,        /* content encoding starting point: position */
  701.         encoding_len;        /* content encoding length */
  702.  
  703.     magic_rsl *frag;        /* list-traversal pointer */
  704.     rsl_states state;
  705.  
  706.     magic_req_rec *req_dat = (magic_req_rec *)
  707.             ap_get_module_config(r->request_config, &mime_magic_module);
  708.  
  709.     /* check if we have a result */
  710.     if (!req_dat || !req_dat->head) {
  711.     /* empty - no match, we defer to other Apache modules */
  712.     return DECLINED;
  713.     }
  714.  
  715.     /* start searching for the type and encoding */
  716.     state = rsl_leading_space;
  717.     type_frag = type_pos = type_len = 0;
  718.     encoding_frag = encoding_pos = encoding_len = 0;
  719.     for (frag = req_dat->head, cur_frag = 0;
  720.      frag && frag->next;
  721.      frag = frag->next, cur_frag++) {
  722.     /* loop through the characters in the fragment */
  723.     for (cur_pos = 0; frag->str[cur_pos]; cur_pos++) {
  724.         if (ap_isspace(frag->str[cur_pos])) {
  725.         /* process whitespace actions for each state */
  726.         if (state == rsl_leading_space) {
  727.             /* eat whitespace in this state */
  728.             continue;
  729.         }
  730.         else if (state == rsl_type) {
  731.             /* whitespace: type has no slash! */
  732.             return DECLINED;
  733.         }
  734.         else if (state == rsl_subtype) {
  735.             /* whitespace: end of MIME type */
  736.             state++;
  737.             continue;
  738.         }
  739.         else if (state == rsl_separator) {
  740.             /* eat whitespace in this state */
  741.             continue;
  742.         }
  743.         else if (state == rsl_encoding) {
  744.             /* whitespace: end of MIME encoding */
  745.             /* we're done */
  746.             frag = req_dat->tail;
  747.             break;
  748.         }
  749.         else {
  750.             /* should not be possible */
  751.             /* abandon malfunctioning module */
  752.             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, r,
  753.                 MODNAME ": bad state %d (ws)", state);
  754.             return DECLINED;
  755.         }
  756.         /* NOTREACHED */
  757.         }
  758.         else if (state == rsl_type &&
  759.              frag->str[cur_pos] == '/') {
  760.         /* copy the char and go to rsl_subtype state */
  761.         type_len++;
  762.         state++;
  763.         }
  764.         else {
  765.         /* process non-space actions for each state */
  766.         if (state == rsl_leading_space) {
  767.             /* non-space: begin MIME type */
  768.             state++;
  769.             type_frag = cur_frag;
  770.             type_pos = cur_pos;
  771.             type_len = 1;
  772.             continue;
  773.         }
  774.         else if (state == rsl_type ||
  775.              state == rsl_subtype) {
  776.             /* non-space: adds to type */
  777.             type_len++;
  778.             continue;
  779.         }
  780.         else if (state == rsl_separator) {
  781.             /* non-space: begin MIME encoding */
  782.             state++;
  783.             encoding_frag = cur_frag;
  784.             encoding_pos = cur_pos;
  785.             encoding_len = 1;
  786.             continue;
  787.         }
  788.         else if (state == rsl_encoding) {
  789.             /* non-space: adds to encoding */
  790.             encoding_len++;
  791.             continue;
  792.         }
  793.         else {
  794.             /* should not be possible */
  795.             /* abandon malfunctioning module */
  796.             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, r,
  797.                 MODNAME ": bad state %d (ns)", state);
  798.             return DECLINED;
  799.         }
  800.         /* NOTREACHED */
  801.         }
  802.         /* NOTREACHED */
  803.     }
  804.     }
  805.  
  806.     /* if we ended prior to state rsl_subtype, we had incomplete info */
  807.     if (state != rsl_subtype && state != rsl_separator &&
  808.     state != rsl_encoding) {
  809.     /* defer to other modules */
  810.     return DECLINED;
  811.     }
  812.  
  813.     /* save the info in the request record */
  814.     if (state == rsl_subtype || state == rsl_encoding ||
  815.     state == rsl_encoding) {
  816.         char *tmp;
  817.     tmp = rsl_strdup(r, type_frag, type_pos, type_len);
  818.     /* XXX: this could be done at config time I'm sure... but I'm
  819.      * confused by all this magic_rsl stuff. -djg */
  820.     ap_content_type_tolower(tmp);
  821.     r->content_type = tmp;
  822.     }
  823.     if (state == rsl_encoding) {
  824.         char *tmp;
  825.     tmp = rsl_strdup(r, encoding_frag,
  826.                      encoding_pos, encoding_len);
  827.     /* XXX: this could be done at config time I'm sure... but I'm
  828.      * confused by all this magic_rsl stuff. -djg */
  829.     ap_str_tolower(tmp);
  830.     r->content_encoding = tmp;
  831.     }
  832.  
  833.     /* detect memory allocation errors */
  834.     if (!r->content_type ||
  835.     (state == rsl_encoding && !r->content_encoding)) {
  836.     return HTTP_INTERNAL_SERVER_ERROR;
  837.     }
  838.  
  839.     /* success! */
  840.     return OK;
  841. }
  842.  
  843. /*
  844.  * magic_process - process input file r        Apache API request record
  845.  * (formerly called "process" in file command, prefix added for clarity) Opens
  846.  * the file and reads a fixed-size buffer to begin processing the contents.
  847.  */
  848. static int magic_process(request_rec *r)
  849. {
  850.     int fd = 0;
  851.     unsigned char buf[HOWMANY + 1];    /* one extra for terminating '\0' */
  852.     int nbytes = 0;        /* number of bytes read from a datafile */
  853.     int result;
  854.  
  855.     /*
  856.      * first try judging the file based on its filesystem status
  857.      */
  858.     switch ((result = fsmagic(r, r->filename))) {
  859.     case DONE:
  860.     magic_rsl_putchar(r, '\n');
  861.     return OK;
  862.     case OK:
  863.     break;
  864.     default:
  865.     /* fatal error, bail out */
  866.     return result;
  867.     }
  868.  
  869.     if ((fd = ap_popenf(r->pool, r->filename, O_RDONLY, 0)) < 0) {
  870.     /* We can't open it, but we were able to stat it. */
  871.     ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
  872.             MODNAME ": can't read `%s'", r->filename);
  873.     /* let some other handler decide what the problem is */
  874.     return DECLINED;
  875.     }
  876.  
  877.     /*
  878.      * try looking at the first HOWMANY bytes
  879.      */
  880.     if ((nbytes = read(fd, (char *) buf, sizeof(buf) - 1)) == -1) {
  881.     ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
  882.             MODNAME ": read failed: %s", r->filename);
  883.     return HTTP_INTERNAL_SERVER_ERROR;
  884.     }
  885.  
  886.     if (nbytes == 0)
  887.     magic_rsl_puts(r, MIME_TEXT_UNKNOWN);
  888.     else {
  889.     buf[nbytes++] = '\0';    /* null-terminate it */
  890.     tryit(r, buf, nbytes);
  891.     }
  892.  
  893.     (void) ap_pclosef(r->pool, fd);
  894.     (void) magic_rsl_putchar(r, '\n');
  895.  
  896.     return OK;
  897. }
  898.  
  899.  
  900. static void tryit(request_rec *r, unsigned char *buf, int nb)
  901. {
  902.     /*
  903.      * Try compression stuff
  904.      */
  905.     if (zmagic(r, buf, nb) == 1)
  906.     return;
  907.  
  908.     /*
  909.      * try tests in /etc/magic (or surrogate magic file)
  910.      */
  911.     if (softmagic(r, buf, nb) == 1)
  912.     return;
  913.  
  914.     /*
  915.      * try known keywords, check for ascii-ness too.
  916.      */
  917.     if (ascmagic(r, buf, nb) == 1)
  918.     return;
  919.  
  920.     /*
  921.      * abandon hope, all ye who remain here
  922.      */
  923.     magic_rsl_puts(r, MIME_BINARY_UNKNOWN);
  924. }
  925.  
  926. #define    EATAB {while (ap_isspace((unsigned char) *l))  ++l;}
  927.  
  928. /*
  929.  * apprentice - load configuration from the magic file r
  930.  *  API request record
  931.  */
  932. static int apprentice(server_rec *s, pool *p)
  933. {
  934.     FILE *f;
  935.     char line[BUFSIZ + 1];
  936.     int errs = 0;
  937.     int lineno;
  938. #if MIME_MAGIC_DEBUG
  939.     int rule = 0;
  940.     struct magic *m, *prevm;
  941. #endif
  942.     char *fname;
  943.  
  944.     magic_server_config_rec *conf = (magic_server_config_rec *)
  945.             ap_get_module_config(s->module_config, &mime_magic_module);
  946.  
  947.     fname = ap_server_root_relative(p, conf->magicfile);
  948.     f = ap_pfopen(p, fname, "r");
  949.     if (f == NULL) {
  950.     ap_log_error(APLOG_MARK, APLOG_ERR, s,
  951.             MODNAME ": can't read magic file %s", fname);
  952.     return -1;
  953.     }
  954.  
  955.     /* set up the magic list (empty) */
  956.     conf->magic = conf->last = NULL;
  957.  
  958.     /* parse it */
  959.     for (lineno = 1; fgets(line, BUFSIZ, f) != NULL; lineno++) {
  960.     int ws_offset;
  961.  
  962.     /* delete newline */
  963.     if (line[0]) {
  964.         line[strlen(line) - 1] = '\0';
  965.     }
  966.  
  967.     /* skip leading whitespace */
  968.     ws_offset = 0;
  969.     while (line[ws_offset] && ap_isspace(line[ws_offset])) {
  970.         ws_offset++;
  971.     }
  972.  
  973.     /* skip blank lines */
  974.     if (line[ws_offset] == 0) {
  975.         continue;
  976.     }
  977.  
  978.     /* comment, do not parse */
  979.     if (line[ws_offset] == '#')
  980.         continue;
  981.  
  982. #if MIME_MAGIC_DEBUG
  983.     /* if we get here, we're going to use it so count it */
  984.     rule++;
  985. #endif
  986.  
  987.     /* parse it */
  988.     if (parse(s, p, line + ws_offset, lineno) != 0)
  989.         ++errs;
  990.     }
  991.  
  992.     (void) ap_pfclose(p, f);
  993.  
  994. #if MIME_MAGIC_DEBUG
  995.     ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, s,
  996.         MODNAME ": apprentice conf=%x file=%s m=%s m->next=%s last=%s",
  997.         conf,
  998.         conf->magicfile ? conf->magicfile : "NULL",
  999.         conf->magic ? "set" : "NULL",
  1000.         (conf->magic && conf->magic->next) ? "set" : "NULL",
  1001.         conf->last ? "set" : "NULL");
  1002.     ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, s,
  1003.         MODNAME ": apprentice read %d lines, %d rules, %d errors",
  1004.         lineno, rule, errs);
  1005. #endif
  1006.  
  1007. #if MIME_MAGIC_DEBUG
  1008.     prevm = 0;
  1009.     ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, s,
  1010.         MODNAME ": apprentice test");
  1011.     for (m = conf->magic; m; m = m->next) {
  1012.     if (ap_isprint((((unsigned long) m) >> 24) & 255) &&
  1013.         ap_isprint((((unsigned long) m) >> 16) & 255) &&
  1014.         ap_isprint((((unsigned long) m) >> 8) & 255) &&
  1015.         ap_isprint(((unsigned long) m) & 255)) {
  1016.         ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, s,
  1017.             MODNAME ": apprentice: POINTER CLOBBERED! "
  1018.             "m=\"%c%c%c%c\" line=%d",
  1019.             (((unsigned long) m) >> 24) & 255,
  1020.             (((unsigned long) m) >> 16) & 255,
  1021.             (((unsigned long) m) >> 8) & 255,
  1022.             ((unsigned long) m) & 255,
  1023.             prevm ? prevm->lineno : -1);
  1024.         break;
  1025.     }
  1026.     prevm = m;
  1027.     }
  1028. #endif
  1029.  
  1030.     return (errs ? -1 : 0);
  1031. }
  1032.  
  1033. /*
  1034.  * extend the sign bit if the comparison is to be signed
  1035.  */
  1036. static unsigned long signextend(server_rec *s, struct magic *m, unsigned long v)
  1037. {
  1038.     if (!(m->flag & UNSIGNED))
  1039.     switch (m->type) {
  1040.         /*
  1041.          * Do not remove the casts below.  They are vital. When later
  1042.          * compared with the data, the sign extension must have happened.
  1043.          */
  1044.     case BYTE:
  1045.         v = (char) v;
  1046.         break;
  1047.     case SHORT:
  1048.     case BESHORT:
  1049.     case LESHORT:
  1050.         v = (short) v;
  1051.         break;
  1052.     case DATE:
  1053.     case BEDATE:
  1054.     case LEDATE:
  1055.     case LONG:
  1056.     case BELONG:
  1057.     case LELONG:
  1058.         v = (long) v;
  1059.         break;
  1060.     case STRING:
  1061.         break;
  1062.     default:
  1063.         ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, s,
  1064.             MODNAME ": can't happen: m->type=%d", m->type);
  1065.         return -1;
  1066.     }
  1067.     return v;
  1068. }
  1069.  
  1070. /*
  1071.  * parse one line from magic file, put into magic[index++] if valid
  1072.  */
  1073. static int parse(server_rec *serv, pool *p, char *l, int lineno)
  1074. {
  1075.     struct magic *m;
  1076.     char *t, *s;
  1077.     magic_server_config_rec *conf = (magic_server_config_rec *)
  1078.             ap_get_module_config(serv->module_config, &mime_magic_module);
  1079.  
  1080.     /* allocate magic structure entry */
  1081.     m = (struct magic *) ap_pcalloc(p, sizeof(struct magic));
  1082.  
  1083.     /* append to linked list */
  1084.     m->next = NULL;
  1085.     if (!conf->magic || !conf->last) {
  1086.     conf->magic = conf->last = m;
  1087.     }
  1088.     else {
  1089.     conf->last->next = m;
  1090.     conf->last = m;
  1091.     }
  1092.  
  1093.     /* set values in magic structure */
  1094.     m->flag = 0;
  1095.     m->cont_level = 0;
  1096.     m->lineno = lineno;
  1097.  
  1098.     while (*l == '>') {
  1099.     ++l;            /* step over */
  1100.     m->cont_level++;
  1101.     }
  1102.  
  1103.     if (m->cont_level != 0 && *l == '(') {
  1104.     ++l;            /* step over */
  1105.     m->flag |= INDIR;
  1106.     }
  1107.  
  1108.     /* get offset, then skip over it */
  1109.     m->offset = (int) strtol(l, &t, 0);
  1110.     if (l == t) {
  1111.     ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, serv,
  1112.             MODNAME ": offset %s invalid", l);
  1113.     }
  1114.     l = t;
  1115.  
  1116.     if (m->flag & INDIR) {
  1117.     m->in.type = LONG;
  1118.     m->in.offset = 0;
  1119.     /*
  1120.      * read [.lbs][+-]nnnnn)
  1121.      */
  1122.     if (*l == '.') {
  1123.         switch (*++l) {
  1124.         case 'l':
  1125.         m->in.type = LONG;
  1126.         break;
  1127.         case 's':
  1128.         m->in.type = SHORT;
  1129.         break;
  1130.         case 'b':
  1131.         m->in.type = BYTE;
  1132.         break;
  1133.         default:
  1134.         ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, serv,
  1135.             MODNAME ": indirect offset type %c invalid", *l);
  1136.         break;
  1137.         }
  1138.         l++;
  1139.     }
  1140.     s = l;
  1141.     if (*l == '+' || *l == '-')
  1142.         l++;
  1143.     if (ap_isdigit((unsigned char) *l)) {
  1144.         m->in.offset = strtol(l, &t, 0);
  1145.         if (*s == '-')
  1146.         m->in.offset = -m->in.offset;
  1147.     }
  1148.     else
  1149.         t = l;
  1150.     if (*t++ != ')') {
  1151.         ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, serv,
  1152.             MODNAME ": missing ')' in indirect offset");
  1153.     }
  1154.     l = t;
  1155.     }
  1156.  
  1157.  
  1158.     while (ap_isdigit((unsigned char) *l))
  1159.     ++l;
  1160.     EATAB;
  1161.  
  1162. #define NBYTE           4
  1163. #define NSHORT          5
  1164. #define NLONG           4
  1165. #define NSTRING         6
  1166. #define NDATE           4
  1167. #define NBESHORT        7
  1168. #define NBELONG         6
  1169. #define NBEDATE         6
  1170. #define NLESHORT        7
  1171. #define NLELONG         6
  1172. #define NLEDATE         6
  1173.  
  1174.     if (*l == 'u') {
  1175.     ++l;
  1176.     m->flag |= UNSIGNED;
  1177.     }
  1178.  
  1179.     /* get type, skip it */
  1180.     if (strncmp(l, "byte", NBYTE) == 0) {
  1181.     m->type = BYTE;
  1182.     l += NBYTE;
  1183.     }
  1184.     else if (strncmp(l, "short", NSHORT) == 0) {
  1185.     m->type = SHORT;
  1186.     l += NSHORT;
  1187.     }
  1188.     else if (strncmp(l, "long", NLONG) == 0) {
  1189.     m->type = LONG;
  1190.     l += NLONG;
  1191.     }
  1192.     else if (strncmp(l, "string", NSTRING) == 0) {
  1193.     m->type = STRING;
  1194.     l += NSTRING;
  1195.     }
  1196.     else if (strncmp(l, "date", NDATE) == 0) {
  1197.     m->type = DATE;
  1198.     l += NDATE;
  1199.     }
  1200.     else if (strncmp(l, "beshort", NBESHORT) == 0) {
  1201.     m->type = BESHORT;
  1202.     l += NBESHORT;
  1203.     }
  1204.     else if (strncmp(l, "belong", NBELONG) == 0) {
  1205.     m->type = BELONG;
  1206.     l += NBELONG;
  1207.     }
  1208.     else if (strncmp(l, "bedate", NBEDATE) == 0) {
  1209.     m->type = BEDATE;
  1210.     l += NBEDATE;
  1211.     }
  1212.     else if (strncmp(l, "leshort", NLESHORT) == 0) {
  1213.     m->type = LESHORT;
  1214.     l += NLESHORT;
  1215.     }
  1216.     else if (strncmp(l, "lelong", NLELONG) == 0) {
  1217.     m->type = LELONG;
  1218.     l += NLELONG;
  1219.     }
  1220.     else if (strncmp(l, "ledate", NLEDATE) == 0) {
  1221.     m->type = LEDATE;
  1222.     l += NLEDATE;
  1223.     }
  1224.     else {
  1225.     ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, serv,
  1226.             MODNAME ": type %s invalid", l);
  1227.     return -1;
  1228.     }
  1229.     /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
  1230.     if (*l == '&') {
  1231.     ++l;
  1232.     m->mask = signextend(serv, m, strtol(l, &l, 0));
  1233.     }
  1234.     else
  1235.     m->mask = ~0L;
  1236.     EATAB;
  1237.  
  1238.     switch (*l) {
  1239.     case '>':
  1240.     case '<':
  1241.     /* Old-style anding: "0 byte &0x80 dynamically linked" */
  1242.     case '&':
  1243.     case '^':
  1244.     case '=':
  1245.     m->reln = *l;
  1246.     ++l;
  1247.     break;
  1248.     case '!':
  1249.     if (m->type != STRING) {
  1250.         m->reln = *l;
  1251.         ++l;
  1252.         break;
  1253.     }
  1254.     /* FALL THROUGH */
  1255.     default:
  1256.     if (*l == 'x' && ap_isspace((unsigned char) l[1])) {
  1257.         m->reln = *l;
  1258.         ++l;
  1259.         goto GetDesc;    /* Bill The Cat */
  1260.     }
  1261.     m->reln = '=';
  1262.     break;
  1263.     }
  1264.     EATAB;
  1265.  
  1266.     if (getvalue(serv, m, &l))
  1267.     return -1;
  1268.     /*
  1269.      * now get last part - the description
  1270.      */
  1271.   GetDesc:
  1272.     EATAB;
  1273.     if (l[0] == '\b') {
  1274.     ++l;
  1275.     m->nospflag = 1;
  1276.     }
  1277.     else if ((l[0] == '\\') && (l[1] == 'b')) {
  1278.     ++l;
  1279.     ++l;
  1280.     m->nospflag = 1;
  1281.     }
  1282.     else
  1283.     m->nospflag = 0;
  1284.     strncpy(m->desc, l, sizeof(m->desc) - 1);
  1285.     m->desc[sizeof(m->desc) - 1] = '\0';
  1286.  
  1287. #if MIME_MAGIC_DEBUG
  1288.     ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, serv,
  1289.         MODNAME ": parse line=%d m=%x next=%x cont=%d desc=%s",
  1290.         lineno, m, m->next, m->cont_level, m->desc);
  1291. #endif /* MIME_MAGIC_DEBUG */
  1292.  
  1293.     return 0;
  1294. }
  1295.  
  1296. /*
  1297.  * Read a numeric value from a pointer, into the value union of a magic
  1298.  * pointer, according to the magic type.  Update the string pointer to point
  1299.  * just after the number read.  Return 0 for success, non-zero for failure.
  1300.  */
  1301. static int getvalue(server_rec *s, struct magic *m, char **p)
  1302. {
  1303.     int slen;
  1304.  
  1305.     if (m->type == STRING) {
  1306.     *p = getstr(s, *p, m->value.s, sizeof(m->value.s), &slen);
  1307.     m->vallen = slen;
  1308.     }
  1309.     else if (m->reln != 'x')
  1310.     m->value.l = signextend(s, m, strtol(*p, p, 0));
  1311.     return 0;
  1312. }
  1313.  
  1314. /*
  1315.  * Convert a string containing C character escapes.  Stop at an unescaped
  1316.  * space or tab. Copy the converted version to "p", returning its length in
  1317.  * *slen. Return updated scan pointer as function result.
  1318.  */
  1319. static char *getstr(server_rec *serv, register char *s, register char *p,
  1320.             int plen, int *slen)
  1321. {
  1322.     char *origs = s, *origp = p;
  1323.     char *pmax = p + plen - 1;
  1324.     register int c;
  1325.     register int val;
  1326.  
  1327.     while ((c = *s++) != '\0') {
  1328.     if (ap_isspace((unsigned char) c))
  1329.         break;
  1330.     if (p >= pmax) {
  1331.         ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, serv,
  1332.             MODNAME ": string too long: %s", origs);
  1333.         break;
  1334.     }
  1335.     if (c == '\\') {
  1336.         switch (c = *s++) {
  1337.  
  1338.         case '\0':
  1339.         goto out;
  1340.  
  1341.         default:
  1342.         *p++ = (char) c;
  1343.         break;
  1344.  
  1345.         case 'n':
  1346.         *p++ = '\n';
  1347.         break;
  1348.  
  1349.         case 'r':
  1350.         *p++ = '\r';
  1351.         break;
  1352.  
  1353.         case 'b':
  1354.         *p++ = '\b';
  1355.         break;
  1356.  
  1357.         case 't':
  1358.         *p++ = '\t';
  1359.         break;
  1360.  
  1361.         case 'f':
  1362.         *p++ = '\f';
  1363.         break;
  1364.  
  1365.         case 'v':
  1366.         *p++ = '\v';
  1367.         break;
  1368.  
  1369.         /* \ and up to 3 octal digits */
  1370.         case '0':
  1371.         case '1':
  1372.         case '2':
  1373.         case '3':
  1374.         case '4':
  1375.         case '5':
  1376.         case '6':
  1377.         case '7':
  1378.         val = c - '0';
  1379.         c = *s++;    /* try for 2 */
  1380.         if (c >= '0' && c <= '7') {
  1381.             val = (val << 3) | (c - '0');
  1382.             c = *s++;    /* try for 3 */
  1383.             if (c >= '0' && c <= '7')
  1384.             val = (val << 3) | (c - '0');
  1385.             else
  1386.             --s;
  1387.         }
  1388.         else
  1389.             --s;
  1390.         *p++ = (char) val;
  1391.         break;
  1392.  
  1393.         /* \x and up to 3 hex digits */
  1394.         case 'x':
  1395.         val = 'x';    /* Default if no digits */
  1396.         c = hextoint(*s++);    /* Get next char */
  1397.         if (c >= 0) {
  1398.             val = c;
  1399.             c = hextoint(*s++);
  1400.             if (c >= 0) {
  1401.             val = (val << 4) + c;
  1402.             c = hextoint(*s++);
  1403.             if (c >= 0) {
  1404.                 val = (val << 4) + c;
  1405.             }
  1406.             else
  1407.                 --s;
  1408.             }
  1409.             else
  1410.             --s;
  1411.         }
  1412.         else
  1413.             --s;
  1414.         *p++ = (char) val;
  1415.         break;
  1416.         }
  1417.     }
  1418.     else
  1419.         *p++ = (char) c;
  1420.     }
  1421.   out:
  1422.     *p = '\0';
  1423.     *slen = p - origp;
  1424.     return s;
  1425. }
  1426.  
  1427.  
  1428. /* Single hex char to int; -1 if not a hex char. */
  1429. static int hextoint(int c)
  1430. {
  1431.     if (ap_isdigit((unsigned char) c))
  1432.     return c - '0';
  1433.     if ((c >= 'a') && (c <= 'f'))
  1434.     return c + 10 - 'a';
  1435.     if ((c >= 'A') && (c <= 'F'))
  1436.     return c + 10 - 'A';
  1437.     return -1;
  1438. }
  1439.  
  1440.  
  1441. /*
  1442.  * return DONE to indicate it's been handled
  1443.  * return OK to indicate it's a regular file still needing handling
  1444.  * other returns indicate a failure of some sort
  1445.  */
  1446. static int fsmagic(request_rec *r, const char *fn)
  1447. {
  1448.     switch (r->finfo.st_mode & S_IFMT) {
  1449.     case S_IFDIR:
  1450.     magic_rsl_puts(r, DIR_MAGIC_TYPE);
  1451.     return DONE;
  1452.     case S_IFCHR:
  1453.     /*
  1454.      * (void) magic_rsl_printf(r,"character special (%d/%d)",
  1455.      * major(sb->st_rdev), minor(sb->st_rdev));
  1456.      */
  1457.     (void) magic_rsl_puts(r, MIME_BINARY_UNKNOWN);
  1458.     return DONE;
  1459. #ifdef S_IFBLK
  1460.     case S_IFBLK:
  1461.     /*
  1462.      * (void) magic_rsl_printf(r,"block special (%d/%d)",
  1463.      * major(sb->st_rdev), minor(sb->st_rdev));
  1464.      */
  1465.     (void) magic_rsl_puts(r, MIME_BINARY_UNKNOWN);
  1466.     return DONE;
  1467.     /* TODO add code to handle V7 MUX and Blit MUX files */
  1468. #endif
  1469. #ifdef    S_IFIFO
  1470.     case S_IFIFO:
  1471.     /*
  1472.      * magic_rsl_puts(r,"fifo (named pipe)");
  1473.      */
  1474.     (void) magic_rsl_puts(r, MIME_BINARY_UNKNOWN);
  1475.     return DONE;
  1476. #endif
  1477. #ifdef    S_IFLNK
  1478.     case S_IFLNK:
  1479.     /* We used stat(), the only possible reason for this is that the
  1480.      * symlink is broken.
  1481.      */
  1482.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, r,
  1483.             MODNAME ": broken symlink (%s)", fn);
  1484.     return HTTP_INTERNAL_SERVER_ERROR;
  1485. #endif
  1486. #ifdef    S_IFSOCK
  1487. #ifndef __COHERENT__
  1488.     case S_IFSOCK:
  1489.     magic_rsl_puts(r, MIME_BINARY_UNKNOWN);
  1490.     return DONE;
  1491. #endif
  1492. #endif
  1493.     case S_IFREG:
  1494.     break;
  1495.     default:
  1496.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, r,
  1497.             MODNAME ": invalid mode 0%o.", (unsigned int)r->finfo.st_mode);
  1498.     return HTTP_INTERNAL_SERVER_ERROR;
  1499.     }
  1500.  
  1501.     /*
  1502.      * regular file, check next possibility
  1503.      */
  1504.     if (r->finfo.st_size == 0) {
  1505.     magic_rsl_puts(r, MIME_TEXT_UNKNOWN);
  1506.     return DONE;
  1507.     }
  1508.     return OK;
  1509. }
  1510.  
  1511. /*
  1512.  * softmagic - lookup one file in database (already read from /etc/magic by
  1513.  * apprentice.c). Passed the name and FILE * of one file to be typed.
  1514.  */
  1515.         /* ARGSUSED1 *//* nbytes passed for regularity, maybe need later */
  1516. static int softmagic(request_rec *r, unsigned char *buf, int nbytes)
  1517. {
  1518.     if (match(r, buf, nbytes))
  1519.     return 1;
  1520.  
  1521.     return 0;
  1522. }
  1523.  
  1524. /*
  1525.  * Go through the whole list, stopping if you find a match.  Process all the
  1526.  * continuations of that match before returning.
  1527.  *
  1528.  * We support multi-level continuations:
  1529.  *
  1530.  * At any time when processing a successful top-level match, there is a current
  1531.  * continuation level; it represents the level of the last successfully
  1532.  * matched continuation.
  1533.  *
  1534.  * Continuations above that level are skipped as, if we see one, it means that
  1535.  * the continuation that controls them - i.e, the lower-level continuation
  1536.  * preceding them - failed to match.
  1537.  *
  1538.  * Continuations below that level are processed as, if we see one, it means
  1539.  * we've finished processing or skipping higher-level continuations under the
  1540.  * control of a successful or unsuccessful lower-level continuation, and are
  1541.  * now seeing the next lower-level continuation and should process it.  The
  1542.  * current continuation level reverts to the level of the one we're seeing.
  1543.  *
  1544.  * Continuations at the current level are processed as, if we see one, there's
  1545.  * no lower-level continuation that may have failed.
  1546.  *
  1547.  * If a continuation matches, we bump the current continuation level so that
  1548.  * higher-level continuations are processed.
  1549.  */
  1550. static int match(request_rec *r, unsigned char *s, int nbytes)
  1551. {
  1552. #if MIME_MAGIC_DEBUG
  1553.     int rule_counter = 0;
  1554. #endif
  1555.     int cont_level = 0;
  1556.     int need_separator = 0;
  1557.     union VALUETYPE p;
  1558.     magic_server_config_rec *conf = (magic_server_config_rec *)
  1559.         ap_get_module_config(r->server->module_config, &mime_magic_module);
  1560.     struct magic *m;
  1561.  
  1562. #if MIME_MAGIC_DEBUG
  1563.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1564.         MODNAME ": match conf=%x file=%s m=%s m->next=%s last=%s",
  1565.         conf,
  1566.         conf->magicfile ? conf->magicfile : "NULL",
  1567.         conf->magic ? "set" : "NULL",
  1568.         (conf->magic && conf->magic->next) ? "set" : "NULL",
  1569.         conf->last ? "set" : "NULL");
  1570. #endif
  1571.  
  1572. #if MIME_MAGIC_DEBUG
  1573.     for (m = conf->magic; m; m = m->next) {
  1574.     if (ap_isprint((((unsigned long) m) >> 24) & 255) &&
  1575.         ap_isprint((((unsigned long) m) >> 16) & 255) &&
  1576.         ap_isprint((((unsigned long) m) >> 8) & 255) &&
  1577.         ap_isprint(((unsigned long) m) & 255)) {
  1578.         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1579.             MODNAME ": match: POINTER CLOBBERED! "
  1580.             "m=\"%c%c%c%c\"",
  1581.             (((unsigned long) m) >> 24) & 255,
  1582.             (((unsigned long) m) >> 16) & 255,
  1583.             (((unsigned long) m) >> 8) & 255,
  1584.             ((unsigned long) m) & 255);
  1585.         break;
  1586.     }
  1587.     }
  1588. #endif
  1589.  
  1590.     for (m = conf->magic; m; m = m->next) {
  1591. #if MIME_MAGIC_DEBUG
  1592.     rule_counter++;
  1593.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1594.             MODNAME ": line=%d desc=%s", m->lineno, m->desc);
  1595. #endif
  1596.  
  1597.     /* check if main entry matches */
  1598.     if (!mget(r, &p, s, m, nbytes) ||
  1599.         !mcheck(r, &p, m)) {
  1600.         struct magic *m_cont;
  1601.  
  1602.         /*
  1603.          * main entry didn't match, flush its continuations
  1604.          */
  1605.         if (!m->next || (m->next->cont_level == 0)) {
  1606.         continue;
  1607.         }
  1608.  
  1609.         m_cont = m->next;
  1610.         while (m_cont && (m_cont->cont_level != 0)) {
  1611. #if MIME_MAGIC_DEBUG
  1612.         rule_counter++;
  1613.         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1614.             MODNAME ": line=%d mc=%x mc->next=%x cont=%d desc=%s",
  1615.                 m_cont->lineno, m_cont,
  1616.                 m_cont->next, m_cont->cont_level,
  1617.                 m_cont->desc);
  1618. #endif
  1619.         /*
  1620.          * this trick allows us to keep *m in sync when the continue
  1621.          * advances the pointer
  1622.          */
  1623.         m = m_cont;
  1624.         m_cont = m_cont->next;
  1625.         }
  1626.         continue;
  1627.     }
  1628.  
  1629.     /* if we get here, the main entry rule was a match */
  1630.     /* this will be the last run through the loop */
  1631. #if MIME_MAGIC_DEBUG
  1632.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1633.             MODNAME ": rule matched, line=%d type=%d %s",
  1634.             m->lineno, m->type,
  1635.             (m->type == STRING) ? m->value.s : "");
  1636. #endif
  1637.  
  1638.     /* print the match */
  1639.     mprint(r, &p, m);
  1640.  
  1641.     /*
  1642.      * If we printed something, we'll need to print a blank before we
  1643.      * print something else.
  1644.      */
  1645.     if (m->desc[0])
  1646.         need_separator = 1;
  1647.     /* and any continuations that match */
  1648.     cont_level++;
  1649.     /*
  1650.      * while (m && m->next && m->next->cont_level != 0 && ( m = m->next
  1651.      * ))
  1652.      */
  1653.     m = m->next;
  1654.     while (m && (m->cont_level != 0)) {
  1655. #if MIME_MAGIC_DEBUG
  1656.         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1657.             MODNAME ": match line=%d cont=%d type=%d %s",
  1658.             m->lineno, m->cont_level, m->type,
  1659.             (m->type == STRING) ? m->value.s : "");
  1660. #endif
  1661.         if (cont_level >= m->cont_level) {
  1662.         if (cont_level > m->cont_level) {
  1663.             /*
  1664.              * We're at the end of the level "cont_level"
  1665.              * continuations.
  1666.              */
  1667.             cont_level = m->cont_level;
  1668.         }
  1669.         if (mget(r, &p, s, m, nbytes) &&
  1670.             mcheck(r, &p, m)) {
  1671.             /*
  1672.              * This continuation matched. Print its message, with a
  1673.              * blank before it if the previous item printed and this
  1674.              * item isn't empty.
  1675.              */
  1676.             /* space if previous printed */
  1677.             if (need_separator
  1678.             && (m->nospflag == 0)
  1679.             && (m->desc[0] != '\0')
  1680.             ) {
  1681.             (void) magic_rsl_putchar(r, ' ');
  1682.             need_separator = 0;
  1683.             }
  1684.             mprint(r, &p, m);
  1685.             if (m->desc[0])
  1686.             need_separator = 1;
  1687.  
  1688.             /*
  1689.              * If we see any continuations at a higher level, process
  1690.              * them.
  1691.              */
  1692.             cont_level++;
  1693.         }
  1694.         }
  1695.  
  1696.         /* move to next continuation record */
  1697.         m = m->next;
  1698.     }
  1699. #if MIME_MAGIC_DEBUG
  1700.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1701.             MODNAME ": matched after %d rules", rule_counter);
  1702. #endif
  1703.     return 1;        /* all through */
  1704.     }
  1705. #if MIME_MAGIC_DEBUG
  1706.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1707.         MODNAME ": failed after %d rules", rule_counter);
  1708. #endif
  1709.     return 0;            /* no match at all */
  1710. }
  1711.  
  1712. static void mprint(request_rec *r, union VALUETYPE *p, struct magic *m)
  1713. {
  1714.     char *pp, *rt;
  1715.     unsigned long v;
  1716.  
  1717.     switch (m->type) {
  1718.     case BYTE:
  1719.     v = p->b;
  1720.     break;
  1721.  
  1722.     case SHORT:
  1723.     case BESHORT:
  1724.     case LESHORT:
  1725.     v = p->h;
  1726.     break;
  1727.  
  1728.     case LONG:
  1729.     case BELONG:
  1730.     case LELONG:
  1731.     v = p->l;
  1732.     break;
  1733.  
  1734.     case STRING:
  1735.     if (m->reln == '=') {
  1736.         (void) magic_rsl_printf(r, m->desc, m->value.s);
  1737.     }
  1738.     else {
  1739.         (void) magic_rsl_printf(r, m->desc, p->s);
  1740.     }
  1741.     return;
  1742.  
  1743.     case DATE:
  1744.     case BEDATE:
  1745.     case LEDATE:
  1746.     /* XXX: not multithread safe */
  1747.     pp = ctime((time_t *) & p->l);
  1748.     if ((rt = strchr(pp, '\n')) != NULL)
  1749.         *rt = '\0';
  1750.     (void) magic_rsl_printf(r, m->desc, pp);
  1751.     return;
  1752.     default:
  1753.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, r,
  1754.             MODNAME ": invalid m->type (%d) in mprint().",
  1755.             m->type);
  1756.     return;
  1757.     }
  1758.  
  1759.     v = signextend(r->server, m, v) & m->mask;
  1760.     (void) magic_rsl_printf(r, m->desc, (unsigned long) v);
  1761. }
  1762.  
  1763. /*
  1764.  * Convert the byte order of the data we are looking at
  1765.  */
  1766. static int mconvert(request_rec *r, union VALUETYPE *p, struct magic *m)
  1767. {
  1768.     char *rt;
  1769.  
  1770.     switch (m->type) {
  1771.     case BYTE:
  1772.     case SHORT:
  1773.     case LONG:
  1774.     case DATE:
  1775.     return 1;
  1776.     case STRING:
  1777.     /* Null terminate and eat the return */
  1778.     p->s[sizeof(p->s) - 1] = '\0';
  1779.     if ((rt = strchr(p->s, '\n')) != NULL)
  1780.         *rt = '\0';
  1781.     return 1;
  1782.     case BESHORT:
  1783.     p->h = (short) ((p->hs[0] << 8) | (p->hs[1]));
  1784.     return 1;
  1785.     case BELONG:
  1786.     case BEDATE:
  1787.     p->l = (long)
  1788.         ((p->hl[0] << 24) | (p->hl[1] << 16) | (p->hl[2] << 8) | (p->hl[3]));
  1789.     return 1;
  1790.     case LESHORT:
  1791.     p->h = (short) ((p->hs[1] << 8) | (p->hs[0]));
  1792.     return 1;
  1793.     case LELONG:
  1794.     case LEDATE:
  1795.     p->l = (long)
  1796.         ((p->hl[3] << 24) | (p->hl[2] << 16) | (p->hl[1] << 8) | (p->hl[0]));
  1797.     return 1;
  1798.     default:
  1799.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, r,
  1800.             MODNAME ": invalid type %d in mconvert().", m->type);
  1801.     return 0;
  1802.     }
  1803. }
  1804.  
  1805.  
  1806. static int mget(request_rec *r, union VALUETYPE *p, unsigned char *s,
  1807.         struct magic *m, int nbytes)
  1808. {
  1809.     long offset = m->offset;
  1810.  
  1811.     if (offset + sizeof(union VALUETYPE) > nbytes)
  1812.               return 0;
  1813.  
  1814.     memcpy(p, s + offset, sizeof(union VALUETYPE));
  1815.  
  1816.     if (!mconvert(r, p, m))
  1817.     return 0;
  1818.  
  1819.     if (m->flag & INDIR) {
  1820.  
  1821.     switch (m->in.type) {
  1822.     case BYTE:
  1823.         offset = p->b + m->in.offset;
  1824.         break;
  1825.     case SHORT:
  1826.         offset = p->h + m->in.offset;
  1827.         break;
  1828.     case LONG:
  1829.         offset = p->l + m->in.offset;
  1830.         break;
  1831.     }
  1832.  
  1833.     if (offset + sizeof(union VALUETYPE) > nbytes)
  1834.                   return 0;
  1835.  
  1836.     memcpy(p, s + offset, sizeof(union VALUETYPE));
  1837.  
  1838.     if (!mconvert(r, p, m))
  1839.         return 0;
  1840.     }
  1841.     return 1;
  1842. }
  1843.  
  1844. static int mcheck(request_rec *r, union VALUETYPE *p, struct magic *m)
  1845. {
  1846.     register unsigned long l = m->value.l;
  1847.     register unsigned long v;
  1848.     int matched;
  1849.  
  1850.     if ((m->value.s[0] == 'x') && (m->value.s[1] == '\0')) {
  1851.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, r,
  1852.             MODNAME ": BOINK");
  1853.     return 1;
  1854.     }
  1855.  
  1856.     switch (m->type) {
  1857.     case BYTE:
  1858.     v = p->b;
  1859.     break;
  1860.  
  1861.     case SHORT:
  1862.     case BESHORT:
  1863.     case LESHORT:
  1864.     v = p->h;
  1865.     break;
  1866.  
  1867.     case LONG:
  1868.     case BELONG:
  1869.     case LELONG:
  1870.     case DATE:
  1871.     case BEDATE:
  1872.     case LEDATE:
  1873.     v = p->l;
  1874.     break;
  1875.  
  1876.     case STRING:
  1877.     l = 0;
  1878.     /*
  1879.      * What we want here is: v = strncmp(m->value.s, p->s, m->vallen);
  1880.      * but ignoring any nulls.  bcmp doesn't give -/+/0 and isn't
  1881.      * universally available anyway.
  1882.      */
  1883.     v = 0;
  1884.     {
  1885.         register unsigned char *a = (unsigned char *) m->value.s;
  1886.         register unsigned char *b = (unsigned char *) p->s;
  1887.         register int len = m->vallen;
  1888.  
  1889.         while (--len >= 0)
  1890.         if ((v = *b++ - *a++) != 0)
  1891.             break;
  1892.     }
  1893.     break;
  1894.     default:
  1895.     /*  bogosity, pretend that it just wasn't a match */
  1896.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, r,
  1897.             MODNAME ": invalid type %d in mcheck().", m->type);
  1898.     return 0;
  1899.     }
  1900.  
  1901.     v = signextend(r->server, m, v) & m->mask;
  1902.  
  1903.     switch (m->reln) {
  1904.     case 'x':
  1905. #if MIME_MAGIC_DEBUG
  1906.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1907.             "%lu == *any* = 1", v);
  1908. #endif
  1909.     matched = 1;
  1910.     break;
  1911.  
  1912.     case '!':
  1913.     matched = v != l;
  1914. #if MIME_MAGIC_DEBUG
  1915.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1916.             "%lu != %lu = %d", v, l, matched);
  1917. #endif
  1918.     break;
  1919.  
  1920.     case '=':
  1921.     matched = v == l;
  1922. #if MIME_MAGIC_DEBUG
  1923.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1924.             "%lu == %lu = %d", v, l, matched);
  1925. #endif
  1926.     break;
  1927.  
  1928.     case '>':
  1929.     if (m->flag & UNSIGNED) {
  1930.         matched = v > l;
  1931. #if MIME_MAGIC_DEBUG
  1932.         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1933.             "%lu > %lu = %d", v, l, matched);
  1934. #endif
  1935.     }
  1936.     else {
  1937.         matched = (long) v > (long) l;
  1938. #if MIME_MAGIC_DEBUG
  1939.         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1940.             "%ld > %ld = %d", v, l, matched);
  1941. #endif
  1942.     }
  1943.     break;
  1944.  
  1945.     case '<':
  1946.     if (m->flag & UNSIGNED) {
  1947.         matched = v < l;
  1948. #if MIME_MAGIC_DEBUG
  1949.         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1950.             "%lu < %lu = %d", v, l, matched);
  1951. #endif
  1952.     }
  1953.     else {
  1954.         matched = (long) v < (long) l;
  1955. #if MIME_MAGIC_DEBUG
  1956.         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1957.             "%ld < %ld = %d", v, l, matched);
  1958. #endif
  1959.     }
  1960.     break;
  1961.  
  1962.     case '&':
  1963.     matched = (v & l) == l;
  1964. #if MIME_MAGIC_DEBUG
  1965.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1966.             "((%lx & %lx) == %lx) = %d", v, l, l, matched);
  1967. #endif
  1968.     break;
  1969.  
  1970.     case '^':
  1971.     matched = (v & l) != l;
  1972. #if MIME_MAGIC_DEBUG
  1973.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  1974.             "((%lx & %lx) != %lx) = %d", v, l, l, matched);
  1975. #endif
  1976.     break;
  1977.  
  1978.     default:
  1979.     /* bogosity, pretend it didn't match */
  1980.     matched = 0;
  1981.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_ERR, r,
  1982.             MODNAME ": mcheck: can't happen: invalid relation %d.",
  1983.             m->reln);
  1984.     break;
  1985.     }
  1986.  
  1987.     return matched;
  1988. }
  1989.  
  1990. /* an optimization over plain strcmp() */
  1991. #define    STREQ(a, b)    (*(a) == *(b) && strcmp((a), (b)) == 0)
  1992.  
  1993. static int ascmagic(request_rec *r, unsigned char *buf, int nbytes)
  1994. {
  1995.     int has_escapes = 0;
  1996.     unsigned char *s;
  1997.     char nbuf[HOWMANY + 1];    /* one extra for terminating '\0' */
  1998.     char *token;
  1999.     register struct names *p;
  2000.     int small_nbytes;
  2001.  
  2002.     /* these are easy, do them first */
  2003.  
  2004.     /*
  2005.      * for troff, look for . + letter + letter or .\"; this must be done to
  2006.      * disambiguate tar archives' ./file and other trash from real troff
  2007.      * input.
  2008.      */
  2009.     if (*buf == '.') {
  2010.     unsigned char *tp = buf + 1;
  2011.  
  2012.     while (ap_isspace(*tp))
  2013.         ++tp;        /* skip leading whitespace */
  2014.     if ((ap_isalnum(*tp) || *tp == '\\') &&
  2015.          (ap_isalnum(*(tp + 1)) || *tp == '"')) {
  2016.         magic_rsl_puts(r, "application/x-troff");
  2017.         return 1;
  2018.     }
  2019.     }
  2020.     if ((*buf == 'c' || *buf == 'C') && ap_isspace(*(buf + 1))) {
  2021.     /* Fortran */
  2022.     magic_rsl_puts(r, "text/plain");
  2023.     return 1;
  2024.     }
  2025.  
  2026.     /* look for tokens from names.h - this is expensive!, so we'll limit
  2027.      * ourselves to only SMALL_HOWMANY bytes */
  2028.     small_nbytes = (nbytes > SMALL_HOWMANY) ? SMALL_HOWMANY : nbytes;
  2029.     /* make a copy of the buffer here because strtok() will destroy it */
  2030.     s = (unsigned char *) memcpy(nbuf, buf, small_nbytes);
  2031.     s[small_nbytes] = '\0';
  2032.     has_escapes = (memchr(s, '\033', small_nbytes) != NULL);
  2033.     /* XXX: not multithread safe */
  2034.     while ((token = strtok((char *) s, " \t\n\r\f")) != NULL) {
  2035.     s = NULL;        /* make strtok() keep on tokin' */
  2036.     for (p = names; p < names + NNAMES; p++) {
  2037.         if (STREQ(p->name, token)) {
  2038.         magic_rsl_puts(r, types[p->type]);
  2039.         if (has_escapes)
  2040.             magic_rsl_puts(r, " (with escape sequences)");
  2041.         return 1;
  2042.         }
  2043.     }
  2044.     }
  2045.  
  2046.     switch (is_tar(buf, nbytes)) {
  2047.     case 1:
  2048.     /* V7 tar archive */
  2049.     magic_rsl_puts(r, "application/x-tar");
  2050.     return 1;
  2051.     case 2:
  2052.     /* POSIX tar archive */
  2053.     magic_rsl_puts(r, "application/x-tar");
  2054.     return 1;
  2055.     }
  2056.  
  2057.     /* all else fails, but it is ascii... */
  2058.     if (has_escapes) {
  2059.     /* text with escape sequences */
  2060.     /* we leave this open for further differentiation later */
  2061.     magic_rsl_puts(r, "text/plain");
  2062.     }
  2063.     else {
  2064.     /* plain text */
  2065.     magic_rsl_puts(r, "text/plain");
  2066.     }
  2067.     return 1;
  2068. }
  2069.  
  2070.  
  2071. /*
  2072.  * compress routines: zmagic() - returns 0 if not recognized, uncompresses
  2073.  * and prints information if recognized uncompress(s, method, old, n, newch)
  2074.  * - uncompress old into new, using method, return sizeof new
  2075.  */
  2076.  
  2077. static struct {
  2078.     char *magic;
  2079.     int maglen;
  2080.     char *argv[3];
  2081.     int silent;
  2082.     char *encoding;    /* MUST be lowercase */
  2083. } compr[] = {
  2084.  
  2085.     {
  2086.     "\037\235", 2, {
  2087.         "uncompress", "-c", NULL
  2088.     }, 0, "x-compress"
  2089.     },
  2090.     {
  2091.     "\037\213", 2, {
  2092.         "gzip", "-dcq", NULL
  2093.     }, 1, "x-gzip"
  2094.     },
  2095.     /*
  2096.      * XXX pcat does not work, cause I don't know how to make it read stdin,
  2097.      * so we use gzip
  2098.      */
  2099.     {
  2100.     "\037\036", 2, {
  2101.         "gzip", "-dcq", NULL
  2102.     }, 0, "x-gzip"
  2103.     },
  2104. };
  2105.  
  2106. static int ncompr = sizeof(compr) / sizeof(compr[0]);
  2107.  
  2108. static int zmagic(request_rec *r, unsigned char *buf, int nbytes)
  2109. {
  2110.     unsigned char *newbuf;
  2111.     int newsize;
  2112.     int i;
  2113.  
  2114.     for (i = 0; i < ncompr; i++) {
  2115.     if (nbytes < compr[i].maglen)
  2116.         continue;
  2117.     if (memcmp(buf, compr[i].magic, compr[i].maglen) == 0)
  2118.         break;
  2119.     }
  2120.  
  2121.     if (i == ncompr)
  2122.     return 0;
  2123.  
  2124.     if ((newsize = uncompress(r, i, buf, &newbuf, nbytes)) > 0) {
  2125.     tryit(r, newbuf, newsize);
  2126.  
  2127.     /* set encoding type in the request record */
  2128.     r->content_encoding = compr[i].encoding;
  2129.     }
  2130.     return 1;
  2131. }
  2132.  
  2133.  
  2134. struct uncompress_parms {
  2135.     request_rec *r;
  2136.     int method;
  2137. };
  2138.  
  2139. static int uncompress_child(void *data, child_info *pinfo)
  2140. {
  2141.     struct uncompress_parms *parm = data;
  2142. #if defined(WIN32)
  2143.     int child_pid;
  2144. #endif
  2145.  
  2146.     if (compr[parm->method].silent) {
  2147.     close(STDERR_FILENO);
  2148.     }
  2149.  
  2150. #if defined(WIN32)
  2151.     child_pid = spawnvp(compr[parm->method].argv[0],
  2152.             compr[parm->method].argv);
  2153.     return (child_pid);
  2154. #else
  2155.     execvp(compr[parm->method].argv[0], compr[parm->method].argv);
  2156.     ap_log_rerror(APLOG_MARK, APLOG_ERR, parm->r,
  2157.         MODNAME ": could not execute `%s'.",
  2158.         compr[parm->method].argv[0]);
  2159.     return -1;
  2160. #endif
  2161. }
  2162.  
  2163.  
  2164. static int uncompress(request_rec *r, int method, const unsigned char *old,
  2165.               unsigned char **newch, int n)
  2166. {
  2167.     struct uncompress_parms parm;
  2168.     BUFF *bin, *bout;
  2169.     pool *sub_pool;
  2170.  
  2171.     parm.r = r;
  2172.     parm.method = method;
  2173.  
  2174.     /* We make a sub_pool so that we can collect our child early, otherwise
  2175.      * there are cases (i.e. generating directory indicies with mod_autoindex)
  2176.      * where we would end up with LOTS of zombies.
  2177.      */
  2178.     sub_pool = ap_make_sub_pool(r->pool);
  2179.  
  2180.     if (!ap_bspawn_child(sub_pool, uncompress_child, &parm, kill_always,
  2181.              &bin, &bout, NULL)) {
  2182.     ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
  2183.             MODNAME ": couldn't spawn uncompress process: %s", r->uri);
  2184.     return -1;
  2185.     }
  2186.  
  2187.     if (ap_bwrite(bin, old, n) != n) {
  2188.     ap_destroy_pool(sub_pool);
  2189.     ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
  2190.             MODNAME ": write failed.");
  2191.     return -1;
  2192.     }
  2193.     ap_bclose(bin);
  2194.     *newch = (unsigned char *) ap_palloc(r->pool, n);
  2195.     if ((n = ap_bread(bout, *newch, n)) <= 0) {
  2196.     ap_destroy_pool(sub_pool);
  2197.     ap_log_rerror(APLOG_MARK, APLOG_ERR, r,
  2198.         MODNAME ": read failed %s", r->filename);
  2199.     return -1;
  2200.     }
  2201.     ap_destroy_pool(sub_pool);
  2202.     return n;
  2203. }
  2204.  
  2205. /*
  2206.  * is_tar() -- figure out whether file is a tar archive.
  2207.  *
  2208.  * Stolen (by author of file utility) from the public domain tar program: Public
  2209.  * Domain version written 26 Aug 1985 John Gilmore (ihnp4!hoptoad!gnu).
  2210.  *
  2211.  * @(#)list.c 1.18 9/23/86 Public Domain - gnu $Id: mod_mime_magic.c,v 1.7
  2212.  * 1997/06/24 00:41:02 ikluft Exp ikluft $
  2213.  *
  2214.  * Comments changed and some code/comments reformatted for file command by Ian
  2215.  * Darwin.
  2216.  */
  2217.  
  2218. #define    isodigit(c)    ( ((c) >= '0') && ((c) <= '7') )
  2219.  
  2220. /*
  2221.  * Return 0 if the checksum is bad (i.e., probably not a tar archive), 1 for
  2222.  * old UNIX tar file, 2 for Unix Std (POSIX) tar file.
  2223.  */
  2224.  
  2225. static int is_tar(unsigned char *buf, int nbytes)
  2226. {
  2227.     register union record *header = (union record *) buf;
  2228.     register int i;
  2229.     register long sum, recsum;
  2230.     register char *p;
  2231.  
  2232.     if (nbytes < sizeof(union record))
  2233.            return 0;
  2234.  
  2235.     recsum = from_oct(8, header->header.chksum);
  2236.  
  2237.     sum = 0;
  2238.     p = header->charptr;
  2239.     for (i = sizeof(union record); --i >= 0;) {
  2240.     /*
  2241.      * We can't use unsigned char here because of old compilers, e.g. V7.
  2242.      */
  2243.     sum += 0xFF & *p++;
  2244.     }
  2245.  
  2246.     /* Adjust checksum to count the "chksum" field as blanks. */
  2247.     for (i = sizeof(header->header.chksum); --i >= 0;)
  2248.     sum -= 0xFF & header->header.chksum[i];
  2249.     sum += ' ' * sizeof header->header.chksum;
  2250.  
  2251.     if (sum != recsum)
  2252.     return 0;        /* Not a tar archive */
  2253.  
  2254.     if (0 == strcmp(header->header.magic, TMAGIC))
  2255.     return 2;        /* Unix Standard tar archive */
  2256.  
  2257.     return 1;            /* Old fashioned tar archive */
  2258. }
  2259.  
  2260.  
  2261. /*
  2262.  * Quick and dirty octal conversion.
  2263.  *
  2264.  * Result is -1 if the field is invalid (all blank, or nonoctal).
  2265.  */
  2266. static long from_oct(int digs, char *where)
  2267. {
  2268.     register long value;
  2269.  
  2270.     while (ap_isspace(*where)) {    /* Skip spaces */
  2271.     where++;
  2272.     if (--digs <= 0)
  2273.         return -1;        /* All blank field */
  2274.     }
  2275.     value = 0;
  2276.     while (digs > 0 && isodigit(*where)) {    /* Scan til nonoctal */
  2277.     value = (value << 3) | (*where++ - '0');
  2278.     --digs;
  2279.     }
  2280.  
  2281.     if (digs > 0 && *where && !ap_isspace(*where))
  2282.     return -1;        /* Ended on non-space/nul */
  2283.  
  2284.     return value;
  2285. }
  2286.  
  2287. /*
  2288.  * Check for file-revision suffix
  2289.  *
  2290.  * This is for an obscure document control system used on an intranet.
  2291.  * The web representation of each file's revision has an @1, @2, etc
  2292.  * appended with the revision number.  This needs to be stripped off to
  2293.  * find the file suffix, which can be recognized by sending the name back
  2294.  * through a sub-request.  The base file name (without the @num suffix)
  2295.  * must exist because its type will be used as the result.
  2296.  */
  2297. static int revision_suffix(request_rec *r)
  2298. {
  2299.     int suffix_pos, result;
  2300.     char *sub_filename;
  2301.     request_rec *sub;
  2302.  
  2303. #if MIME_MAGIC_DEBUG
  2304.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  2305.         MODNAME ": revision_suffix checking %s", r->filename);
  2306. #endif /* MIME_MAGIC_DEBUG */
  2307.  
  2308.     /* check for recognized revision suffix */
  2309.     suffix_pos = strlen(r->filename) - 1;
  2310.     if (!ap_isdigit(r->filename[suffix_pos])) {
  2311.     return 0;
  2312.     }
  2313.     while (suffix_pos >= 0 && ap_isdigit(r->filename[suffix_pos]))
  2314.     suffix_pos--;
  2315.     if (suffix_pos < 0 || r->filename[suffix_pos] != '@') {
  2316.     return 0;
  2317.     }
  2318.  
  2319.     /* perform sub-request for the file name without the suffix */
  2320.     result = 0;
  2321.     sub_filename = ap_pstrndup(r->pool, r->filename, suffix_pos);
  2322. #if MIME_MAGIC_DEBUG
  2323.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  2324.         MODNAME ": subrequest lookup for %s", sub_filename);
  2325. #endif /* MIME_MAGIC_DEBUG */
  2326.     sub = ap_sub_req_lookup_file(sub_filename, r);
  2327.  
  2328.     /* extract content type/encoding/language from sub-request */
  2329.     if (sub->content_type) {
  2330.     r->content_type = ap_pstrdup(r->pool, sub->content_type);
  2331. #if MIME_MAGIC_DEBUG
  2332.     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, r,
  2333.             MODNAME ": subrequest %s got %s",
  2334.             sub_filename, r->content_type);
  2335. #endif /* MIME_MAGIC_DEBUG */
  2336.     if (sub->content_encoding)
  2337.         r->content_encoding =
  2338.         ap_pstrdup(r->pool, sub->content_encoding);
  2339.     if (sub->content_language)
  2340.         r->content_language =
  2341.         ap_pstrdup(r->pool, sub->content_language);
  2342.     result = 1;
  2343.     }
  2344.  
  2345.     /* clean up */
  2346.     ap_destroy_sub_req(sub);
  2347.  
  2348.     return result;
  2349. }
  2350.  
  2351. /*
  2352.  * initialize the module
  2353.  */
  2354.  
  2355. static void magic_init(server_rec *main_server, pool *p)
  2356. {
  2357.     int result;
  2358.     magic_server_config_rec *conf;
  2359.     magic_server_config_rec *main_conf;
  2360.     server_rec *s;
  2361. #if MIME_MAGIC_DEBUG
  2362.     struct magic *m, *prevm;
  2363. #endif /* MIME_MAGIC_DEBUG */
  2364.  
  2365.     main_conf = ap_get_module_config(main_server->module_config, &mime_magic_module);
  2366.     for (s = main_server; s; s = s->next) {
  2367.     conf = ap_get_module_config(s->module_config, &mime_magic_module);
  2368.     if (conf->magicfile == NULL && s != main_server) {
  2369.         /* inherits from the parent */
  2370.         *conf = *main_conf;
  2371.     }
  2372.     else if (conf->magicfile) {
  2373.         result = apprentice(s, p);
  2374.         if (result == -1)
  2375.         return;
  2376. #if MIME_MAGIC_DEBUG
  2377.         prevm = 0;
  2378.         ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, s,
  2379.             MODNAME ": magic_init 1 test");
  2380.         for (m = conf->magic; m; m = m->next) {
  2381.         if (ap_isprint((((unsigned long) m) >> 24) & 255) &&
  2382.             ap_isprint((((unsigned long) m) >> 16) & 255) &&
  2383.             ap_isprint((((unsigned long) m) >> 8) & 255) &&
  2384.             ap_isprint(((unsigned long) m) & 255)) {
  2385.             ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_DEBUG, s,
  2386.                 MODNAME ": magic_init 1: POINTER CLOBBERED! "
  2387.                 "m=\"%c%c%c%c\" line=%d",
  2388.                 (((unsigned long) m) >> 24) & 255,
  2389.                 (((unsigned long) m) >> 16) & 255,
  2390.                 (((unsigned long) m) >> 8) & 255,
  2391.                 ((unsigned long) m) & 255,
  2392.                 prevm ? prevm->lineno : -1);
  2393.             break;
  2394.         }
  2395.         prevm = m;
  2396.         }
  2397. #endif
  2398.     }
  2399.     }
  2400. }
  2401.  
  2402. /*
  2403.  * Find the Content-Type from any resource this module has available
  2404.  */
  2405.  
  2406. static int magic_find_ct(request_rec *r)
  2407. {
  2408.     int result;
  2409.     magic_server_config_rec *conf;
  2410.  
  2411.     /* the file has to exist */
  2412.     if (r->finfo.st_mode == 0 || !r->filename) {
  2413.     return DECLINED;
  2414.     }
  2415.  
  2416.     /* was someone else already here? */
  2417.     if (r->content_type) {
  2418.     return DECLINED;
  2419.     }
  2420.  
  2421.     conf = ap_get_module_config(r->server->module_config, &mime_magic_module);
  2422.     if (!conf || !conf->magic) {
  2423.     return DECLINED;
  2424.     }
  2425.  
  2426.     /* initialize per-request info */
  2427.     if (!magic_set_config(r)) {
  2428.     return HTTP_INTERNAL_SERVER_ERROR;
  2429.     }
  2430.  
  2431.     /* try excluding file-revision suffixes */
  2432.     if (revision_suffix(r) != 1) {
  2433.     /* process it based on the file contents */
  2434.     if ((result = magic_process(r)) != OK) {
  2435.         return result;
  2436.     }
  2437.     }
  2438.  
  2439.     /* if we have any results, put them in the request structure */
  2440.     return magic_rsl_to_request(r);
  2441. }
  2442.  
  2443. /*
  2444.  * Apache API module interface
  2445.  */
  2446.  
  2447. module mime_magic_module =
  2448. {
  2449.     STANDARD_MODULE_STUFF,
  2450.     magic_init,            /* initializer */
  2451.     NULL,            /* dir config creator */
  2452.     NULL,            /* dir merger --- default is to override */
  2453.     create_magic_server_config,    /* server config */
  2454.     merge_magic_server_config,    /* merge server config */
  2455.     mime_magic_cmds,        /* command table */
  2456.     NULL,            /* handlers */
  2457.     NULL,            /* filename translation */
  2458.     NULL,            /* check_user_id */
  2459.     NULL,            /* check auth */
  2460.     NULL,            /* check access */
  2461.     magic_find_ct,        /* type_checker */
  2462.     NULL,            /* fixups */
  2463.     NULL,            /* logger */
  2464.     NULL,            /* header parser */
  2465.     NULL,            /* child_init */
  2466.     NULL,            /* child_exit */
  2467.     NULL            /* post read-request */
  2468. };
  2469.