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