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