xref: /freebsd/usr.bin/diff/diff.c (revision 105fd928b0b5b35ab529e5f6914788dc49582901)
1 /*	$OpenBSD: diff.c,v 1.67 2019/06/28 13:35:00 deraadt Exp $	*/
2 
3 /*
4  * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
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 USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  *
18  * Sponsored in part by the Defense Advanced Research Projects
19  * Agency (DARPA) and Air Force Research Laboratory, Air Force
20  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
21  */
22 
23 #include <sys/cdefs.h>
24 __FBSDID("$FreeBSD$");
25 
26 #include <sys/stat.h>
27 
28 #include <ctype.h>
29 #include <err.h>
30 #include <errno.h>
31 #include <getopt.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <limits.h>
37 
38 #include "diff.h"
39 #include "xmalloc.h"
40 
41 bool	 lflag, Nflag, Pflag, rflag, sflag, Tflag, cflag;
42 bool	 ignore_file_case, suppress_common, color;
43 int	 diff_format, diff_context, status;
44 int	 tabsize = 8, width = 130;
45 static int	colorflag = COLORFLAG_NEVER;
46 char	*start, *ifdefname, *diffargs, *label[2];
47 char	*ignore_pats, *most_recent_pat;
48 char	*group_format = NULL;
49 const char	*add_code, *del_code;
50 struct stat stb1, stb2;
51 struct excludes *excludes_list;
52 regex_t	 ignore_re, most_recent_re;
53 
54 #define	OPTIONS	"0123456789aBbC:cdD:efF:HhI:iL:lnNPpqrS:sTtU:uwW:X:x:y"
55 enum {
56 	OPT_TSIZE = CHAR_MAX + 1,
57 	OPT_STRIPCR,
58 	OPT_IGN_FN_CASE,
59 	OPT_NO_IGN_FN_CASE,
60 	OPT_NORMAL,
61 	OPT_HORIZON_LINES,
62 	OPT_CHANGED_GROUP_FORMAT,
63 	OPT_SUPPRESS_COMMON,
64 	OPT_COLOR,
65 };
66 
67 static struct option longopts[] = {
68 	{ "text",			no_argument,		0,	'a' },
69 	{ "ignore-space-change",	no_argument,		0,	'b' },
70 	{ "context",			optional_argument,	0,	'C' },
71 	{ "ifdef",			required_argument,	0,	'D' },
72 	{ "minimal",			no_argument,		0,	'd' },
73 	{ "ed",				no_argument,		0,	'e' },
74 	{ "forward-ed",			no_argument,		0,	'f' },
75 	{ "show-function-line",		required_argument,	0,	'F' },
76 	{ "speed-large-files",		no_argument,		NULL,	'H' },
77 	{ "ignore-blank-lines",		no_argument,		0,	'B' },
78 	{ "ignore-matching-lines",	required_argument,	0,	'I' },
79 	{ "ignore-case",		no_argument,		0,	'i' },
80 	{ "paginate",			no_argument,		NULL,	'l' },
81 	{ "label",			required_argument,	0,	'L' },
82 	{ "new-file",			no_argument,		0,	'N' },
83 	{ "rcs",			no_argument,		0,	'n' },
84 	{ "unidirectional-new-file",	no_argument,		0,	'P' },
85 	{ "show-c-function",		no_argument,		0,	'p' },
86 	{ "brief",			no_argument,		0,	'q' },
87 	{ "recursive",			no_argument,		0,	'r' },
88 	{ "report-identical-files",	no_argument,		0,	's' },
89 	{ "starting-file",		required_argument,	0,	'S' },
90 	{ "expand-tabs",		no_argument,		0,	't' },
91 	{ "initial-tab",		no_argument,		0,	'T' },
92 	{ "unified",			optional_argument,	0,	'U' },
93 	{ "ignore-all-space",		no_argument,		0,	'w' },
94 	{ "width",			required_argument,	0,	'W' },
95 	{ "exclude",			required_argument,	0,	'x' },
96 	{ "exclude-from",		required_argument,	0,	'X' },
97 	{ "side-by-side",		no_argument,		NULL,	'y' },
98 	{ "ignore-file-name-case",	no_argument,		NULL,	OPT_IGN_FN_CASE },
99 	{ "horizon-lines",		required_argument,	NULL,	OPT_HORIZON_LINES },
100 	{ "no-ignore-file-name-case",	no_argument,		NULL,	OPT_NO_IGN_FN_CASE },
101 	{ "normal",			no_argument,		NULL,	OPT_NORMAL },
102 	{ "strip-trailing-cr",		no_argument,		NULL,	OPT_STRIPCR },
103 	{ "tabsize",			required_argument,	NULL,	OPT_TSIZE },
104 	{ "changed-group-format",	required_argument,	NULL,	OPT_CHANGED_GROUP_FORMAT},
105 	{ "suppress-common-lines",	no_argument,		NULL,	OPT_SUPPRESS_COMMON },
106 	{ "color",			optional_argument,	NULL,	OPT_COLOR },
107 	{ NULL,				0,			0,	'\0'}
108 };
109 
110 static void checked_regcomp(char const *, regex_t *);
111 static void usage(void) __dead2;
112 static void conflicting_format(void) __dead2;
113 static void push_excludes(char *);
114 static void push_ignore_pats(char *);
115 static void read_excludes_file(char *file);
116 static void set_argstr(char **, char **);
117 static char *splice(char *, char *);
118 static bool do_color(void);
119 
120 int
121 main(int argc, char **argv)
122 {
123 	const char *errstr = NULL;
124 	char *ep, **oargv;
125 	long  l;
126 	int   ch, dflags, lastch, gotstdin, prevoptind, newarg;
127 
128 	oargv = argv;
129 	gotstdin = 0;
130 	dflags = 0;
131 	lastch = '\0';
132 	prevoptind = 1;
133 	newarg = 1;
134 	diff_context = 3;
135 	diff_format = D_UNSET;
136 #define	FORMAT_MISMATCHED(type)	\
137 	(diff_format != D_UNSET && diff_format != (type))
138 	while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) {
139 		switch (ch) {
140 		case '0': case '1': case '2': case '3': case '4':
141 		case '5': case '6': case '7': case '8': case '9':
142 			if (newarg)
143 				usage();	/* disallow -[0-9]+ */
144 			else if (lastch == 'c' || lastch == 'u')
145 				diff_context = 0;
146 			else if (!isdigit(lastch) || diff_context > INT_MAX / 10)
147 				usage();
148 			diff_context = (diff_context * 10) + (ch - '0');
149 			break;
150 		case 'a':
151 			dflags |= D_FORCEASCII;
152 			break;
153 		case 'b':
154 			dflags |= D_FOLDBLANKS;
155 			break;
156 		case 'C':
157 		case 'c':
158 			if (FORMAT_MISMATCHED(D_CONTEXT))
159 				conflicting_format();
160 			diff_format = D_CONTEXT;
161 			if (optarg != NULL) {
162 				l = strtol(optarg, &ep, 10);
163 				if (*ep != '\0' || l < 0 || l >= INT_MAX)
164 					usage();
165 				diff_context = (int)l;
166 			}
167 			break;
168 		case 'd':
169 			dflags |= D_MINIMAL;
170 			break;
171 		case 'D':
172 			if (FORMAT_MISMATCHED(D_IFDEF))
173 				conflicting_format();
174 			diff_format = D_IFDEF;
175 			ifdefname = optarg;
176 			break;
177 		case 'e':
178 			if (FORMAT_MISMATCHED(D_EDIT))
179 				conflicting_format();
180 			diff_format = D_EDIT;
181 			break;
182 		case 'f':
183 			if (FORMAT_MISMATCHED(D_REVERSE))
184 				conflicting_format();
185 			diff_format = D_REVERSE;
186 			break;
187 		case 'H':
188 			/* ignore but needed for compatibility with GNU diff */
189 			break;
190 		case 'h':
191 			/* silently ignore for backwards compatibility */
192 			break;
193 		case 'B':
194 			dflags |= D_SKIPBLANKLINES;
195 			break;
196 		case 'F':
197 			if (dflags & D_PROTOTYPE)
198 				conflicting_format();
199 			dflags |= D_MATCHLAST;
200 			most_recent_pat = xstrdup(optarg);
201 			break;
202 		case 'I':
203 			push_ignore_pats(optarg);
204 			break;
205 		case 'i':
206 			dflags |= D_IGNORECASE;
207 			break;
208 		case 'L':
209 			if (label[0] == NULL)
210 				label[0] = optarg;
211 			else if (label[1] == NULL)
212 				label[1] = optarg;
213 			else
214 				usage();
215 			break;
216 		case 'l':
217 			lflag = true;
218 			break;
219 		case 'N':
220 			Nflag = true;
221 			break;
222 		case 'n':
223 			if (FORMAT_MISMATCHED(D_NREVERSE))
224 				conflicting_format();
225 			diff_format = D_NREVERSE;
226 			break;
227 		case 'p':
228 			if (dflags & D_MATCHLAST)
229 				conflicting_format();
230 			dflags |= D_PROTOTYPE;
231 			break;
232 		case 'P':
233 			Pflag = true;
234 			break;
235 		case 'r':
236 			rflag = true;
237 			break;
238 		case 'q':
239 			if (FORMAT_MISMATCHED(D_BRIEF))
240 				conflicting_format();
241 			diff_format = D_BRIEF;
242 			break;
243 		case 'S':
244 			start = optarg;
245 			break;
246 		case 's':
247 			sflag = true;
248 			break;
249 		case 'T':
250 			Tflag = true;
251 			break;
252 		case 't':
253 			dflags |= D_EXPANDTABS;
254 			break;
255 		case 'U':
256 		case 'u':
257 			if (FORMAT_MISMATCHED(D_UNIFIED))
258 				conflicting_format();
259 			diff_format = D_UNIFIED;
260 			if (optarg != NULL) {
261 				l = strtol(optarg, &ep, 10);
262 				if (*ep != '\0' || l < 0 || l >= INT_MAX)
263 					usage();
264 				diff_context = (int)l;
265 			}
266 			break;
267 		case 'w':
268 			dflags |= D_IGNOREBLANKS;
269 			break;
270 		case 'W':
271 			width = (int) strtonum(optarg, 1, INT_MAX, &errstr);
272 			if (errstr) {
273 				warnx("Invalid argument for width");
274 				usage();
275 			}
276 			break;
277 		case 'X':
278 			read_excludes_file(optarg);
279 			break;
280 		case 'x':
281 			push_excludes(optarg);
282 			break;
283 		case 'y':
284 			if (FORMAT_MISMATCHED(D_SIDEBYSIDE))
285 				conflicting_format();
286 			diff_format = D_SIDEBYSIDE;
287 			break;
288 		case OPT_CHANGED_GROUP_FORMAT:
289 			if (FORMAT_MISMATCHED(D_GFORMAT))
290 				conflicting_format();
291 			diff_format = D_GFORMAT;
292 			group_format = optarg;
293 			break;
294 		case OPT_HORIZON_LINES:
295 			break; /* XXX TODO for compatibility with GNU diff3 */
296 		case OPT_IGN_FN_CASE:
297 			ignore_file_case = true;
298 			break;
299 		case OPT_NO_IGN_FN_CASE:
300 			ignore_file_case = false;
301 			break;
302 		case OPT_NORMAL:
303 			if (FORMAT_MISMATCHED(D_NORMAL))
304 				conflicting_format();
305 			diff_format = D_NORMAL;
306 			break;
307 		case OPT_TSIZE:
308 			tabsize = (int) strtonum(optarg, 1, INT_MAX, &errstr);
309 			if (errstr) {
310 				warnx("Invalid argument for tabsize");
311 				usage();
312 			}
313 			break;
314 		case OPT_STRIPCR:
315 			dflags |= D_STRIPCR;
316 			break;
317 		case OPT_SUPPRESS_COMMON:
318 			suppress_common = 1;
319 			break;
320 		case OPT_COLOR:
321 			if (optarg == NULL || strncmp(optarg, "auto", 4) == 0)
322 				colorflag = COLORFLAG_AUTO;
323 			else if (strncmp(optarg, "always", 6) == 0)
324 				colorflag = COLORFLAG_ALWAYS;
325 			else if (strncmp(optarg, "never", 5) == 0)
326 				colorflag = COLORFLAG_NEVER;
327 			else
328 				errx(2, "unsupported --color value '%s' (must be always, auto, or never)",
329 					optarg);
330 			break;
331 		default:
332 			usage();
333 			break;
334 		}
335 		lastch = ch;
336 		newarg = optind != prevoptind;
337 		prevoptind = optind;
338 	}
339 	if (diff_format == D_UNSET && (dflags & D_PROTOTYPE) != 0)
340 		diff_format = D_CONTEXT;
341 	if (diff_format == D_UNSET)
342 		diff_format = D_NORMAL;
343 	argc -= optind;
344 	argv += optind;
345 
346 	if (do_color()) {
347 		char *p;
348 		const char *env;
349 
350 		color = true;
351 		add_code = "32";
352 		del_code = "31";
353 		env = getenv("DIFFCOLORS");
354 		if (env != NULL && *env != '\0' && (p = strdup(env))) {
355 			add_code = p;
356 			strsep(&p, ":");
357 			if (p != NULL)
358 				del_code = p;
359 		}
360 	}
361 
362 #ifdef __OpenBSD__
363 	if (pledge("stdio rpath tmppath", NULL) == -1)
364 		err(2, "pledge");
365 #endif
366 
367 	/*
368 	 * Do sanity checks, fill in stb1 and stb2 and call the appropriate
369 	 * driver routine.  Both drivers use the contents of stb1 and stb2.
370 	 */
371 	if (argc != 2)
372 		usage();
373 	checked_regcomp(ignore_pats, &ignore_re);
374 	checked_regcomp(most_recent_pat, &most_recent_re);
375 	if (strcmp(argv[0], "-") == 0) {
376 		fstat(STDIN_FILENO, &stb1);
377 		gotstdin = 1;
378 	} else if (stat(argv[0], &stb1) != 0) {
379 		if (!Nflag || errno != ENOENT)
380 			err(2, "%s", argv[0]);
381 		dflags |= D_EMPTY1;
382 		memset(&stb1, 0, sizeof(struct stat));
383 	}
384 
385 	if (strcmp(argv[1], "-") == 0) {
386 		fstat(STDIN_FILENO, &stb2);
387 		gotstdin = 1;
388 	} else if (stat(argv[1], &stb2) != 0) {
389 		if (!Nflag || errno != ENOENT)
390 			err(2, "%s", argv[1]);
391 		dflags |= D_EMPTY2;
392 		memset(&stb2, 0, sizeof(stb2));
393 		stb2.st_mode = stb1.st_mode;
394 	}
395 
396 	if (dflags & D_EMPTY1 && dflags & D_EMPTY2){
397 		warn("%s", argv[0]);
398 		warn("%s", argv[1]);
399 		exit(2);
400 	}
401 
402 	if (stb1.st_mode == 0)
403 		stb1.st_mode = stb2.st_mode;
404 
405 	if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
406 		errx(2, "can't compare - to a directory");
407 	set_argstr(oargv, argv);
408 	if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
409 		if (diff_format == D_IFDEF)
410 			errx(2, "-D option not supported with directories");
411 		diffdir(argv[0], argv[1], dflags);
412 	} else {
413 		if (S_ISDIR(stb1.st_mode)) {
414 			argv[0] = splice(argv[0], argv[1]);
415 			if (stat(argv[0], &stb1) == -1)
416 				err(2, "%s", argv[0]);
417 		}
418 		if (S_ISDIR(stb2.st_mode)) {
419 			argv[1] = splice(argv[1], argv[0]);
420 			if (stat(argv[1], &stb2) == -1)
421 				err(2, "%s", argv[1]);
422 		}
423 		print_status(diffreg(argv[0], argv[1], dflags, 1), argv[0],
424 		    argv[1], "");
425 	}
426 	exit(status);
427 }
428 
429 static void
430 checked_regcomp(char const *pattern, regex_t *comp)
431 {
432 	char buf[BUFSIZ];
433 	int error;
434 
435 	if (pattern == NULL)
436 		return;
437 
438 	error = regcomp(comp, pattern, REG_NEWLINE | REG_EXTENDED);
439 	if (error != 0) {
440 		regerror(error, comp, buf, sizeof(buf));
441 		if (*pattern != '\0')
442 			errx(2, "%s: %s", pattern, buf);
443 		else
444 			errx(2, "%s", buf);
445 	}
446 }
447 
448 static void
449 set_argstr(char **av, char **ave)
450 {
451 	size_t argsize;
452 	char **ap;
453 
454 	argsize = 4 + *ave - *av + 1;
455 	diffargs = xmalloc(argsize);
456 	strlcpy(diffargs, "diff", argsize);
457 	for (ap = av + 1; ap < ave; ap++) {
458 		if (strcmp(*ap, "--") != 0) {
459 			strlcat(diffargs, " ", argsize);
460 			strlcat(diffargs, *ap, argsize);
461 		}
462 	}
463 }
464 
465 /*
466  * Read in an excludes file and push each line.
467  */
468 static void
469 read_excludes_file(char *file)
470 {
471 	FILE *fp;
472 	char *buf, *pattern;
473 	size_t len;
474 
475 	if (strcmp(file, "-") == 0)
476 		fp = stdin;
477 	else if ((fp = fopen(file, "r")) == NULL)
478 		err(2, "%s", file);
479 	while ((buf = fgetln(fp, &len)) != NULL) {
480 		if (buf[len - 1] == '\n')
481 			len--;
482 		if ((pattern = strndup(buf, len)) == NULL)
483 			err(2, "xstrndup");
484 		push_excludes(pattern);
485 	}
486 	if (strcmp(file, "-") != 0)
487 		fclose(fp);
488 }
489 
490 /*
491  * Push a pattern onto the excludes list.
492  */
493 static void
494 push_excludes(char *pattern)
495 {
496 	struct excludes *entry;
497 
498 	entry = xmalloc(sizeof(*entry));
499 	entry->pattern = pattern;
500 	entry->next = excludes_list;
501 	excludes_list = entry;
502 }
503 
504 static void
505 push_ignore_pats(char *pattern)
506 {
507 	size_t len;
508 
509 	if (ignore_pats == NULL)
510 		ignore_pats = xstrdup(pattern);
511 	else {
512 		/* old + "|" + new + NUL */
513 		len = strlen(ignore_pats) + strlen(pattern) + 2;
514 		ignore_pats = xreallocarray(ignore_pats, 1, len);
515 		strlcat(ignore_pats, "|", len);
516 		strlcat(ignore_pats, pattern, len);
517 	}
518 }
519 
520 void
521 print_status(int val, char *path1, char *path2, const char *entry)
522 {
523 	if (label[0] != NULL)
524 		path1 = label[0];
525 	if (label[1] != NULL)
526 		path2 = label[1];
527 
528 	switch (val) {
529 	case D_BINARY:
530 		printf("Binary files %s%s and %s%s differ\n",
531 		    path1, entry, path2, entry);
532 		break;
533 	case D_DIFFER:
534 		if (diff_format == D_BRIEF)
535 			printf("Files %s%s and %s%s differ\n",
536 			    path1, entry, path2, entry);
537 		break;
538 	case D_SAME:
539 		if (sflag)
540 			printf("Files %s%s and %s%s are identical\n",
541 			    path1, entry, path2, entry);
542 		break;
543 	case D_MISMATCH1:
544 		printf("File %s%s is a directory while file %s%s is a regular file\n",
545 		    path1, entry, path2, entry);
546 		break;
547 	case D_MISMATCH2:
548 		printf("File %s%s is a regular file while file %s%s is a directory\n",
549 		    path1, entry, path2, entry);
550 		break;
551 	case D_SKIPPED1:
552 		printf("File %s%s is not a regular file or directory and was skipped\n",
553 		    path1, entry);
554 		break;
555 	case D_SKIPPED2:
556 		printf("File %s%s is not a regular file or directory and was skipped\n",
557 		    path2, entry);
558 		break;
559 	case D_ERROR:
560 		break;
561 	}
562 }
563 
564 static void
565 usage(void)
566 {
567 	(void)fprintf(stderr,
568 	    "usage: diff [-aBbdilpTtw] [-c | -e | -f | -n | -q | -u] [--ignore-case]\n"
569 	    "            [--no-ignore-case] [--normal] [--strip-trailing-cr] [--tabsize]\n"
570 	    "            [-I pattern] [-F pattern] [-L label] file1 file2\n"
571 	    "       diff [-aBbdilpTtw] [-I pattern] [-L label] [--ignore-case]\n"
572 	    "            [--no-ignore-case] [--normal] [--strip-trailing-cr] [--tabsize]\n"
573 	    "            [-F pattern] -C number file1 file2\n"
574 	    "       diff [-aBbdiltw] [-I pattern] [--ignore-case] [--no-ignore-case]\n"
575 	    "            [--normal] [--strip-trailing-cr] [--tabsize] -D string file1 file2\n"
576 	    "       diff [-aBbdilpTtw] [-I pattern] [-L label] [--ignore-case]\n"
577 	    "            [--no-ignore-case] [--normal] [--tabsize] [--strip-trailing-cr]\n"
578 	    "            [-F pattern] -U number file1 file2\n"
579 	    "       diff [-aBbdilNPprsTtw] [-c | -e | -f | -n | -q | -u] [--ignore-case]\n"
580 	    "            [--no-ignore-case] [--normal] [--tabsize] [-I pattern] [-L label]\n"
581 	    "            [-F pattern] [-S name] [-X file] [-x pattern] dir1 dir2\n"
582 	    "       diff [-aBbditwW] [--expand-tabs] [--ignore-all-blanks]\n"
583 	    "            [--ignore-blank-lines] [--ignore-case] [--minimal]\n"
584 	    "            [--no-ignore-file-name-case] [--strip-trailing-cr]\n"
585 	    "            [--suppress-common-lines] [--tabsize] [--text] [--width]\n"
586 	    "            -y | --side-by-side file1 file2\n");
587 
588 	exit(2);
589 }
590 
591 static void
592 conflicting_format(void)
593 {
594 
595 	fprintf(stderr, "error: conflicting output format options.\n");
596 	usage();
597 }
598 
599 static bool
600 do_color(void)
601 {
602 	const char *p, *p2;
603 
604 	switch (colorflag) {
605 	case COLORFLAG_AUTO:
606 		p = getenv("CLICOLOR");
607 		p2 = getenv("COLORTERM");
608 		if ((p != NULL && *p != '\0') || (p2 != NULL && *p2 != '\0'))
609 			return isatty(STDOUT_FILENO);
610 		break;
611 	case COLORFLAG_ALWAYS:
612 		return (true);
613 	case COLORFLAG_NEVER:
614 		return (false);
615 	}
616 
617 	return (false);
618 }
619 
620 static char *
621 splice(char *dir, char *path)
622 {
623 	char *tail, *buf;
624 	size_t dirlen;
625 
626 	dirlen = strlen(dir);
627 	while (dirlen != 0 && dir[dirlen - 1] == '/')
628 	    dirlen--;
629 	if ((tail = strrchr(path, '/')) == NULL)
630 		tail = path;
631 	else
632 		tail++;
633 	xasprintf(&buf, "%.*s/%s", (int)dirlen, dir, tail);
634 	return (buf);
635 }
636