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