xref: /openbsd/games/fortune/fortune/fortune.c (revision 1d26f69e)
1 /*	$OpenBSD: fortune.c,v 1.67 2024/10/21 06:39:03 tb Exp $	*/
2 /*	$NetBSD: fortune.c,v 1.8 1995/03/23 08:28:40 cgd Exp $	*/
3 
4 /*-
5  * Copyright (c) 1986, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Ken Arnold.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/stat.h>
37 
38 #include <assert.h>
39 #include <ctype.h>
40 #include <dirent.h>
41 #include <err.h>
42 #include <fcntl.h>
43 #include <limits.h>
44 #include <locale.h>
45 #include <stdbool.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <regex.h>
50 #include <unistd.h>
51 
52 #include "pathnames.h"
53 #include "strfile.h"
54 
55 #define	MINW	6		/* minimum wait if desired */
56 #define	CPERS	20		/* # of chars for each sec */
57 #define	SLEN	160		/* # of chars in short fortune */
58 
59 #define	POS_UNKNOWN	((int32_t) -1)	/* pos for file unknown */
60 #define	NO_PROB		(-1)		/* no prob specified for file */
61 
62 #ifdef DEBUG
63 #define	DPRINTF(l,x)	if (Debug >= l) fprintf x; else
64 #undef		NDEBUG
65 #else
66 #define	DPRINTF(l,x)
67 #define	NDEBUG	1
68 #endif
69 
70 typedef struct fd {
71 	int		percent;
72 	int		fd, datfd;
73 	int32_t		pos;
74 	FILE		*inf;
75 	char		*name;
76 	char		*path;
77 	char		*datfile;
78 	bool		read_tbl;
79 	STRFILE		tbl;
80 	int		num_children;
81 	struct fd	*child, *parent;
82 	struct fd	*next, *prev;
83 } FILEDESC;
84 
85 bool	Found_one	= false;	/* did we find a match? */
86 bool	Find_files	= false;	/* display a list of fortune files */
87 bool	Wait		= false;	/* wait desired after fortune */
88 bool	Short_only	= false;	/* short fortune desired */
89 bool	Long_only	= false;	/* long fortune desired */
90 bool	Offend		= false;	/* offensive fortunes only */
91 bool	All_forts	= false;	/* any fortune allowed */
92 bool	Equal_probs	= false;	/* scatter un-allocted prob equally */
93 bool	Match		= false;	/* dump fortunes matching a pattern */
94 #ifdef DEBUG
95 int	Debug = 0;			/* print debug messages */
96 #endif
97 
98 char	*Fortbuf = NULL;			/* fortune buffer for -m */
99 
100 size_t	Fort_len = 0;
101 
102 int32_t	Seekpts[2];			/* seek pointers to fortunes */
103 
104 FILEDESC	*File_list = NULL,	/* Head of file list */
105 		*File_tail = NULL;	/* Tail of file list */
106 FILEDESC	*Fortfile;		/* Fortune file to use */
107 
108 STRFILE		Noprob_tbl;		/* sum of data for all no prob files */
109 
110 int	 add_dir(FILEDESC *);
111 int	 add_file(int,
112 	    char *, char *, FILEDESC **, FILEDESC **, FILEDESC *);
113 void	 all_forts(FILEDESC *, char *);
114 char	*copy(char *, char *);
115 void	 display(FILEDESC *);
116 int	 form_file_list(char **, int);
117 int	 fortlen(void);
118 void	 get_fort(void);
119 void	 get_pos(FILEDESC *);
120 void	 get_tbl(FILEDESC *);
121 void	 getargs(int, char *[]);
122 void	 init_prob(void);
123 int	 is_dir(char *);
124 int	 is_fortfile(char *, char **, int);
125 int	 is_off_name(char *);
126 int	 max(int, int);
127 FILEDESC *
128 	 new_fp(void);
129 char	*off_name(char *);
130 void	 open_dat(FILEDESC *);
131 void	 open_fp(FILEDESC *);
132 FILEDESC *
133 	 pick_child(FILEDESC *);
134 void	 print_file_list(void);
135 void	 print_list(FILEDESC *, int);
136 void	 rot13(char *, size_t);
137 void	 sanitize(unsigned char *cp);
138 void	 sum_noprobs(FILEDESC *);
139 void	 sum_tbl(STRFILE *, STRFILE *);
140 __dead void	 usage(void);
141 void	 zero_tbl(STRFILE *);
142 
143 int	 find_matches(void);
144 void	 matches_in_list(FILEDESC *);
145 int	 maxlen_in_list(FILEDESC *);
146 int	 minlen_in_list(FILEDESC *);
147 regex_t regex;
148 
149 int
main(int ac,char * av[])150 main(int ac, char *av[])
151 {
152 	setlocale(LC_CTYPE, "");
153 
154 	if (pledge("stdio rpath", NULL) == -1) {
155 		perror("pledge");
156 		return 1;
157 	}
158 
159 	getargs(ac, av);
160 
161 	if (Match)
162 		return find_matches() == 0;
163 
164 	init_prob();
165 	if ((Short_only && minlen_in_list(File_list) > SLEN) ||
166 	    (Long_only && maxlen_in_list(File_list) <= SLEN)) {
167 		fprintf(stderr,
168 		    "no fortunes matching length constraint found\n");
169 		return 1;
170 	}
171 
172 	do {
173 		get_fort();
174 	} while ((Short_only && fortlen() > SLEN) ||
175 		 (Long_only && fortlen() <= SLEN));
176 
177 	display(Fortfile);
178 
179 	if (Wait) {
180 		if (Fort_len == 0)
181 			(void) fortlen();
182 		sleep((unsigned int) max(Fort_len / CPERS, MINW));
183 	}
184 	return 0;
185 }
186 
187 void
rot13(char * p,size_t len)188 rot13(char *p, size_t len)
189 {
190 	while (len--) {
191 		unsigned char ch = *p;
192 		if (isupper(ch))
193 			*p = 'A' + (ch - 'A' + 13) % 26;
194 		else if (islower(ch))
195 			*p = 'a' + (ch - 'a' + 13) % 26;
196 		p++;
197 	}
198 }
199 
200 void
sanitize(unsigned char * cp)201 sanitize(unsigned char *cp)
202 {
203 	if (MB_CUR_MAX > 1)
204 		return;
205 	for (; *cp != '\0'; cp++)
206 		if (!isprint(*cp) && !isspace(*cp) && *cp != '\b')
207 			*cp = '?';
208 }
209 
210 void
display(FILEDESC * fp)211 display(FILEDESC *fp)
212 {
213 	char	line[BUFSIZ];
214 
215 	open_fp(fp);
216 	(void) fseek(fp->inf, (long)Seekpts[0], SEEK_SET);
217 	for (Fort_len = 0; fgets(line, sizeof line, fp->inf) != NULL &&
218 	    !STR_ENDSTRING(line, fp->tbl); Fort_len++) {
219 		if (fp->tbl.str_flags & STR_ROTATED)
220 			rot13(line, strlen(line));
221 		sanitize(line);
222 		fputs(line, stdout);
223 	}
224 	(void) fflush(stdout);
225 }
226 
227 /*
228  * fortlen:
229  *	Return the length of the fortune.
230  */
231 int
fortlen(void)232 fortlen(void)
233 {
234 	size_t	nchar;
235 	char	line[BUFSIZ];
236 
237 	if (!(Fortfile->tbl.str_flags & (STR_RANDOM | STR_ORDERED)))
238 		nchar = Seekpts[1] - Seekpts[0];
239 	else {
240 		open_fp(Fortfile);
241 		(void) fseek(Fortfile->inf, (long)Seekpts[0], SEEK_SET);
242 		nchar = 0;
243 		while (fgets(line, sizeof line, Fortfile->inf) != NULL &&
244 		       !STR_ENDSTRING(line, Fortfile->tbl))
245 			nchar += strlen(line);
246 	}
247 	Fort_len = nchar;
248 	return nchar;
249 }
250 
251 /*
252  *	This routine evaluates the arguments on the command line
253  */
254 void
getargs(int argc,char * argv[])255 getargs(int argc, char *argv[])
256 {
257 	int	ignore_case;
258 	char	*pat = NULL;
259 	int ch;
260 
261 	ignore_case = 0;
262 
263 #ifdef DEBUG
264 	while ((ch = getopt(argc, argv, "aDefhilm:osw")) != -1)
265 #else
266 	while ((ch = getopt(argc, argv, "aefhilm:osw")) != -1)
267 #endif /* DEBUG */
268 		switch(ch) {
269 		case 'a':		/* any fortune */
270 			All_forts = true;
271 			break;
272 #ifdef DEBUG
273 		case 'D':
274 			Debug++;
275 			break;
276 #endif /* DEBUG */
277 		case 'e':		/* scatter un-allocted prob equally */
278 			Equal_probs = true;
279 			break;
280 		case 'f':		/* find fortune files */
281 			Find_files = true;
282 			break;
283 		case 'l':		/* long ones only */
284 			Long_only = true;
285 			Short_only = false;
286 			break;
287 		case 'o':		/* offensive ones only */
288 			Offend = true;
289 			break;
290 		case 's':		/* short ones only */
291 			Short_only = true;
292 			Long_only = false;
293 			break;
294 		case 'w':		/* give time to read */
295 			Wait = true;
296 			break;
297 		case 'm':			/* dump out the fortunes */
298 			Match = true;
299 			pat = optarg;
300 			break;
301 		case 'i':			/* case-insensitive match */
302 			ignore_case = 1;
303 			break;
304 		case 'h':
305 		default:
306 			usage();
307 		}
308 	argc -= optind;
309 	argv += optind;
310 
311 	if (!form_file_list(argv, argc))
312 		exit(1);	/* errors printed through form_file_list() */
313 #ifdef DEBUG
314 	if (Debug >= 1)
315 		print_file_list();
316 #endif /* DEBUG */
317 	if (Find_files) {
318 		print_file_list();
319 		exit(0);
320 	}
321 
322 	if (pat != NULL) {
323 		if (regcomp(&regex, pat, ignore_case ? REG_ICASE : 0))
324 			fprintf(stderr, "bad pattern: %s\n", pat);
325 	}
326 }
327 
328 /*
329  * form_file_list:
330  *	Form the file list from the file specifications.
331  */
332 int
form_file_list(char ** files,int file_cnt)333 form_file_list(char **files, int file_cnt)
334 {
335 	int	i, percent;
336 	char	*sp;
337 
338 	if (file_cnt == 0) {
339 		if (Find_files)
340 			return add_file(NO_PROB, FORTDIR, NULL, &File_list,
341 					&File_tail, NULL);
342 		else
343 			return add_file(NO_PROB, "fortunes", FORTDIR,
344 					&File_list, &File_tail, NULL);
345 	}
346 	for (i = 0; i < file_cnt; i++) {
347 		percent = NO_PROB;
348 
349 		if (isdigit((unsigned char)files[i][0])) {
350 			int pos = strspn(files[i], "0123456789.");
351 
352 			/*
353 			 * Only try to interpret files[i] as a percentage if
354 			 * it ends in '%'. Otherwise assume it's a file name.
355 			 */
356 			if (files[i][pos] == '%' && files[i][pos+1] == '\0') {
357 				const char *errstr;
358 				char *prefix;
359 
360 				if ((prefix = strndup(files[i], pos)) == NULL)
361 					err(1, NULL);
362 				if (strchr(prefix, '.') != NULL)
363 					errx(1, "percentages must be integers");
364 				percent = strtonum(prefix, 0, 100, &errstr);
365 				if (errstr != NULL)
366 					errx(1, "percentage is %s: %s", errstr,
367 					    prefix);
368 				free(prefix);
369 
370 				if (++i >= file_cnt)
371 					errx(1,
372 					    "percentages must precede files");
373 			}
374 		}
375 		sp = files[i];
376 		if (strcmp(sp, "all") == 0)
377 			sp = FORTDIR;
378 		if (!add_file(percent, sp, NULL, &File_list, &File_tail, NULL))
379 			return 0;
380 	}
381 	return 1;
382 }
383 
384 /*
385  * add_file:
386  *	Add a file to the file list.
387  */
388 int
add_file(int percent,char * file,char * dir,FILEDESC ** head,FILEDESC ** tail,FILEDESC * parent)389 add_file(int percent, char *file, char *dir, FILEDESC **head, FILEDESC **tail,
390     FILEDESC *parent)
391 {
392 	FILEDESC	*fp;
393 	int		fd;
394 	char		*path, *offensive;
395 	bool		was_malloc;
396 	bool		isdir;
397 
398 	if (dir == NULL) {
399 		path = file;
400 		was_malloc = false;
401 	} else {
402 		if (asprintf(&path, "%s/%s", dir, file) == -1)
403 			err(1, NULL);
404 		was_malloc = true;
405 	}
406 	if ((isdir = is_dir(path)) && parent != NULL) {
407 		if (was_malloc)
408 			free(path);
409 		return 0;	/* don't recurse */
410 	}
411 	offensive = NULL;
412 	if (!isdir && parent == NULL && (All_forts || Offend) &&
413 	    !is_off_name(path)) {
414 		offensive = off_name(path);
415 		if (Offend) {
416 			if (was_malloc)
417 				free(path);
418 			path = offensive;
419 			offensive = NULL;
420 			file = off_name(file);
421 			was_malloc = true;
422 		}
423 	}
424 
425 	DPRINTF(1, (stderr, "adding file \"%s\"\n", path));
426 over:
427 	if ((fd = open(path, O_RDONLY)) < 0) {
428 		/*
429 		 * This is a sneak.  If the user said -a, and if the
430 		 * file we're given isn't a file, we check to see if
431 		 * there is a -o version.  If there is, we treat it as
432 		 * if *that* were the file given.  We only do this for
433 		 * individual files -- if we're scanning a directory,
434 		 * we'll pick up the -o file anyway.
435 		 */
436 		if (All_forts && offensive != NULL) {
437 			if (was_malloc)
438 				free(path);
439 			path = offensive;
440 			offensive = NULL;
441 			was_malloc = true;
442 			DPRINTF(1, (stderr, "\ttrying \"%s\"\n", path));
443 			file = off_name(file);
444 			goto over;
445 		}
446 		if (dir == NULL && file[0] != '/')
447 			return add_file(percent, file, FORTDIR, head, tail,
448 					parent);
449 		if (parent == NULL)
450 			perror(path);
451 		if (was_malloc)
452 			free(path);
453 		return 0;
454 	}
455 
456 	DPRINTF(2, (stderr, "path = \"%s\"\n", path));
457 
458 	fp = new_fp();
459 	fp->fd = fd;
460 	fp->percent = percent;
461 	fp->name = file;
462 	fp->path = path;
463 	fp->parent = parent;
464 
465 	if ((isdir && !add_dir(fp)) ||
466 	    (!isdir &&
467 	     !is_fortfile(path, &fp->datfile, (parent != NULL))))
468 	{
469 		if (parent == NULL)
470 			fprintf(stderr,
471 				"fortune: %s not a fortune file or directory\n",
472 				path);
473 		if (was_malloc)
474 			free(path);
475 		free(fp->datfile);
476 		free((char *) fp);
477 		free(offensive);
478 		return 0;
479 	}
480 	/*
481 	 * If the user said -a, we need to make this node a pointer to
482 	 * both files, if there are two.  We don't need to do this if
483 	 * we are scanning a directory, since the scan will pick up the
484 	 * -o file anyway.
485 	 */
486 	if (All_forts && parent == NULL && !is_off_name(path))
487 		all_forts(fp, offensive);
488 	if (*head == NULL)
489 		*head = *tail = fp;
490 	else if (fp->percent == NO_PROB) {
491 		(*tail)->next = fp;
492 		fp->prev = *tail;
493 		*tail = fp;
494 	}
495 	else {
496 		(*head)->prev = fp;
497 		fp->next = *head;
498 		*head = fp;
499 	}
500 
501 	return 1;
502 }
503 
504 /*
505  * new_fp:
506  *	Return a pointer to an initialized new FILEDESC.
507  */
508 FILEDESC *
new_fp(void)509 new_fp(void)
510 {
511 	FILEDESC	*fp;
512 
513 	if ((fp = malloc(sizeof *fp)) == NULL)
514 		err(1, NULL);
515 	fp->datfd = -1;
516 	fp->pos = POS_UNKNOWN;
517 	fp->inf = NULL;
518 	fp->fd = -1;
519 	fp->percent = NO_PROB;
520 	fp->read_tbl = 0;
521 	fp->next = NULL;
522 	fp->prev = NULL;
523 	fp->child = NULL;
524 	fp->parent = NULL;
525 	fp->datfile = NULL;
526 	return fp;
527 }
528 
529 /*
530  * off_name:
531  *	Return a pointer to the offensive version of a file of this name.
532  */
533 char *
off_name(char * file)534 off_name(char *file)
535 {
536 	return (copy(file, "-o"));
537 }
538 
539 /*
540  * is_off_name:
541  *	Is the file an offensive-style name?
542  */
543 int
is_off_name(char * file)544 is_off_name(char *file)
545 {
546 	int	len;
547 
548 	len = strlen(file);
549 	return (len >= 3 && file[len - 2] == '-' && file[len - 1] == 'o');
550 }
551 
552 /*
553  * all_forts:
554  *	Modify a FILEDESC element to be the parent of two children if
555  *	there are two children to be a parent of.
556  */
557 void
all_forts(FILEDESC * fp,char * offensive)558 all_forts(FILEDESC *fp, char *offensive)
559 {
560 	char		*sp;
561 	FILEDESC	*scene, *obscene;
562 	int		fd;
563 	char		*datfile;
564 
565 	if (fp->child != NULL)	/* this is a directory, not a file */
566 		return;
567 	if (!is_fortfile(offensive, &datfile, 0))
568 		return;
569 	if ((fd = open(offensive, O_RDONLY)) < 0)
570 		return;
571 	DPRINTF(1, (stderr, "adding \"%s\" because of -a\n", offensive));
572 	scene = new_fp();
573 	obscene = new_fp();
574 	*scene = *fp;
575 
576 	fp->num_children = 2;
577 	fp->child = scene;
578 	scene->next = obscene;
579 	obscene->next = NULL;
580 	scene->child = obscene->child = NULL;
581 	scene->parent = obscene->parent = fp;
582 
583 	fp->fd = -1;
584 	scene->percent = obscene->percent = NO_PROB;
585 
586 	obscene->fd = fd;
587 	obscene->inf = NULL;
588 	obscene->path = offensive;
589 	if ((sp = strrchr(offensive, '/')) == NULL)
590 		obscene->name = offensive;
591 	else
592 		obscene->name = ++sp;
593 	obscene->datfile = datfile;
594 	obscene->read_tbl = 0;
595 }
596 
597 /*
598  * add_dir:
599  *	Add the contents of an entire directory.
600  */
601 int
add_dir(FILEDESC * fp)602 add_dir(FILEDESC *fp)
603 {
604 	DIR		*dir;
605 	struct dirent  *dirent;
606 	FILEDESC	*tailp;
607 	char		*name;
608 
609 	(void) close(fp->fd);
610 	fp->fd = -1;
611 	if ((dir = opendir(fp->path)) == NULL) {
612 		perror(fp->path);
613 		return 0;
614 	}
615 	tailp = NULL;
616 	DPRINTF(1, (stderr, "adding dir \"%s\"\n", fp->path));
617 	fp->num_children = 0;
618 	while ((dirent = readdir(dir)) != NULL) {
619 		if (dirent->d_namlen == 0)
620 			continue;
621 		name = copy(dirent->d_name, NULL);
622 		if (add_file(NO_PROB, name, fp->path, &fp->child, &tailp, fp))
623 			fp->num_children++;
624 		else
625 			free(name);
626 	}
627 	if (fp->num_children == 0) {
628 		(void) fprintf(stderr,
629 		    "fortune: %s: No fortune files in directory.\n", fp->path);
630 		closedir(dir);
631 		return 0;
632 	}
633 	closedir(dir);
634 	return 1;
635 }
636 
637 /*
638  * is_dir:
639  *	Return 1 if the file is a directory, 0 otherwise.
640  */
641 int
is_dir(char * file)642 is_dir(char *file)
643 {
644 	struct stat	sbuf;
645 
646 	if (stat(file, &sbuf) < 0)
647 		return 0;
648 	return S_ISDIR(sbuf.st_mode);
649 }
650 
651 /*
652  * is_fortfile:
653  *	Return 1 if the file is a fortune database file.  We try and
654  *	exclude files without reading them if possible to avoid
655  *	overhead.  Files which start with ".", or which have "illegal"
656  *	suffixes, as contained in suflist[], are ruled out.
657  */
658 int
is_fortfile(char * file,char ** datp,int check_for_offend)659 is_fortfile(char *file, char **datp, int check_for_offend)
660 {
661 	int	i;
662 	char	*sp;
663 	char	*datfile;
664 	static char	*suflist[] = {	/* list of "illegal" suffixes" */
665 				"dat", "pos", "c", "h", "p", "i", "f",
666 				"pas", "ftn", "ins.c", "ins,pas",
667 				"ins.ftn", "sml",
668 				NULL
669 			};
670 
671 	DPRINTF(2, (stderr, "is_fortfile(%s) returns ", file));
672 
673 	/*
674 	 * Preclude any -o files for offendable people, and any non -o
675 	 * files for completely offensive people.
676 	 */
677 	if (check_for_offend && !All_forts) {
678 		i = strlen(file);
679 		if (Offend ^ (file[i - 2] == '-' && file[i - 1] == 'o'))
680 			return 0;
681 	}
682 
683 	if ((sp = strrchr(file, '/')) == NULL)
684 		sp = file;
685 	else
686 		sp++;
687 	if (*sp == '.') {
688 		DPRINTF(2, (stderr, "0 (file starts with '.')\n"));
689 		return 0;
690 	}
691 	if ((sp = strrchr(sp, '.')) != NULL) {
692 		sp++;
693 		for (i = 0; suflist[i] != NULL; i++)
694 			if (strcmp(sp, suflist[i]) == 0) {
695 				DPRINTF(2, (stderr, "0 (file has suffix \".%s\")\n", sp));
696 				return 0;
697 			}
698 	}
699 
700 	datfile = copy(file, ".dat");
701 	if (access(datfile, R_OK) < 0) {
702 		free(datfile);
703 		DPRINTF(2, (stderr, "0 (no \".dat\" file)\n"));
704 		return 0;
705 	}
706 	if (datp != NULL)
707 		*datp = datfile;
708 	else
709 		free(datfile);
710 	DPRINTF(2, (stderr, "1\n"));
711 	return 1;
712 }
713 
714 /*
715  * copy:
716  *	Return a malloc()'ed copy of the string + an optional suffix
717  */
718 char *
copy(char * str,char * suf)719 copy(char *str, char *suf)
720 {
721 	char	*new;
722 
723 	if (asprintf(&new, "%s%s", str, suf ? suf : "") == -1)
724 		err(1, NULL);
725 	return new;
726 }
727 
728 /*
729  * init_prob:
730  *	Initialize the fortune probabilities.
731  */
732 void
init_prob(void)733 init_prob(void)
734 {
735 	FILEDESC	*fp, *last;
736 	int		percent, num_noprob, frac;
737 
738 	/*
739 	 * Distribute the residual probability (if any) across all
740 	 * files with unspecified probability (i.e., probability of 0)
741 	 * (if any).
742 	 */
743 
744 	percent = 0;
745 	num_noprob = 0;
746 	for (fp = File_tail; fp != NULL; fp = fp->prev)
747 		if (fp->percent == NO_PROB) {
748 			num_noprob++;
749 			if (Equal_probs)
750 				last = fp;
751 		}
752 		else
753 			percent += fp->percent;
754 	DPRINTF(1, (stderr, "summing probabilities:%d%% with %d NO_PROB's",
755 		    percent, num_noprob));
756 	if (percent > 100) {
757 		(void) fprintf(stderr,
758 		    "fortune: probabilities sum to %d%%!\n", percent);
759 		exit(1);
760 	}
761 	else if (percent < 100 && num_noprob == 0) {
762 		(void) fprintf(stderr,
763 		    "fortune: no place to put residual probability (%d%%)\n",
764 		    percent);
765 		exit(1);
766 	}
767 	else if (percent == 100 && num_noprob != 0) {
768 		(void) fprintf(stderr,
769 		    "fortune: no probability left to put in residual files\n");
770 		exit(1);
771 	}
772 	percent = 100 - percent;
773 	if (Equal_probs) {
774 		if (num_noprob != 0) {
775 			if (num_noprob > 1) {
776 				frac = percent / num_noprob;
777 				DPRINTF(1, (stderr, ", frac = %d%%", frac));
778 				for (fp = File_list; fp != last; fp = fp->next)
779 					if (fp->percent == NO_PROB) {
780 						fp->percent = frac;
781 						percent -= frac;
782 					}
783 			}
784 			last->percent = percent;
785 			DPRINTF(1, (stderr, ", residual = %d%%", percent));
786 		}
787 	} else {
788 		DPRINTF(1, (stderr,
789 			    ", %d%% distributed over remaining fortunes\n",
790 			    percent));
791 	}
792 	DPRINTF(1, (stderr, "\n"));
793 
794 #ifdef DEBUG
795 	if (Debug >= 1)
796 		print_file_list();
797 #endif
798 }
799 
800 /*
801  * get_fort:
802  *	Get the fortune data file's seek pointer for the next fortune.
803  */
804 void
get_fort(void)805 get_fort(void)
806 {
807 	FILEDESC	*fp;
808 	int		choice;
809 
810 	if (File_list->next == NULL || File_list->percent == NO_PROB)
811 		fp = File_list;
812 	else {
813 		choice = arc4random_uniform(100);
814 		DPRINTF(1, (stderr, "choice = %d\n", choice));
815 		for (fp = File_list; fp->percent != NO_PROB; fp = fp->next)
816 			if (choice < fp->percent)
817 				break;
818 			else {
819 				choice -= fp->percent;
820 				DPRINTF(1, (stderr,
821 					    "    skip \"%s\", %d%% (choice = %d)\n",
822 					    fp->name, fp->percent, choice));
823 			}
824 			DPRINTF(1, (stderr,
825 				    "using \"%s\", %d%% (choice = %d)\n",
826 				    fp->name, fp->percent, choice));
827 	}
828 	if (fp->percent != NO_PROB)
829 		get_tbl(fp);
830 	else {
831 		if (fp->next != NULL) {
832 			sum_noprobs(fp);
833 			choice = arc4random_uniform(Noprob_tbl.str_numstr);
834 			DPRINTF(1, (stderr, "choice = %d (of %d) \n", choice,
835 				    Noprob_tbl.str_numstr));
836 			while (choice >= fp->tbl.str_numstr) {
837 				choice -= fp->tbl.str_numstr;
838 				fp = fp->next;
839 				DPRINTF(1, (stderr,
840 					    "    skip \"%s\", %d (choice = %d)\n",
841 					    fp->name, fp->tbl.str_numstr,
842 					    choice));
843 			}
844 			DPRINTF(1, (stderr, "using \"%s\", %d\n", fp->name,
845 				    fp->tbl.str_numstr));
846 		}
847 		get_tbl(fp);
848 	}
849 	if (fp->child != NULL) {
850 		DPRINTF(1, (stderr, "picking child\n"));
851 		fp = pick_child(fp);
852 	}
853 	Fortfile = fp;
854 	get_pos(fp);
855 	open_dat(fp);
856 	(void) lseek(fp->datfd,
857 		     (off_t) (sizeof fp->tbl + fp->pos * sizeof Seekpts[0]), 0);
858 	read(fp->datfd, &Seekpts[0], sizeof Seekpts[0]);
859 	Seekpts[0] = ntohl(Seekpts[0]);
860 	read(fp->datfd, &Seekpts[1], sizeof Seekpts[1]);
861 	Seekpts[1] = ntohl(Seekpts[1]);
862 }
863 
864 /*
865  * pick_child
866  *	Pick a child from a chosen parent.
867  */
868 FILEDESC *
pick_child(FILEDESC * parent)869 pick_child(FILEDESC *parent)
870 {
871 	FILEDESC	*fp;
872 	int		choice;
873 
874 	if (Equal_probs) {
875 		choice = arc4random_uniform(parent->num_children);
876 		DPRINTF(1, (stderr, "    choice = %d (of %d)\n",
877 			    choice, parent->num_children));
878 		for (fp = parent->child; choice--; fp = fp->next)
879 			continue;
880 		DPRINTF(1, (stderr, "    using %s\n", fp->name));
881 		return fp;
882 	}
883 	else {
884 		get_tbl(parent);
885 		choice = arc4random_uniform(parent->tbl.str_numstr);
886 		DPRINTF(1, (stderr, "    choice = %d (of %d)\n",
887 			    choice, parent->tbl.str_numstr));
888 		for (fp = parent->child; choice >= fp->tbl.str_numstr;
889 		     fp = fp->next) {
890 			choice -= fp->tbl.str_numstr;
891 			DPRINTF(1, (stderr, "\tskip %s, %d (choice = %d)\n",
892 				    fp->name, fp->tbl.str_numstr, choice));
893 		}
894 		DPRINTF(1, (stderr, "    using %s, %d\n", fp->name,
895 			    fp->tbl.str_numstr));
896 		return fp;
897 	}
898 }
899 
900 /*
901  * sum_noprobs:
902  *	Sum up all the noprob probabilities, starting with fp.
903  */
904 void
sum_noprobs(FILEDESC * fp)905 sum_noprobs(FILEDESC *fp)
906 {
907 	static bool	did_noprobs = false;
908 
909 	if (did_noprobs)
910 		return;
911 	zero_tbl(&Noprob_tbl);
912 	while (fp != NULL) {
913 		get_tbl(fp);
914 		sum_tbl(&Noprob_tbl, &fp->tbl);
915 		fp = fp->next;
916 	}
917 	did_noprobs = true;
918 }
919 
920 int
max(int i,int j)921 max(int i, int j)
922 {
923 	return (i >= j ? i : j);
924 }
925 
926 /*
927  * open_fp:
928  *	Assocatiate a FILE * with the given FILEDESC.
929  */
930 void
open_fp(FILEDESC * fp)931 open_fp(FILEDESC *fp)
932 {
933 	if (fp->inf == NULL && (fp->inf = fdopen(fp->fd, "r")) == NULL) {
934 		perror(fp->path);
935 		exit(1);
936 	}
937 }
938 
939 /*
940  * open_dat:
941  *	Open up the dat file if we need to.
942  */
943 void
open_dat(FILEDESC * fp)944 open_dat(FILEDESC *fp)
945 {
946 	if (fp->datfd < 0 && (fp->datfd = open(fp->datfile, O_RDONLY)) < 0) {
947 		perror(fp->datfile);
948 		exit(1);
949 	}
950 }
951 
952 /*
953  * get_pos:
954  *	Get the position from the pos file, if there is one.  If not,
955  *	return a random number.
956  */
957 void
get_pos(FILEDESC * fp)958 get_pos(FILEDESC *fp)
959 {
960 	assert(fp->read_tbl);
961 	if (fp->pos == POS_UNKNOWN) {
962 		fp->pos = arc4random_uniform(fp->tbl.str_numstr);
963 	}
964 	if (++(fp->pos) >= fp->tbl.str_numstr)
965 		fp->pos -= fp->tbl.str_numstr;
966 	DPRINTF(1, (stderr, "pos for %s is %d\n", fp->name, fp->pos));
967 }
968 
969 /*
970  * get_tbl:
971  *	Get the tbl data file the datfile.
972  */
973 void
get_tbl(FILEDESC * fp)974 get_tbl(FILEDESC *fp)
975 {
976 	int		fd;
977 	FILEDESC	*child;
978 
979 	if (fp->read_tbl)
980 		return;
981 	if (fp->child == NULL) {
982 		if ((fd = open(fp->datfile, O_RDONLY)) < 0) {
983 			perror(fp->datfile);
984 			exit(1);
985 		}
986 		if (read(fd, &fp->tbl.str_version,  sizeof(fp->tbl.str_version)) !=
987 		    sizeof(fp->tbl.str_version)) {
988 			(void)fprintf(stderr,
989 			    "fortune: %s corrupted\n", fp->path);
990 			exit(1);
991 		}
992 		if (read(fd, &fp->tbl.str_numstr,   sizeof(fp->tbl.str_numstr)) !=
993 		    sizeof(fp->tbl.str_numstr)) {
994 			(void)fprintf(stderr,
995 			    "fortune: %s corrupted\n", fp->path);
996 			exit(1);
997 		}
998 		if (read(fd, &fp->tbl.str_longlen,  sizeof(fp->tbl.str_longlen)) !=
999 		    sizeof(fp->tbl.str_longlen)) {
1000 			(void)fprintf(stderr,
1001 			    "fortune: %s corrupted\n", fp->path);
1002 			exit(1);
1003 		}
1004 		if (read(fd, &fp->tbl.str_shortlen, sizeof(fp->tbl.str_shortlen)) !=
1005 		    sizeof(fp->tbl.str_shortlen)) {
1006 			(void)fprintf(stderr,
1007 			    "fortune: %s corrupted\n", fp->path);
1008 			exit(1);
1009 		}
1010 		if (read(fd, &fp->tbl.str_flags,    sizeof(fp->tbl.str_flags)) !=
1011 		    sizeof(fp->tbl.str_flags)) {
1012 			(void)fprintf(stderr,
1013 			    "fortune: %s corrupted\n", fp->path);
1014 			exit(1);
1015 		}
1016 		if (read(fd, fp->tbl.stuff,	    sizeof(fp->tbl.stuff)) !=
1017 		    sizeof(fp->tbl.stuff)) {
1018 			(void)fprintf(stderr,
1019 			    "fortune: %s corrupted\n", fp->path);
1020 			exit(1);
1021 		}
1022 
1023 		/* fp->tbl.str_version = ntohl(fp->tbl.str_version); */
1024 		fp->tbl.str_numstr = ntohl(fp->tbl.str_numstr);
1025 		fp->tbl.str_longlen = ntohl(fp->tbl.str_longlen);
1026 		fp->tbl.str_shortlen = ntohl(fp->tbl.str_shortlen);
1027 		fp->tbl.str_flags = ntohl(fp->tbl.str_flags);
1028 		(void) close(fd);
1029 
1030 		if (fp->tbl.str_numstr == 0) {
1031 			fprintf(stderr, "fortune: %s is empty\n", fp->path);
1032 			exit(1);
1033 		}
1034 	}
1035 	else {
1036 		zero_tbl(&fp->tbl);
1037 		for (child = fp->child; child != NULL; child = child->next) {
1038 			get_tbl(child);
1039 			sum_tbl(&fp->tbl, &child->tbl);
1040 		}
1041 	}
1042 	fp->read_tbl = 1;
1043 }
1044 
1045 /*
1046  * zero_tbl:
1047  *	Zero out the fields we care about in a tbl structure.
1048  */
1049 void
zero_tbl(STRFILE * tp)1050 zero_tbl(STRFILE *tp)
1051 {
1052 	tp->str_numstr = 0;
1053 	tp->str_longlen = 0;
1054 	tp->str_shortlen = -1;
1055 }
1056 
1057 /*
1058  * sum_tbl:
1059  *	Merge the tbl data of t2 into t1.
1060  */
1061 void
sum_tbl(STRFILE * t1,STRFILE * t2)1062 sum_tbl(STRFILE *t1, STRFILE *t2)
1063 {
1064 	t1->str_numstr += t2->str_numstr;
1065 	if (t1->str_longlen < t2->str_longlen)
1066 		t1->str_longlen = t2->str_longlen;
1067 	if (t1->str_shortlen > t2->str_shortlen)
1068 		t1->str_shortlen = t2->str_shortlen;
1069 }
1070 
1071 #define	STR(str)	((str) == NULL ? "NULL" : (str))
1072 
1073 /*
1074  * print_file_list:
1075  *	Print out the file list
1076  */
1077 void
print_file_list(void)1078 print_file_list(void)
1079 {
1080 	print_list(File_list, 0);
1081 }
1082 
1083 /*
1084  * print_list:
1085  *	Print out the actual list, recursively.
1086  */
1087 void
print_list(FILEDESC * list,int lev)1088 print_list(FILEDESC *list, int lev)
1089 {
1090 	while (list != NULL) {
1091 		fprintf(stderr, "%*s", lev * 4, "");
1092 		if (list->percent == NO_PROB)
1093 			fprintf(stderr, "___%%");
1094 		else
1095 			fprintf(stderr, "%3d%%", list->percent);
1096 		fprintf(stderr, " %s", STR(list->name));
1097 		DPRINTF(1, (stderr, " (%s, %s)\n", STR(list->path),
1098 			    STR(list->datfile)));
1099 		putc('\n', stderr);
1100 		if (list->child != NULL)
1101 			print_list(list->child, lev + 1);
1102 		list = list->next;
1103 	}
1104 }
1105 
1106 
1107 /*
1108  * find_matches:
1109  *	Find all the fortunes which match the pattern we've been given.
1110  */
1111 int
find_matches(void)1112 find_matches(void)
1113 {
1114 	Fort_len = maxlen_in_list(File_list);
1115 	DPRINTF(2, (stderr, "Maximum length is %zu\n", Fort_len));
1116 	/* extra length, "%\n" is appended */
1117 	if ((Fortbuf = malloc(Fort_len + 10)) == NULL)
1118 		err(1, NULL);
1119 
1120 	Found_one = false;
1121 	matches_in_list(File_list);
1122 	free(Fortbuf);
1123 	Fortbuf = NULL;
1124 	return Found_one;
1125 }
1126 
1127 /*
1128  * maxlen_in_list
1129  *	Return the maximum fortune len in the file list.
1130  */
1131 int
maxlen_in_list(FILEDESC * list)1132 maxlen_in_list(FILEDESC *list)
1133 {
1134 	FILEDESC	*fp;
1135 	int		len, maxlen;
1136 
1137 	maxlen = 0;
1138 	for (fp = list; fp != NULL; fp = fp->next) {
1139 		if (fp->child != NULL) {
1140 			if ((len = maxlen_in_list(fp->child)) > maxlen)
1141 				maxlen = len;
1142 		}
1143 		else {
1144 			get_tbl(fp);
1145 			if (fp->tbl.str_longlen > maxlen)
1146 				maxlen = fp->tbl.str_longlen;
1147 		}
1148 	}
1149 	return maxlen;
1150 }
1151 
1152 /*
1153  * minlen_in_list
1154  *	Return the minimum fortune len in the file list.
1155  */
1156 int
minlen_in_list(FILEDESC * list)1157 minlen_in_list(FILEDESC *list)
1158 {
1159 	FILEDESC	*fp;
1160 	int		len, minlen;
1161 
1162 	minlen = INT_MAX;
1163 	for (fp = list; fp != NULL; fp = fp->next) {
1164 		if (fp->child != NULL) {
1165 			if ((len = minlen_in_list(fp->child)) < minlen)
1166 				minlen = len;
1167 		} else {
1168 			get_tbl(fp);
1169 			if (fp->tbl.str_shortlen < minlen)
1170 				minlen = fp->tbl.str_shortlen;
1171 		}
1172 	}
1173 	return minlen;
1174 }
1175 
1176 /*
1177  * matches_in_list
1178  *	Print out the matches from the files in the list.
1179  */
1180 void
matches_in_list(FILEDESC * list)1181 matches_in_list(FILEDESC *list)
1182 {
1183 	char		*sp;
1184 	FILEDESC	*fp;
1185 	int			in_file;
1186 
1187 	for (fp = list; fp != NULL; fp = fp->next) {
1188 		if (fp->child != NULL) {
1189 			matches_in_list(fp->child);
1190 			continue;
1191 		}
1192 		DPRINTF(1, (stderr, "searching in %s\n", fp->path));
1193 		open_fp(fp);
1194 		sp = Fortbuf;
1195 		in_file = 0;
1196 		while (fgets(sp, Fort_len, fp->inf) != NULL)
1197 			if (!STR_ENDSTRING(sp, fp->tbl))
1198 				sp += strlen(sp);
1199 			else {
1200 				*sp = '\0';
1201 				if (fp->tbl.str_flags & STR_ROTATED)
1202 					rot13(Fortbuf, sp - Fortbuf);
1203 				if (regexec(&regex, Fortbuf, 0, NULL, 0) == 0) {
1204 					printf("%c%c", fp->tbl.str_delim,
1205 					    fp->tbl.str_delim);
1206 					if (!in_file) {
1207 						printf(" (%s)", fp->name);
1208 						Found_one = true;
1209 						in_file = 1;
1210 					}
1211 					putchar('\n');
1212 					sanitize(Fortbuf);
1213 					(void) fwrite(Fortbuf, 1, (sp - Fortbuf), stdout);
1214 				}
1215 				sp = Fortbuf;
1216 			}
1217 	}
1218 }
1219 
1220 void
usage(void)1221 usage(void)
1222 {
1223 	(void) fprintf(stderr, "usage: fortune [-ae");
1224 #ifdef	DEBUG
1225 	(void) fprintf(stderr, "D");
1226 #endif	/* DEBUG */
1227 	(void) fprintf(stderr, "f");
1228 	(void) fprintf(stderr, "i");
1229 	(void) fprintf(stderr, "losw]");
1230 	(void) fprintf(stderr, " [-m pattern]");
1231 	(void) fprintf(stderr, " [[N%%] file/directory/all]\n");
1232 	exit(1);
1233 }
1234