xref: /freebsd/usr.bin/diff/diff.c (revision 869cc06480b75b4caea0d049e0cf7f82bb5aeed1)
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  			dflags |= D_PROTOTYPE;
214  			break;
215  		case 'P':
216  			Pflag = 1;
217  			break;
218  		case 'r':
219  			rflag = 1;
220  			break;
221  		case 'q':
222  			if (FORMAT_MISMATCHED(D_BRIEF))
223  				conflicting_format();
224  			diff_format = D_BRIEF;
225  			break;
226  		case 'S':
227  			start = optarg;
228  			break;
229  		case 's':
230  			sflag = 1;
231  			break;
232  		case 'T':
233  			Tflag = 1;
234  			break;
235  		case 't':
236  			dflags |= D_EXPANDTABS;
237  			break;
238  		case 'U':
239  		case 'u':
240  			if (FORMAT_MISMATCHED(D_UNIFIED))
241  				conflicting_format();
242  			diff_format = D_UNIFIED;
243  			if (optarg != NULL) {
244  				l = strtol(optarg, &ep, 10);
245  				if (*ep != '\0' || l < 0 || l >= INT_MAX)
246  					usage();
247  				diff_context = (int)l;
248  			}
249  			break;
250  		case 'w':
251  			dflags |= D_IGNOREBLANKS;
252  			break;
253  		case 'W':
254  			Wflag = 1;
255  			width = (int) strtonum(optarg, 1, INT_MAX, &errstr);
256  			if (errstr) {
257  				warnx("Invalid argument for width");
258  				usage();
259  			}
260  			break;
261  		case 'X':
262  			read_excludes_file(optarg);
263  			break;
264  		case 'x':
265  			push_excludes(optarg);
266  			break;
267  		case 'y':
268  			if (FORMAT_MISMATCHED(D_SIDEBYSIDE))
269  				conflicting_format();
270  			diff_format = D_SIDEBYSIDE;
271  			break;
272  		case OPT_CHANGED_GROUP_FORMAT:
273  			if (FORMAT_MISMATCHED(D_GFORMAT))
274  				conflicting_format();
275  			diff_format = D_GFORMAT;
276  			group_format = optarg;
277  			break;
278  		case OPT_HORIZON_LINES:
279  			break; /* XXX TODO for compatibility with GNU diff3 */
280  		case OPT_IGN_FN_CASE:
281  			ignore_file_case = 1;
282  			break;
283  		case OPT_NO_IGN_FN_CASE:
284  			ignore_file_case = 0;
285  			break;
286  		case OPT_NORMAL:
287  			if (FORMAT_MISMATCHED(D_NORMAL))
288  				conflicting_format();
289  			diff_format = D_NORMAL;
290  			break;
291  		case OPT_TSIZE:
292  			tabsize = (int) strtonum(optarg, 1, INT_MAX, &errstr);
293  			if (errstr) {
294  				warnx("Invalid argument for tabsize");
295  				usage();
296  			}
297  			break;
298  		case OPT_STRIPCR:
299  			dflags |= D_STRIPCR;
300  			break;
301  		case OPT_SUPPRESS_COMMON:
302  			suppress_common = 1;
303  			break;
304  		default:
305  			usage();
306  			break;
307  		}
308  		lastch = ch;
309  		newarg = optind != prevoptind;
310  		prevoptind = optind;
311  	}
312  	if (diff_format == D_UNSET && (dflags & D_PROTOTYPE) != 0)
313  		diff_format = D_CONTEXT;
314  	if (diff_format == D_UNSET)
315  		diff_format = D_NORMAL;
316  	argc -= optind;
317  	argv += optind;
318  
319  #ifdef __OpenBSD__
320  	if (pledge("stdio rpath tmppath", NULL) == -1)
321  		err(2, "pledge");
322  #endif
323  
324  	/*
325  	 * Do sanity checks, fill in stb1 and stb2 and call the appropriate
326  	 * driver routine.  Both drivers use the contents of stb1 and stb2.
327  	 */
328  	if (argc != 2)
329  		usage();
330  	if (ignore_pats != NULL) {
331  		char buf[BUFSIZ];
332  		int error;
333  
334  		if ((error = regcomp(&ignore_re, ignore_pats,
335  				     REG_NEWLINE | REG_EXTENDED)) != 0) {
336  			regerror(error, &ignore_re, buf, sizeof(buf));
337  			if (*ignore_pats != '\0')
338  				errx(2, "%s: %s", ignore_pats, buf);
339  			else
340  				errx(2, "%s", buf);
341  		}
342  	}
343  	if (strcmp(argv[0], "-") == 0) {
344  		fstat(STDIN_FILENO, &stb1);
345  		gotstdin = 1;
346  	} else if (stat(argv[0], &stb1) != 0) {
347  		if (!Nflag || errno != ENOENT)
348  			err(2, "%s", argv[0]);
349  		dflags |= D_EMPTY1;
350  		memset(&stb1, 0, sizeof(struct stat));
351  	}
352  
353  	if (strcmp(argv[1], "-") == 0) {
354  		fstat(STDIN_FILENO, &stb2);
355  		gotstdin = 1;
356  	} else if (stat(argv[1], &stb2) != 0) {
357  		if (!Nflag || errno != ENOENT)
358  			err(2, "%s", argv[1]);
359  		dflags |= D_EMPTY2;
360  		memset(&stb2, 0, sizeof(stb2));
361  		stb2.st_mode = stb1.st_mode;
362  	}
363  
364  	if (dflags & D_EMPTY1 && dflags & D_EMPTY2){
365  		warn("%s", argv[0]);
366  		warn("%s", argv[1]);
367  		exit(2);
368  	}
369  
370  	if (stb1.st_mode == 0)
371  		stb1.st_mode = stb2.st_mode;
372  
373  	if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
374  		errx(2, "can't compare - to a directory");
375  	set_argstr(oargv, argv);
376  	if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
377  		if (diff_format == D_IFDEF)
378  			errx(2, "-D option not supported with directories");
379  		diffdir(argv[0], argv[1], dflags);
380  	} else {
381  		if (S_ISDIR(stb1.st_mode)) {
382  			argv[0] = splice(argv[0], argv[1]);
383  			if (stat(argv[0], &stb1) == -1)
384  				err(2, "%s", argv[0]);
385  		}
386  		if (S_ISDIR(stb2.st_mode)) {
387  			argv[1] = splice(argv[1], argv[0]);
388  			if (stat(argv[1], &stb2) == -1)
389  				err(2, "%s", argv[1]);
390  		}
391  		print_status(diffreg(argv[0], argv[1], dflags, 1), argv[0],
392  		    argv[1], "");
393  	}
394  	exit(status);
395  }
396  
397  void
398  set_argstr(char **av, char **ave)
399  {
400  	size_t argsize;
401  	char **ap;
402  
403  	argsize = 4 + *ave - *av + 1;
404  	diffargs = xmalloc(argsize);
405  	strlcpy(diffargs, "diff", argsize);
406  	for (ap = av + 1; ap < ave; ap++) {
407  		if (strcmp(*ap, "--") != 0) {
408  			strlcat(diffargs, " ", argsize);
409  			strlcat(diffargs, *ap, argsize);
410  		}
411  	}
412  }
413  
414  /*
415   * Read in an excludes file and push each line.
416   */
417  void
418  read_excludes_file(char *file)
419  {
420  	FILE *fp;
421  	char *buf, *pattern;
422  	size_t len;
423  
424  	if (strcmp(file, "-") == 0)
425  		fp = stdin;
426  	else if ((fp = fopen(file, "r")) == NULL)
427  		err(2, "%s", file);
428  	while ((buf = fgetln(fp, &len)) != NULL) {
429  		if (buf[len - 1] == '\n')
430  			len--;
431  		if ((pattern = strndup(buf, len)) == NULL)
432  			err(2, "xstrndup");
433  		push_excludes(pattern);
434  	}
435  	if (strcmp(file, "-") != 0)
436  		fclose(fp);
437  }
438  
439  /*
440   * Push a pattern onto the excludes list.
441   */
442  void
443  push_excludes(char *pattern)
444  {
445  	struct excludes *entry;
446  
447  	entry = xmalloc(sizeof(*entry));
448  	entry->pattern = pattern;
449  	entry->next = excludes_list;
450  	excludes_list = entry;
451  }
452  
453  void
454  push_ignore_pats(char *pattern)
455  {
456  	size_t len;
457  
458  	if (ignore_pats == NULL)
459  		ignore_pats = xstrdup(pattern);
460  	else {
461  		/* old + "|" + new + NUL */
462  		len = strlen(ignore_pats) + strlen(pattern) + 2;
463  		ignore_pats = xreallocarray(ignore_pats, 1, len);
464  		strlcat(ignore_pats, "|", len);
465  		strlcat(ignore_pats, pattern, len);
466  	}
467  }
468  
469  void
470  print_only(const char *path, size_t dirlen, const char *entry)
471  {
472  	if (dirlen > 1)
473  		dirlen--;
474  	printf("Only in %.*s: %s\n", (int)dirlen, path, entry);
475  }
476  
477  void
478  print_status(int val, char *path1, char *path2, const char *entry)
479  {
480  	if (label[0] != NULL) path1 = label[0];
481  	if (label[1] != NULL) path2 = label[1];
482  
483  	switch (val) {
484  	case D_BINARY:
485  		printf("Binary files %s%s and %s%s differ\n",
486  		    path1, entry, path2, entry);
487  		break;
488  	case D_DIFFER:
489  		if (diff_format == D_BRIEF)
490  			printf("Files %s%s and %s%s differ\n",
491  			    path1, entry, path2, entry);
492  		break;
493  	case D_SAME:
494  		if (sflag)
495  			printf("Files %s%s and %s%s are identical\n",
496  			    path1, entry, path2, entry);
497  		break;
498  	case D_MISMATCH1:
499  		printf("File %s%s is a directory while file %s%s is a regular file\n",
500  		    path1, entry, path2, entry);
501  		break;
502  	case D_MISMATCH2:
503  		printf("File %s%s is a regular file while file %s%s is a directory\n",
504  		    path1, entry, path2, entry);
505  		break;
506  	case D_SKIPPED1:
507  		printf("File %s%s is not a regular file or directory and was skipped\n",
508  		    path1, entry);
509  		break;
510  	case D_SKIPPED2:
511  		printf("File %s%s is not a regular file or directory and was skipped\n",
512  		    path2, entry);
513  		break;
514  	case D_ERROR:
515  		break;
516  	}
517  }
518  
519  void
520  usage(void)
521  {
522  	(void)fprintf(stderr,
523  	    "usage: diff [-aBbdilpTtw] [-c | -e | -f | -n | -q | -u] [--ignore-case]\n"
524  	    "            [--no-ignore-case] [--normal] [--strip-trailing-cr] [--tabsize]\n"
525  	    "            [-I pattern] [-L label] file1 file2\n"
526  	    "       diff [-aBbdilpTtw] [-I pattern] [-L label] [--ignore-case]\n"
527  	    "            [--no-ignore-case] [--normal] [--strip-trailing-cr] [--tabsize]\n"
528  	    "            -C number file1 file2\n"
529  	    "       diff [-aBbdiltw] [-I pattern] [--ignore-case] [--no-ignore-case]\n"
530  	    "            [--normal] [--strip-trailing-cr] [--tabsize] -D string file1 file2\n"
531  	    "       diff [-aBbdilpTtw] [-I pattern] [-L label] [--ignore-case]\n"
532  	    "            [--no-ignore-case] [--normal] [--tabsize] [--strip-trailing-cr]\n"
533  	    "            -U number file1 file2\n"
534  	    "       diff [-aBbdilNPprsTtw] [-c | -e | -f | -n | -q | -u] [--ignore-case]\n"
535  	    "            [--no-ignore-case] [--normal] [--tabsize] [-I pattern] [-L label]\n"
536  	    "            [-S name] [-X file] [-x pattern] dir1 dir2\n"
537  	    "       diff [-aBbditwW] [--expand-tabs] [--ignore-all-blanks]\n"
538              "            [--ignore-blank-lines] [--ignore-case] [--minimal]\n"
539              "            [--no-ignore-file-name-case] [--strip-trailing-cr]\n"
540              "            [--suppress-common-lines] [--tabsize] [--text] [--width]\n"
541              "            -y | --side-by-side file1 file2\n");
542  
543  	exit(2);
544  }
545  
546  void
547  conflicting_format(void)
548  {
549  
550  	fprintf(stderr, "error: conflicting output format options.\n");
551  	usage();
552  }
553