xref: /freebsd/usr.bin/diff/diff.c (revision 9e4c35f867aca020df8d01fb7371bf5ae1cc8a2d)
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 int	 lflag, Nflag, Pflag, rflag, sflag, Tflag, cflag, Wflag;
42 int	 diff_format, diff_context, status, ignore_file_case, suppress_common;
43 int	 tabsize = 8, width = 130;
44 char	*start, *ifdefname, *diffargs, *label[2], *ignore_pats;
45 char	*group_format = NULL;
46 struct stat stb1, stb2;
47 struct excludes *excludes_list;
48 regex_t	 ignore_re;
49 
50 #define	OPTIONS	"0123456789aBbC:cdD:efHhI:iL:lnNPpqrS:sTtU:uwW:X:x:y"
51 enum {
52 	OPT_TSIZE = CHAR_MAX + 1,
53 	OPT_STRIPCR,
54 	OPT_IGN_FN_CASE,
55 	OPT_NO_IGN_FN_CASE,
56 	OPT_NORMAL,
57 	OPT_HORIZON_LINES,
58 	OPT_CHANGED_GROUP_FORMAT,
59 	OPT_SUPPRESS_COMMON,
60 };
61 
62 static struct option longopts[] = {
63 	{ "text",			no_argument,		0,	'a' },
64 	{ "ignore-space-change",	no_argument,		0,	'b' },
65 	{ "context",			optional_argument,	0,	'C' },
66 	{ "ifdef",			required_argument,	0,	'D' },
67 	{ "minimal",			no_argument,		0,	'd' },
68 	{ "ed",				no_argument,		0,	'e' },
69 	{ "forward-ed",			no_argument,		0,	'f' },
70 	{ "speed-large-files",		no_argument,		NULL,	'H' },
71 	{ "ignore-blank-lines",		no_argument,		0,	'B' },
72 	{ "ignore-matching-lines",	required_argument,	0,	'I' },
73 	{ "ignore-case",		no_argument,		0,	'i' },
74 	{ "paginate",			no_argument,		NULL,	'l' },
75 	{ "label",			required_argument,	0,	'L' },
76 	{ "new-file",			no_argument,		0,	'N' },
77 	{ "rcs",			no_argument,		0,	'n' },
78 	{ "unidirectional-new-file",	no_argument,		0,	'P' },
79 	{ "show-c-function",		no_argument,		0,	'p' },
80 	{ "brief",			no_argument,		0,	'q' },
81 	{ "recursive",			no_argument,		0,	'r' },
82 	{ "report-identical-files",	no_argument,		0,	's' },
83 	{ "starting-file",		required_argument,	0,	'S' },
84 	{ "expand-tabs",		no_argument,		0,	't' },
85 	{ "initial-tab",		no_argument,		0,	'T' },
86 	{ "unified",			optional_argument,	0,	'U' },
87 	{ "ignore-all-space",		no_argument,		0,	'w' },
88 	{ "width",			required_argument,	0,	'W' },
89 	{ "exclude",			required_argument,	0,	'x' },
90 	{ "exclude-from",		required_argument,	0,	'X' },
91 	{ "side-by-side",		no_argument,		NULL,	'y' },
92 	{ "ignore-file-name-case",	no_argument,		NULL,	OPT_IGN_FN_CASE },
93 	{ "horizon-lines",		required_argument,	NULL,	OPT_HORIZON_LINES },
94 	{ "no-ignore-file-name-case",	no_argument,		NULL,	OPT_NO_IGN_FN_CASE },
95 	{ "normal",			no_argument,		NULL,	OPT_NORMAL },
96 	{ "strip-trailing-cr",		no_argument,		NULL,	OPT_STRIPCR },
97 	{ "tabsize",			required_argument,	NULL,	OPT_TSIZE },
98 	{ "changed-group-format",	required_argument,	NULL,	OPT_CHANGED_GROUP_FORMAT},
99 	{ "suppress-common-lines",	no_argument,		NULL,	OPT_SUPPRESS_COMMON },
100 	{ NULL,				0,			0,	'\0'}
101 };
102 
103 void usage(void) __dead2;
104 void conflicting_format(void) __dead2;
105 void push_excludes(char *);
106 void push_ignore_pats(char *);
107 void read_excludes_file(char *file);
108 void set_argstr(char **, char **);
109 
110 int
111 main(int argc, char **argv)
112 {
113 	const char *errstr = NULL;
114 	char *ep, **oargv;
115 	long  l;
116 	int   ch, dflags, lastch, gotstdin, prevoptind, newarg;
117 
118 	oargv = argv;
119 	gotstdin = 0;
120 	dflags = 0;
121 	lastch = '\0';
122 	prevoptind = 1;
123 	newarg = 1;
124 	diff_context = 3;
125 	diff_format = D_UNSET;
126 #define	FORMAT_MISMATCHED(type)	\
127 	(diff_format != D_UNSET && diff_format != (type))
128 	while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) {
129 		switch (ch) {
130 		case '0': case '1': case '2': case '3': case '4':
131 		case '5': case '6': case '7': case '8': case '9':
132 			if (newarg)
133 				usage();	/* disallow -[0-9]+ */
134 			else if (lastch == 'c' || lastch == 'u')
135 				diff_context = 0;
136 			else if (!isdigit(lastch) || diff_context > INT_MAX / 10)
137 				usage();
138 			diff_context = (diff_context * 10) + (ch - '0');
139 			break;
140 		case 'a':
141 			dflags |= D_FORCEASCII;
142 			break;
143 		case 'b':
144 			dflags |= D_FOLDBLANKS;
145 			break;
146 		case 'C':
147 		case 'c':
148 			if (FORMAT_MISMATCHED(D_CONTEXT))
149 				conflicting_format();
150 			cflag = 1;
151 			diff_format = D_CONTEXT;
152 			if (optarg != NULL) {
153 				l = strtol(optarg, &ep, 10);
154 				if (*ep != '\0' || l < 0 || l >= INT_MAX)
155 					usage();
156 				diff_context = (int)l;
157 			}
158 			break;
159 		case 'd':
160 			dflags |= D_MINIMAL;
161 			break;
162 		case 'D':
163 			if (FORMAT_MISMATCHED(D_IFDEF))
164 				conflicting_format();
165 			diff_format = D_IFDEF;
166 			ifdefname = optarg;
167 			break;
168 		case 'e':
169 			if (FORMAT_MISMATCHED(D_EDIT))
170 				conflicting_format();
171 			diff_format = D_EDIT;
172 			break;
173 		case 'f':
174 			if (FORMAT_MISMATCHED(D_REVERSE))
175 				conflicting_format();
176 			diff_format = D_REVERSE;
177 			break;
178 		case 'H':
179 			/* ignore but needed for compatibility with GNU diff */
180 			break;
181 		case 'h':
182 			/* silently ignore for backwards compatibility */
183 			break;
184 		case 'B':
185 			dflags |= D_SKIPBLANKLINES;
186 			break;
187 		case 'I':
188 			push_ignore_pats(optarg);
189 			break;
190 		case 'i':
191 			dflags |= D_IGNORECASE;
192 			break;
193 		case 'L':
194 			if (label[0] == NULL)
195 				label[0] = optarg;
196 			else if (label[1] == NULL)
197 				label[1] = optarg;
198 			else
199 				usage();
200 			break;
201 		case 'l':
202 			lflag = 1;
203 			break;
204 		case 'N':
205 			Nflag = 1;
206 			break;
207 		case 'n':
208 			if (FORMAT_MISMATCHED(D_NREVERSE))
209 				conflicting_format();
210 			diff_format = D_NREVERSE;
211 			break;
212 		case 'p':
213 			/*
214 			 * If it's not unset and it's not set to context or
215 			 * unified, we'll error out here as a conflicting
216 			 * format.  If it's unset, we'll go ahead and set it to
217 			 * context.
218 			 */
219 			if (FORMAT_MISMATCHED(D_CONTEXT) &&
220 			    FORMAT_MISMATCHED(D_UNIFIED))
221 				conflicting_format();
222 			if (diff_format == D_UNSET)
223 				diff_format = D_CONTEXT;
224 			dflags |= D_PROTOTYPE;
225 			break;
226 		case 'P':
227 			Pflag = 1;
228 			break;
229 		case 'r':
230 			rflag = 1;
231 			break;
232 		case 'q':
233 			if (FORMAT_MISMATCHED(D_BRIEF))
234 				conflicting_format();
235 			diff_format = D_BRIEF;
236 			break;
237 		case 'S':
238 			start = optarg;
239 			break;
240 		case 's':
241 			sflag = 1;
242 			break;
243 		case 'T':
244 			Tflag = 1;
245 			break;
246 		case 't':
247 			dflags |= D_EXPANDTABS;
248 			break;
249 		case 'U':
250 		case 'u':
251 			if (FORMAT_MISMATCHED(D_UNIFIED))
252 				conflicting_format();
253 			diff_format = D_UNIFIED;
254 			if (optarg != NULL) {
255 				l = strtol(optarg, &ep, 10);
256 				if (*ep != '\0' || l < 0 || l >= INT_MAX)
257 					usage();
258 				diff_context = (int)l;
259 			}
260 			break;
261 		case 'w':
262 			dflags |= D_IGNOREBLANKS;
263 			break;
264 		case 'W':
265 			Wflag = 1;
266 			width = (int) strtonum(optarg, 1, INT_MAX, &errstr);
267 			if (errstr) {
268 				warnx("Invalid argument for width");
269 				usage();
270 			}
271 			break;
272 		case 'X':
273 			read_excludes_file(optarg);
274 			break;
275 		case 'x':
276 			push_excludes(optarg);
277 			break;
278 		case 'y':
279 			if (FORMAT_MISMATCHED(D_SIDEBYSIDE))
280 				conflicting_format();
281 			diff_format = D_SIDEBYSIDE;
282 			break;
283 		case OPT_CHANGED_GROUP_FORMAT:
284 			if (FORMAT_MISMATCHED(D_GFORMAT))
285 				conflicting_format();
286 			diff_format = D_GFORMAT;
287 			group_format = optarg;
288 			break;
289 		case OPT_HORIZON_LINES:
290 			break; /* XXX TODO for compatibility with GNU diff3 */
291 		case OPT_IGN_FN_CASE:
292 			ignore_file_case = 1;
293 			break;
294 		case OPT_NO_IGN_FN_CASE:
295 			ignore_file_case = 0;
296 			break;
297 		case OPT_NORMAL:
298 			if (FORMAT_MISMATCHED(D_NORMAL))
299 				conflicting_format();
300 			diff_format = D_NORMAL;
301 			break;
302 		case OPT_TSIZE:
303 			tabsize = (int) strtonum(optarg, 1, INT_MAX, &errstr);
304 			if (errstr) {
305 				warnx("Invalid argument for tabsize");
306 				usage();
307 			}
308 			break;
309 		case OPT_STRIPCR:
310 			dflags |= D_STRIPCR;
311 			break;
312 		case OPT_SUPPRESS_COMMON:
313 			suppress_common = 1;
314 			break;
315 		default:
316 			usage();
317 			break;
318 		}
319 		lastch = ch;
320 		newarg = optind != prevoptind;
321 		prevoptind = optind;
322 	}
323 	if (diff_format == D_UNSET)
324 		diff_format = D_NORMAL;
325 	argc -= optind;
326 	argv += optind;
327 
328 #ifdef __OpenBSD__
329 	if (pledge("stdio rpath tmppath", NULL) == -1)
330 		err(2, "pledge");
331 #endif
332 
333 	/*
334 	 * Do sanity checks, fill in stb1 and stb2 and call the appropriate
335 	 * driver routine.  Both drivers use the contents of stb1 and stb2.
336 	 */
337 	if (argc != 2)
338 		usage();
339 	if (ignore_pats != NULL) {
340 		char buf[BUFSIZ];
341 		int error;
342 
343 		if ((error = regcomp(&ignore_re, ignore_pats,
344 				     REG_NEWLINE | REG_EXTENDED)) != 0) {
345 			regerror(error, &ignore_re, buf, sizeof(buf));
346 			if (*ignore_pats != '\0')
347 				errx(2, "%s: %s", ignore_pats, buf);
348 			else
349 				errx(2, "%s", buf);
350 		}
351 	}
352 	if (strcmp(argv[0], "-") == 0) {
353 		fstat(STDIN_FILENO, &stb1);
354 		gotstdin = 1;
355 	} else if (stat(argv[0], &stb1) != 0) {
356 		if (!Nflag || errno != ENOENT)
357 			err(2, "%s", argv[0]);
358 		dflags |= D_EMPTY1;
359 		memset(&stb1, 0, sizeof(struct stat));
360 	}
361 
362 	if (strcmp(argv[1], "-") == 0) {
363 		fstat(STDIN_FILENO, &stb2);
364 		gotstdin = 1;
365 	} else if (stat(argv[1], &stb2) != 0) {
366 		if (!Nflag || errno != ENOENT)
367 			err(2, "%s", argv[1]);
368 		dflags |= D_EMPTY2;
369 		memset(&stb2, 0, sizeof(stb2));
370 		stb2.st_mode = stb1.st_mode;
371 	}
372 
373 	if (dflags & D_EMPTY1 && dflags & D_EMPTY2){
374 		warn("%s", argv[0]);
375 		warn("%s", argv[1]);
376 		exit(2);
377 	}
378 
379 	if (stb1.st_mode == 0)
380 		stb1.st_mode = stb2.st_mode;
381 
382 	if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
383 		errx(2, "can't compare - to a directory");
384 	set_argstr(oargv, argv);
385 	if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
386 		if (diff_format == D_IFDEF)
387 			errx(2, "-D option not supported with directories");
388 		diffdir(argv[0], argv[1], dflags);
389 	} else {
390 		if (S_ISDIR(stb1.st_mode)) {
391 			argv[0] = splice(argv[0], argv[1]);
392 			if (stat(argv[0], &stb1) == -1)
393 				err(2, "%s", argv[0]);
394 		}
395 		if (S_ISDIR(stb2.st_mode)) {
396 			argv[1] = splice(argv[1], argv[0]);
397 			if (stat(argv[1], &stb2) == -1)
398 				err(2, "%s", argv[1]);
399 		}
400 		print_status(diffreg(argv[0], argv[1], dflags, 1), argv[0],
401 		    argv[1], "");
402 	}
403 	exit(status);
404 }
405 
406 void
407 set_argstr(char **av, char **ave)
408 {
409 	size_t argsize;
410 	char **ap;
411 
412 	argsize = 4 + *ave - *av + 1;
413 	diffargs = xmalloc(argsize);
414 	strlcpy(diffargs, "diff", argsize);
415 	for (ap = av + 1; ap < ave; ap++) {
416 		if (strcmp(*ap, "--") != 0) {
417 			strlcat(diffargs, " ", argsize);
418 			strlcat(diffargs, *ap, argsize);
419 		}
420 	}
421 }
422 
423 /*
424  * Read in an excludes file and push each line.
425  */
426 void
427 read_excludes_file(char *file)
428 {
429 	FILE *fp;
430 	char *buf, *pattern;
431 	size_t len;
432 
433 	if (strcmp(file, "-") == 0)
434 		fp = stdin;
435 	else if ((fp = fopen(file, "r")) == NULL)
436 		err(2, "%s", file);
437 	while ((buf = fgetln(fp, &len)) != NULL) {
438 		if (buf[len - 1] == '\n')
439 			len--;
440 		if ((pattern = strndup(buf, len)) == NULL)
441 			err(2, "xstrndup");
442 		push_excludes(pattern);
443 	}
444 	if (strcmp(file, "-") != 0)
445 		fclose(fp);
446 }
447 
448 /*
449  * Push a pattern onto the excludes list.
450  */
451 void
452 push_excludes(char *pattern)
453 {
454 	struct excludes *entry;
455 
456 	entry = xmalloc(sizeof(*entry));
457 	entry->pattern = pattern;
458 	entry->next = excludes_list;
459 	excludes_list = entry;
460 }
461 
462 void
463 push_ignore_pats(char *pattern)
464 {
465 	size_t len;
466 
467 	if (ignore_pats == NULL)
468 		ignore_pats = xstrdup(pattern);
469 	else {
470 		/* old + "|" + new + NUL */
471 		len = strlen(ignore_pats) + strlen(pattern) + 2;
472 		ignore_pats = xreallocarray(ignore_pats, 1, len);
473 		strlcat(ignore_pats, "|", len);
474 		strlcat(ignore_pats, pattern, len);
475 	}
476 }
477 
478 void
479 print_only(const char *path, size_t dirlen, const char *entry)
480 {
481 	if (dirlen > 1)
482 		dirlen--;
483 	printf("Only in %.*s: %s\n", (int)dirlen, path, entry);
484 }
485 
486 void
487 print_status(int val, char *path1, char *path2, const char *entry)
488 {
489 	if (label[0] != NULL) path1 = label[0];
490 	if (label[1] != NULL) path2 = label[1];
491 
492 	switch (val) {
493 	case D_BINARY:
494 		printf("Binary files %s%s and %s%s differ\n",
495 		    path1, entry, path2, entry);
496 		break;
497 	case D_DIFFER:
498 		if (diff_format == D_BRIEF)
499 			printf("Files %s%s and %s%s differ\n",
500 			    path1, entry, path2, entry);
501 		break;
502 	case D_SAME:
503 		if (sflag)
504 			printf("Files %s%s and %s%s are identical\n",
505 			    path1, entry, path2, entry);
506 		break;
507 	case D_MISMATCH1:
508 		printf("File %s%s is a directory while file %s%s is a regular file\n",
509 		    path1, entry, path2, entry);
510 		break;
511 	case D_MISMATCH2:
512 		printf("File %s%s is a regular file while file %s%s is a directory\n",
513 		    path1, entry, path2, entry);
514 		break;
515 	case D_SKIPPED1:
516 		printf("File %s%s is not a regular file or directory and was skipped\n",
517 		    path1, entry);
518 		break;
519 	case D_SKIPPED2:
520 		printf("File %s%s is not a regular file or directory and was skipped\n",
521 		    path2, entry);
522 		break;
523 	}
524 }
525 
526 void
527 usage(void)
528 {
529 	(void)fprintf(stderr,
530 	    "usage: diff [-aBbdilpTtw] [-c | -e | -f | -n | -q | -u] [--ignore-case]\n"
531 	    "            [--no-ignore-case] [--normal] [--strip-trailing-cr] [--tabsize]\n"
532 	    "            [-I pattern] [-L label] file1 file2\n"
533 	    "       diff [-aBbdilpTtw] [-I pattern] [-L label] [--ignore-case]\n"
534 	    "            [--no-ignore-case] [--normal] [--strip-trailing-cr] [--tabsize]\n"
535 	    "            -C number file1 file2\n"
536 	    "       diff [-aBbdiltw] [-I pattern] [--ignore-case] [--no-ignore-case]\n"
537 	    "            [--normal] [--strip-trailing-cr] [--tabsize] -D string file1 file2\n"
538 	    "       diff [-aBbdilpTtw] [-I pattern] [-L label] [--ignore-case]\n"
539 	    "            [--no-ignore-case] [--normal] [--tabsize] [--strip-trailing-cr]\n"
540 	    "            -U number file1 file2\n"
541 	    "       diff [-aBbdilNPprsTtw] [-c | -e | -f | -n | -q | -u] [--ignore-case]\n"
542 	    "            [--no-ignore-case] [--normal] [--tabsize] [-I pattern] [-L label]\n"
543 	    "            [-S name] [-X file] [-x pattern] dir1 dir2\n"
544 	    "       diff [-aBbditwW] [--expand-tabs] [--ignore-all-blanks]\n"
545             "            [--ignore-blank-lines] [--ignore-case] [--minimal]\n"
546             "            [--no-ignore-file-name-case] [--strip-trailing-cr]\n"
547             "            [--suppress-common-lines] [--tabsize] [--text] [--width]\n"
548             "            -y | --side-by-side file1 file2\n");
549 
550 	exit(2);
551 }
552 
553 void
554 conflicting_format(void)
555 {
556 
557 	fprintf(stderr, "error: conflicting output format options.\n");
558 	usage();
559 }
560