aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

mgtext.c (21859B)


      1 /* see LICENSE file for copyright and license details */
      2 #ifndef _POSIX_C_SOURCE
      3 #define _POSIX_C_SOURCE 200809L
      4 #endif
      5 
      6 #include "mgint.h"
      7 
      8 #include <stdlib.h>
      9 #include <string.h>
     10 
     11 /* a line longer than this is reported as very long */
     12 #define MAXLINELEN 300
     13 
     14 #define JSON_MAXDEPTH 500
     15 #define CSV_LINES     10
     16 
     17 /* what a byte is in text: never, ascii, iso-8859 or other extended ascii */
     18 enum TextClass { TC_F, TC_T, TC_I, TC_X };
     19 
     20 static const unsigned char text_chars[256] = {
     21     /* bel bs ht lf vt ff cr are text, so are sub and esc */
     22     0,
     23     0,
     24     0,
     25     0,
     26     0,
     27     0,
     28     0,
     29     1,
     30     1,
     31     1,
     32     1,
     33     1,
     34     1,
     35     1,
     36     0,
     37     0,
     38     0,
     39     0,
     40     0,
     41     0,
     42     0,
     43     0,
     44     0,
     45     0,
     46     0,
     47     0,
     48     1,
     49     1,
     50     0,
     51     0,
     52     0,
     53     0,
     54     1,
     55     1,
     56     1,
     57     1,
     58     1,
     59     1,
     60     1,
     61     1,
     62     1,
     63     1,
     64     1,
     65     1,
     66     1,
     67     1,
     68     1,
     69     1,
     70     1,
     71     1,
     72     1,
     73     1,
     74     1,
     75     1,
     76     1,
     77     1,
     78     1,
     79     1,
     80     1,
     81     1,
     82     1,
     83     1,
     84     1,
     85     1,
     86     1,
     87     1,
     88     1,
     89     1,
     90     1,
     91     1,
     92     1,
     93     1,
     94     1,
     95     1,
     96     1,
     97     1,
     98     1,
     99     1,
    100     1,
    101     1,
    102     1,
    103     1,
    104     1,
    105     1,
    106     1,
    107     1,
    108     1,
    109     1,
    110     1,
    111     1,
    112     1,
    113     1,
    114     1,
    115     1,
    116     1,
    117     1,
    118     1,
    119     1,
    120     1,
    121     1,
    122     1,
    123     1,
    124     1,
    125     1,
    126     1,
    127     1,
    128     1,
    129     1,
    130     1,
    131     1,
    132     1,
    133     1,
    134     1,
    135     1,
    136     1,
    137     1,
    138     1,
    139     1,
    140     1,
    141     1,
    142     1,
    143     1,
    144     1,
    145     1,
    146     1,
    147     1,
    148     1,
    149     0,
    150     /* nel, 0x85, counts as ascii text */
    151     3,
    152     3,
    153     3,
    154     3,
    155     3,
    156     1,
    157     3,
    158     3,
    159     3,
    160     3,
    161     3,
    162     3,
    163     3,
    164     3,
    165     3,
    166     3,
    167     3,
    168     3,
    169     3,
    170     3,
    171     3,
    172     3,
    173     3,
    174     3,
    175     3,
    176     3,
    177     3,
    178     3,
    179     3,
    180     3,
    181     3,
    182     3,
    183     2,
    184     2,
    185     2,
    186     2,
    187     2,
    188     2,
    189     2,
    190     2,
    191     2,
    192     2,
    193     2,
    194     2,
    195     2,
    196     2,
    197     2,
    198     2,
    199     2,
    200     2,
    201     2,
    202     2,
    203     2,
    204     2,
    205     2,
    206     2,
    207     2,
    208     2,
    209     2,
    210     2,
    211     2,
    212     2,
    213     2,
    214     2,
    215     2,
    216     2,
    217     2,
    218     2,
    219     2,
    220     2,
    221     2,
    222     2,
    223     2,
    224     2,
    225     2,
    226     2,
    227     2,
    228     2,
    229     2,
    230     2,
    231     2,
    232     2,
    233     2,
    234     2,
    235     2,
    236     2,
    237     2,
    238     2,
    239     2,
    240     2,
    241     2,
    242     2,
    243     2,
    244     2,
    245     2,
    246     2,
    247     2,
    248     2,
    249     2,
    250     2,
    251     2,
    252     2,
    253     2,
    254     2,
    255     2,
    256     2,
    257     2,
    258     2,
    259     2,
    260     2,
    261     2,
    262     2,
    263     2,
    264     2,
    265     2,
    266     2,
    267     2,
    268     2,
    269     2,
    270     2,
    271     2,
    272     2,
    273     2,
    274     2,
    275     2,
    276     2,
    277     2,
    278     2,
    279 };
    280 
    281 /* the dd(1) ebcdic to ascii table of posix p1003.2 draft 11.2 */
    282 static const unsigned char ebcdic_to_ascii[256] = {
    283     0,   1,   2,   3,   156, 9,   134, 127, 151, 141, 142, 11,   12,  13,  14,  15,   16,  17,  18,
    284     19,  157, 133, 8,   135, 24,  25,  146, 143, 28,  29,  30,   31,  128, 129, 130,  131, 132, 10,
    285     23,  27,  136, 137, 138, 139, 140, 5,   6,   7,   144, 145,  22,  147, 148, 149,  150, 4,   152,
    286     153, 154, 155, 20,  21,  158, 26,  ' ', 160, 161, 162, 163,  164, 165, 166, 167,  168, 213, '.',
    287     '<', '(', '+', '|', '&', 169, 170, 171, 172, 173, 174, 175,  176, 177, '!', '$',  '*', ')', ';',
    288     '~', '-', '/', 178, 179, 180, 181, 182, 183, 184, 185, 203,  ',', '%', '_', '>',  '?', 186, 187,
    289     188, 189, 190, 191, 192, 193, 194, '`', ':', '#', '@', '\'', '=', '"', 195, 'a',  'b', 'c', 'd',
    290     'e', 'f', 'g', 'h', 'i', 196, 197, 198, 199, 200, 201, 202,  'j', 'k', 'l', 'm',  'n', 'o', 'p',
    291     'q', 'r', '^', 204, 205, 206, 207, 208, 209, 229, 's', 't',  'u', 'v', 'w', 'x',  'y', 'z', 210,
    292     211, 212, '[', 214, 215, 216, 217, 218, 219, 220, 221, 222,  223, 224, 225, 226,  227, 228, ']',
    293     230, 231, '{', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',  232, 233, 234, 235,  236, 237, '}',
    294     'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 238, 239, 240,  241, 242, 243, '\\', 159, 'S', 'T',
    295     'U', 'V', 'W', 'X', 'Y', 'Z', 244, 245, 246, 247, 248, 249,  '0', '1', '2', '3',  '4', '5', '6',
    296     '7', '8', '9', 250, 251, 252, 253, 254, 255,
    297 };
    298 
    299 /* every byte is of class at most max */
    300 static int
    301 looks_class(const unsigned char *buf, size_t n, uint32_t *ubuf, size_t *ulen, int max)
    302 {
    303   size_t i;
    304   int    t;
    305 
    306   *ulen = 0;
    307   for (i = 0; i < n; i++) {
    308     t = text_chars[buf[i]];
    309     if (t == TC_F || t > max)
    310       return 0;
    311     ubuf[(*ulen)++] = buf[i];
    312   }
    313   return 1;
    314 }
    315 
    316 /*
    317  * -1 invalid utf-8, 0 valid but with odd control characters, 1 plain
    318  * ascii, 2 utf-8 with multibyte sequences. decodes into ubuf if given
    319  */
    320 int
    321 mg_looks_utf8(const unsigned char *buf, size_t n, uint32_t *ubuf, size_t *ulen)
    322 {
    323   uint32_t c;
    324   size_t   i;
    325   int      following, k, gotone = 0, ctrl = 0;
    326   unsigned lo, hi;
    327 
    328   if (ubuf)
    329     *ulen = 0;
    330   for (i = 0; i < n; i++) {
    331     if (!(buf[i] & 0x80)) {
    332       if (text_chars[buf[i]] != TC_T)
    333         ctrl = 1;
    334       if (ubuf)
    335         ubuf[(*ulen)++] = buf[i];
    336       continue;
    337     }
    338     if (!(buf[i] & 0x40))
    339       return -1;
    340     /* the second byte of these leads is narrower, so overlongs and surrogates fail */
    341     lo = 0x80;
    342     hi = 0xbf;
    343     if (buf[i] < 0xc2 || buf[i] > 0xf4)
    344       return -1;
    345     if (buf[i] == 0xe0)
    346       lo = 0xa0;
    347     else if (buf[i] == 0xed)
    348       hi = 0x9f;
    349     else if (buf[i] == 0xf0)
    350       lo = 0x90;
    351     else if (buf[i] == 0xf4)
    352       hi = 0x8f;
    353     if (!(buf[i] & 0x20)) {
    354       c         = buf[i] & 0x1f;
    355       following = 1;
    356     } else if (!(buf[i] & 0x10)) {
    357       c         = buf[i] & 0x0f;
    358       following = 2;
    359     } else {
    360       c         = buf[i] & 0x07;
    361       following = 3;
    362     }
    363     for (k = 0; k < following; k++) {
    364       if (++i >= n)
    365         goto done;
    366       if (k == 0 && (buf[i] < lo || buf[i] > hi))
    367         return -1;
    368       if (!(buf[i] & 0x80) || (buf[i] & 0x40))
    369         return -1;
    370       c = (c << 6) + (buf[i] & 0x3f);
    371     }
    372     if (ubuf)
    373       ubuf[(*ulen)++] = c;
    374     gotone = 1;
    375   }
    376 done:
    377   return ctrl ? 0 : (gotone ? 2 : 1);
    378 }
    379 
    380 static int
    381 looks_utf7(const unsigned char *buf, size_t n, size_t *ulen)
    382 {
    383   if (n > 4 && buf[0] == '+' && buf[1] == '/' && buf[2] == 'v') {
    384     switch (buf[3]) {
    385       case '8':
    386       case '9':
    387       case '+':
    388       case '/':
    389         *ulen = 0;
    390         return 1;
    391       default:
    392         break;
    393     }
    394   }
    395   return -1;
    396 }
    397 
    398 static int
    399 looks_ucs16(const unsigned char *b, size_t n, uint32_t *ubuf, size_t *ulen)
    400 {
    401   uint32_t uc, hi = 0;
    402   size_t   i;
    403   int      be;
    404 
    405   if (n < 2)
    406     return 0;
    407   if (b[0] == 0xff && b[1] == 0xfe)
    408     be = 0;
    409   else if (b[0] == 0xfe && b[1] == 0xff)
    410     be = 1;
    411   else
    412     return 0;
    413   *ulen = 0;
    414   for (i = 2; i + 1 < n; i += 2) {
    415     uc = be ? (uint32_t)(b[i] << 8 | b[i + 1]) : (uint32_t)(b[i + 1] << 8 | b[i]);
    416     if (uc == 0xfffe || uc == 0xffff || (uc >= 0xfdd0 && uc <= 0xfdef))
    417       return 0;
    418     if (hi) {
    419       if (uc < 0xdc00 || uc > 0xdfff)
    420         return 0;
    421       uc = 0x10000 + 0x400 * (hi - 1) + (uc - 0xdc00);
    422       hi = 0;
    423     }
    424     if (uc < 128 && text_chars[uc] != TC_T)
    425       return 0;
    426     ubuf[(*ulen)++] = uc;
    427     if (uc >= 0xd800 && uc <= 0xdbff)
    428       hi = uc - 0xd800 + 1;
    429     if (uc >= 0xdc00 && uc <= 0xdfff)
    430       return 0;
    431   }
    432   return 1 + be;
    433 }
    434 
    435 static int
    436 looks_ucs32(const unsigned char *b, size_t n, uint32_t *ubuf, size_t *ulen)
    437 {
    438   uint32_t uc;
    439   size_t   i;
    440   int      be;
    441 
    442   if (n < 4)
    443     return 0;
    444   if (b[0] == 0xff && b[1] == 0xfe && b[2] == 0 && b[3] == 0)
    445     be = 0;
    446   else if (b[0] == 0 && b[1] == 0 && b[2] == 0xfe && b[3] == 0xff)
    447     be = 1;
    448   else
    449     return 0;
    450   *ulen = 0;
    451   for (i = 4; i + 3 < n; i += 4) {
    452     if (be)
    453       uc = (uint32_t)b[i] << 24 | (uint32_t)b[i + 1] << 16 | (uint32_t)b[i + 2] << 8 | b[i + 3];
    454     else
    455       uc = (uint32_t)b[i + 3] << 24 | (uint32_t)b[i + 2] << 16 | (uint32_t)b[i + 1] << 8 | b[i];
    456     ubuf[(*ulen)++] = uc;
    457     if (uc == 0xfffe || (uc < 128 && text_chars[uc] != TC_T))
    458       return 0;
    459   }
    460   return 1 + be;
    461 }
    462 
    463 /*
    464  * find the character set of buf, as file(1) names it in code and in
    465  * code_mime, and decode it into *ubufp (freed by the caller) unless
    466  * ubufp is NULL. returns 1 if the bytes look like text
    467  */
    468 int
    469 mg_encoding(
    470     const unsigned char *buf,
    471     size_t               n,
    472     uint32_t           **ubufp,
    473     size_t              *ulenp,
    474     const char         **code,
    475     const char         **code_mime,
    476     const char         **type
    477 )
    478 {
    479   unsigned char *nbuf;
    480   uint32_t      *ubuf;
    481   size_t         ulen = 0, i;
    482   int            rv   = 1, t;
    483 
    484   *type      = "text";
    485   *code      = "unknown";
    486   *code_mime = "binary";
    487   if (ubufp)
    488     *ubufp = NULL;
    489   if (ulenp)
    490     *ulenp = 0;
    491   if (n > MG_ENCODING_MAX)
    492     n = MG_ENCODING_MAX;
    493   if (!(ubuf = calloc(n + 1, sizeof(*ubuf))))
    494     return -1;
    495   if (looks_class(buf, n, ubuf, &ulen, TC_T)) {
    496     if (looks_utf7(buf, n, &ulen) > 0) {
    497       *code      = "Unicode text, UTF-7";
    498       *code_mime = "utf-7";
    499     } else {
    500       *code      = "ASCII";
    501       *code_mime = "us-ascii";
    502     }
    503   } else if (
    504       n > 3 && buf[0] == 0xef && buf[1] == 0xbb && buf[2] == 0xbf
    505       && mg_looks_utf8(buf + 3, n - 3, ubuf, &ulen) > 0
    506   ) {
    507     *code      = "Unicode text, UTF-8 (with BOM)";
    508     *code_mime = "utf-8";
    509   } else if (mg_looks_utf8(buf, n, ubuf, &ulen) > 1) {
    510     *code      = "Unicode text, UTF-8";
    511     *code_mime = "utf-8";
    512   } else if ((t = looks_ucs32(buf, n, ubuf, &ulen)) != 0) {
    513     *code = t == 1 ? "Unicode text, UTF-32, little-endian" : "Unicode text, UTF-32, big-endian";
    514     *code_mime = t == 1 ? "utf-32le" : "utf-32be";
    515   } else if ((t = looks_ucs16(buf, n, ubuf, &ulen)) != 0) {
    516     *code = t == 1 ? "Unicode text, UTF-16, little-endian" : "Unicode text, UTF-16, big-endian";
    517     *code_mime = t == 1 ? "utf-16le" : "utf-16be";
    518   } else if (looks_class(buf, n, ubuf, &ulen, TC_I)) {
    519     *code      = "ISO-8859";
    520     *code_mime = "iso-8859-1";
    521   } else if (looks_class(buf, n, ubuf, &ulen, TC_X)) {
    522     *code      = "Non-ISO extended-ASCII";
    523     *code_mime = "unknown-8bit";
    524   } else {
    525     if (!(nbuf = malloc(n + 1))) {
    526       free(ubuf);
    527       return -1;
    528     }
    529     for (i = 0; i < n; i++)
    530       nbuf[i] = ebcdic_to_ascii[buf[i]];
    531     if (looks_class(nbuf, n, ubuf, &ulen, TC_T)) {
    532       *code      = "EBCDIC";
    533       *code_mime = "ebcdic";
    534     } else if (looks_class(nbuf, n, ubuf, &ulen, TC_I)) {
    535       *code      = "International EBCDIC";
    536       *code_mime = "ebcdic";
    537     } else {
    538       rv    = 0;
    539       *type = "binary";
    540     }
    541     free(nbuf);
    542   }
    543   if (ubufp) {
    544     *ubufp = ubuf;
    545     *ulenp = ulen;
    546   } else {
    547     free(ubuf);
    548   }
    549   return rv;
    550 }
    551 
    552 static unsigned char *
    553 encode_utf8(unsigned char *b, size_t len, const uint32_t *u, size_t n)
    554 {
    555   unsigned char *end = b + len;
    556   uint32_t       c;
    557   size_t         i;
    558   int            k, extra;
    559 
    560   for (i = 0; i < n; i++) {
    561     c = u[i];
    562     if (c <= 0x7f) {
    563       if (end - b < 1)
    564         return NULL;
    565       *b++ = (unsigned char)c;
    566       continue;
    567     }
    568     if (c <= 0x7ff)
    569       extra = 1;
    570     else if (c <= 0xffff)
    571       extra = 2;
    572     else if (c <= 0x1fffff)
    573       extra = 3;
    574     else if (c <= 0x3ffffff)
    575       extra = 4;
    576     else if (c <= 0x7fffffff)
    577       extra = 5;
    578     else
    579       return NULL;
    580     if (end - b < extra + 1)
    581       return NULL;
    582     *b++ = (unsigned char)((0xff00 >> (extra + 1)) + (c >> (6 * extra)));
    583     for (k = extra - 1; k >= 0; k--)
    584       *b++ = (unsigned char)(((c >> (6 * k)) & 0x3f) + 0x80);
    585   }
    586   return b;
    587 }
    588 
    589 static size_t
    590 trim_nuls(const unsigned char *buf, size_t n)
    591 {
    592   while (n > 1 && buf[n - 1] == '\0')
    593     n--;
    594   return n;
    595 }
    596 
    597 static void
    598 describe_terminators(struct MagicOut *o, size_t crlf, size_t cr, size_t lf, size_t nel)
    599 {
    600   /* only line ends other than lf, or none at all, are worth naming */
    601   if (crlf || cr || nel || !lf) {
    602     mg_puts(o, ", with");
    603     if (!crlf && !cr && !nel && !lf) {
    604       mg_puts(o, " no");
    605     } else {
    606       if (crlf) {
    607         mg_puts(o, " CRLF");
    608         if (cr || lf || nel)
    609           mg_puts(o, ",");
    610       }
    611       if (cr) {
    612         mg_puts(o, " CR");
    613         if (lf || nel)
    614           mg_puts(o, ",");
    615       }
    616       if (lf) {
    617         mg_puts(o, " LF");
    618         if (nel)
    619           mg_puts(o, ",");
    620       }
    621       if (nel)
    622         mg_puts(o, " NEL");
    623     }
    624     mg_puts(o, " line terminators");
    625   }
    626 }
    627 
    628 /* describe text: its text tests, then its character set and line ends. 0 if not text */
    629 int
    630 mg_ascmagic(struct MagicRun *r, int text)
    631 {
    632   struct MagicBuf bb;
    633   const char     *code, *code_mime, *type;
    634   unsigned char  *u8 = NULL, *u8end;
    635   uint32_t       *ubuf;
    636   size_t          n, ulen, i, crlf = 0, lf = 0, cr = 0, nel = 0, longest = 0, last = (size_t)-1;
    637   int             rv, seen_cr = 0, esc = 0, bs = 0, executable = 0;
    638 
    639   n = trim_nuls(r->head.p, r->head.n);
    640   /* dont lose the last character of utf-16 le text */
    641   if ((n & 1) && !(r->head.n & 1))
    642     n++;
    643   if ((rv = mg_encoding(r->head.p, n, &ubuf, &ulen, &code, &code_mime, &type)) <= 0) {
    644     free(ubuf);
    645     return rv;
    646   }
    647   rv = 0;
    648   if (trim_nuls(r->head.p, n) <= 1)
    649     goto done;
    650   if (ulen > 0) {
    651     if (!(u8 = malloc(ulen * 6)) || !(u8end = encode_utf8(u8, ulen * 6, ubuf, ulen))) {
    652       rv = u8 ? 0 : -1;
    653       goto done;
    654     }
    655     bb.p    = u8;
    656     bb.n    = (size_t)(u8end - u8);
    657     bb.file = r->head.file;
    658     if (mg_softmagic(r, &bb, MF_TEXTTEST, text) < 0) {
    659       rv = -1;
    660       goto done;
    661     }
    662   }
    663   for (i = 0; i < ulen; i++) {
    664     if (ubuf[i] == '\n') {
    665       if (seen_cr)
    666         crlf++;
    667       else
    668         lf++;
    669       last = i;
    670     } else if (seen_cr) {
    671       cr++;
    672     }
    673     seen_cr = ubuf[i] == '\r';
    674     if (seen_cr)
    675       last = i;
    676     if (ubuf[i] == 0x85) {
    677       nel++;
    678       last = i;
    679     }
    680     if (i > last + MAXLINELEN && i - last > longest)
    681       longest = i - last;
    682     if (ubuf[i] == '\033')
    683       esc = 1;
    684     if (ubuf[i] == '\b')
    685       bs = 1;
    686   }
    687   if (seen_cr && !cr && !crlf)
    688     cr++;
    689   rv = 1;
    690   if (r->mime) {
    691     if (!r->out.n)
    692       mg_puts(&r->out, "text/plain");
    693     goto done;
    694   }
    695   if (r->out.n) {
    696     if (!mg_replace_end(&r->out, " text", ", ")) {
    697       if (mg_replace_end(&r->out, " text executable", ", "))
    698         executable = 1;
    699       else
    700         mg_puts(&r->out, ", ");
    701     }
    702   }
    703   mg_puts(&r->out, code);
    704   mg_puts(&r->out, " ");
    705   mg_puts(&r->out, type);
    706   if (executable)
    707     mg_puts(&r->out, " executable");
    708   if (longest)
    709     mg_printf(&r->out, ", with very long lines (%lu)", (unsigned long)longest);
    710   describe_terminators(&r->out, crlf, cr, lf, nel);
    711   if (esc)
    712     mg_puts(&r->out, ", with escape sequences");
    713   if (bs)
    714     mg_puts(&r->out, ", with overstriking");
    715 done:
    716   free(u8);
    717   free(ubuf);
    718   return rv;
    719 }
    720 
    721 /* tar: 1 old unix, 2 posix ustar, 3 gnu, 0 when the header checksum is wrong */
    722 static int
    723 from_oct(const unsigned char *p, size_t n)
    724 {
    725   int v = 0;
    726 
    727   while (n > 0 && (*p == ' ' || (*p >= '\t' && *p <= '\r'))) {
    728     p++;
    729     n--;
    730   }
    731   if (!n)
    732     return -1;
    733   while (n > 0 && *p >= '0' && *p <= '7') {
    734     v = (v << 3) | (*p++ - '0');
    735     n--;
    736   }
    737   if (n > 0 && *p && !(*p == ' ' || (*p >= '\t' && *p <= '\r')))
    738     return -1;
    739   return v;
    740 }
    741 
    742 int
    743 mg_istar(const unsigned char *b, size_t n)
    744 {
    745   static const char    gpkg[] = "/gpkg-1";
    746   const unsigned char *nul;
    747   size_t               i;
    748   int                  sum = 0, rec;
    749 
    750   if (n < 512)
    751     return 0;
    752   /* gentoo binary packages look like tar, the magic tests tell them apart */
    753   nul = memchr(b, 0, 100);
    754   if (nul && nul >= b + sizeof(gpkg) && memcmp(nul - sizeof(gpkg) + 1, gpkg, sizeof(gpkg)) == 0)
    755     return 0;
    756   rec = from_oct(b + 148, 8);
    757   for (i = 0; i < 512; i++)
    758     sum += b[i];
    759   for (i = 148; i < 156; i++)
    760     sum -= b[i];
    761   sum += ' ' * 8;
    762   if (sum != rec)
    763     return 0;
    764   if (memcmp(b + 257, "ustar  ", 8) == 0)
    765     return 3;
    766   if (memcmp(b + 257, "ustar", 6) == 0)
    767     return 2;
    768   return 1;
    769 }
    770 
    771 /* json, a validating parser that gives up at the first error */
    772 enum JsonCount { J_ARRAY, J_CONSTANT, J_NUMBER, J_OBJECT, J_STRING, J_ARRAYN, J_MAX };
    773 
    774 static int json_parse(const unsigned char **, const unsigned char *, size_t *, size_t);
    775 
    776 static int
    777 json_space(int c)
    778 {
    779   return c == ' ' || c == '\n' || c == '\r' || c == '\t';
    780 }
    781 
    782 static int
    783 json_xdigit(int c)
    784 {
    785   return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
    786 }
    787 
    788 static const unsigned char *
    789 json_skip(const unsigned char *uc, const unsigned char *ue)
    790 {
    791   while (uc < ue && json_space(*uc))
    792     uc++;
    793   return uc;
    794 }
    795 
    796 static int
    797 json_string(const unsigned char **ucp, const unsigned char *ue)
    798 {
    799   const unsigned char *uc = *ucp;
    800   size_t               i;
    801 
    802   while (uc < ue) {
    803     switch (*uc++) {
    804       case '\0':
    805         goto out;
    806       case '\\':
    807         if (uc == ue)
    808           goto out;
    809         switch (*uc++) {
    810           case '\0':
    811             goto out;
    812           case '"':
    813           case '\\':
    814           case '/':
    815           case 'b':
    816           case 'f':
    817           case 'n':
    818           case 'r':
    819           case 't':
    820             continue;
    821           case 'u':
    822             if (ue - uc < 4) {
    823               uc = ue;
    824               goto out;
    825             }
    826             for (i = 0; i < 4; i++) {
    827               if (!json_xdigit(*uc++))
    828                 goto out;
    829             }
    830             continue;
    831           default:
    832             goto out;
    833         }
    834       case '"':
    835         *ucp = uc;
    836         return 1;
    837       default:
    838         continue;
    839     }
    840   }
    841 out:
    842   *ucp = uc;
    843   return 0;
    844 }
    845 
    846 static int
    847 json_array(const unsigned char **ucp, const unsigned char *ue, size_t *st, size_t lvl)
    848 {
    849   const unsigned char *uc = *ucp;
    850 
    851   while (uc < ue) {
    852     uc = json_skip(uc, ue);
    853     if (uc == ue)
    854       goto out;
    855     if (*uc == ']')
    856       goto done;
    857     if (!json_parse(&uc, ue, st, lvl + 1) || uc == ue)
    858       goto out;
    859     switch (*uc) {
    860       case ',':
    861         uc++;
    862         continue;
    863       case ']':
    864       done:
    865         st[J_ARRAYN]++;
    866         *ucp = uc + 1;
    867         return 1;
    868       default:
    869         goto out;
    870     }
    871   }
    872 out:
    873   *ucp = uc;
    874   return 0;
    875 }
    876 
    877 static int
    878 json_object(const unsigned char **ucp, const unsigned char *ue, size_t *st, size_t lvl)
    879 {
    880   const unsigned char *uc = *ucp;
    881 
    882   while (uc < ue) {
    883     uc = json_skip(uc, ue);
    884     if (uc == ue)
    885       goto out;
    886     if (*uc == '}') {
    887       *ucp = uc + 1;
    888       return 1;
    889     }
    890     if (*uc++ != '"' || !json_string(&uc, ue))
    891       goto out;
    892     uc = json_skip(uc, ue);
    893     if (uc == ue || *uc++ != ':')
    894       goto out;
    895     if (!json_parse(&uc, ue, st, lvl + 1) || uc == ue)
    896       goto out;
    897     switch (*uc++) {
    898       case ',':
    899         continue;
    900       case '}':
    901         *ucp = uc;
    902         return 1;
    903       default:
    904         *ucp = uc - 1;
    905         return 0;
    906     }
    907   }
    908 out:
    909   *ucp = uc;
    910   return 0;
    911 }
    912 
    913 static int
    914 json_digit(int c)
    915 {
    916   return c >= '0' && c <= '9';
    917 }
    918 
    919 static int
    920 json_number(const unsigned char **ucp, const unsigned char *ue)
    921 {
    922   const unsigned char *uc  = *ucp;
    923   int                  got = 0;
    924 
    925   if (uc == ue)
    926     return 0;
    927   if (*uc == '-')
    928     uc++;
    929   for (; uc < ue && json_digit(*uc); uc++)
    930     got = 1;
    931   if (uc == ue)
    932     goto out;
    933   if (*uc == '.')
    934     uc++;
    935   for (; uc < ue && json_digit(*uc); uc++)
    936     got = 1;
    937   if (uc == ue)
    938     goto out;
    939   if (got && (*uc == 'e' || *uc == 'E')) {
    940     uc++;
    941     got = 0;
    942     if (uc == ue)
    943       goto out;
    944     if (*uc == '+' || *uc == '-')
    945       uc++;
    946     for (; uc < ue && json_digit(*uc); uc++)
    947       got = 1;
    948   }
    949 out:
    950   if (got)
    951     *ucp = uc;
    952   return got;
    953 }
    954 
    955 /* true, false and null: file(1) compares all but the first letter */
    956 static int
    957 json_const(const unsigned char **ucp, const unsigned char *ue, const char *str)
    958 {
    959   const unsigned char *uc  = *ucp;
    960   size_t               len = strlen(str);
    961 
    962   *ucp += len - 1;
    963   if (*ucp > ue)
    964     *ucp = ue;
    965   for (str++, len--; uc < ue && len; len--) {
    966     if (*uc++ != (unsigned char)*str++)
    967       return 0;
    968   }
    969   return 1;
    970 }
    971 
    972 static int
    973 json_parse(const unsigned char **ucp, const unsigned char *ue, size_t *st, size_t lvl)
    974 {
    975   const unsigned char *uc, *ouc;
    976   int                  rv = 0, t = J_NUMBER;
    977 
    978   ouc = uc = json_skip(*ucp, ue);
    979   if (uc == ue)
    980     goto out;
    981   if (lvl > JSON_MAXDEPTH)
    982     return 0;
    983   switch (*uc++) {
    984     case '"':
    985       rv = json_string(&uc, ue);
    986       t  = J_STRING;
    987       break;
    988     case '[':
    989       rv = json_array(&uc, ue, st, lvl + 1);
    990       t  = J_ARRAY;
    991       break;
    992     case '{':
    993       rv = json_object(&uc, ue, st, lvl + 1);
    994       t  = J_OBJECT;
    995       break;
    996     case 't':
    997       rv = json_const(&uc, ue, "true");
    998       t  = J_CONSTANT;
    999       break;
   1000     case 'f':
   1001       rv = json_const(&uc, ue, "false");
   1002       t  = J_CONSTANT;
   1003       break;
   1004     case 'n':
   1005       rv = json_const(&uc, ue, "null");
   1006       t  = J_CONSTANT;
   1007       break;
   1008     default:
   1009       --uc;
   1010       rv = json_number(&uc, ue);
   1011       break;
   1012   }
   1013   if (rv)
   1014     st[t]++;
   1015   uc = json_skip(uc, ue);
   1016 out:
   1017   *ucp = uc;
   1018   if (lvl == 0) {
   1019     if (!rv)
   1020       return 0;
   1021     if (uc == ue)
   1022       return (st[J_ARRAYN] || st[J_OBJECT]) ? 1 : 0;
   1023     if (*ouc == *uc && json_parse(&uc, ue, st, 1))
   1024       return (st[J_ARRAYN] || st[J_OBJECT]) ? 2 : 0;
   1025     return 0;
   1026   }
   1027   return rv;
   1028 }
   1029 
   1030 /* 1 for json, 2 for newline delimited json */
   1031 int
   1032 mg_isjson(const unsigned char *b, size_t n)
   1033 {
   1034   size_t st[J_MAX];
   1035 
   1036   memset(st, 0, sizeof(st));
   1037   return json_parse(&b, b + n, st, 0);
   1038 }
   1039 
   1040 static const unsigned char *
   1041 csv_quote(const unsigned char *uc, const unsigned char *ue)
   1042 {
   1043   int quote = 0;
   1044 
   1045   while (uc < ue) {
   1046     if (*uc++ != '"') {
   1047       if (quote)
   1048         return uc - 1;
   1049       continue;
   1050     }
   1051     /* two quotes in a row are an escaped quote */
   1052     quote = !quote;
   1053   }
   1054   return ue;
   1055 }
   1056 
   1057 /* comma separated values: the same number of fields on the first lines */
   1058 int
   1059 mg_iscsv(const unsigned char *uc, size_t n)
   1060 {
   1061   const unsigned char *ue = uc + n;
   1062   size_t               nf = 0, tf = 0, nl = 0;
   1063 
   1064   while (uc < ue) {
   1065     switch (*uc++) {
   1066       case '"':
   1067         uc = csv_quote(uc, ue);
   1068         break;
   1069       case ',':
   1070         nf++;
   1071         break;
   1072       case '\n':
   1073         if (++nl == CSV_LINES)
   1074           return tf > 1 && tf == nf;
   1075         if (tf == 0) {
   1076           if (nf == 0)
   1077             return 0;
   1078           tf = nf;
   1079         } else if (tf != nf) {
   1080           return 0;
   1081         }
   1082         nf = 0;
   1083         break;
   1084       default:
   1085         break;
   1086     }
   1087   }
   1088   return tf >= 1 && nl >= 2;
   1089 }