xref: /freebsd/usr.bin/uniq/uniq.c (revision d2033021a73db7b8d910c1ffc52f4d1d0def7162)
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 #include <sys/capsicum.h>
36 
37 #include <capsicum_helpers.h>
38 #include <ctype.h>
39 #include <err.h>
40 #include <errno.h>
41 #include <getopt.h>
42 #include <limits.h>
43 #include <locale.h>
44 #include <nl_types.h>
45 #include <stdint.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <termios.h>
50 #include <unistd.h>
51 #include <wchar.h>
52 #include <wctype.h>
53 
54 static int Dflag, cflag, dflag, uflag, iflag;
55 static int numchars, numfields, repeats;
56 
57 /* Dflag values */
58 #define	DF_NONE		0
59 #define	DF_NOSEP	1
60 #define	DF_PRESEP	2
61 #define	DF_POSTSEP	3
62 
63 static const struct option long_opts[] =
64 {
65 	{"all-repeated",optional_argument,	NULL, 'D'},
66 	{"count",	no_argument,		NULL, 'c'},
67 	{"repeated",	no_argument,		NULL, 'd'},
68 	{"skip-fields",	required_argument,	NULL, 'f'},
69 	{"ignore-case",	no_argument,		NULL, 'i'},
70 	{"skip-chars",	required_argument,	NULL, 's'},
71 	{"unique",	no_argument,		NULL, 'u'},
72 	{NULL,		no_argument,		NULL, 0}
73 };
74 
75 static FILE	*file(const char *, const char *);
76 static wchar_t	*convert(const char *);
77 static int	 inlcmp(const char *, const char *);
78 static void	 show(FILE *, const char *);
79 static wchar_t	*skip(wchar_t *);
80 static void	 obsolete(char *[]);
81 static void	 usage(void);
82 
83 int
84 main (int argc, char *argv[])
85 {
86 	wchar_t *tprev, *tthis;
87 	FILE *ifp, *ofp;
88 	int ch, comp;
89 	size_t prevbuflen, thisbuflen, b1;
90 	char *prevline, *thisline, *p;
91 	const char *ifn, *errstr;;
92 	cap_rights_t rights;
93 
94 	(void) setlocale(LC_ALL, "");
95 
96 	obsolete(argv);
97 	while ((ch = getopt_long(argc, argv, "+D::cdif:s:u", long_opts,
98 	    NULL)) != -1)
99 		switch (ch) {
100 		case 'D':
101 			if (optarg == NULL || strcasecmp(optarg, "none") == 0)
102 				Dflag = DF_NOSEP;
103 			else if (strcasecmp(optarg, "prepend") == 0)
104 				Dflag = DF_PRESEP;
105 			else if (strcasecmp(optarg, "separate") == 0)
106 				Dflag = DF_POSTSEP;
107 			else
108 				usage();
109 			break;
110 		case 'c':
111 			cflag = 1;
112 			break;
113 		case 'd':
114 			dflag = 1;
115 			break;
116 		case 'i':
117 			iflag = 1;
118 			break;
119 		case 'f':
120 			numfields = strtonum(optarg, 0, INT_MAX, &errstr);
121 			if (errstr)
122 				errx(1, "field skip value is %s: %s", errstr, optarg);
123 			break;
124 		case 's':
125 			numchars = strtonum(optarg, 0, INT_MAX, &errstr);
126 			if (errstr != NULL)
127 				errx(1, "character skip value is %s: %s", errstr, optarg);
128 			break;
129 		case 'u':
130 			uflag = 1;
131 			break;
132 		case '?':
133 		default:
134 			usage();
135 		}
136 
137 	argc -= optind;
138 	argv += optind;
139 
140 	if (argc > 2)
141 		usage();
142 
143 	ifp = stdin;
144 	ifn = "stdin";
145 	ofp = stdout;
146 	if (argc > 0 && strcmp(argv[0], "-") != 0)
147 		ifp = file(ifn = argv[0], "r");
148 	cap_rights_init(&rights, CAP_FSTAT, CAP_READ);
149 	if (caph_rights_limit(fileno(ifp), &rights) < 0)
150 		err(1, "unable to limit rights for %s", ifn);
151 	cap_rights_init(&rights, CAP_FSTAT, CAP_WRITE);
152 	if (argc > 1)
153 		ofp = file(argv[1], "w");
154 	else
155 		cap_rights_set(&rights, CAP_IOCTL);
156 	if (caph_rights_limit(fileno(ofp), &rights) < 0) {
157 		err(1, "unable to limit rights for %s",
158 		    argc > 1 ? argv[1] : "stdout");
159 	}
160 	if (cap_rights_is_set(&rights, CAP_IOCTL)) {
161 		unsigned long cmd;
162 
163 		cmd = TIOCGETA; /* required by isatty(3) in printf(3) */
164 
165 		if (caph_ioctls_limit(fileno(ofp), &cmd, 1) < 0) {
166 			err(1, "unable to limit ioctls for %s",
167 			    argc > 1 ? argv[1] : "stdout");
168 		}
169 	}
170 
171 	caph_cache_catpages();
172 	if (caph_enter() < 0)
173 		err(1, "unable to enter capability mode");
174 
175 	prevbuflen = thisbuflen = 0;
176 	prevline = thisline = NULL;
177 
178 	if (getline(&prevline, &prevbuflen, ifp) < 0) {
179 		if (ferror(ifp))
180 			err(1, "%s", ifn);
181 		exit(0);
182 	}
183 	tprev = convert(prevline);
184 
185 	tthis = NULL;
186 	while (getline(&thisline, &thisbuflen, ifp) >= 0) {
187 		if (tthis != NULL)
188 			free(tthis);
189 		tthis = convert(thisline);
190 
191 		if (tthis == NULL && tprev == NULL)
192 			comp = inlcmp(thisline, prevline);
193 		else if (tthis == NULL || tprev == NULL)
194 			comp = 1;
195 		else
196 			comp = wcscoll(tthis, tprev);
197 
198 		if (comp) {
199 			/* If different, print; set previous to new value. */
200 			if (Dflag == DF_POSTSEP && repeats > 0)
201 				fputc('\n', ofp);
202 			if (!Dflag)
203 				show(ofp, prevline);
204 			p = prevline;
205 			b1 = prevbuflen;
206 			prevline = thisline;
207 			prevbuflen = thisbuflen;
208 			if (tprev != NULL)
209 				free(tprev);
210 			tprev = tthis;
211 			thisline = p;
212 			thisbuflen = b1;
213 			tthis = NULL;
214 			repeats = 0;
215 		} else {
216 			if (Dflag) {
217 				if (repeats == 0) {
218 					if (Dflag == DF_PRESEP)
219 						fputc('\n', ofp);
220 					show(ofp, prevline);
221 				}
222 				show(ofp, thisline);
223 			}
224 			++repeats;
225 		}
226 	}
227 	if (ferror(ifp))
228 		err(1, "%s", ifn);
229 	if (!Dflag)
230 		show(ofp, prevline);
231 	exit(0);
232 }
233 
234 static wchar_t *
235 convert(const char *str)
236 {
237 	size_t n;
238 	wchar_t *buf, *ret, *p;
239 
240 	if ((n = mbstowcs(NULL, str, 0)) == (size_t)-1)
241 		return (NULL);
242 	if (SIZE_MAX / sizeof(*buf) < n + 1)
243 		errx(1, "conversion buffer length overflow");
244 	if ((buf = malloc((n + 1) * sizeof(*buf))) == NULL)
245 		err(1, "malloc");
246 	if (mbstowcs(buf, str, n + 1) != n)
247 		errx(1, "internal mbstowcs() error");
248 	/* The last line may not end with \n. */
249 	if (n > 0 && buf[n - 1] == L'\n')
250 		buf[n - 1] = L'\0';
251 
252 	/* If requested get the chosen fields + character offsets. */
253 	if (numfields || numchars) {
254 		if ((ret = wcsdup(skip(buf))) == NULL)
255 			err(1, "wcsdup");
256 		free(buf);
257 	} else
258 		ret = buf;
259 
260 	if (iflag) {
261 		for (p = ret; *p != L'\0'; p++)
262 			*p = towlower(*p);
263 	}
264 
265 	return (ret);
266 }
267 
268 static int
269 inlcmp(const char *s1, const char *s2)
270 {
271 	int c1, c2;
272 
273 	while (*s1 == *s2++)
274 		if (*s1++ == '\0')
275 			return (0);
276 	c1 = (unsigned char)*s1;
277 	c2 = (unsigned char)*(s2 - 1);
278 	/* The last line may not end with \n. */
279 	if (c1 == '\n')
280 		c1 = '\0';
281 	if (c2 == '\n')
282 		c2 = '\0';
283 	return (c1 - c2);
284 }
285 
286 /*
287  * show --
288  *	Output a line depending on the flags and number of repetitions
289  *	of the line.
290  */
291 static void
292 show(FILE *ofp, const char *str)
293 {
294 
295 	if ((!Dflag && dflag && repeats == 0) || (uflag && repeats > 0))
296 		return;
297 	if (cflag)
298 		(void)fprintf(ofp, "%4d %s", repeats + 1, str);
299 	else
300 		(void)fprintf(ofp, "%s", str);
301 }
302 
303 static wchar_t *
304 skip(wchar_t *str)
305 {
306 	int nchars, nfields;
307 
308 	for (nfields = 0; *str != L'\0' && nfields++ != numfields; ) {
309 		while (iswblank(*str))
310 			str++;
311 		while (*str != L'\0' && !iswblank(*str))
312 			str++;
313 	}
314 	for (nchars = numchars; nchars-- && *str != L'\0'; ++str)
315 		;
316 	return(str);
317 }
318 
319 static FILE *
320 file(const char *name, const char *mode)
321 {
322 	FILE *fp;
323 
324 	if ((fp = fopen(name, mode)) == NULL)
325 		err(1, "%s", name);
326 	return(fp);
327 }
328 
329 static void
330 obsolete(char *argv[])
331 {
332 	int len;
333 	char *ap, *p, *start;
334 
335 	while ((ap = *++argv)) {
336 		/* Return if "--" or not an option of any form. */
337 		if (ap[0] != '-') {
338 			if (ap[0] != '+')
339 				return;
340 		} else if (ap[1] == '-')
341 			return;
342 		if (!isdigit((unsigned char)ap[1]))
343 			continue;
344 		/*
345 		 * Digit signifies an old-style option.  Malloc space for dash,
346 		 * new option and argument.
347 		 */
348 		len = strlen(ap);
349 		if ((start = p = malloc(len + 3)) == NULL)
350 			err(1, "malloc");
351 		*p++ = '-';
352 		*p++ = ap[0] == '+' ? 's' : 'f';
353 		(void)strcpy(p, ap + 1);
354 		*argv = start;
355 	}
356 }
357 
358 static void
359 usage(void)
360 {
361 	(void)fprintf(stderr,
362 "usage: uniq [-c | -d | -D | -u] [-i] [-f fields] [-s chars] [input [output]]\n");
363 	exit(1);
364 }
365