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