xref: /openbsd/usr.bin/split/split.c (revision 09467b48)
1 /*	$OpenBSD: split.c,v 1.21 2015/12/31 16:13:01 millert Exp $	*/
2 /*	$NetBSD: split.c,v 1.5 1995/08/31 22:22:05 jtc Exp $	*/
3 
4 /*
5  * Copyright (c) 1987, 1993, 1994
6  *	The Regents of the University of California.  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  * 3. 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 #include <sys/param.h>	/* MAXBSIZE */
34 #include <sys/types.h>
35 
36 #include <ctype.h>
37 #include <err.h>
38 #include <fcntl.h>
39 #include <limits.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 #include <regex.h>
45 
46 #define DEFLINE	1000			/* Default num lines per file. */
47 
48 ssize_t	 bytecnt;			/* Byte count to split on. */
49 long	 numlines;			/* Line count to split on. */
50 int	 file_open;			/* If a file open. */
51 int	 ifd = -1, ofd = -1;		/* Input/output file descriptors. */
52 char	 bfr[MAXBSIZE];			/* I/O buffer. */
53 char	 fname[PATH_MAX];		/* File name prefix. */
54 regex_t	 rgx;
55 int	 pflag;
56 int	 sufflen = 2;			/* File name suffix length. */
57 
58 void newfile(void);
59 void split1(void);
60 void split2(void);
61 __dead void usage(void);
62 
63 int
64 main(int argc, char *argv[])
65 {
66 	int ch, scale;
67 	char *ep, *p;
68 	const char *errstr;
69 
70 	if (pledge("stdio rpath wpath cpath", NULL) == -1)
71 		err(1, "pledge");
72 
73 	while ((ch = getopt(argc, argv, "0123456789a:b:l:p:-")) != -1)
74 		switch (ch) {
75 		case '0': case '1': case '2': case '3': case '4':
76 		case '5': case '6': case '7': case '8': case '9':
77 			/*
78 			 * Undocumented kludge: split was originally designed
79 			 * to take a number after a dash.
80 			 */
81 			if (numlines == 0) {
82 				p = argv[optind - 1];
83 				if (p[0] == '-' && p[1] == ch && !p[2])
84 					numlines = strtol(++p, &ep, 10);
85 				else
86 					numlines =
87 					    strtol(argv[optind] + 1, &ep, 10);
88 				if (numlines <= 0 || *ep)
89 					errx(1, "%s: illegal line count",
90 					    optarg);
91 			}
92 			break;
93 		case '-':		/* Undocumented: historic stdin flag. */
94 			if (ifd != -1)
95 				usage();
96 			ifd = 0;
97 			break;
98 		case 'a':		/* suffix length. */
99 			sufflen = strtonum(optarg, 1, NAME_MAX, &errstr);
100 			if (errstr)
101 				errx(1, "%s: %s", optarg, errstr);
102 			break;
103 		case 'b':		/* Byte count. */
104 			if ((bytecnt = strtol(optarg, &ep, 10)) <= 0 ||
105 			    (*ep != '\0' && *ep != 'k' && *ep != 'm'))
106 				errx(1, "%s: illegal byte count", optarg);
107 			if (*ep == 'k')
108 				scale = 1024;
109 			else if (*ep == 'm')
110 				scale = 1048576;
111 			else
112 				scale = 1;
113 			if (bytecnt > SSIZE_MAX / scale)
114 				errx(1, "%s: byte count too large", optarg);
115 			bytecnt *= scale;
116 			break;
117 		case 'p' :      /* pattern matching. */
118 			if (regcomp(&rgx, optarg, REG_EXTENDED|REG_NOSUB) != 0)
119 				errx(1, "%s: illegal regexp", optarg);
120 			pflag = 1;
121 			break;
122 		case 'l':		/* Line count. */
123 			if (numlines != 0)
124 				usage();
125 			if ((numlines = strtol(optarg, &ep, 10)) <= 0 || *ep)
126 				errx(1, "%s: illegal line count", optarg);
127 			break;
128 		default:
129 			usage();
130 		}
131 	argv += optind;
132 	argc -= optind;
133 
134 	if (*argv != NULL)
135 		if (ifd == -1) {		/* Input file. */
136 			if ((ifd = open(*argv, O_RDONLY, 0)) < 0)
137 				err(1, "%s", *argv);
138 			++argv;
139 		}
140 	if (*argv != NULL)			/* File name prefix. */
141 		(void)strlcpy(fname, *argv++, sizeof(fname));
142 	if (*argv != NULL)
143 		usage();
144 
145 	if (strlen(fname) + sufflen >= sizeof(fname))
146 		errx(1, "suffix is too long");
147 	if (pflag && (numlines != 0 || bytecnt != 0))
148 		usage();
149 
150 	if (numlines == 0)
151 		numlines = DEFLINE;
152 	else if (bytecnt != 0)
153 		usage();
154 
155 	if (ifd == -1)				/* Stdin by default. */
156 		ifd = 0;
157 
158 	if (bytecnt) {
159 		split1();
160 		exit (0);
161 	}
162 	split2();
163 	if (pflag)
164 		regfree(&rgx);
165 	exit(0);
166 }
167 
168 /*
169  * split1 --
170  *	Split the input by bytes.
171  */
172 void
173 split1(void)
174 {
175 	ssize_t bcnt, dist, len;
176 	char *C;
177 
178 	for (bcnt = 0;;)
179 		switch ((len = read(ifd, bfr, MAXBSIZE))) {
180 		case 0:
181 			exit(0);
182 		case -1:
183 			err(1, "read");
184 			/* NOTREACHED */
185 		default:
186 			if (!file_open)
187 				newfile();
188 			if (bcnt + len >= bytecnt) {
189 				dist = bytecnt - bcnt;
190 				if (write(ofd, bfr, dist) != dist)
191 					err(1, "write");
192 				len -= dist;
193 				for (C = bfr + dist; len >= bytecnt;
194 				    len -= bytecnt, C += bytecnt) {
195 					newfile();
196 					if (write(ofd, C, bytecnt) != bytecnt)
197 						err(1, "write");
198 				}
199 				if (len != 0) {
200 					newfile();
201 					if (write(ofd, C, len) != len)
202 						err(1, "write");
203 				} else
204 					file_open = 0;
205 				bcnt = len;
206 			} else {
207 				bcnt += len;
208 				if (write(ofd, bfr, len) != len)
209 					err(1, "write");
210 			}
211 		}
212 }
213 
214 /*
215  * split2 --
216  *	Split the input by lines.
217  */
218 void
219 split2(void)
220 {
221 	long lcnt = 0;
222 	FILE *infp;
223 
224 	/* Stick a stream on top of input file descriptor */
225 	if ((infp = fdopen(ifd, "r")) == NULL)
226 		err(1, "fdopen");
227 
228 	/* Process input one line at a time */
229 	while (fgets(bfr, sizeof(bfr), infp) != NULL) {
230 		const int len = strlen(bfr);
231 
232 		if (len == 0)
233 			continue;
234 
235 		/* If line is too long to deal with, just write it out */
236 		if (bfr[len - 1] != '\n')
237 			goto writeit;
238 
239 		/* Check if we need to start a new file */
240 		if (pflag) {
241 			regmatch_t pmatch;
242 
243 			pmatch.rm_so = 0;
244 			pmatch.rm_eo = len - 1;
245 			if (regexec(&rgx, bfr, 0, &pmatch, REG_STARTEND) == 0)
246 				newfile();
247 		} else if (lcnt++ == numlines) {
248 			newfile();
249 			lcnt = 1;
250 		}
251 
252 writeit:
253 		/* Open output file if needed */
254 		if (!file_open)
255 			newfile();
256 
257 		/* Write out line */
258 		if (write(ofd, bfr, len) != len)
259 			err(1, "write");
260 	}
261 
262 	/* EOF or error? */
263 	if (ferror(infp))
264 		err(1, "read");
265 	else
266 		exit(0);
267 }
268 
269 /*
270  * newfile --
271  *	Open a new output file.
272  */
273 void
274 newfile(void)
275 {
276 	static char *suffix, *sufftail;
277 	char *sptr;
278 
279 	if (ofd == -1) {
280 		ofd = fileno(stdout);
281 		if (*fname == '\0') {
282 			*fname = 'x';	/* no name specified, use 'x' */
283 			memset(fname + 1, 'a', sufflen);
284 			suffix = fname;
285 			sufflen++;	/* treat 'x' as part of suffix */
286 		} else {
287 			suffix = fname + strlen(fname);
288 			memset(suffix, 'a', sufflen);
289 		}
290 		suffix[sufflen] = '\0';
291 		sufftail = suffix + sufflen - 1;
292 	} else {
293 		for (sptr = sufftail; sptr >= suffix; sptr--) {
294 			if (*sptr != 'z') {
295 				(*sptr)++;
296 				break;
297 			} else
298 				*sptr = 'a';
299 		}
300 		if (sptr < suffix)
301 			errx(1, "too many files");
302 	}
303 
304 	if (!freopen(fname, "w", stdout))
305 		err(1, "%s", fname);
306 	file_open = 1;
307 }
308 
309 __dead void
310 usage(void)
311 {
312 	extern char *__progname;
313 
314 	(void)fprintf(stderr, "usage: %s [-a suffix_length]\n"
315 	    "             [-b byte_count[k|m] | -l line_count | -p pattern] "
316 	    "[file [name]]\n", __progname);
317 	exit(1);
318 }
319