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