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