Home | History | Annotate | Line # | Download | only in src
      1 /*	$NetBSD: ascmagic.c,v 1.1.1.17 2026/06/10 15:59:13 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (c) Ian F. Darwin 1986-1995.
      5  * Software written by Ian F. Darwin and others;
      6  * maintained 1995-present by Christos Zoulas and others.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice immediately at the beginning of the file, without modification,
     13  *    this list of conditions, and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  *
     18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     21  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
     22  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     28  * SUCH DAMAGE.
     29  */
     30 /*
     31  * ASCII magic -- try to detect text encoding.
     32  *
     33  * Extensively modified by Eric Fischer <enf (at) pobox.com> in July, 2000,
     34  * to handle character codes other than ASCII on a unified basis.
     35  */
     36 
     37 #include "file.h"
     38 
     39 #ifndef	lint
     40 #if 0
     41 FILE_RCSID("@(#)$File: ascmagic.c,v 1.118 2026/06/02 19:58:38 christos Exp $")
     42 #else
     43 __RCSID("$NetBSD: ascmagic.c,v 1.1.1.17 2026/06/10 15:59:13 christos Exp $");
     44 #endif
     45 #endif	/* lint */
     46 
     47 #include "magic.h"
     48 #include <string.h>
     49 #include <ctype.h>
     50 #include <stdlib.h>
     51 #ifdef HAVE_UNISTD_H
     52 #include <unistd.h>
     53 #endif
     54 
     55 #define MAXLINELEN 300	/* longest sane line length */
     56 #define ISSPC(x) ((x) == ' ' || (x) == '\t' || (x) == '\r' || (x) == '\n' \
     57 		  || (x) == 0x85 || (x) == '\f')
     58 
     59 file_private unsigned char *encode_utf8(unsigned char *, size_t, file_unichar_t *,
     60     size_t);
     61 file_private size_t trim_nuls(const unsigned char *, size_t);
     62 
     63 /*
     64  * Undo the NUL-termination kindly provided by process()
     65  * but leave at least one byte to look at
     66  */
     67 file_private size_t
     68 trim_nuls(const unsigned char *buf, size_t nbytes)
     69 {
     70 	while (nbytes > 1 && buf[nbytes - 1] == '\0')
     71 		nbytes--;
     72 
     73 	return nbytes;
     74 }
     75 
     76 file_protected int
     77 file_ascmagic(struct magic_set *ms, const struct buffer *b, int text)
     78 {
     79 	file_unichar_t *ubuf = NULL;
     80 	size_t ulen = 0;
     81 	int rv = 1;
     82 	struct buffer bb;
     83 
     84 	const char *code = NULL;
     85 	const char *code_mime = NULL;
     86 	const char *type = NULL;
     87 
     88 	bb = *b;
     89 	bb.flen = trim_nuls(CAST(const unsigned char *, b->fbuf), b->flen);
     90 	/*
     91 	 * Avoid trimming at an odd byte if the original buffer was evenly
     92 	 * sized; this avoids losing the last character on UTF-16 LE text
     93 	 */
     94 	if ((bb.flen & 1) && !(b->flen & 1))
     95 		bb.flen++;
     96 
     97 	/* If file doesn't look like any sort of text, give up. */
     98 	if (file_encoding(ms, &bb, &ubuf, &ulen, &code, &code_mime,
     99 	    &type) == 0)
    100 		rv = 0;
    101         else
    102 		rv = file_ascmagic_with_encoding(ms, &bb,
    103 		    ubuf, ulen, code, type, text);
    104 
    105 	free(ubuf);
    106 
    107 	return rv;
    108 }
    109 
    110 file_protected int
    111 file_ascmagic_with_encoding(struct magic_set *ms, const struct buffer *b,
    112     file_unichar_t *ubuf, size_t ulen, const char *code, const char *type,
    113     int text)
    114 {
    115 	struct buffer bb;
    116 	const unsigned char *buf = CAST(const unsigned char *, b->fbuf);
    117 	size_t nbytes = b->flen;
    118 	unsigned char *utf8_buf = NULL, *utf8_end;
    119 	size_t mlen, i, len;
    120 	int rv = -1;
    121 	int mime = ms->flags & MAGIC_MIME;
    122 	int need_separator = 0;
    123 
    124 	const char *subtype = NULL;
    125 
    126 	int has_escapes = 0;
    127 	int has_backspace = 0;
    128 	int seen_cr = 0;
    129 
    130 	size_t n_crlf = 0;
    131 	size_t n_lf = 0;
    132 	size_t n_cr = 0;
    133 	size_t n_nel = 0;
    134 	int executable = 0;
    135 
    136 	size_t last_line_end = CAST(size_t, -1);
    137 	size_t has_long_lines = 0;
    138 
    139 	nbytes = trim_nuls(buf, nbytes);
    140 
    141 	/* If we have fewer than 2 bytes, give up. */
    142 	if (nbytes <= 1) {
    143 		rv = 0;
    144 		goto done;
    145 	}
    146 
    147 	if (ulen > 0 && (ms->flags & MAGIC_NO_CHECK_SOFT) == 0) {
    148 		/* Convert ubuf to UTF-8 and try text soft magic */
    149 		/* malloc size is a conservative overestimate; could be
    150 		   improved, or at least realloced after conversion. */
    151 		if (ulen > SIZE_MAX / 6) {
    152 			goto done;
    153 		}
    154 		mlen = ulen * 6;
    155 		if ((utf8_buf = CAST(unsigned char *, malloc(mlen))) == NULL) {
    156 			file_oomem(ms, mlen);
    157 			goto done;
    158 		}
    159 		if ((utf8_end = encode_utf8(utf8_buf, mlen, ubuf, ulen))
    160 		    == NULL) {
    161 			rv = 0;
    162 			goto done;
    163 		}
    164 		buffer_init(&bb, b->fd, &b->st, utf8_buf,
    165 		    CAST(size_t, utf8_end - utf8_buf));
    166 
    167 		if ((rv = file_softmagic(ms, &bb, NULL, NULL,
    168 		    TEXTTEST, text)) == 0)
    169 			rv = -1;
    170 		else
    171 			need_separator = 1;
    172 		buffer_fini(&bb);
    173 		if ((ms->flags & (MAGIC_APPLE|MAGIC_EXTENSION))) {
    174 			rv = rv == -1 ? 0 : 1;
    175 			goto done;
    176 		}
    177 	}
    178 
    179 	if ((ms->flags & (MAGIC_APPLE|MAGIC_EXTENSION))) {
    180 		rv = 0;
    181 		goto done;
    182 	}
    183 
    184 	/* Now try to discover other details about the file. */
    185 	for (i = 0; i < ulen; i++) {
    186 		if (ubuf[i] == '\n') {
    187 			if (seen_cr)
    188 				n_crlf++;
    189 			else
    190 				n_lf++;
    191 			last_line_end = i;
    192 		} else if (seen_cr)
    193 			n_cr++;
    194 
    195 		seen_cr = (ubuf[i] == '\r');
    196 		if (seen_cr)
    197 			last_line_end = i;
    198 
    199 		if (ubuf[i] == 0x85) { /* X3.64/ECMA-43 "next line" character */
    200 			n_nel++;
    201 			last_line_end = i;
    202 		}
    203 
    204 		/* If this line is _longer_ than MAXLINELEN, remember it. */
    205 		if (i > last_line_end + MAXLINELEN) {
    206 			size_t ll = i - last_line_end;
    207 			if (ll > has_long_lines)
    208 				has_long_lines = ll;
    209 		}
    210 
    211 		if (ubuf[i] == '\033')
    212 			has_escapes = 1;
    213 		if (ubuf[i] == '\b')
    214 			has_backspace = 1;
    215 	}
    216 
    217 	if (seen_cr && n_cr == 0 && n_crlf == 0)
    218 		n_cr++;
    219 
    220 	if (strcmp(type, "binary") == 0) {
    221 		rv = 0;
    222 		goto done;
    223 	}
    224 	len = file_printedlen(ms);
    225 	if (mime) {
    226 		if ((mime & MAGIC_MIME_TYPE) != 0) {
    227 			if (len) {
    228 				/*
    229 				 * Softmagic printed something, we
    230 				 * are either done, or we need a separator
    231 				 */
    232 				if ((ms->flags & MAGIC_CONTINUE) == 0) {
    233 					rv = 1;
    234 					goto done;
    235 				}
    236 				if (need_separator && file_separator(ms) == -1)
    237 					goto done;
    238 			}
    239 			if (file_printf(ms, "text/plain") == -1)
    240 				goto done;
    241 		}
    242 	} else {
    243 		if (len) {
    244 			switch (file_replace(ms, " text$", ", ")) {
    245 			case 0:
    246 				switch (file_replace(ms, " text executable$",
    247 				    ", ")) {
    248 				case 0:
    249 					if (file_printf(ms, ", ") == -1)
    250 						goto done;
    251 					break;
    252 				case -1:
    253 					goto done;
    254 				default:
    255 					executable = 1;
    256 					break;
    257 				}
    258 				break;
    259 			case -1:
    260 				goto done;
    261 			default:
    262 				break;
    263 			}
    264 		}
    265 
    266 		if (file_printf(ms, "%s", code) == -1)
    267 			goto done;
    268 
    269 		if (subtype) {
    270 			if (file_printf(ms, " %s", subtype) == -1)
    271 				goto done;
    272 		}
    273 
    274 		if (file_printf(ms, " %s", type) == -1)
    275 			goto done;
    276 
    277 		if (executable)
    278 			if (file_printf(ms, " executable") == -1)
    279 				goto done;
    280 
    281 		if (has_long_lines)
    282 			if (file_printf(ms, ", with very long lines (%"
    283 			    SIZE_T_FORMAT "u)", has_long_lines) == -1)
    284 				goto done;
    285 
    286 		/*
    287 		 * Only report line terminators if we find one other than LF,
    288 		 * or if we find none at all.
    289 		 */
    290 		if ((n_crlf == 0 && n_cr == 0 && n_nel == 0 && n_lf == 0) ||
    291 		    (n_crlf != 0 || n_cr != 0 || n_nel != 0)) {
    292 			if (file_printf(ms, ", with") == -1)
    293 				goto done;
    294 
    295 			if (n_crlf == 0 && n_cr == 0 &&
    296 			    n_nel == 0 && n_lf == 0) {
    297 				if (file_printf(ms, " no") == -1)
    298 					goto done;
    299 			} else {
    300 				if (n_crlf) {
    301 					if (file_printf(ms, " CRLF") == -1)
    302 						goto done;
    303 					if (n_cr || n_lf || n_nel)
    304 						if (file_printf(ms, ",") == -1)
    305 							goto done;
    306 				}
    307 				if (n_cr) {
    308 					if (file_printf(ms, " CR") == -1)
    309 						goto done;
    310 					if (n_lf || n_nel)
    311 						if (file_printf(ms, ",") == -1)
    312 							goto done;
    313 				}
    314 				if (n_lf) {
    315 					if (file_printf(ms, " LF") == -1)
    316 						goto done;
    317 					if (n_nel)
    318 						if (file_printf(ms, ",") == -1)
    319 							goto done;
    320 				}
    321 				if (n_nel)
    322 					if (file_printf(ms, " NEL") == -1)
    323 						goto done;
    324 			}
    325 
    326 			if (file_printf(ms, " line terminators") == -1)
    327 				goto done;
    328 		}
    329 
    330 		if (has_escapes)
    331 			if (file_printf(ms, ", with escape sequences") == -1)
    332 				goto done;
    333 		if (has_backspace)
    334 			if (file_printf(ms, ", with overstriking") == -1)
    335 				goto done;
    336 	}
    337 	rv = 1;
    338 done:
    339 	free(utf8_buf);
    340 
    341 	return rv;
    342 }
    343 
    344 /*
    345  * Encode Unicode string as UTF-8, returning pointer to character
    346  * after end of string, or NULL if an invalid character is found.
    347  */
    348 file_private unsigned char *
    349 encode_utf8(unsigned char *buf, size_t len, file_unichar_t *ubuf, size_t ulen)
    350 {
    351 	size_t i;
    352 	unsigned char *end = buf + len;
    353 
    354 	for (i = 0; i < ulen; i++) {
    355 		if (ubuf[i] <= 0x7f) {
    356 			if (end - buf < 1)
    357 				return NULL;
    358 			*buf++ = CAST(unsigned char, ubuf[i]);
    359 			continue;
    360 		}
    361 		if (ubuf[i] <= 0x7ff) {
    362 			if (end - buf < 2)
    363 				return NULL;
    364 			*buf++ = CAST(unsigned char, (ubuf[i] >> 6) + 0xc0);
    365 			goto out1;
    366 		}
    367 		if (ubuf[i] <= 0xffff) {
    368 			if (end - buf < 3)
    369 				return NULL;
    370 			*buf++ = CAST(unsigned char, (ubuf[i] >> 12) + 0xe0);
    371 			goto out2;
    372 		}
    373 		if (ubuf[i] <= 0x1fffff) {
    374 			if (end - buf < 4)
    375 				return NULL;
    376 			*buf++ = CAST(unsigned char, (ubuf[i] >> 18) + 0xf0);
    377 			goto out3;
    378 		}
    379 		if (ubuf[i] <= 0x3ffffff) {
    380 			if (end - buf < 5)
    381 				return NULL;
    382 			*buf++ = CAST(unsigned char, (ubuf[i] >> 24) + 0xf8);
    383 			goto out4;
    384 		}
    385 		if (ubuf[i] <= 0x7fffffff) {
    386 			if (end - buf < 6)
    387 				return NULL;
    388 			*buf++ = CAST(unsigned char, (ubuf[i] >> 30) + 0xfc);
    389 			goto out5;
    390 		}
    391 		/* Invalid character */
    392 		return NULL;
    393 	out5:	*buf++ = CAST(unsigned char, ((ubuf[i] >> 24) & 0x3f) + 0x80);
    394 	out4:	*buf++ = CAST(unsigned char, ((ubuf[i] >> 18) & 0x3f) + 0x80);
    395 	out3:	*buf++ = CAST(unsigned char, ((ubuf[i] >> 12) & 0x3f) + 0x80);
    396 	out2:	*buf++ = CAST(unsigned char, ((ubuf[i] >>  6) & 0x3f) + 0x80);
    397 	out1:	*buf++ = CAST(unsigned char, ((ubuf[i] >>  0) & 0x3f) + 0x80);
    398 	}
    399 
    400 	return buf;
    401 }
    402