xref: /freebsd/usr.bin/uniq/uniq.c (revision f1951fd745b894fe6586c298874af98544a5e272)
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 (cap_rights_limit(fileno(ifp), &rights) < 0 && errno != ENOSYS)
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 (cap_rights_limit(fileno(ofp), &rights) < 0 && errno != ENOSYS) {
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 (cap_ioctls_limit(fileno(ofp), &cmd, 1) < 0 &&
163 		    errno != ENOSYS) {
164 			err(1, "unable to limit ioctls for %s",
165 			    argc > 1 ? argv[1] : "stdout");
166 		}
167 	}
168 
169 	caph_cache_catpages();
170 	if (caph_enter() < 0)
171 		err(1, "unable to enter capability mode");
172 
173 	prevbuflen = thisbuflen = 0;
174 	prevline = thisline = NULL;
175 
176 	if (getline(&prevline, &prevbuflen, ifp) < 0) {
177 		if (ferror(ifp))
178 			err(1, "%s", ifn);
179 		exit(0);
180 	}
181 	tprev = convert(prevline);
182 
183 	tthis = NULL;
184 	while (getline(&thisline, &thisbuflen, ifp) >= 0) {
185 		if (tthis != NULL)
186 			free(tthis);
187 		tthis = convert(thisline);
188 
189 		if (tthis == NULL && tprev == NULL)
190 			comp = inlcmp(thisline, prevline);
191 		else if (tthis == NULL || tprev == NULL)
192 			comp = 1;
193 		else
194 			comp = wcscoll(tthis, tprev);
195 
196 		if (comp) {
197 			/* If different, print; set previous to new value. */
198 			show(ofp, prevline);
199 			p = prevline;
200 			b1 = prevbuflen;
201 			prevline = thisline;
202 			prevbuflen = thisbuflen;
203 			if (tprev != NULL)
204 				free(tprev);
205 			tprev = tthis;
206 			thisline = p;
207 			thisbuflen = b1;
208 			tthis = NULL;
209 			repeats = 0;
210 		} else
211 			++repeats;
212 	}
213 	if (ferror(ifp))
214 		err(1, "%s", ifn);
215 	show(ofp, prevline);
216 	exit(0);
217 }
218 
219 static wchar_t *
220 convert(const char *str)
221 {
222 	size_t n;
223 	wchar_t *buf, *ret, *p;
224 
225 	if ((n = mbstowcs(NULL, str, 0)) == (size_t)-1)
226 		return (NULL);
227 	if (SIZE_MAX / sizeof(*buf) < n + 1)
228 		errx(1, "conversion buffer length overflow");
229 	if ((buf = malloc((n + 1) * sizeof(*buf))) == NULL)
230 		err(1, "malloc");
231 	if (mbstowcs(buf, str, n + 1) != n)
232 		errx(1, "internal mbstowcs() error");
233 	/* The last line may not end with \n. */
234 	if (n > 0 && buf[n - 1] == L'\n')
235 		buf[n - 1] = L'\0';
236 
237 	/* If requested get the chosen fields + character offsets. */
238 	if (numfields || numchars) {
239 		if ((ret = wcsdup(skip(buf))) == NULL)
240 			err(1, "wcsdup");
241 		free(buf);
242 	} else
243 		ret = buf;
244 
245 	if (iflag) {
246 		for (p = ret; *p != L'\0'; p++)
247 			*p = towlower(*p);
248 	}
249 
250 	return (ret);
251 }
252 
253 static int
254 inlcmp(const char *s1, const char *s2)
255 {
256 	int c1, c2;
257 
258 	while (*s1 == *s2++)
259 		if (*s1++ == '\0')
260 			return (0);
261 	c1 = (unsigned char)*s1;
262 	c2 = (unsigned char)*(s2 - 1);
263 	/* The last line may not end with \n. */
264 	if (c1 == '\n')
265 		c1 = '\0';
266 	if (c2 == '\n')
267 		c2 = '\0';
268 	return (c1 - c2);
269 }
270 
271 /*
272  * show --
273  *	Output a line depending on the flags and number of repetitions
274  *	of the line.
275  */
276 static void
277 show(FILE *ofp, const char *str)
278 {
279 
280 	if ((dflag && repeats == 0) || (uflag && repeats > 0))
281 		return;
282 	if (cflag)
283 		(void)fprintf(ofp, "%4d %s", repeats + 1, str);
284 	else
285 		(void)fprintf(ofp, "%s", str);
286 }
287 
288 static wchar_t *
289 skip(wchar_t *str)
290 {
291 	int nchars, nfields;
292 
293 	for (nfields = 0; *str != L'\0' && nfields++ != numfields; ) {
294 		while (iswblank(*str))
295 			str++;
296 		while (*str != L'\0' && !iswblank(*str))
297 			str++;
298 	}
299 	for (nchars = numchars; nchars-- && *str != L'\0'; ++str)
300 		;
301 	return(str);
302 }
303 
304 static FILE *
305 file(const char *name, const char *mode)
306 {
307 	FILE *fp;
308 
309 	if ((fp = fopen(name, mode)) == NULL)
310 		err(1, "%s", name);
311 	return(fp);
312 }
313 
314 static void
315 obsolete(char *argv[])
316 {
317 	int len;
318 	char *ap, *p, *start;
319 
320 	while ((ap = *++argv)) {
321 		/* Return if "--" or not an option of any form. */
322 		if (ap[0] != '-') {
323 			if (ap[0] != '+')
324 				return;
325 		} else if (ap[1] == '-')
326 			return;
327 		if (!isdigit((unsigned char)ap[1]))
328 			continue;
329 		/*
330 		 * Digit signifies an old-style option.  Malloc space for dash,
331 		 * new option and argument.
332 		 */
333 		len = strlen(ap);
334 		if ((start = p = malloc(len + 3)) == NULL)
335 			err(1, "malloc");
336 		*p++ = '-';
337 		*p++ = ap[0] == '+' ? 's' : 'f';
338 		(void)strcpy(p, ap + 1);
339 		*argv = start;
340 	}
341 }
342 
343 static void
344 usage(void)
345 {
346 	(void)fprintf(stderr,
347 "usage: uniq [-c] [-d | -u] [-i] [-f fields] [-s chars] [input [output]]\n");
348 	exit(1);
349 }
350