xref: /openbsd-src/usr.bin/file/file.c (revision 25f90b54fc586187d792f4d69f508f5b665df1c4)
1 /* $OpenBSD: file.c,v 1.48 2015/10/02 18:06:27 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/socket.h>
23 #include <sys/queue.h>
24 #include <sys/uio.h>
25 #include <sys/wait.h>
26 
27 #include <errno.h>
28 #include <imsg.h>
29 #include <libgen.h>
30 #include <getopt.h>
31 #include <fcntl.h>
32 #include <pwd.h>
33 #include <stdlib.h>
34 #include <time.h>
35 #include <unistd.h>
36 #include <limits.h>
37 
38 #include "file.h"
39 #include "magic.h"
40 #include "xmalloc.h"
41 
42 struct input_msg
43 {
44 	int		idx;
45 
46 	struct stat	sb;
47 	int		error;
48 
49 	char		link_path[PATH_MAX];
50 	int		link_error;
51 	int		link_target;
52 };
53 
54 struct input_ack
55 {
56 	int		idx;
57 };
58 
59 struct input_file
60 {
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 void	 send_message(struct imsgbuf *, void *, size_t, int);
78 static int	 read_message(struct imsgbuf *, struct imsg *, pid_t);
79 
80 static void	 read_link(struct input_msg *, const char *);
81 
82 static __dead void child(int, pid_t, int, char **);
83 
84 static void	 test_file(struct input_file *, size_t);
85 
86 static int	 try_stat(struct input_file *);
87 static int	 try_empty(struct input_file *);
88 static int	 try_access(struct input_file *);
89 static int	 try_text(struct input_file *);
90 static int	 try_magic(struct input_file *);
91 static int	 try_unknown(struct input_file *);
92 
93 static int	 bflag;
94 static int	 cflag;
95 static int	 iflag;
96 static int	 Lflag;
97 static int	 sflag;
98 static int	 Wflag;
99 
100 static char	*magicpath;
101 static FILE	*magicfp;
102 
103 static struct option longopts[] = {
104 	{ "mime",      no_argument, NULL, 'i' },
105 	{ "mime-type", no_argument, NULL, 'i' },
106 	{ NULL,        0,           NULL, 0   }
107 };
108 
109 __dead void
110 usage(void)
111 {
112 	fprintf(stderr, "usage: %s [-bchiLsW] file ...\n", __progname);
113 	exit(1);
114 }
115 
116 int
117 main(int argc, char **argv)
118 {
119 	int			 opt, pair[2], fd, idx;
120 	char			*home;
121 	struct passwd		*pw;
122 	struct imsgbuf		 ibuf;
123 	struct imsg		 imsg;
124 	struct input_msg	 msg;
125 	struct input_ack	*ack;
126 	pid_t			 pid, parent;
127 
128 	tzset();
129 
130 	for (;;) {
131 		opt = getopt_long(argc, argv, "bchiLsW", longopts, NULL);
132 		if (opt == -1)
133 			break;
134 		switch (opt) {
135 		case 'b':
136 			bflag = 1;
137 			break;
138 		case 'c':
139 			cflag = 1;
140 			break;
141 		case 'h':
142 			Lflag = 0;
143 			break;
144 		case 'i':
145 			iflag = 1;
146 			break;
147 		case 'L':
148 			Lflag = 1;
149 			break;
150 		case 's':
151 			sflag = 1;
152 			break;
153 		case 'W':
154 			Wflag = 1;
155 			break;
156 		default:
157 			usage();
158 		}
159 	}
160 	argc -= optind;
161 	argv += optind;
162 	if (cflag) {
163 		if (argc != 0)
164 			usage();
165 	} else if (argc == 0)
166 		usage();
167 
168 	magicfp = NULL;
169 	if (geteuid() != 0 && !issetugid()) {
170 		home = getenv("HOME");
171 		if (home == NULL || *home == '\0') {
172 			pw = getpwuid(getuid());
173 			if (pw != NULL)
174 				home = pw->pw_dir;
175 			else
176 				home = NULL;
177 		}
178 		if (home != NULL) {
179 			xasprintf(&magicpath, "%s/.magic", home);
180 			magicfp = fopen(magicpath, "r");
181 			if (magicfp == NULL)
182 				free(magicpath);
183 		}
184 	}
185 	if (magicfp == NULL) {
186 		magicpath = xstrdup("/etc/magic");
187 		magicfp = fopen(magicpath, "r");
188 	}
189 	if (magicfp == NULL)
190 		err(1, "%s", magicpath);
191 
192 	parent = getpid();
193 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pair) != 0)
194 		err(1, "socketpair");
195 	pid = sandbox_fork(FILE_USER);
196 	if (pid == 0) {
197 		close(pair[0]);
198 		child(pair[1], parent, argc, argv);
199 	}
200 	close(pair[1]);
201 
202 	fclose(magicfp);
203 	magicfp = NULL;
204 
205 	if (cflag)
206 		goto wait_for_child;
207 
208 	imsg_init(&ibuf, pair[0]);
209 	for (idx = 0; idx < argc; idx++) {
210 		memset(&msg, 0, sizeof msg);
211 		msg.idx = idx;
212 
213 		if (strcmp(argv[idx], "-") == 0) {
214 			if (fstat(STDIN_FILENO, &msg.sb) == -1) {
215 				fd = -1;
216 				msg.error = errno;
217 			} else
218 				fd = STDIN_FILENO;
219 		} else if (lstat(argv[idx], &msg.sb) == -1) {
220 			fd = -1;
221 			msg.error = errno;
222 		} else {
223 			fd = open(argv[idx], O_RDONLY|O_NONBLOCK);
224 			if (fd == -1 && (errno == ENFILE || errno == EMFILE))
225 				err(1, "open");
226 			if (S_ISLNK(msg.sb.st_mode))
227 				read_link(&msg, argv[idx]);
228 		}
229 		send_message(&ibuf, &msg, sizeof msg, fd);
230 
231 		if (read_message(&ibuf, &imsg, pid) == 0)
232 			break;
233 		if (imsg.hdr.len != IMSG_HEADER_SIZE + sizeof *ack)
234 			errx(1, "message too small");
235 		ack = imsg.data;
236 		if (ack->idx != idx)
237 			errx(1, "index not expected");
238 		imsg_free(&imsg);
239 	}
240 
241 wait_for_child:
242 	close(pair[0]);
243 	while (wait(NULL) == -1 && errno != ECHILD) {
244 		if (errno != EINTR)
245 			err(1, "wait");
246 	}
247 	_exit(0); /* let the child flush */
248 }
249 
250 static void
251 send_message(struct imsgbuf *ibuf, void *msg, size_t msglen, int fd)
252 {
253 	if (imsg_compose(ibuf, -1, -1, 0, fd, msg, msglen) != 1)
254 		err(1, "imsg_compose");
255 	if (imsg_flush(ibuf) != 0)
256 		err(1, "imsg_flush");
257 }
258 
259 static int
260 read_message(struct imsgbuf *ibuf, struct imsg *imsg, pid_t from)
261 {
262 	int	n;
263 
264 	if ((n = imsg_read(ibuf)) == -1)
265 		err(1, "imsg_read");
266 	if (n == 0)
267 		return (0);
268 
269 	if ((n = imsg_get(ibuf, imsg)) == -1)
270 		err(1, "imsg_get");
271 	if (n == 0)
272 		return (0);
273 
274 	if ((pid_t)imsg->hdr.pid != from)
275 		errx(1, "PIDs don't match");
276 
277 	return (n);
278 
279 }
280 
281 static void
282 read_link(struct input_msg *msg, const char *path)
283 {
284 	struct stat	 sb;
285 	char		 lpath[PATH_MAX];
286 	char		*copy, *root;
287 	int		 used;
288 	ssize_t		 size;
289 
290 	size = readlink(path, lpath, sizeof lpath - 1);
291 	if (size == -1) {
292 		msg->link_error = errno;
293 		return;
294 	}
295 	lpath[size] = '\0';
296 
297 	if (*lpath == '/')
298 		strlcpy(msg->link_path, lpath, sizeof msg->link_path);
299 	else {
300 		copy = xstrdup(path);
301 
302 		root = dirname(copy);
303 		if (*root == '\0' || strcmp(root, ".") == 0 ||
304 		    strcmp (root, "/") == 0)
305 			strlcpy(msg->link_path, lpath, sizeof msg->link_path);
306 		else {
307 			used = snprintf(msg->link_path, sizeof msg->link_path,
308 			    "%s/%s", root, lpath);
309 			if (used < 0 || (size_t)used >= sizeof msg->link_path) {
310 				msg->link_error = ENAMETOOLONG;
311 				free(copy);
312 				return;
313 			}
314 		}
315 
316 		free(copy);
317 	}
318 
319 	if (Lflag) {
320 		if (stat(path, &msg->sb) == -1)
321 			msg->error = errno;
322 	} else {
323 		if (stat(path, &sb) == -1)
324 			msg->link_target = errno;
325 	}
326 }
327 
328 static __dead void
329 child(int fd, pid_t parent, int argc, char **argv)
330 {
331 	struct magic		*m;
332 	struct imsgbuf		 ibuf;
333 	struct imsg		 imsg;
334 	struct input_msg	*msg;
335 	struct input_ack	 ack;
336 	struct input_file	 inf;
337 	int			 i, idx;
338 	size_t			 len, width = 0;
339 
340 	m = magic_load(magicfp, magicpath, cflag || Wflag);
341 	if (cflag) {
342 		magic_dump(m);
343 		exit(0);
344 	}
345 
346 	for (i = 0; i < argc; i++) {
347 		len = strlen(argv[i]) + 1;
348 		if (len > width)
349 			width = len;
350 	}
351 
352 	imsg_init(&ibuf, fd);
353 	for (;;) {
354 		if (read_message(&ibuf, &imsg, parent) == 0)
355 			break;
356 		if (imsg.hdr.len != IMSG_HEADER_SIZE + sizeof *msg)
357 			errx(1, "message too small");
358 		msg = imsg.data;
359 
360 		idx = msg->idx;
361 		if (idx < 0 || idx >= argc)
362 			errx(1, "index out of range");
363 
364 		memset(&inf, 0, sizeof inf);
365 		inf.m = m;
366 		inf.msg = msg;
367 
368 		inf.path = argv[idx];
369 		inf.fd = imsg.fd;
370 
371 		test_file(&inf, width);
372 
373 		if (imsg.fd != -1)
374 			close(imsg.fd);
375 		imsg_free(&imsg);
376 
377 		ack.idx = idx;
378 		send_message(&ibuf, &ack, sizeof ack, -1);
379 	}
380 	exit(0);
381 }
382 
383 static void *
384 fill_buffer(int fd, size_t size, size_t *used)
385 {
386 	static void	*buffer;
387 	ssize_t		 got;
388 	size_t		 left;
389 	void		*next;
390 
391 	if (buffer == NULL)
392 		buffer = xmalloc(FILE_READ_SIZE);
393 
394 	next = buffer;
395 	left = size;
396 	while (left != 0) {
397 		got = read(fd, next, left);
398 		if (got == -1) {
399 			if (errno == EINTR)
400 				continue;
401 			return NULL;
402 		}
403 		if (got == 0)
404 			break;
405 		next = (char *)next + got;
406 		left -= got;
407 	}
408 	*used = size - left;
409 	return buffer;
410 }
411 
412 static int
413 load_file(struct input_file *inf)
414 {
415 	size_t	used;
416 
417 	if (inf->msg->sb.st_size == 0 && S_ISREG(inf->msg->sb.st_mode))
418 		return (0); /* empty file */
419 	if (inf->msg->sb.st_size == 0 || inf->msg->sb.st_size > FILE_READ_SIZE)
420 		inf->size = FILE_READ_SIZE;
421 	else
422 		inf->size = inf->msg->sb.st_size;
423 
424 	if (!S_ISREG(inf->msg->sb.st_mode))
425 		goto try_read;
426 
427 	inf->base = mmap(NULL, inf->size, PROT_READ, MAP_PRIVATE, inf->fd, 0);
428 	if (inf->base == MAP_FAILED)
429 		goto try_read;
430 	inf->mapped = 1;
431 	return (0);
432 
433 try_read:
434 	inf->base = fill_buffer(inf->fd, inf->size, &used);
435 	if (inf->base == NULL) {
436 		xasprintf(&inf->result, "cannot read '%s' (%s)", inf->path,
437 		    strerror(errno));
438 		return (1);
439 	}
440 	inf->size = used;
441 	return (0);
442 }
443 
444 static int
445 try_stat(struct input_file *inf)
446 {
447 	if (inf->msg->error != 0) {
448 		xasprintf(&inf->result, "cannot stat '%s' (%s)", inf->path,
449 		    strerror(inf->msg->error));
450 		return (1);
451 	}
452 	if (sflag || strcmp(inf->path, "-") == 0) {
453 		switch (inf->msg->sb.st_mode & S_IFMT) {
454 		case S_IFIFO:
455 			if (strcmp(inf->path, "-") != 0)
456 				break;
457 		case S_IFBLK:
458 		case S_IFCHR:
459 		case S_IFREG:
460 			return (0);
461 		}
462 	}
463 
464 	if (iflag && (inf->msg->sb.st_mode & S_IFMT) != S_IFREG) {
465 		xasprintf(&inf->result, "application/x-not-regular-file");
466 		return (1);
467 	}
468 
469 	switch (inf->msg->sb.st_mode & S_IFMT) {
470 	case S_IFDIR:
471 		xasprintf(&inf->result, "directory");
472 		return (1);
473 	case S_IFLNK:
474 		if (inf->msg->link_error != 0) {
475 			xasprintf(&inf->result, "unreadable symlink '%s' (%s)",
476 			    inf->path, strerror(inf->msg->link_error));
477 			return (1);
478 		}
479 		if (inf->msg->link_target == ELOOP)
480 			xasprintf(&inf->result, "symbolic link in a loop");
481 		else if (inf->msg->link_target != 0) {
482 			xasprintf(&inf->result, "broken symbolic link to '%s'",
483 			    inf->msg->link_path);
484 		} else {
485 			xasprintf(&inf->result, "symbolic link to '%s'",
486 			    inf->msg->link_path);
487 		}
488 		return (1);
489 	case S_IFSOCK:
490 		xasprintf(&inf->result, "socket");
491 		return (1);
492 	case S_IFBLK:
493 		xasprintf(&inf->result, "block special (%ld/%ld)",
494 		    (long)major(inf->msg->sb.st_rdev),
495 		    (long)minor(inf->msg->sb.st_rdev));
496 		return (1);
497 	case S_IFCHR:
498 		xasprintf(&inf->result, "character special (%ld/%ld)",
499 		    (long)major(inf->msg->sb.st_rdev),
500 		    (long)minor(inf->msg->sb.st_rdev));
501 		return (1);
502 	case S_IFIFO:
503 		xasprintf(&inf->result, "fifo (named pipe)");
504 		return (1);
505 	}
506 	return (0);
507 }
508 
509 static int
510 try_empty(struct input_file *inf)
511 {
512 	if (inf->size != 0)
513 		return (0);
514 
515 	if (iflag)
516 		xasprintf(&inf->result, "application/x-empty");
517 	else
518 		xasprintf(&inf->result, "empty");
519 	return (1);
520 }
521 
522 static int
523 try_access(struct input_file *inf)
524 {
525 	char tmp[256] = "";
526 
527 	if (inf->fd != -1)
528 		return (0);
529 
530 	if (inf->msg->sb.st_mode & (S_IWUSR|S_IWGRP|S_IWOTH))
531 		strlcat(tmp, "writable, ", sizeof tmp);
532 	if (inf->msg->sb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH))
533 		strlcat(tmp, "executable, ", sizeof tmp);
534 	if (S_ISREG(inf->msg->sb.st_mode))
535 		strlcat(tmp, "regular file, ", sizeof tmp);
536 	strlcat(tmp, "no read permission", sizeof tmp);
537 
538 	inf->result = xstrdup(tmp);
539 	return (1);
540 }
541 
542 static int
543 try_text(struct input_file *inf)
544 {
545 	const char	*type, *s;
546 	int		 flags;
547 
548 	flags = MAGIC_TEST_TEXT;
549 	if (iflag)
550 		flags |= MAGIC_TEST_MIME;
551 
552 	type = text_get_type(inf->base, inf->size);
553 	if (type == NULL)
554 		return (0);
555 
556 	s = magic_test(inf->m, inf->base, inf->size, flags);
557 	if (s != NULL) {
558 		inf->result = xstrdup(s);
559 		return (1);
560 	}
561 
562 	s = text_try_words(inf->base, inf->size, flags);
563 	if (s != NULL) {
564 		if (iflag)
565 			inf->result = xstrdup(s);
566 		else
567 			xasprintf(&inf->result, "%s %s text", type, s);
568 		return (1);
569 	}
570 
571 	if (iflag)
572 		inf->result = xstrdup("text/plain");
573 	else
574 		xasprintf(&inf->result, "%s text", type);
575 	return (1);
576 }
577 
578 static int
579 try_magic(struct input_file *inf)
580 {
581 	const char	*s;
582 	int		 flags;
583 
584 	flags = 0;
585 	if (iflag)
586 		flags |= MAGIC_TEST_MIME;
587 
588 	s = magic_test(inf->m, inf->base, inf->size, flags);
589 	if (s != NULL) {
590 		inf->result = xstrdup(s);
591 		return (1);
592 	}
593 	return (0);
594 }
595 
596 static int
597 try_unknown(struct input_file *inf)
598 {
599 	if (iflag)
600 		xasprintf(&inf->result, "application/x-not-regular-file");
601 	else
602 		xasprintf(&inf->result, "data");
603 	return (1);
604 }
605 
606 static void
607 test_file(struct input_file *inf, size_t width)
608 {
609 	char	*label;
610 	int	 stop;
611 
612 	stop = 0;
613 	if (!stop)
614 		stop = try_stat(inf);
615 	if (!stop)
616 		stop = try_access(inf);
617 	if (!stop)
618 		stop = load_file(inf);
619 	if (!stop)
620 		stop = try_empty(inf);
621 	if (!stop)
622 		stop = try_magic(inf);
623 	if (!stop)
624 		stop = try_text(inf);
625 	if (!stop)
626 		stop = try_unknown(inf);
627 
628 	if (bflag)
629 		printf("%s\n", inf->result);
630 	else {
631 		if (strcmp(inf->path, "-") == 0)
632 			xasprintf(&label, "/dev/stdin:");
633 		else
634 			xasprintf(&label, "%s:", inf->path);
635 		printf("%-*s %s\n", (int)width, label, inf->result);
636 		free(label);
637 	}
638 	free(inf->result);
639 
640 	if (inf->mapped && inf->base != NULL)
641 		munmap(inf->base, inf->size);
642 }
643