xref: /freebsd/usr.bin/uniq/uniq.c (revision 61ba55bcf70f2340f9c943c9571113b3fd8eda69)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Case Larsen.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #ifndef lint
36 static const char copyright[] =
37 "@(#) Copyright (c) 1989, 1993\n\
38 	The Regents of the University of California.  All rights reserved.\n";
39 #endif /* not lint */
40 
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)uniq.c	8.3 (Berkeley) 5/4/95";
44 #endif
45 #endif /* not lint */
46 
47 #include <sys/capsicum.h>
48 
49 #include <capsicum_helpers.h>
50 #include <ctype.h>
51 #include <err.h>
52 #include <errno.h>
53 #include <getopt.h>
54 #include <limits.h>
55 #include <locale.h>
56 #include <nl_types.h>
57 #include <stdint.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <termios.h>
62 #include <unistd.h>
63 #include <wchar.h>
64 #include <wctype.h>
65 
66 static int Dflag, cflag, dflag, uflag, iflag;
67 static int numchars, numfields, repeats;
68 
69 /* Dflag values */
70 #define	DF_NONE		0
71 #define	DF_NOSEP	1
72 #define	DF_PRESEP	2
73 #define	DF_POSTSEP	3
74 
75 static const struct option long_opts[] =
76 {
77 	{"all-repeated",optional_argument,	NULL, 'D'},
78 	{"count",	no_argument,		NULL, 'c'},
79 	{"repeated",	no_argument,		NULL, 'd'},
80 	{"skip-fields",	required_argument,	NULL, 'f'},
81 	{"ignore-case",	no_argument,		NULL, 'i'},
82 	{"skip-chars",	required_argument,	NULL, 's'},
83 	{"unique",	no_argument,		NULL, 'u'},
84 	{NULL,		no_argument,		NULL, 0}
85 };
86 
87 static FILE	*file(const char *, const char *);
88 static wchar_t	*convert(const char *);
89 static int	 inlcmp(const char *, const char *);
90 static void	 show(FILE *, const char *);
91 static wchar_t	*skip(wchar_t *);
92 static void	 obsolete(char *[]);
93 static void	 usage(void);
94 
95 int
96 main (int argc, char *argv[])
97 {
98 	wchar_t *tprev, *tthis;
99 	FILE *ifp, *ofp;
100 	int ch, comp;
101 	size_t prevbuflen, thisbuflen, b1;
102 	char *prevline, *thisline, *p;
103 	const char *ifn, *errstr;;
104 	cap_rights_t rights;
105 
106 	(void) setlocale(LC_ALL, "");
107 
108 	obsolete(argv);
109 	while ((ch = getopt_long(argc, argv, "+D::cdif:s:u", long_opts,
110 	    NULL)) != -1)
111 		switch (ch) {
112 		case 'D':
113 			if (optarg == NULL || strcasecmp(optarg, "none") == 0)
114 				Dflag = DF_NOSEP;
115 			else if (strcasecmp(optarg, "prepend") == 0)
116 				Dflag = DF_PRESEP;
117 			else if (strcasecmp(optarg, "separate") == 0)
118 				Dflag = DF_POSTSEP;
119 			else
120 				usage();
121 			break;
122 		case 'c':
123 			cflag = 1;
124 			break;
125 		case 'd':
126 			dflag = 1;
127 			break;
128 		case 'i':
129 			iflag = 1;
130 			break;
131 		case 'f':
132 			numfields = strtonum(optarg, 0, INT_MAX, &errstr);
133 			if (errstr)
134 				errx(1, "field skip value is %s: %s", errstr, optarg);
135 			break;
136 		case 's':
137 			numchars = strtonum(optarg, 0, INT_MAX, &errstr);
138 			if (errstr != NULL)
139 				errx(1, "character skip value is %s: %s", errstr, optarg);
140 			break;
141 		case 'u':
142 			uflag = 1;
143 			break;
144 		case '?':
145 		default:
146 			usage();
147 		}
148 
149 	argc -= optind;
150 	argv += optind;
151 
152 	if (argc > 2)
153 		usage();
154 
155 	ifp = stdin;
156 	ifn = "stdin";
157 	ofp = stdout;
158 	if (argc > 0 && strcmp(argv[0], "-") != 0)
159 		ifp = file(ifn = argv[0], "r");
160 	cap_rights_init(&rights, CAP_FSTAT, CAP_READ);
161 	if (caph_rights_limit(fileno(ifp), &rights) < 0)
162 		err(1, "unable to limit rights for %s", ifn);
163 	cap_rights_init(&rights, CAP_FSTAT, CAP_WRITE);
164 	if (argc > 1)
165 		ofp = file(argv[1], "w");
166 	else
167 		cap_rights_set(&rights, CAP_IOCTL);
168 	if (caph_rights_limit(fileno(ofp), &rights) < 0) {
169 		err(1, "unable to limit rights for %s",
170 		    argc > 1 ? argv[1] : "stdout");
171 	}
172 	if (cap_rights_is_set(&rights, CAP_IOCTL)) {
173 		unsigned long cmd;
174 
175 		cmd = TIOCGETA; /* required by isatty(3) in printf(3) */
176 
177 		if (caph_ioctls_limit(fileno(ofp), &cmd, 1) < 0) {
178 			err(1, "unable to limit ioctls for %s",
179 			    argc > 1 ? argv[1] : "stdout");
180 		}
181 	}
182 
183 	caph_cache_catpages();
184 	if (caph_enter() < 0)
185 		err(1, "unable to enter capability mode");
186 
187 	prevbuflen = thisbuflen = 0;
188 	prevline = thisline = NULL;
189 
190 	if (getline(&prevline, &prevbuflen, ifp) < 0) {
191 		if (ferror(ifp))
192 			err(1, "%s", ifn);
193 		exit(0);
194 	}
195 	tprev = convert(prevline);
196 
197 	tthis = NULL;
198 	while (getline(&thisline, &thisbuflen, ifp) >= 0) {
199 		if (tthis != NULL)
200 			free(tthis);
201 		tthis = convert(thisline);
202 
203 		if (tthis == NULL && tprev == NULL)
204 			comp = inlcmp(thisline, prevline);
205 		else if (tthis == NULL || tprev == NULL)
206 			comp = 1;
207 		else
208 			comp = wcscoll(tthis, tprev);
209 
210 		if (comp) {
211 			/* If different, print; set previous to new value. */
212 			if (Dflag == DF_POSTSEP && repeats > 0)
213 				fputc('\n', ofp);
214 			if (!Dflag)
215 				show(ofp, prevline);
216 			p = prevline;
217 			b1 = prevbuflen;
218 			prevline = thisline;
219 			prevbuflen = thisbuflen;
220 			if (tprev != NULL)
221 				free(tprev);
222 			tprev = tthis;
223 			thisline = p;
224 			thisbuflen = b1;
225 			tthis = NULL;
226 			repeats = 0;
227 		} else {
228 			if (Dflag) {
229 				if (repeats == 0) {
230 					if (Dflag == DF_PRESEP)
231 						fputc('\n', ofp);
232 					show(ofp, prevline);
233 				}
234 				show(ofp, thisline);
235 			}
236 			++repeats;
237 		}
238 	}
239 	if (ferror(ifp))
240 		err(1, "%s", ifn);
241 	if (!Dflag)
242 		show(ofp, prevline);
243 	exit(0);
244 }
245 
246 static wchar_t *
247 convert(const char *str)
248 {
249 	size_t n;
250 	wchar_t *buf, *ret, *p;
251 
252 	if ((n = mbstowcs(NULL, str, 0)) == (size_t)-1)
253 		return (NULL);
254 	if (SIZE_MAX / sizeof(*buf) < n + 1)
255 		errx(1, "conversion buffer length overflow");
256 	if ((buf = malloc((n + 1) * sizeof(*buf))) == NULL)
257 		err(1, "malloc");
258 	if (mbstowcs(buf, str, n + 1) != n)
259 		errx(1, "internal mbstowcs() error");
260 	/* The last line may not end with \n. */
261 	if (n > 0 && buf[n - 1] == L'\n')
262 		buf[n - 1] = L'\0';
263 
264 	/* If requested get the chosen fields + character offsets. */
265 	if (numfields || numchars) {
266 		if ((ret = wcsdup(skip(buf))) == NULL)
267 			err(1, "wcsdup");
268 		free(buf);
269 	} else
270 		ret = buf;
271 
272 	if (iflag) {
273 		for (p = ret; *p != L'\0'; p++)
274 			*p = towlower(*p);
275 	}
276 
277 	return (ret);
278 }
279 
280 static int
281 inlcmp(const char *s1, const char *s2)
282 {
283 	int c1, c2;
284 
285 	while (*s1 == *s2++)
286 		if (*s1++ == '\0')
287 			return (0);
288 	c1 = (unsigned char)*s1;
289 	c2 = (unsigned char)*(s2 - 1);
290 	/* The last line may not end with \n. */
291 	if (c1 == '\n')
292 		c1 = '\0';
293 	if (c2 == '\n')
294 		c2 = '\0';
295 	return (c1 - c2);
296 }
297 
298 /*
299  * show --
300  *	Output a line depending on the flags and number of repetitions
301  *	of the line.
302  */
303 static void
304 show(FILE *ofp, const char *str)
305 {
306 
307 	if ((!Dflag && dflag && repeats == 0) || (uflag && repeats > 0))
308 		return;
309 	if (cflag)
310 		(void)fprintf(ofp, "%4d %s", repeats + 1, str);
311 	else
312 		(void)fprintf(ofp, "%s", str);
313 }
314 
315 static wchar_t *
316 skip(wchar_t *str)
317 {
318 	int nchars, nfields;
319 
320 	for (nfields = 0; *str != L'\0' && nfields++ != numfields; ) {
321 		while (iswblank(*str))
322 			str++;
323 		while (*str != L'\0' && !iswblank(*str))
324 			str++;
325 	}
326 	for (nchars = numchars; nchars-- && *str != L'\0'; ++str)
327 		;
328 	return(str);
329 }
330 
331 static FILE *
332 file(const char *name, const char *mode)
333 {
334 	FILE *fp;
335 
336 	if ((fp = fopen(name, mode)) == NULL)
337 		err(1, "%s", name);
338 	return(fp);
339 }
340 
341 static void
342 obsolete(char *argv[])
343 {
344 	int len;
345 	char *ap, *p, *start;
346 
347 	while ((ap = *++argv)) {
348 		/* Return if "--" or not an option of any form. */
349 		if (ap[0] != '-') {
350 			if (ap[0] != '+')
351 				return;
352 		} else if (ap[1] == '-')
353 			return;
354 		if (!isdigit((unsigned char)ap[1]))
355 			continue;
356 		/*
357 		 * Digit signifies an old-style option.  Malloc space for dash,
358 		 * new option and argument.
359 		 */
360 		len = strlen(ap);
361 		if ((start = p = malloc(len + 3)) == NULL)
362 			err(1, "malloc");
363 		*p++ = '-';
364 		*p++ = ap[0] == '+' ? 's' : 'f';
365 		(void)strcpy(p, ap + 1);
366 		*argv = start;
367 	}
368 }
369 
370 static void
371 usage(void)
372 {
373 	(void)fprintf(stderr,
374 "usage: uniq [-c | -d | -D | -u] [-i] [-f fields] [-s chars] [input [output]]\n");
375 	exit(1);
376 }
377