xref: /freebsd/usr.bin/jot/jot.c (revision af6a5351a1fdb1130f18be6c782c4d48916eb971)
1 /*-
2  * Copyright (c) 1993
3  *	The Regents of the University of California.  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  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 #ifndef lint
31 static const char copyright[] =
32 "@(#) Copyright (c) 1993\n\
33 	The Regents of the University of California.  All rights reserved.\n";
34 #endif /* not lint */
35 
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)jot.c	8.1 (Berkeley) 6/6/93";
39 #endif
40 #endif
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 /*
45  * jot - print sequential or random data
46  *
47  * Author:  John Kunze, Office of Comp. Affairs, UCB
48  */
49 
50 #include <sys/capsicum.h>
51 #include <capsicum_helpers.h>
52 #include <ctype.h>
53 #include <err.h>
54 #include <errno.h>
55 #include <limits.h>
56 #include <stdio.h>
57 #include <stdint.h>
58 #include <stdlib.h>
59 #include <stdbool.h>
60 #include <string.h>
61 #include <time.h>
62 #include <unistd.h>
63 
64 /* Defaults */
65 #define	REPS_DEF	100
66 #define	BEGIN_DEF	1
67 #define	ENDER_DEF	100
68 #define	STEP_DEF	1
69 
70 /* Flags of options that have been set */
71 #define HAVE_STEP	1
72 #define HAVE_ENDER	2
73 #define HAVE_BEGIN	4
74 #define HAVE_REPS	8
75 
76 #define	is_default(s)	(*(s) == 0 || strcmp((s), "-") == 0)
77 
78 static bool	boring;
79 static int	prec = -1;
80 static bool	longdata;
81 static bool	intdata;
82 static bool	chardata;
83 static bool	nosign;
84 static const	char *sepstring = "\n";
85 static char	format[BUFSIZ];
86 
87 static void	getformat(void);
88 static int	getprec(const char *);
89 static int	putdata(double, bool);
90 static void	usage(void);
91 
92 int
93 main(int argc, char **argv)
94 {
95 	cap_rights_t rights;
96 	bool	have_format = false;
97 	bool	infinity = false;
98 	bool	nofinalnl = false;
99 	bool	randomize = false;
100 	bool	use_random = false;
101 	int	ch;
102 	int	mask = 0;
103 	int	n = 0;
104 	double	begin = BEGIN_DEF;
105 	double	divisor;
106 	double	ender = ENDER_DEF;
107 	double	s = STEP_DEF;
108 	double	x, y;
109 	long	i;
110 	long	reps = REPS_DEF;
111 
112 	if (caph_limit_stdio() < 0)
113 		err(1, "unable to limit rights for stdio");
114 	cap_rights_init(&rights);
115 	if (cap_rights_limit(STDIN_FILENO, &rights) < 0 && errno != ENOSYS)
116 		err(1, "unable to limit rights for stdin");
117 
118 	/*
119 	 * Cache NLS data, for strerror, for err(3), before entering capability
120 	 * mode.
121 	 */
122 	caph_cache_catpages();
123 
124 	if (cap_enter() < 0 && errno != ENOSYS)
125 		err(1, "unable to enter capability mode");
126 
127 	while ((ch = getopt(argc, argv, "b:cnp:rs:w:")) != -1)
128 		switch (ch) {
129 		case 'b':
130 			boring = true;
131 			/* FALLTHROUGH */
132 		case 'w':
133 			if (strlcpy(format, optarg, sizeof(format)) >=
134 			    sizeof(format))
135 				errx(1, "-%c word too long", ch);
136 			have_format = true;
137 			break;
138 		case 'c':
139 			chardata = true;
140 			break;
141 		case 'n':
142 			nofinalnl = true;
143 			break;
144 		case 'p':
145 			prec = atoi(optarg);
146 			if (prec < 0)
147 				errx(1, "bad precision value");
148 			have_format = true;
149 			break;
150 		case 'r':
151 			randomize = true;
152 			break;
153 		case 's':
154 			sepstring = optarg;
155 			break;
156 		default:
157 			usage();
158 		}
159 	argc -= optind;
160 	argv += optind;
161 
162 	switch (argc) {	/* examine args right to left, falling thru cases */
163 	case 4:
164 		if (!is_default(argv[3])) {
165 			if (!sscanf(argv[3], "%lf", &s))
166 				errx(1, "bad s value: %s", argv[3]);
167 			mask |= HAVE_STEP;
168 			if (randomize)
169 				use_random = true;
170 		}
171 		/* FALLTHROUGH */
172 	case 3:
173 		if (!is_default(argv[2])) {
174 			if (!sscanf(argv[2], "%lf", &ender))
175 				ender = argv[2][strlen(argv[2])-1];
176 			mask |= HAVE_ENDER;
177 			if (prec < 0)
178 				n = getprec(argv[2]);
179 		}
180 		/* FALLTHROUGH */
181 	case 2:
182 		if (!is_default(argv[1])) {
183 			if (!sscanf(argv[1], "%lf", &begin))
184 				begin = argv[1][strlen(argv[1])-1];
185 			mask |= HAVE_BEGIN;
186 			if (prec < 0)
187 				prec = getprec(argv[1]);
188 			if (n > prec)		/* maximum precision */
189 				prec = n;
190 		}
191 		/* FALLTHROUGH */
192 	case 1:
193 		if (!is_default(argv[0])) {
194 			if (!sscanf(argv[0], "%ld", &reps))
195 				errx(1, "bad reps value: %s", argv[0]);
196 			mask |= HAVE_REPS;
197 		}
198 		break;
199 	case 0:
200 		usage();
201 	default:
202 		errx(1, "too many arguments.  What do you mean by %s?",
203 		    argv[4]);
204 	}
205 	getformat();
206 
207 	if (prec == -1)
208 		prec = 0;
209 
210 	while (mask)	/* 4 bit mask has 1's where last 4 args were given */
211 		switch (mask) {	/* fill in the 0's by default or computation */
212 		case HAVE_STEP:
213 		case HAVE_ENDER:
214 		case HAVE_ENDER | HAVE_STEP:
215 		case HAVE_BEGIN:
216 		case HAVE_BEGIN | HAVE_STEP:
217 			reps = REPS_DEF;
218 			mask |= HAVE_REPS;
219 			break;
220 		case HAVE_BEGIN | HAVE_ENDER:
221 			s = ender > begin ? 1 : -1;
222 			mask |= HAVE_STEP;
223 			break;
224 		case HAVE_BEGIN | HAVE_ENDER | HAVE_STEP:
225 			if (randomize)
226 				reps = REPS_DEF;
227 			else if (s == 0.0)
228 				reps = 0;
229 			else
230 				reps = (ender - begin + s) / s;
231 			if (reps <= 0)
232 				errx(1, "impossible stepsize");
233 			mask = 0;
234 			break;
235 		case HAVE_REPS:
236 		case HAVE_REPS | HAVE_STEP:
237 			begin = BEGIN_DEF;
238 			mask |= HAVE_BEGIN;
239 			break;
240 		case HAVE_REPS | HAVE_ENDER:
241 			s = STEP_DEF;
242 			mask = HAVE_REPS | HAVE_ENDER | HAVE_STEP;
243 			break;
244 		case HAVE_REPS | HAVE_ENDER | HAVE_STEP:
245 			if (randomize)
246 				begin = BEGIN_DEF;
247 			else if (reps == 0)
248 				errx(1, "must specify begin if reps == 0");
249 			begin = ender - reps * s + s;
250 			mask = 0;
251 			break;
252 		case HAVE_REPS | HAVE_BEGIN:
253 			s = STEP_DEF;
254 			mask = HAVE_REPS | HAVE_BEGIN | HAVE_STEP;
255 			break;
256 		case HAVE_REPS | HAVE_BEGIN | HAVE_STEP:
257 			if (randomize)
258 				ender = ENDER_DEF;
259 			else
260 				ender = begin + reps * s - s;
261 			mask = 0;
262 			break;
263 		case HAVE_REPS | HAVE_BEGIN | HAVE_ENDER:
264 			if (reps == 0)
265 				errx(1, "infinite sequences cannot be bounded");
266 			else if (reps == 1)
267 				s = 0.0;
268 			else
269 				s = (ender - begin) / (reps - 1);
270 			mask = 0;
271 			break;
272 		case HAVE_REPS | HAVE_BEGIN | HAVE_ENDER | HAVE_STEP:
273 			/* if reps given and implied, */
274 			if (!randomize && s != 0.0) {
275 				long t = (ender - begin + s) / s;
276 				if (t <= 0)
277 					errx(1, "impossible stepsize");
278 				if (t < reps)		/* take lesser */
279 					reps = t;
280 			}
281 			mask = 0;
282 			break;
283 		default:
284 			errx(1, "bad mask");
285 		}
286 	if (reps == 0)
287 		infinity = true;
288 	if (randomize) {
289 		if (use_random) {
290 			srandom((unsigned long)s);
291 			divisor = (double)INT32_MAX + 1;
292 		} else
293 			divisor = (double)UINT32_MAX + 1;
294 
295 		/*
296 		 * Attempt to DWIM when the user has specified an
297 		 * integer range within that of the random number
298 		 * generator: distribute the numbers equally in
299 		 * the range [begin .. ender].  Jot's default %.0f
300 		 * format would make the appearance of the first and
301 		 * last specified value half as likely as the rest.
302 		 */
303 		if (!have_format && prec == 0 &&
304 		    begin >= 0 && begin < divisor &&
305 		    ender >= 0 && ender < divisor) {
306 			if (begin <= ender)
307 				ender += 1;
308 			else
309 				begin += 1;
310 			nosign = true;
311 			intdata = true;
312 			(void)strlcpy(format,
313 			    chardata ? "%c" : "%u", sizeof(format));
314 		}
315 		x = ender - begin;
316 		for (i = 1; i <= reps || infinity; i++) {
317 			if (use_random)
318 				y = random() / divisor;
319 			else
320 				y = arc4random() / divisor;
321 			if (putdata(y * x + begin, !(reps - i)))
322 				errx(1, "range error in conversion");
323 		}
324 	} else
325 		for (i = 1, x = begin; i <= reps || infinity; i++, x += s)
326 			if (putdata(x, !(reps - i)))
327 				errx(1, "range error in conversion");
328 	if (!nofinalnl)
329 		putchar('\n');
330 	exit(0);
331 }
332 
333 /*
334  * Send x to stdout using the specified format.
335  * Last is  true if this is the set's last value.
336  * Return 0 if OK, or a positive number if the number passed was
337  * outside the range specified by the various flags.
338  */
339 static int
340 putdata(double x, bool last)
341 {
342 
343 	if (boring)
344 		printf("%s", format);
345 	else if (longdata && nosign) {
346 		if (x <= (double)ULONG_MAX && x >= (double)0)
347 			printf(format, (unsigned long)x);
348 		else
349 			return (1);
350 	} else if (longdata) {
351 		if (x <= (double)LONG_MAX && x >= (double)LONG_MIN)
352 			printf(format, (long)x);
353 		else
354 			return (1);
355 	} else if (chardata || (intdata && !nosign)) {
356 		if (x <= (double)INT_MAX && x >= (double)INT_MIN)
357 			printf(format, (int)x);
358 		else
359 			return (1);
360 	} else if (intdata) {
361 		if (x <= (double)UINT_MAX && x >= (double)0)
362 			printf(format, (unsigned int)x);
363 		else
364 			return (1);
365 
366 	} else
367 		printf(format, x);
368 	if (!last)
369 		fputs(sepstring, stdout);
370 
371 	return (0);
372 }
373 
374 static void
375 usage(void)
376 {
377 	fprintf(stderr, "%s\n%s\n",
378 	"usage: jot [-cnr] [-b word] [-w word] [-s string] [-p precision]",
379 	"           [reps [begin [end [s]]]]");
380 	exit(1);
381 }
382 
383 /*
384  * Return the number of digits following the number's decimal point.
385  * Return 0 if no decimal point is found.
386  */
387 static int
388 getprec(const char *str)
389 {
390 	const char	*p;
391 	const char	*q;
392 
393 	for (p = str; *p; p++)
394 		if (*p == '.')
395 			break;
396 	if (!*p)
397 		return (0);
398 	for (q = ++p; *p; p++)
399 		if (!isdigit((unsigned char)*p))
400 			break;
401 	return (p - q);
402 }
403 
404 /*
405  * Set format, intdata, chardata, longdata, and nosign
406  * based on the command line arguments.
407  */
408 static void
409 getformat(void)
410 {
411 	char	*p, *p2;
412 	int dot, hash, space, sign, numbers = 0;
413 	size_t sz;
414 
415 	if (boring)				/* no need to bother */
416 		return;
417 	for (p = format; *p; p++)		/* look for '%' */
418 		if (*p == '%') {
419 			if (p[1] == '%')
420 				p++;		/* leave %% alone */
421 			else
422 				break;
423 		}
424 	sz = sizeof(format) - strlen(format) - 1;
425 	if (!*p && !chardata) {
426 		if (snprintf(p, sz, "%%.%df", prec) >= (int)sz)
427 			errx(1, "-w word too long");
428 	} else if (!*p && chardata) {
429 		if (strlcpy(p, "%c", sz) >= sz)
430 			errx(1, "-w word too long");
431 		intdata = true;
432 	} else if (!*(p+1)) {
433 		if (sz <= 0)
434 			errx(1, "-w word too long");
435 		strcat(format, "%");		/* cannot end in single '%' */
436 	} else {
437 		/*
438 		 * Allow conversion format specifiers of the form
439 		 * %[#][ ][{+,-}][0-9]*[.[0-9]*]? where ? must be one of
440 		 * [l]{d,i,o,u,x} or {f,e,g,E,G,d,o,x,D,O,U,X,c,u}
441 		 */
442 		p2 = p++;
443 		dot = hash = space = sign = numbers = 0;
444 		while (!isalpha((unsigned char)*p)) {
445 			if (isdigit((unsigned char)*p)) {
446 				numbers++;
447 				p++;
448 			} else if ((*p == '#' && !(numbers|dot|sign|space|
449 			    hash++)) ||
450 			    (*p == ' ' && !(numbers|dot|space++)) ||
451 			    ((*p == '+' || *p == '-') && !(numbers|dot|sign++))
452 			    || (*p == '.' && !(dot++)))
453 				p++;
454 			else
455 				goto fmt_broken;
456 		}
457 		if (*p == 'l') {
458 			longdata = true;
459 			if (*++p == 'l') {
460 				if (p[1] != '\0')
461 					p++;
462 				goto fmt_broken;
463 			}
464 		}
465 		switch (*p) {
466 		case 'o': case 'u': case 'x': case 'X':
467 			intdata = nosign = true;
468 			break;
469 		case 'd': case 'i':
470 			intdata = true;
471 			break;
472 		case 'D':
473 			if (!longdata) {
474 				intdata = true;
475 				break;
476 			}
477 		case 'O': case 'U':
478 			if (!longdata) {
479 				intdata = nosign = true;
480 				break;
481 			}
482 		case 'c':
483 			if (!(intdata | longdata)) {
484 				chardata = true;
485 				break;
486 			}
487 		case 'h': case 'n': case 'p': case 'q': case 's': case 'L':
488 		case '$': case '*':
489 			goto fmt_broken;
490 		case 'f': case 'e': case 'g': case 'E': case 'G':
491 			if (!longdata)
492 				break;
493 			/* FALLTHROUGH */
494 		default:
495 fmt_broken:
496 			*++p = '\0';
497 			errx(1, "illegal or unsupported format '%s'", p2);
498 			/* NOTREACHED */
499 		}
500 		while (*++p)
501 			if (*p == '%' && *(p+1) && *(p+1) != '%')
502 				errx(1, "too many conversions");
503 			else if (*p == '%' && *(p+1) == '%')
504 				p++;
505 			else if (*p == '%' && !*(p+1)) {
506 				if (strlcat(format, "%", sizeof(format)) >=
507 				    sizeof(format))
508 					errx(1, "-w word too long");
509 				break;
510 			}
511 	}
512 }
513