xref: /freebsd/usr.bin/jot/jot.c (revision bdcbfde31e8e9b343f113a1956384bdf30d1ed62)
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 #endif
40 #include <sys/cdefs.h>
41 /*
42  * jot - print sequential or random data
43  *
44  * Author:  John Kunze, Office of Comp. Affairs, UCB
45  */
46 
47 #include <sys/capsicum.h>
48 #include <capsicum_helpers.h>
49 #include <ctype.h>
50 #include <err.h>
51 #include <errno.h>
52 #include <limits.h>
53 #include <stdio.h>
54 #include <stdint.h>
55 #include <stdlib.h>
56 #include <stdbool.h>
57 #include <string.h>
58 #include <time.h>
59 #include <unistd.h>
60 
61 /* Defaults */
62 #define	REPS_DEF	100
63 #define	BEGIN_DEF	1
64 #define	ENDER_DEF	100
65 #define	STEP_DEF	1
66 
67 /* Flags of options that have been set */
68 #define HAVE_STEP	1
69 #define HAVE_ENDER	2
70 #define HAVE_BEGIN	4
71 #define HAVE_REPS	8
72 
73 #define	is_default(s)	(*(s) == 0 || strcmp((s), "-") == 0)
74 
75 static bool	boring;
76 static int	prec = -1;
77 static bool	longdata;
78 static bool	intdata;
79 static bool	chardata;
80 static bool	nosign;
81 static const	char *sepstring = "\n";
82 static char	format[BUFSIZ];
83 
84 static void	getformat(void);
85 static int	getprec(const char *);
86 static int	putdata(double, bool);
87 static void	usage(void);
88 
89 int
90 main(int argc, char **argv)
91 {
92 	cap_rights_t rights;
93 	bool	have_format = false;
94 	bool	infinity = false;
95 	bool	nofinalnl = false;
96 	bool	randomize = false;
97 	bool	use_random = false;
98 	int	ch;
99 	int	mask = 0;
100 	int	n = 0;
101 	double	begin = BEGIN_DEF;
102 	double	divisor;
103 	double	ender = ENDER_DEF;
104 	double	s = STEP_DEF;
105 	double	x, y;
106 	long	i;
107 	long	reps = REPS_DEF;
108 
109 	if (caph_limit_stdio() < 0)
110 		err(1, "unable to limit rights for stdio");
111 	cap_rights_init(&rights);
112 	if (caph_rights_limit(STDIN_FILENO, &rights) < 0)
113 		err(1, "unable to limit rights for stdin");
114 
115 	/*
116 	 * Cache NLS data, for strerror, for err(3), before entering capability
117 	 * mode.
118 	 */
119 	caph_cache_catpages();
120 
121 	if (caph_enter() < 0)
122 		err(1, "unable to enter capability mode");
123 
124 	while ((ch = getopt(argc, argv, "b:cnp:rs:w:")) != -1)
125 		switch (ch) {
126 		case 'b':
127 			boring = true;
128 			/* FALLTHROUGH */
129 		case 'w':
130 			if (strlcpy(format, optarg, sizeof(format)) >=
131 			    sizeof(format))
132 				errx(1, "-%c word too long", ch);
133 			have_format = true;
134 			break;
135 		case 'c':
136 			chardata = true;
137 			break;
138 		case 'n':
139 			nofinalnl = true;
140 			break;
141 		case 'p':
142 			prec = atoi(optarg);
143 			if (prec < 0)
144 				errx(1, "bad precision value");
145 			have_format = true;
146 			break;
147 		case 'r':
148 			randomize = true;
149 			break;
150 		case 's':
151 			sepstring = optarg;
152 			break;
153 		default:
154 			usage();
155 		}
156 	argc -= optind;
157 	argv += optind;
158 
159 	switch (argc) {	/* examine args right to left, falling thru cases */
160 	case 4:
161 		if (!is_default(argv[3])) {
162 			if (!sscanf(argv[3], "%lf", &s))
163 				errx(1, "bad s value: %s", argv[3]);
164 			mask |= HAVE_STEP;
165 			if (randomize)
166 				use_random = true;
167 		}
168 		/* FALLTHROUGH */
169 	case 3:
170 		if (!is_default(argv[2])) {
171 			if (!sscanf(argv[2], "%lf", &ender))
172 				ender = argv[2][strlen(argv[2])-1];
173 			mask |= HAVE_ENDER;
174 			if (prec < 0)
175 				n = getprec(argv[2]);
176 		}
177 		/* FALLTHROUGH */
178 	case 2:
179 		if (!is_default(argv[1])) {
180 			if (!sscanf(argv[1], "%lf", &begin))
181 				begin = argv[1][strlen(argv[1])-1];
182 			mask |= HAVE_BEGIN;
183 			if (prec < 0)
184 				prec = getprec(argv[1]);
185 			if (n > prec)		/* maximum precision */
186 				prec = n;
187 		}
188 		/* FALLTHROUGH */
189 	case 1:
190 		if (!is_default(argv[0])) {
191 			if (!sscanf(argv[0], "%ld", &reps))
192 				errx(1, "bad reps value: %s", argv[0]);
193 			mask |= HAVE_REPS;
194 		}
195 		break;
196 	case 0:
197 		usage();
198 	default:
199 		errx(1, "too many arguments.  What do you mean by %s?",
200 		    argv[4]);
201 	}
202 	getformat();
203 
204 	if (prec == -1)
205 		prec = 0;
206 
207 	while (mask)	/* 4 bit mask has 1's where last 4 args were given */
208 		switch (mask) {	/* fill in the 0's by default or computation */
209 		case HAVE_STEP:
210 		case HAVE_ENDER:
211 		case HAVE_ENDER | HAVE_STEP:
212 		case HAVE_BEGIN:
213 		case HAVE_BEGIN | HAVE_STEP:
214 			reps = REPS_DEF;
215 			mask |= HAVE_REPS;
216 			break;
217 		case HAVE_BEGIN | HAVE_ENDER:
218 			s = ender > begin ? 1 : -1;
219 			mask |= HAVE_STEP;
220 			break;
221 		case HAVE_BEGIN | HAVE_ENDER | HAVE_STEP:
222 			if (randomize)
223 				reps = REPS_DEF;
224 			else if (s == 0.0)
225 				reps = 0;
226 			else
227 				reps = (ender - begin + s) / s;
228 			if (reps <= 0)
229 				errx(1, "impossible stepsize");
230 			mask = 0;
231 			break;
232 		case HAVE_REPS:
233 		case HAVE_REPS | HAVE_STEP:
234 			begin = BEGIN_DEF;
235 			mask |= HAVE_BEGIN;
236 			break;
237 		case HAVE_REPS | HAVE_ENDER:
238 			s = STEP_DEF;
239 			mask = HAVE_REPS | HAVE_ENDER | HAVE_STEP;
240 			break;
241 		case HAVE_REPS | HAVE_ENDER | HAVE_STEP:
242 			if (randomize)
243 				begin = BEGIN_DEF;
244 			else if (reps == 0)
245 				errx(1, "must specify begin if reps == 0");
246 			begin = ender - reps * s + s;
247 			mask = 0;
248 			break;
249 		case HAVE_REPS | HAVE_BEGIN:
250 			s = STEP_DEF;
251 			mask = HAVE_REPS | HAVE_BEGIN | HAVE_STEP;
252 			break;
253 		case HAVE_REPS | HAVE_BEGIN | HAVE_STEP:
254 			if (randomize)
255 				ender = ENDER_DEF;
256 			else
257 				ender = begin + reps * s - s;
258 			mask = 0;
259 			break;
260 		case HAVE_REPS | HAVE_BEGIN | HAVE_ENDER:
261 			if (!randomize) {
262 				if (reps == 0)
263 					errx(1, "infinite sequences cannot "
264 					    "be bounded");
265 				else if (reps == 1)
266 					s = 0.0;
267 				else
268 					s = (ender - begin) / (reps - 1);
269 			}
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