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