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