Annotation of src/usr.bin/csplit/csplit.c, Revision 1.7
1.7 ! deraadt 1: /* $OpenBSD: csplit.c,v 1.6 2015/10/07 03:50:10 deraadt Exp $ */
1.1 millert 2: /* $FreeBSD: src/usr.bin/csplit/csplit.c,v 1.9 2004/03/22 11:15:03 tjr Exp $ */
3:
4: /*-
5: * Copyright (c) 2002 Tim J. Robbins.
6: * All rights reserved.
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: *
17: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18: * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20: * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21: * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22: * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23: * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24: * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25: * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26: * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27: * SUCH DAMAGE.
28: */
29:
30: /*
31: * csplit -- split files based on context
32: *
33: * This utility splits its input into numbered output files by line number
34: * or by a regular expression. Regular expression matches have an optional
35: * offset with them, allowing the split to occur a specified number of
36: * lines before or after the match.
37: *
38: * To handle negative offsets, we stop reading when the match occurs and
39: * store the offset that the file should have been split at, then use
40: * this output file as input until all the "overflowed" lines have been read.
41: * The file is then closed and truncated to the correct length.
42: *
43: * We assume that the output files can be seeked upon (ie. they cannot be
44: * symlinks to named pipes or character devices), but make no such
45: * assumption about the input.
46: */
47:
48: #include <sys/types.h>
49:
50: #include <ctype.h>
51: #include <err.h>
52: #include <errno.h>
53: #include <limits.h>
54: #include <locale.h>
55: #include <regex.h>
56: #include <signal.h>
57: #include <stdint.h>
58: #include <stdio.h>
59: #include <stdlib.h>
60: #include <string.h>
61: #include <unistd.h>
62:
63: void cleanup(void);
64: void do_lineno(const char *);
65: void do_rexp(const char *);
1.4 fgsch 66: char *get_line(void);
1.1 millert 67: void handlesig(int);
68: FILE *newfile(void);
69: void toomuch(FILE *, long);
70: void usage(void);
71:
72: /*
73: * Command line options
74: */
75: const char *prefix; /* File name prefix */
76: long sufflen; /* Number of decimal digits for suffix */
77: int sflag; /* Suppress output of file names */
78: int kflag; /* Keep output if error occurs */
79:
80: /*
81: * Other miscellaneous globals (XXX too many)
82: */
83: long lineno; /* Current line number in input file */
84: long reps; /* Number of repetitions for this pattern */
85: long nfiles; /* Number of files output so far */
86: long maxfiles; /* Maximum number of files we can create */
87: char currfile[PATH_MAX]; /* Current output file */
88: const char *infn; /* Name of the input file */
89: FILE *infile; /* Input file handle */
90: FILE *overfile; /* Overflow file for toomuch() */
91: off_t truncofs; /* Offset this file should be truncated at */
92: int doclean; /* Should cleanup() remove output? */
93:
94: int
95: main(int argc, char *argv[])
96: {
97: struct sigaction sa;
98: long i;
99: int ch;
100: const char *expr;
101: char *ep, *p;
102: FILE *ofp;
103:
104: setlocale(LC_ALL, "");
105:
1.7 ! deraadt 106: if (pledge("stdio rpath wpath cpath", NULL) == -1)
! 107: err(1, "pledge");
1.6 deraadt 108:
1.1 millert 109: kflag = sflag = 0;
110: prefix = "xx";
111: sufflen = 2;
112: while ((ch = getopt(argc, argv, "f:kn:s")) != -1) {
113: switch (ch) {
114: case 'f':
115: prefix = optarg;
116: break;
117: case 'k':
118: kflag = 1;
119: break;
120: case 'n':
121: errno = 0;
122: sufflen = strtol(optarg, &ep, 10);
123: if (sufflen <= 0 || *ep != '\0' || errno != 0)
124: errx(1, "%s: bad suffix length", optarg);
125: break;
126: case 's':
127: sflag = 1;
128: break;
129: default:
130: usage();
131: /*NOTREACHED*/
132: }
133: }
134:
135: if (sufflen + strlen(prefix) >= PATH_MAX)
136: errx(1, "name too long");
137:
138: argc -= optind;
139: argv += optind;
140:
141: if ((infn = *argv++) == NULL)
142: usage();
143: if (strcmp(infn, "-") == 0) {
144: infile = stdin;
145: infn = "stdin";
1.7 ! deraadt 146: if (pledge("stdio wpath cpath", NULL) == -1)
! 147: err(1, "pledge");
1.1 millert 148: } else if ((infile = fopen(infn, "r")) == NULL)
149: err(1, "%s", infn);
150:
151: if (!kflag) {
152: doclean = 1;
153: atexit(cleanup);
154: sa.sa_flags = 0;
155: sa.sa_handler = handlesig;
156: sigemptyset(&sa.sa_mask);
157: sigaddset(&sa.sa_mask, SIGHUP);
158: sigaddset(&sa.sa_mask, SIGINT);
159: sigaddset(&sa.sa_mask, SIGTERM);
160: sigaction(SIGHUP, &sa, NULL);
161: sigaction(SIGINT, &sa, NULL);
162: sigaction(SIGTERM, &sa, NULL);
163: }
164:
165: lineno = 0;
166: nfiles = 0;
167: truncofs = 0;
168: overfile = NULL;
169:
170: /* Ensure 10^sufflen < LONG_MAX. */
171: for (maxfiles = 1, i = 0; i < sufflen; i++) {
172: if (maxfiles > LONG_MAX / 10)
173: errx(1, "%ld: suffix too long (limit %ld)",
174: sufflen, i);
175: maxfiles *= 10;
176: }
177:
178: /* Create files based on supplied patterns. */
179: while (nfiles < maxfiles - 1 && (expr = *argv++) != NULL) {
180: /* Look ahead & see if this pattern has any repetitions. */
181: if (*argv != NULL && **argv == '{') {
182: errno = 0;
183: reps = strtol(*argv + 1, &ep, 10);
184: if (reps < 0 || *ep != '}' || errno != 0)
185: errx(1, "%s: bad repetition count", *argv + 1);
186: argv++;
187: } else
188: reps = 0;
189:
190: if (*expr == '/' || *expr == '%') {
191: do {
192: do_rexp(expr);
193: } while (reps-- != 0 && nfiles < maxfiles - 1);
194: } else if (isdigit((unsigned char)*expr))
195: do_lineno(expr);
196: else
197: errx(1, "%s: unrecognised pattern", expr);
198: }
199:
200: /* Copy the rest into a new file. */
201: if (!feof(infile)) {
202: ofp = newfile();
1.4 fgsch 203: while ((p = get_line()) != NULL && fputs(p, ofp) == 0)
1.1 millert 204: ;
205: if (!sflag)
206: printf("%jd\n", (intmax_t)ftello(ofp));
207: if (fclose(ofp) != 0)
208: err(1, "%s", currfile);
209: }
210:
211: toomuch(NULL, 0);
212: doclean = 0;
213:
214: return (0);
215: }
216:
217: void
218: usage(void)
219: {
220: extern char *__progname;
221:
222: fprintf(stderr,
223: "usage: %s [-ks] [-f prefix] [-n number] file args ...\n",
224: __progname);
225: exit(1);
226: }
227:
1.3 deraadt 228: /* ARGSUSED */
1.1 millert 229: void
230: handlesig(int sig)
231: {
232: const char msg[] = "csplit: caught signal, cleaning up\n";
233:
234: write(STDERR_FILENO, msg, sizeof(msg) - 1);
235: cleanup();
236: _exit(2);
237: }
238:
239: /* Create a new output file. */
240: FILE *
241: newfile(void)
242: {
243: FILE *fp;
244:
245: if ((size_t)snprintf(currfile, sizeof(currfile), "%s%0*ld", prefix,
246: (int)sufflen, nfiles) >= sizeof(currfile))
1.5 guenther 247: errc(1, ENAMETOOLONG, "%s", currfile);
1.1 millert 248: if ((fp = fopen(currfile, "w+")) == NULL)
249: err(1, "%s", currfile);
250: nfiles++;
251:
252: return (fp);
253: }
254:
255: /* Remove partial output, called before exiting. */
256: void
257: cleanup(void)
258: {
259: char fnbuf[PATH_MAX];
260: long i;
261:
262: if (!doclean)
263: return;
264:
265: /*
1.2 millert 266: * NOTE: One cannot portably assume to be able to call snprintf() from
267: * inside a signal handler. It is, however, safe to do on OpenBSD.
1.1 millert 268: */
269: for (i = 0; i < nfiles; i++) {
270: snprintf(fnbuf, sizeof(fnbuf), "%s%0*ld", prefix,
271: (int)sufflen, i);
272: unlink(fnbuf);
273: }
274: }
275:
276: /* Read a line from the input into a static buffer. */
277: char *
1.4 fgsch 278: get_line(void)
1.1 millert 279: {
280: static char lbuf[LINE_MAX];
281: FILE *src;
282:
283: src = overfile != NULL ? overfile : infile;
284:
285: again: if (fgets(lbuf, sizeof(lbuf), src) == NULL) {
286: if (src == overfile) {
287: src = infile;
288: goto again;
289: }
290: return (NULL);
291: }
292: if (ferror(src))
293: err(1, "%s", infn);
294: lineno++;
295:
296: return (lbuf);
297: }
298:
1.4 fgsch 299: /* Conceptually rewind the input (as obtained by get_line()) back `n' lines. */
1.1 millert 300: void
301: toomuch(FILE *ofp, long n)
302: {
303: char buf[BUFSIZ];
304: size_t i, nread;
305:
306: if (overfile != NULL) {
307: /*
308: * Truncate the previous file we overflowed into back to
309: * the correct length, close it.
310: */
311: if (fflush(overfile) != 0)
312: err(1, "overflow");
313: if (ftruncate(fileno(overfile), truncofs) != 0)
314: err(1, "overflow");
315: if (fclose(overfile) != 0)
316: err(1, "overflow");
317: overfile = NULL;
318: }
319:
320: if (n == 0)
321: /* Just tidying up */
322: return;
323:
324: lineno -= n;
325:
326: /*
327: * Wind the overflow file backwards to `n' lines before the
328: * current one.
329: */
330: do {
331: if (ftello(ofp) < (off_t)sizeof(buf))
332: rewind(ofp);
333: else
334: fseeko(ofp, -(off_t)sizeof(buf), SEEK_CUR);
335: if (ferror(ofp))
336: errx(1, "%s: can't seek", currfile);
337: if ((nread = fread(buf, 1, sizeof(buf), ofp)) == 0)
338: errx(1, "can't read overflowed output");
339: if (fseeko(ofp, -(off_t)nread, SEEK_CUR) != 0)
340: err(1, "%s", currfile);
341: for (i = 1; i <= nread; i++)
342: if (buf[nread - i] == '\n' && n-- == 0)
343: break;
344: if (ftello(ofp) == 0)
345: break;
346: } while (n > 0);
347: if (fseeko(ofp, (off_t)(nread - i + 1), SEEK_CUR) != 0)
348: err(1, "%s", currfile);
349:
350: /*
1.4 fgsch 351: * get_line() will read from here. Next call will truncate to
1.1 millert 352: * truncofs in this file.
353: */
354: overfile = ofp;
355: truncofs = ftello(overfile);
356: }
357:
358: /* Handle splits for /regexp/ and %regexp% patterns. */
359: void
360: do_rexp(const char *expr)
361: {
362: regex_t cre;
363: intmax_t nwritten;
364: long ofs;
365: int first;
366: char *ecopy, *ep, *p, *pofs, *re;
367: FILE *ofp;
368:
369: if ((ecopy = strdup(expr)) == NULL)
370: err(1, "strdup");
371:
372: re = ecopy + 1;
373: if ((pofs = strrchr(ecopy, *expr)) == NULL || pofs[-1] == '\\')
374: errx(1, "%s: missing trailing %c", expr, *expr);
375: *pofs++ = '\0';
376:
377: if (*pofs != '\0') {
378: errno = 0;
379: ofs = strtol(pofs, &ep, 10);
380: if (*ep != '\0' || errno != 0)
381: errx(1, "%s: bad offset", pofs);
382: } else
383: ofs = 0;
384:
385: if (regcomp(&cre, re, REG_BASIC|REG_NOSUB) != 0)
386: errx(1, "%s: bad regular expression", re);
387:
388: if (*expr == '/')
389: /* /regexp/: Save results to a file. */
390: ofp = newfile();
391: else {
392: /* %regexp%: Make a temporary file for overflow. */
393: if ((ofp = tmpfile()) == NULL)
394: err(1, "tmpfile");
395: }
396:
397: /* Read and output lines until we get a match. */
398: first = 1;
1.4 fgsch 399: while ((p = get_line()) != NULL) {
1.1 millert 400: if (fputs(p, ofp) != 0)
401: break;
402: if (!first && regexec(&cre, p, 0, NULL, 0) == 0)
403: break;
404: first = 0;
405: }
406:
407: if (p == NULL)
408: errx(1, "%s: no match", re);
409:
410: if (ofs <= 0) {
411: /*
412: * Negative (or zero) offset: throw back any lines we should
413: * not have read yet.
414: */
415: if (p != NULL) {
416: toomuch(ofp, -ofs + 1);
417: nwritten = (intmax_t)truncofs;
418: } else
419: nwritten = (intmax_t)ftello(ofp);
420: } else {
421: /*
422: * Positive offset: copy the requested number of lines
423: * after the match.
424: */
1.4 fgsch 425: while (--ofs > 0 && (p = get_line()) != NULL)
1.1 millert 426: fputs(p, ofp);
427: toomuch(NULL, 0);
428: nwritten = (intmax_t)ftello(ofp);
429: if (fclose(ofp) != 0)
430: err(1, "%s", currfile);
431: }
432:
433: if (!sflag && *expr == '/')
434: printf("%jd\n", nwritten);
435:
436: regfree(&cre);
437: free(ecopy);
438: }
439:
440: /* Handle splits based on line number. */
441: void
442: do_lineno(const char *expr)
443: {
444: long lastline, tgtline;
445: char *ep, *p;
446: FILE *ofp;
447:
448: errno = 0;
449: tgtline = strtol(expr, &ep, 10);
450: if (tgtline <= 0 || errno != 0 || *ep != '\0')
451: errx(1, "%s: bad line number", expr);
452: lastline = tgtline;
453: if (lastline <= lineno)
454: errx(1, "%s: can't go backwards", expr);
455:
456: while (nfiles < maxfiles - 1) {
457: ofp = newfile();
458: while (lineno + 1 != lastline) {
1.4 fgsch 459: if ((p = get_line()) == NULL)
1.1 millert 460: errx(1, "%ld: out of range", lastline);
461: if (fputs(p, ofp) != 0)
462: break;
463: }
464: if (!sflag)
465: printf("%jd\n", (intmax_t)ftello(ofp));
466: if (fclose(ofp) != 0)
467: err(1, "%s", currfile);
468: if (reps-- == 0)
469: break;
470: lastline += tgtline;
471: }
472: }