xref: /openbsd/usr.bin/file/file.c (revision 7aa9f692)
1 /* $OpenBSD: file.c,v 1.68 2019/02/05 02:17:32 deraadt Exp $ */
2 
3 /*
4  * Copyright (c) 2015 Nicholas Marriott <nicm@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/ioctl.h>
21 #include <sys/mman.h>
22 #include <sys/queue.h>
23 #include <sys/socket.h>
24 #include <sys/stat.h>
25 #include <sys/uio.h>
26 #include <sys/wait.h>
27 
28 #include <err.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <getopt.h>
32 #include <imsg.h>
33 #include <libgen.h>
34 #include <limits.h>
35 #include <pwd.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <time.h>
39 #include <unistd.h>
40 
41 #include "file.h"
42 #include "magic.h"
43 #include "xmalloc.h"
44 
45 struct input_msg {
46 	int		idx;
47 
48 	struct stat	sb;
49 	int		error;
50 
51 	char		link_path[PATH_MAX];
52 	int		link_error;
53 	int		link_target;
54 };
55 
56 struct input_ack {
57 	int		idx;
58 };
59 
60 struct input_file {
61 	struct magic		*m;
62 	struct input_msg	*msg;
63 
64 	const char		*path;
65 	int			 fd;
66 
67 	void			*base;
68 	size_t			 size;
69 	int			 mapped;
70 	char			*result;
71 };
72 
73 extern char	*__progname;
74 
75 __dead void	 usage(void);
76 
77 static int	 prepare_message(struct input_msg *, int, const char *);
78 static void	 send_message(struct imsgbuf *, void *, size_t, int);
79 static int	 read_message(struct imsgbuf *, struct imsg *, pid_t);
80 
81 static void	 read_link(struct input_msg *, const char *);
82 
83 static __dead void child(int, pid_t, int, char **);
84 
85 static void	 test_file(struct input_file *, size_t);
86 
87 static int	 try_stat(struct input_file *);
88 static int	 try_empty(struct input_file *);
89 static int	 try_access(struct input_file *);
90 static int	 try_text(struct input_file *);
91 static int	 try_magic(struct input_file *);
92 static int	 try_unknown(struct input_file *);
93 
94 static int	 bflag;
95 static int	 cflag;
96 static int	 iflag;
97 static int	 Lflag;
98 static int	 sflag;
99 static int	 Wflag;
100 
101 static char	*magicpath;
102 static FILE	*magicfp;
103 
104 static struct option longopts[] = {
105 	{ "brief",       no_argument, NULL, 'b' },
106 	{ "dereference", no_argument, NULL, 'L' },
107 	{ "mime",        no_argument, NULL, 'i' },
108 	{ "mime-type",   no_argument, NULL, 'i' },
109 	{ NULL,          0,           NULL, 0   }
110 };
111 
112 __dead void
113 usage(void)
114 {
115 	fprintf(stderr, "usage: %s [-bchiLsW] file ...\n", __progname);
116 	exit(1);
117 }
118 
119 int
120 main(int argc, char **argv)
121 {
122 	int			 opt, pair[2], fd, idx;
123 	char			*home;
124 	struct passwd		*pw;
125 	struct imsgbuf		 ibuf;
126 	struct imsg		 imsg;
127 	struct input_msg	 msg;
128 	struct input_ack	*ack;
129 	pid_t			 pid, parent;
130 
131 	tzset();
132 
133 	for (;;) {
134 		opt = getopt_long(argc, argv, "bchiLsW", longopts, NULL);
135 		if (opt == -1)
136 			break;
137 		switch (opt) {
138 		case 'b':
139 			bflag = 1;
140 			break;
141 		case 'c':
142 			cflag = 1;
143 			break;
144 		case 'h':
145 			Lflag = 0;
146 			break;
147 		case 'i':
148 			iflag = 1;
149 			break;
150 		case 'L':
151 			Lflag = 1;
152 			break;
153 		case 's':
154 			sflag = 1;
155 			break;
156 		case 'W':
157 			Wflag = 1;
158 			break;
159 		default:
160 			usage();
161 		}
162 	}
163 	argc -= optind;
164 	argv += optind;
165 	if (cflag) {
166 		if (argc != 0)
167 			usage();
168 	} else if (argc == 0)
169 		usage();
170 
171 	if (pledge("stdio rpath getpw recvfd sendfd id proc", NULL) == -1)
172 		err(1, "pledge");
173 
174 	magicfp = NULL;
175 	if (geteuid() != 0 && !issetugid()) {
176 		home = getenv("HOME");
177 		if (home == NULL || *home == '\0') {
178 			pw = getpwuid(getuid());
179 			if (pw != NULL)
180 				home = pw->pw_dir;
181 			else
182 				home = NULL;
183 		}
184 		if (home != NULL) {
185 			xasprintf(&magicpath, "%s/.magic", home);
186 			magicfp = fopen(magicpath, "r");
187 			if (magicfp == NULL)
188 				free(magicpath);
189 		}
190 	}
191 	if (magicfp == NULL) {
192 		magicpath = xstrdup("/etc/magic");
193 		magicfp = fopen(magicpath, "r");
194 	}
195 	if (magicfp == NULL)
196 		err(1, "%s", magicpath);
197 
198 	parent = getpid();
199 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pair) != 0)
200 		err(1, "socketpair");
201 	switch (pid = fork()) {
202 	case -1:
203 		err(1, "fork");
204 	case 0:
205 		close(pair[0]);
206 		child(pair[1], parent, argc, argv);
207 	}
208 	close(pair[1]);
209 
210 	fclose(magicfp);
211 	magicfp = NULL;
212 
213 	if (cflag)
214 		goto wait_for_child;
215 
216 	imsg_init(&ibuf, pair[0]);
217 	for (idx = 0; idx < argc; idx++) {
218 		fd = prepare_message(&msg, idx, argv[idx]);
219 		send_message(&ibuf, &msg, sizeof msg, fd);
220 
221 		if (read_message(&ibuf, &imsg, pid) == 0)
222 			break;
223 		if (imsg.hdr.len != IMSG_HEADER_SIZE + sizeof *ack)
224 			errx(1, "message too small");
225 		ack = imsg.data;
226 		if (ack->idx != idx)
227 			errx(1, "index not expected");
228 		imsg_free(&imsg);
229 	}
230 
231 wait_for_child:
232 	close(pair[0]);
233 	while (wait(NULL) == -1 && errno != ECHILD) {
234 		if (errno != EINTR)
235 			err(1, "wait");
236 	}
237 	_exit(0); /* let the child flush */
238 }
239 
240 static int
241 prepare_message(struct input_msg *msg, int idx, const char *path)
242 {
243 	int	fd, mode, error;
244 
245 	memset(msg, 0, sizeof *msg);
246 	msg->idx = idx;
247 
248 	if (strcmp(path, "-") == 0) {
249 		if (fstat(STDIN_FILENO, &msg->sb) == -1) {
250 			msg->error = errno;
251 			return (-1);
252 		}
253 		return (STDIN_FILENO);
254 	}
255 
256 	if (Lflag)
257 		error = stat(path, &msg->sb);
258 	else
259 		error = lstat(path, &msg->sb);
260 	if (error == -1) {
261 		msg->error = errno;
262 		return (-1);
263 	}
264 
265 	/*
266 	 * pledge(2) doesn't let us pass directory file descriptors around -
267 	 * but in fact we don't need them, so just don't open directories or
268 	 * symlinks (which could be to directories).
269 	 */
270 	mode = msg->sb.st_mode;
271 	if (!S_ISDIR(mode) && !S_ISLNK(mode)) {
272 		fd = open(path, O_RDONLY|O_NONBLOCK);
273 		if (fd == -1 && (errno == ENFILE || errno == EMFILE))
274 			err(1, "open");
275 	} else
276 		fd = -1;
277 	if (S_ISLNK(mode))
278 		read_link(msg, path);
279 	return (fd);
280 
281 }
282 
283 static void
284 send_message(struct imsgbuf *ibuf, void *msg, size_t msglen, int fd)
285 {
286 	if (imsg_compose(ibuf, -1, -1, 0, fd, msg, msglen) != 1)
287 		err(1, "imsg_compose");
288 	if (imsg_flush(ibuf) != 0)
289 		err(1, "imsg_flush");
290 }
291 
292 static int
293 read_message(struct imsgbuf *ibuf, struct imsg *imsg, pid_t from)
294 {
295 	int	n;
296 
297 	while ((n = imsg_read(ibuf)) == -1 && errno == EAGAIN)
298 		/* nothing */ ;
299 	if (n == -1)
300 		err(1, "imsg_read");
301 	if (n == 0)
302 		return (0);
303 
304 	if ((n = imsg_get(ibuf, imsg)) == -1)
305 		err(1, "imsg_get");
306 	if (n == 0)
307 		return (0);
308 
309 	if ((pid_t)imsg->hdr.pid != from)
310 		errx(1, "PIDs don't match");
311 
312 	return (n);
313 
314 }
315 
316 static void
317 read_link(struct input_msg *msg, const char *path)
318 {
319 	struct stat	 sb;
320 	char		 lpath[PATH_MAX];
321 	char		*copy, *root;
322 	int		 used;
323 	ssize_t		 size;
324 
325 	size = readlink(path, lpath, sizeof lpath - 1);
326 	if (size == -1) {
327 		msg->link_error = errno;
328 		return;
329 	}
330 	lpath[size] = '\0';
331 
332 	if (*lpath == '/')
333 		strlcpy(msg->link_path, lpath, sizeof msg->link_path);
334 	else {
335 		copy = xstrdup(path);
336 
337 		root = dirname(copy);
338 		if (*root == '\0' || strcmp(root, ".") == 0 ||
339 		    strcmp (root, "/") == 0)
340 			strlcpy(msg->link_path, lpath, sizeof msg->link_path);
341 		else {
342 			used = snprintf(msg->link_path, sizeof msg->link_path,
343 			    "%s/%s", root, lpath);
344 			if (used < 0 || (size_t)used >= sizeof msg->link_path) {
345 				msg->link_error = ENAMETOOLONG;
346 				free(copy);
347 				return;
348 			}
349 		}
350 
351 		free(copy);
352 	}
353 
354 	if (!Lflag && stat(path, &sb) == -1)
355 		msg->link_target = errno;
356 }
357 
358 static __dead void
359 child(int fd, pid_t parent, int argc, char **argv)
360 {
361 	struct passwd		*pw;
362 	struct magic		*m;
363 	struct imsgbuf		 ibuf;
364 	struct imsg		 imsg;
365 	struct input_msg	*msg;
366 	struct input_ack	 ack;
367 	struct input_file	 inf;
368 	int			 i, idx;
369 	size_t			 len, width = 0;
370 
371 	if (pledge("stdio getpw recvfd id", NULL) == -1)
372 		err(1, "pledge");
373 
374 	if (geteuid() == 0) {
375 		pw = getpwnam(FILE_USER);
376 		if (pw == NULL)
377 			errx(1, "unknown user %s", FILE_USER);
378 		if (setgroups(1, &pw->pw_gid) != 0)
379 			err(1, "setgroups");
380 		if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0)
381 			err(1, "setresgid");
382 		if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0)
383 			err(1, "setresuid");
384 	}
385 
386 	if (pledge("stdio recvfd", NULL) == -1)
387 		err(1, "pledge");
388 
389 	m = magic_load(magicfp, magicpath, cflag || Wflag);
390 	if (cflag) {
391 		magic_dump(m);
392 		exit(0);
393 	}
394 
395 	for (i = 0; i < argc; i++) {
396 		len = strlen(argv[i]) + 1;
397 		if (len > width)
398 			width = len;
399 	}
400 
401 	imsg_init(&ibuf, fd);
402 	for (;;) {
403 		if (read_message(&ibuf, &imsg, parent) == 0)
404 			break;
405 		if (imsg.hdr.len != IMSG_HEADER_SIZE + sizeof *msg)
406 			errx(1, "message too small");
407 		msg = imsg.data;
408 
409 		idx = msg->idx;
410 		if (idx < 0 || idx >= argc)
411 			errx(1, "index out of range");
412 
413 		memset(&inf, 0, sizeof inf);
414 		inf.m = m;
415 		inf.msg = msg;
416 
417 		inf.path = argv[idx];
418 		inf.fd = imsg.fd;
419 
420 		test_file(&inf, width);
421 
422 		if (imsg.fd != -1)
423 			close(imsg.fd);
424 		imsg_free(&imsg);
425 
426 		ack.idx = idx;
427 		send_message(&ibuf, &ack, sizeof ack, -1);
428 	}
429 	exit(0);
430 }
431 
432 static void *
433 fill_buffer(int fd, size_t size, size_t *used)
434 {
435 	static void	*buffer;
436 	ssize_t		 got;
437 	size_t		 left;
438 	void		*next;
439 
440 	if (buffer == NULL)
441 		buffer = xmalloc(FILE_READ_SIZE);
442 
443 	next = buffer;
444 	left = size;
445 	while (left != 0) {
446 		got = read(fd, next, left);
447 		if (got == -1) {
448 			if (errno == EINTR)
449 				continue;
450 			return (NULL);
451 		}
452 		if (got == 0)
453 			break;
454 		next = (char *)next + got;
455 		left -= got;
456 	}
457 	*used = size - left;
458 	return (buffer);
459 }
460 
461 static int
462 load_file(struct input_file *inf)
463 {
464 	size_t	used;
465 
466 	if (inf->msg->sb.st_size == 0 && S_ISREG(inf->msg->sb.st_mode))
467 		return (0); /* empty file */
468 	if (inf->msg->sb.st_size == 0 || inf->msg->sb.st_size > FILE_READ_SIZE)
469 		inf->size = FILE_READ_SIZE;
470 	else
471 		inf->size = inf->msg->sb.st_size;
472 
473 	if (!S_ISREG(inf->msg->sb.st_mode))
474 		goto try_read;
475 
476 	inf->base = mmap(NULL, inf->size, PROT_READ, MAP_PRIVATE, inf->fd, 0);
477 	if (inf->base == MAP_FAILED)
478 		goto try_read;
479 	inf->mapped = 1;
480 	return (0);
481 
482 try_read:
483 	inf->base = fill_buffer(inf->fd, inf->size, &used);
484 	if (inf->base == NULL) {
485 		xasprintf(&inf->result, "cannot read '%s' (%s)", inf->path,
486 		    strerror(errno));
487 		return (1);
488 	}
489 	inf->size = used;
490 	return (0);
491 }
492 
493 static int
494 try_stat(struct input_file *inf)
495 {
496 	if (inf->msg->error != 0) {
497 		xasprintf(&inf->result, "cannot stat '%s' (%s)", inf->path,
498 		    strerror(inf->msg->error));
499 		return (1);
500 	}
501 	if (sflag || strcmp(inf->path, "-") == 0) {
502 		switch (inf->msg->sb.st_mode & S_IFMT) {
503 		case S_IFIFO:
504 			if (strcmp(inf->path, "-") != 0)
505 				break;
506 		case S_IFBLK:
507 		case S_IFCHR:
508 		case S_IFREG:
509 			return (0);
510 		}
511 	}
512 
513 	if (iflag && (inf->msg->sb.st_mode & S_IFMT) != S_IFREG) {
514 		xasprintf(&inf->result, "application/x-not-regular-file");
515 		return (1);
516 	}
517 
518 	switch (inf->msg->sb.st_mode & S_IFMT) {
519 	case S_IFDIR:
520 		xasprintf(&inf->result, "directory");
521 		return (1);
522 	case S_IFLNK:
523 		if (inf->msg->link_error != 0) {
524 			xasprintf(&inf->result, "unreadable symlink '%s' (%s)",
525 			    inf->path, strerror(inf->msg->link_error));
526 			return (1);
527 		}
528 		if (inf->msg->link_target == ELOOP)
529 			xasprintf(&inf->result, "symbolic link in a loop");
530 		else if (inf->msg->link_target != 0) {
531 			xasprintf(&inf->result, "broken symbolic link to '%s'",
532 			    inf->msg->link_path);
533 		} else {
534 			xasprintf(&inf->result, "symbolic link to '%s'",
535 			    inf->msg->link_path);
536 		}
537 		return (1);
538 	case S_IFSOCK:
539 		xasprintf(&inf->result, "socket");
540 		return (1);
541 	case S_IFBLK:
542 		xasprintf(&inf->result, "block special (%lu/%lu)",
543 		    (long)major(inf->msg->sb.st_rdev),
544 		    (long)minor(inf->msg->sb.st_rdev));
545 		return (1);
546 	case S_IFCHR:
547 		xasprintf(&inf->result, "character special (%lu/%lu)",
548 		    (long)major(inf->msg->sb.st_rdev),
549 		    (long)minor(inf->msg->sb.st_rdev));
550 		return (1);
551 	case S_IFIFO:
552 		xasprintf(&inf->result, "fifo (named pipe)");
553 		return (1);
554 	}
555 	return (0);
556 }
557 
558 static int
559 try_empty(struct input_file *inf)
560 {
561 	if (inf->size != 0)
562 		return (0);
563 
564 	if (iflag)
565 		xasprintf(&inf->result, "application/x-empty");
566 	else
567 		xasprintf(&inf->result, "empty");
568 	return (1);
569 }
570 
571 static int
572 try_access(struct input_file *inf)
573 {
574 	char tmp[256] = "";
575 
576 	if (inf->msg->sb.st_size == 0 && S_ISREG(inf->msg->sb.st_mode))
577 		return (0); /* empty file */
578 	if (inf->fd != -1)
579 		return (0);
580 
581 	if (inf->msg->sb.st_mode & (S_IWUSR|S_IWGRP|S_IWOTH))
582 		strlcat(tmp, "writable, ", sizeof tmp);
583 	if (inf->msg->sb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH))
584 		strlcat(tmp, "executable, ", sizeof tmp);
585 	if (S_ISREG(inf->msg->sb.st_mode))
586 		strlcat(tmp, "regular file, ", sizeof tmp);
587 	strlcat(tmp, "no read permission", sizeof tmp);
588 
589 	inf->result = xstrdup(tmp);
590 	return (1);
591 }
592 
593 static int
594 try_text(struct input_file *inf)
595 {
596 	const char	*type, *s;
597 	int		 flags;
598 
599 	flags = MAGIC_TEST_TEXT;
600 	if (iflag)
601 		flags |= MAGIC_TEST_MIME;
602 
603 	type = text_get_type(inf->base, inf->size);
604 	if (type == NULL)
605 		return (0);
606 
607 	s = magic_test(inf->m, inf->base, inf->size, flags);
608 	if (s != NULL) {
609 		inf->result = xstrdup(s);
610 		return (1);
611 	}
612 
613 	s = text_try_words(inf->base, inf->size, flags);
614 	if (s != NULL) {
615 		if (iflag)
616 			inf->result = xstrdup(s);
617 		else
618 			xasprintf(&inf->result, "%s %s text", type, s);
619 		return (1);
620 	}
621 
622 	if (iflag)
623 		inf->result = xstrdup("text/plain");
624 	else
625 		xasprintf(&inf->result, "%s text", type);
626 	return (1);
627 }
628 
629 static int
630 try_magic(struct input_file *inf)
631 {
632 	const char	*s;
633 	int		 flags;
634 
635 	flags = 0;
636 	if (iflag)
637 		flags |= MAGIC_TEST_MIME;
638 
639 	s = magic_test(inf->m, inf->base, inf->size, flags);
640 	if (s != NULL) {
641 		inf->result = xstrdup(s);
642 		return (1);
643 	}
644 	return (0);
645 }
646 
647 static int
648 try_unknown(struct input_file *inf)
649 {
650 	if (iflag)
651 		xasprintf(&inf->result, "application/octet-stream");
652 	else
653 		xasprintf(&inf->result, "data");
654 	return (1);
655 }
656 
657 static void
658 test_file(struct input_file *inf, size_t width)
659 {
660 	char	*label;
661 	int	 stop;
662 
663 	stop = 0;
664 	if (!stop)
665 		stop = try_stat(inf);
666 	if (!stop)
667 		stop = try_access(inf);
668 	if (!stop)
669 		stop = load_file(inf);
670 	if (!stop)
671 		stop = try_empty(inf);
672 	if (!stop)
673 		stop = try_magic(inf);
674 	if (!stop)
675 		stop = try_text(inf);
676 	if (!stop)
677 		stop = try_unknown(inf);
678 
679 	if (bflag)
680 		printf("%s\n", inf->result);
681 	else {
682 		if (strcmp(inf->path, "-") == 0)
683 			xasprintf(&label, "/dev/stdin:");
684 		else
685 			xasprintf(&label, "%s:", inf->path);
686 		printf("%-*s %s\n", (int)width, label, inf->result);
687 		free(label);
688 	}
689 	free(inf->result);
690 
691 	if (inf->mapped && inf->base != NULL)
692 		munmap(inf->base, inf->size);
693 }
694