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