xref: /openbsd-src/usr.bin/diff/diff.c (revision 6c036d4aa576416de7808e27a519c1c28aabb984)
1 /*	$OpenBSD: diff.c,v 1.60 2015/10/05 15:16:23 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/stat.h>
24 
25 #include <ctype.h>
26 #include <err.h>
27 #include <errno.h>
28 #include <getopt.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <stdarg.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;
41 int	 diff_format, diff_context, status;
42 char	*start, *ifdefname, *diffargs, *label[2], *ignore_pats;
43 struct stat stb1, stb2;
44 struct excludes *excludes_list;
45 regex_t	 ignore_re;
46 
47 #define	OPTIONS	"0123456789abC:cdD:efhI:iL:lnNPpqrS:sTtU:uwX:x:"
48 static struct option longopts[] = {
49 	{ "text",			no_argument,		0,	'a' },
50 	{ "ignore-space-change",	no_argument,		0,	'b' },
51 	{ "context",			optional_argument,	0,	'C' },
52 	{ "ifdef",			required_argument,	0,	'D' },
53 	{ "minimal",			no_argument,		0,	'd' },
54 	{ "ed",				no_argument,		0,	'e' },
55 	{ "forward-ed",			no_argument,		0,	'f' },
56 	{ "ignore-matching-lines",	required_argument,	0,	'I' },
57 	{ "ignore-case",		no_argument,		0,	'i' },
58 	{ "paginate",			no_argument,		0,	'l' },
59 	{ "label",			required_argument,	0,	'L' },
60 	{ "new-file",			no_argument,		0,	'N' },
61 	{ "rcs",			no_argument,		0,	'n' },
62 	{ "unidirectional-new-file",	no_argument,		0,	'P' },
63 	{ "show-c-function",		no_argument,		0,	'p' },
64 	{ "brief",			no_argument,		0,	'q' },
65 	{ "recursive",			no_argument,		0,	'r' },
66 	{ "report-identical-files",	no_argument,		0,	's' },
67 	{ "starting-file",		required_argument,	0,	'S' },
68 	{ "expand-tabs",		no_argument,		0,	't' },
69 	{ "initial-tab",		no_argument,		0,	'T' },
70 	{ "unified",			optional_argument,	0,	'U' },
71 	{ "ignore-all-space",		no_argument,		0,	'w' },
72 	{ "exclude",			required_argument,	0,	'x' },
73 	{ "exclude-from",		required_argument,	0,	'X' },
74 	{ NULL,				0,			0,	'\0'}
75 };
76 
77 __dead void usage(void);
78 void push_excludes(char *);
79 void push_ignore_pats(char *);
80 void read_excludes_file(char *file);
81 void set_argstr(char **, char **);
82 
83 int
84 main(int argc, char **argv)
85 {
86 	char *ep, **oargv;
87 	long  l;
88 	int   ch, dflags, lastch, gotstdin, prevoptind, newarg;
89 
90 	oargv = argv;
91 	gotstdin = 0;
92 	dflags = 0;
93 	lastch = '\0';
94 	prevoptind = 1;
95 	newarg = 1;
96 	while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) {
97 		switch (ch) {
98 		case '0': case '1': case '2': case '3': case '4':
99 		case '5': case '6': case '7': case '8': case '9':
100 			if (newarg)
101 				usage();	/* disallow -[0-9]+ */
102 			else if (lastch == 'c' || lastch == 'u')
103 				diff_context = 0;
104 			else if (!isdigit(lastch) || diff_context > INT_MAX / 10)
105 				usage();
106 			diff_context = (diff_context * 10) + (ch - '0');
107 			break;
108 		case 'a':
109 			dflags |= D_FORCEASCII;
110 			break;
111 		case 'b':
112 			dflags |= D_FOLDBLANKS;
113 			break;
114 		case 'C':
115 		case 'c':
116 			diff_format = D_CONTEXT;
117 			if (optarg != NULL) {
118 				l = strtol(optarg, &ep, 10);
119 				if (*ep != '\0' || l < 0 || l >= INT_MAX)
120 					usage();
121 				diff_context = (int)l;
122 			} else
123 				diff_context = 3;
124 			break;
125 		case 'd':
126 			dflags |= D_MINIMAL;
127 			break;
128 		case 'D':
129 			diff_format = D_IFDEF;
130 			ifdefname = optarg;
131 			break;
132 		case 'e':
133 			diff_format = D_EDIT;
134 			break;
135 		case 'f':
136 			diff_format = D_REVERSE;
137 			break;
138 		case 'h':
139 			/* silently ignore for backwards compatibility */
140 			break;
141 		case 'I':
142 			push_ignore_pats(optarg);
143 			break;
144 		case 'i':
145 			dflags |= D_IGNORECASE;
146 			break;
147 		case 'L':
148 			if (label[0] == NULL)
149 				label[0] = optarg;
150 			else if (label[1] == NULL)
151 				label[1] = optarg;
152 			else
153 				usage();
154 			break;
155 		case 'l':
156 			lflag = 1;
157 			signal(SIGPIPE, SIG_IGN);
158 			break;
159 		case 'N':
160 			Nflag = 1;
161 			break;
162 		case 'n':
163 			diff_format = D_NREVERSE;
164 			break;
165 		case 'p':
166 			dflags |= D_PROTOTYPE;
167 			break;
168 		case 'P':
169 			Pflag = 1;
170 			break;
171 		case 'r':
172 			rflag = 1;
173 			break;
174 		case 'q':
175 			diff_format = D_BRIEF;
176 			break;
177 		case 'S':
178 			start = optarg;
179 			break;
180 		case 's':
181 			sflag = 1;
182 			break;
183 		case 'T':
184 			Tflag = 1;
185 			break;
186 		case 't':
187 			dflags |= D_EXPANDTABS;
188 			break;
189 		case 'U':
190 		case 'u':
191 			diff_format = D_UNIFIED;
192 			if (optarg != NULL) {
193 				l = strtol(optarg, &ep, 10);
194 				if (*ep != '\0' || l < 0 || l >= INT_MAX)
195 					usage();
196 				diff_context = (int)l;
197 			} else
198 				diff_context = 3;
199 			break;
200 		case 'w':
201 			dflags |= D_IGNOREBLANKS;
202 			break;
203 		case 'X':
204 			read_excludes_file(optarg);
205 			break;
206 		case 'x':
207 			push_excludes(optarg);
208 			break;
209 		default:
210 			usage();
211 			break;
212 		}
213 		lastch = ch;
214 		newarg = optind != prevoptind;
215 		prevoptind = optind;
216 	}
217 	argc -= optind;
218 	argv += optind;
219 
220 	if (lflag == 0) {
221 		if (tame("stdio wpath rpath cpath tmppath", NULL) == -1)
222 			err(1, "tame");
223 	}
224 	/*
225 	 * Do sanity checks, fill in stb1 and stb2 and call the appropriate
226 	 * driver routine.  Both drivers use the contents of stb1 and stb2.
227 	 */
228 	if (argc != 2)
229 		usage();
230 	if (ignore_pats != NULL) {
231 		char buf[BUFSIZ];
232 		int error;
233 
234 		if ((error = regcomp(&ignore_re, ignore_pats,
235 				     REG_NEWLINE | REG_EXTENDED)) != 0) {
236 			regerror(error, &ignore_re, buf, sizeof(buf));
237 			if (*ignore_pats != '\0')
238 				errx(2, "%s: %s", ignore_pats, buf);
239 			else
240 				errx(2, "%s", buf);
241 		}
242 	}
243 	if (strcmp(argv[0], "-") == 0) {
244 		fstat(STDIN_FILENO, &stb1);
245 		gotstdin = 1;
246 	} else if (stat(argv[0], &stb1) != 0)
247 		err(2, "%s", argv[0]);
248 	if (strcmp(argv[1], "-") == 0) {
249 		fstat(STDIN_FILENO, &stb2);
250 		gotstdin = 1;
251 	} else if (stat(argv[1], &stb2) != 0)
252 		err(2, "%s", argv[1]);
253 	if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
254 		errx(2, "can't compare - to a directory");
255 	set_argstr(oargv, argv);
256 	if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
257 		if (diff_format == D_IFDEF)
258 			errx(2, "-D option not supported with directories");
259 		diffdir(argv[0], argv[1], dflags);
260 	} else {
261 		if (S_ISDIR(stb1.st_mode)) {
262 			argv[0] = splice(argv[0], argv[1]);
263 			if (stat(argv[0], &stb1) < 0)
264 				err(2, "%s", argv[0]);
265 		}
266 		if (S_ISDIR(stb2.st_mode)) {
267 			argv[1] = splice(argv[1], argv[0]);
268 			if (stat(argv[1], &stb2) < 0)
269 				err(2, "%s", argv[1]);
270 		}
271 		print_status(diffreg(argv[0], argv[1], dflags), argv[0], argv[1],
272 		    "");
273 	}
274 	exit(status);
275 }
276 
277 void
278 set_argstr(char **av, char **ave)
279 {
280 	size_t argsize;
281 	char **ap;
282 
283 	argsize = 4 + *ave - *av + 1;
284 	diffargs = xmalloc(argsize);
285 	strlcpy(diffargs, "diff", argsize);
286 	for (ap = av + 1; ap < ave; ap++) {
287 		if (strcmp(*ap, "--") != 0) {
288 			strlcat(diffargs, " ", argsize);
289 			strlcat(diffargs, *ap, argsize);
290 		}
291 	}
292 }
293 
294 /*
295  * Read in an excludes file and push each line.
296  */
297 void
298 read_excludes_file(char *file)
299 {
300 	FILE *fp;
301 	char *buf, *pattern;
302 	size_t len;
303 
304 	if (strcmp(file, "-") == 0)
305 		fp = stdin;
306 	else if ((fp = fopen(file, "r")) == NULL)
307 		err(2, "%s", file);
308 	while ((buf = fgetln(fp, &len)) != NULL) {
309 		if (buf[len - 1] == '\n')
310 			len--;
311 		pattern = xmalloc(len + 1);
312 		memcpy(pattern, buf, len);
313 		pattern[len] = '\0';
314 		push_excludes(pattern);
315 	}
316 	if (strcmp(file, "-") != 0)
317 		fclose(fp);
318 }
319 
320 /*
321  * Push a pattern onto the excludes list.
322  */
323 void
324 push_excludes(char *pattern)
325 {
326 	struct excludes *entry;
327 
328 	entry = xmalloc(sizeof(*entry));
329 	entry->pattern = pattern;
330 	entry->next = excludes_list;
331 	excludes_list = entry;
332 }
333 
334 void
335 push_ignore_pats(char *pattern)
336 {
337 	size_t len;
338 
339 	if (ignore_pats == NULL)
340 		ignore_pats = xstrdup(pattern);
341 	else {
342 		/* old + "|" + new + NUL */
343 		len = strlen(ignore_pats) + strlen(pattern) + 2;
344 		ignore_pats = xreallocarray(ignore_pats, 1, len);
345 		strlcat(ignore_pats, "|", len);
346 		strlcat(ignore_pats, pattern, len);
347 	}
348 }
349 
350 void
351 print_only(const char *path, size_t dirlen, const char *entry)
352 {
353 	if (dirlen > 1)
354 		dirlen--;
355 	printf("Only in %.*s: %s\n", (int)dirlen, path, entry);
356 }
357 
358 void
359 print_status(int val, char *path1, char *path2, char *entry)
360 {
361 	switch (val) {
362 	case D_ONLY:
363 		print_only(path1, strlen(path1), entry);
364 		break;
365 	case D_COMMON:
366 		printf("Common subdirectories: %s%s and %s%s\n",
367 		    path1, entry, path2, entry);
368 		break;
369 	case D_BINARY:
370 		printf("Binary files %s%s and %s%s differ\n",
371 		    path1, entry, path2, entry);
372 		break;
373 	case D_DIFFER:
374 		if (diff_format == D_BRIEF)
375 			printf("Files %s%s and %s%s differ\n",
376 			    path1, entry, path2, entry);
377 		break;
378 	case D_SAME:
379 		if (sflag)
380 			printf("Files %s%s and %s%s are identical\n",
381 			    path1, entry, path2, entry);
382 		break;
383 	case D_MISMATCH1:
384 		printf("File %s%s is a directory while file %s%s is a regular file\n",
385 		    path1, entry, path2, entry);
386 		break;
387 	case D_MISMATCH2:
388 		printf("File %s%s is a regular file while file %s%s is a directory\n",
389 		    path1, entry, path2, entry);
390 		break;
391 	case D_SKIPPED1:
392 		printf("File %s%s is not a regular file or directory and was skipped\n",
393 		    path1, entry);
394 		break;
395 	case D_SKIPPED2:
396 		printf("File %s%s is not a regular file or directory and was skipped\n",
397 		    path2, entry);
398 		break;
399 	}
400 }
401 
402 __dead void
403 usage(void)
404 {
405 	(void)fprintf(stderr,
406 	    "usage: diff [-abdilpTtw] [-c | -e | -f | -n | -q | -u] [-I pattern] [-L label]\n"
407 	    "            file1 file2\n"
408 	    "       diff [-abdilpTtw] [-I pattern] [-L label] -C number file1 file2\n"
409 	    "       diff [-abdiltw] [-I pattern] -D string file1 file2\n"
410 	    "       diff [-abdilpTtw] [-I pattern] [-L label] -U number file1 file2\n"
411 	    "       diff [-abdilNPprsTtw] [-c | -e | -f | -n | -q | -u] [-I pattern]\n"
412 	    "            [-L label] [-S name] [-X file] [-x pattern] dir1 dir2\n");
413 
414 	exit(2);
415 }
416