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