xref: /freebsd/usr.bin/jot/jot.c (revision eb69d1f144a6fcc765d1b9d44a5ae8082353e70b)
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 (cap_rights_limit(STDIN_FILENO, &rights) < 0 && errno != ENOSYS)
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 (cap_enter() < 0 && errno != ENOSYS)
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 (reps == 0)
267 				errx(1, "infinite sequences cannot be bounded");
268 			else if (reps == 1)
269 				s = 0.0;
270 			else
271 				s = (ender - begin) / (reps - 1);
272 			mask = 0;
273 			break;
274 		case HAVE_REPS | HAVE_BEGIN | HAVE_ENDER | HAVE_STEP:
275 			/* if reps given and implied, */
276 			if (!randomize && s != 0.0) {
277 				long t = (ender - begin + s) / s;
278 				if (t <= 0)
279 					errx(1, "impossible stepsize");
280 				if (t < reps)		/* take lesser */
281 					reps = t;
282 			}
283 			mask = 0;
284 			break;
285 		default:
286 			errx(1, "bad mask");
287 		}
288 	if (reps == 0)
289 		infinity = true;
290 	if (randomize) {
291 		if (use_random) {
292 			srandom((unsigned long)s);
293 			divisor = (double)INT32_MAX + 1;
294 		} else
295 			divisor = (double)UINT32_MAX + 1;
296 
297 		/*
298 		 * Attempt to DWIM when the user has specified an
299 		 * integer range within that of the random number
300 		 * generator: distribute the numbers equally in
301 		 * the range [begin .. ender].  Jot's default %.0f
302 		 * format would make the appearance of the first and
303 		 * last specified value half as likely as the rest.
304 		 */
305 		if (!have_format && prec == 0 &&
306 		    begin >= 0 && begin < divisor &&
307 		    ender >= 0 && ender < divisor) {
308 			if (begin <= ender)
309 				ender += 1;
310 			else
311 				begin += 1;
312 			nosign = true;
313 			intdata = true;
314 			(void)strlcpy(format,
315 			    chardata ? "%c" : "%u", sizeof(format));
316 		}
317 		x = ender - begin;
318 		for (i = 1; i <= reps || infinity; i++) {
319 			if (use_random)
320 				y = random() / divisor;
321 			else
322 				y = arc4random() / divisor;
323 			if (putdata(y * x + begin, !(reps - i)))
324 				errx(1, "range error in conversion");
325 		}
326 	} else
327 		for (i = 1, x = begin; i <= reps || infinity; i++, x += s)
328 			if (putdata(x, !(reps - i)))
329 				errx(1, "range error in conversion");
330 	if (!nofinalnl)
331 		putchar('\n');
332 	exit(0);
333 }
334 
335 /*
336  * Send x to stdout using the specified format.
337  * Last is  true if this is the set's last value.
338  * Return 0 if OK, or a positive number if the number passed was
339  * outside the range specified by the various flags.
340  */
341 static int
342 putdata(double x, bool last)
343 {
344 
345 	if (boring)
346 		printf("%s", format);
347 	else if (longdata && nosign) {
348 		if (x <= (double)ULONG_MAX && x >= (double)0)
349 			printf(format, (unsigned long)x);
350 		else
351 			return (1);
352 	} else if (longdata) {
353 		if (x <= (double)LONG_MAX && x >= (double)LONG_MIN)
354 			printf(format, (long)x);
355 		else
356 			return (1);
357 	} else if (chardata || (intdata && !nosign)) {
358 		if (x <= (double)INT_MAX && x >= (double)INT_MIN)
359 			printf(format, (int)x);
360 		else
361 			return (1);
362 	} else if (intdata) {
363 		if (x <= (double)UINT_MAX && x >= (double)0)
364 			printf(format, (unsigned int)x);
365 		else
366 			return (1);
367 
368 	} else
369 		printf(format, x);
370 	if (!last)
371 		fputs(sepstring, stdout);
372 
373 	return (0);
374 }
375 
376 static void
377 usage(void)
378 {
379 	fprintf(stderr, "%s\n%s\n",
380 	"usage: jot [-cnr] [-b word] [-w word] [-s string] [-p precision]",
381 	"           [reps [begin [end [s]]]]");
382 	exit(1);
383 }
384 
385 /*
386  * Return the number of digits following the number's decimal point.
387  * Return 0 if no decimal point is found.
388  */
389 static int
390 getprec(const char *str)
391 {
392 	const char	*p;
393 	const char	*q;
394 
395 	for (p = str; *p; p++)
396 		if (*p == '.')
397 			break;
398 	if (!*p)
399 		return (0);
400 	for (q = ++p; *p; p++)
401 		if (!isdigit((unsigned char)*p))
402 			break;
403 	return (p - q);
404 }
405 
406 /*
407  * Set format, intdata, chardata, longdata, and nosign
408  * based on the command line arguments.
409  */
410 static void
411 getformat(void)
412 {
413 	char	*p, *p2;
414 	int dot, hash, space, sign, numbers = 0;
415 	size_t sz;
416 
417 	if (boring)				/* no need to bother */
418 		return;
419 	for (p = format; *p; p++)		/* look for '%' */
420 		if (*p == '%') {
421 			if (p[1] == '%')
422 				p++;		/* leave %% alone */
423 			else
424 				break;
425 		}
426 	sz = sizeof(format) - strlen(format) - 1;
427 	if (!*p && !chardata) {
428 		if (snprintf(p, sz, "%%.%df", prec) >= (int)sz)
429 			errx(1, "-w word too long");
430 	} else if (!*p && chardata) {
431 		if (strlcpy(p, "%c", sz) >= sz)
432 			errx(1, "-w word too long");
433 		intdata = true;
434 	} else if (!*(p+1)) {
435 		if (sz <= 0)
436 			errx(1, "-w word too long");
437 		strcat(format, "%");		/* cannot end in single '%' */
438 	} else {
439 		/*
440 		 * Allow conversion format specifiers of the form
441 		 * %[#][ ][{+,-}][0-9]*[.[0-9]*]? where ? must be one of
442 		 * [l]{d,i,o,u,x} or {f,e,g,E,G,d,o,x,D,O,U,X,c,u}
443 		 */
444 		p2 = p++;
445 		dot = hash = space = sign = numbers = 0;
446 		while (!isalpha((unsigned char)*p)) {
447 			if (isdigit((unsigned char)*p)) {
448 				numbers++;
449 				p++;
450 			} else if ((*p == '#' && !(numbers|dot|sign|space|
451 			    hash++)) ||
452 			    (*p == ' ' && !(numbers|dot|space++)) ||
453 			    ((*p == '+' || *p == '-') && !(numbers|dot|sign++))
454 			    || (*p == '.' && !(dot++)))
455 				p++;
456 			else
457 				goto fmt_broken;
458 		}
459 		if (*p == 'l') {
460 			longdata = true;
461 			if (*++p == 'l') {
462 				if (p[1] != '\0')
463 					p++;
464 				goto fmt_broken;
465 			}
466 		}
467 		switch (*p) {
468 		case 'o': case 'u': case 'x': case 'X':
469 			intdata = nosign = true;
470 			break;
471 		case 'd': case 'i':
472 			intdata = true;
473 			break;
474 		case 'D':
475 			if (!longdata) {
476 				intdata = true;
477 				break;
478 			}
479 		case 'O': case 'U':
480 			if (!longdata) {
481 				intdata = nosign = true;
482 				break;
483 			}
484 		case 'c':
485 			if (!(intdata | longdata)) {
486 				chardata = true;
487 				break;
488 			}
489 		case 'h': case 'n': case 'p': case 'q': case 's': case 'L':
490 		case '$': case '*':
491 			goto fmt_broken;
492 		case 'f': case 'e': case 'g': case 'E': case 'G':
493 			if (!longdata)
494 				break;
495 			/* FALLTHROUGH */
496 		default:
497 fmt_broken:
498 			*++p = '\0';
499 			errx(1, "illegal or unsupported format '%s'", p2);
500 			/* NOTREACHED */
501 		}
502 		while (*++p)
503 			if (*p == '%' && *(p+1) && *(p+1) != '%')
504 				errx(1, "too many conversions");
505 			else if (*p == '%' && *(p+1) == '%')
506 				p++;
507 			else if (*p == '%' && !*(p+1)) {
508 				if (strlcat(format, "%", sizeof(format)) >=
509 				    sizeof(format))
510 					errx(1, "-w word too long");
511 				break;
512 			}
513 	}
514 }
515