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