1 /* $NetBSD: fortune.c,v 1.8 1995/03/23 08:28:40 cgd Exp $ */
4 * Copyright (c) 1986, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 /* Modified September, 1995, Amy A. Lewis
40 * 1: removed all file-locking dreck. Unnecessary
41 * 2: Fixed bug that made fortune -f report a different list than
42 * fortune with any other parameters, or none, and which forced
43 * the program to read only one file (named 'fortunes')
44 * 3: removed the unnecessary print_file_list()
45 * 4: Added "OFFDIR" to pathnames.h as the directory in which offensive
46 * fortunes are kept. This considerably simplifies our life by
47 * permitting us to dispense with a lot of silly tests for the string
48 * "-o" at the end of a filename.
49 * 5: I think the problems with trying to find filenames were fixed by
50 * the change in the way that offensive files are defined. Two birds,
52 * 6: Calculated probabilities for all files, so that -f will print them.
55 /* Changes Copyright (c) 1997 Dennis L. Clark. All rights reserved.
57 * The changes in this file may be freely redistributed, modified or
58 * included in other software, as long as both the above copyright
59 * notice and these conditions appear intact.
62 /* Modified May 1997, Dennis L. Clark (dbugger@progsoc.uts.edu.au)
63 * + Various portability fixes
64 * + Percent selection of files with -a now works on datafiles which
65 * appear in both unoffensive and offensive directories (see man page
67 * + The -s and -l options are now more consistent in their
68 * interpretation of fortune length
69 * + The -s and -l options can now be combined wit the -m option
72 /* Modified Jul 1999, Pablo Saratxaga <srtxg@chanae.alphanet.ch>
73 * - added use of the LANG variables; now if called without argument
74 * it will choose (if they exist) fortunes in the users' language.
75 * (that is, under a directory $LANG/ under the main fortunes directory
77 * Added to debian by Alastair McKinstry, <mckinstry@computer.org>, 2002-07-31
80 #define PROGRAM_NAME "fortune-mod"
82 #include "fortune-mod-common.h"
110 #define MINW 6 /* minimum wait if desired */
111 #define CPERS 20 /* # of chars for each sec */
113 #define POS_UNKNOWN ((int32_t)-1) /* pos for file unknown */
114 #define NO_PROB (-1) /* no prob specified for file */
117 #define DPRINTF(l, x) \
121 #define DPRINTF(l, x)
132 char *datfile, *posfile;
138 struct fd *child, *parent;
139 struct fd *next, *prev;
142 static char *env_lang;
144 static bool Found_one; /* did we find a match? */
145 static bool Find_files = false; /* just find a list of proper fortune files */
146 static bool Wait = false; /* wait desired after fortune */
147 static bool Short_only = false; /* short fortune desired */
148 static bool Long_only = false; /* long fortune desired */
149 static bool Offend = false; /* offensive fortunes only */
150 static bool All_forts = false; /* any fortune allowed */
151 static bool Equal_probs = false; /* scatter un-allocated prob equally */
152 static bool Show_filename = false;
153 static bool No_recode = false; /* Do we want to stop recoding from occuring */
155 static bool ErrorMessage =
156 false; /* Set to true if an error message has been displayed */
159 static bool Match = false; /* dump fortunes matching a pattern */
163 static bool Debug = false; /* print debug messages */
167 static unsigned char *Fortbuf = NULL; /* fortune buffer for -m */
169 static int Fort_len = 0, Spec_prob = 0, /* total prob specified on cmd line */
170 Num_files, Num_kids, /* totals of files and children. */
171 SLEN = 160; /* max. characters in a "short" fortune */
173 static int32_t Seekpts[2]; /* seek pointers to fortunes */
175 static FILEDESC *File_list = NULL, /* Head of file list */
176 *File_tail = NULL; /* Tail of file list */
177 static FILEDESC *Fortfile; /* Fortune file to use */
179 static STRFILE Noprob_tbl; /* sum of data for all no prob files */
182 #define RE_COMP(p) regcomp(&Re_pat, (p), REG_NOSUB)
183 #define BAD_COMP(f) ((f) != 0)
184 #define RE_EXEC(p) (regexec(&Re_pat, (p), 0, NULL, 0) == 0)
186 static regex_t Re_pat;
189 #endif /* POSIX_REGEX */
192 static RECODE_REQUEST request;
193 static RECODE_OUTER outer;
196 int add_dir(FILEDESC *);
198 static unsigned long my_random(unsigned long base)
200 unsigned long long l = 0;
201 char *hard_coded_val = getenv("FORTUNE_MOD_RAND_HARD_CODED_VALS");
204 return ((unsigned long)atol(hard_coded_val) % base);
206 if (getenv("FORTUNE_MOD_USE_SRAND"))
210 FILE *const fp = fopen("/dev/urandom", "rb");
215 if (fread(&l, sizeof(l), 1, fp) != 1)
223 return random() % base;
226 static char *program_version(void)
228 static char buf[BUFSIZ];
229 (void)snprintf(buf, sizeof(buf), "%s version %s", PROGRAM_NAME, VERSION);
233 static void __attribute__((noreturn)) usage(void)
235 (void)fprintf(stderr, "%s\n", program_version());
236 (void)fprintf(stderr, "%s", "fortune [-a");
238 (void)fprintf(stderr, "%s", "D");
240 (void)fprintf(stderr, "%s", "f");
242 (void)fprintf(stderr, "%s", "i");
243 #endif /* NO_REGEX */
244 (void)fprintf(stderr, "%s", "l");
246 (void)fprintf(stderr, "%s", "o");
248 (void)fprintf(stderr, "%s", "sw]");
250 (void)fprintf(stderr, "%s", " [-m pattern]");
251 #endif /* NO_REGEX */
252 (void)fprintf(stderr, "%s", " [-n number] [ [#%] file/directory/all]\n");
256 #define STR(str) ((!str) ? "NULL" : (str))
260 * Set the global values for number of files/children, to be used
261 * in printing probabilities when listing files
263 static void calc_equal_probs(void)
265 Num_files = Num_kids = 0;
266 FILEDESC *fiddlylist = File_list;
270 Num_kids += fiddlylist->num_children;
271 fiddlylist = fiddlylist->next;
277 * Print out the actual list, recursively.
279 static void print_list(FILEDESC *list, int lev)
283 fprintf(stderr, "%*s", lev * 4, "");
284 if (list->percent == NO_PROB)
286 /* This, with some changes elsewhere, gives proper percentages
287 * for every case fprintf(stderr, "___%%"); */
288 fprintf(stderr, "%5.2f%%",
289 (100.0 - Spec_prob) * list->tbl.str_numstr /
290 Noprob_tbl.str_numstr);
292 fprintf(stderr, "%5.2f%%", 100.0 / Num_files);
294 fprintf(stderr, "%5.2f%%", 100.0 / Num_kids);
296 fprintf(stderr, "%5.2f%%", 1.0 * list->percent);
297 fprintf(stderr, " %s", STR(list->name));
298 DPRINTF(1, (stderr, " (%s, %s, %s)\n", STR(list->path),
299 STR(list->datfile), STR(list->posfile)));
302 print_list(list->child, lev + 1);
310 * Convert the pattern to an ignore-case equivalent.
312 static char *conv_pat(char *orig)
318 cnt = 1; /* allow for '\0' */
319 for (sp = orig; *sp != '\0'; sp++)
324 if (!(new_buf = malloc(cnt)))
326 fprintf(stderr, "%s", "pattern too long for ignoring case\n");
330 for (sp = new_buf; *orig != '\0'; orig++)
336 *sp++ = (char)toupper(*orig);
339 else if (isupper(*orig))
343 *sp++ = (char)tolower(*orig);
352 #endif /* NO_REGEX */
356 * Do a malloc, checking for NULL return.
358 static void *do_malloc(size_t size)
360 void *new_buf = malloc(size);
364 (void)fprintf(stderr, "%s", "fortune: out of memory.\n");
372 * Return a pointer to an initialized new FILEDESC.
374 static FILEDESC *new_fp(void)
378 fp = (FILEDESC *)do_malloc(sizeof *fp);
380 fp->pos = POS_UNKNOWN;
383 fp->percent = NO_PROB;
384 fp->read_tbl = false;
385 fp->tbl.str_version = 0;
386 fp->tbl.str_numstr = 0;
387 fp->tbl.str_longlen = 0;
388 fp->tbl.str_shortlen = 0;
389 fp->tbl.str_flags = 0;
390 fp->tbl.stuff[0] = 0;
391 fp->tbl.stuff[1] = 0;
392 fp->tbl.stuff[2] = 0;
393 fp->tbl.stuff[3] = 0;
404 static inline void debugprint(const char *msg, ...)
409 vfprintf(stderr, msg, ap);
414 #define debugprint(format, ...) \
420 * Return true if the file is a directory, false otherwise.
422 static int is_dir(const char *const file)
426 if (stat(file, &sbuf) < 0)
428 debugprint("is_dir failed for file=<%s>\n", file);
431 const bool ret = (S_ISDIR(sbuf.st_mode) ? true : false);
432 debugprint("is_dir for file=<%s> gave ret=<%d>\n", file, ret);
438 * Return true if the file exists, false otherwise.
440 static int is_existant(char *file)
444 if (stat(file, &staat) == 0)
452 perror("fortune: bad juju in is_existant");
459 * Return true if the file is a fortune database file. We try and
460 * exclude files without reading them if possible to avoid
461 * overhead. Files which start with ".", or which have "illegal"
462 * suffixes, as contained in suflist[], are ruled out.
464 static int is_fortfile(const char *const file, char **datp)
466 const char *sp = strrchr(file, '/');
467 static const char *suflist[] = {/* list of "illegal" suffixes" */
468 "dat", "pos", "c", "h", "p", "i", "f", "pas", "ftn", "ins.c", "ins,pas",
469 "ins.ftn", "sml", NULL};
471 DPRINTF(2, (stderr, "is_fortfile(%s) returns ", file));
479 DPRINTF(2, (stderr, "%s", "false (file starts with '.')\n"));
482 if ((sp = strrchr(sp, '.')))
485 for (int i = 0; suflist[i]; ++i)
486 if (strcmp(sp, suflist[i]) == 0)
488 DPRINTF(2, (stderr, "false (file has suffix \".%s\")\n", sp));
493 const size_t do_len = (strlen(file) + 6);
494 char *const datfile = do_malloc(do_len + 1);
495 snprintf(datfile, do_len, "%s.dat", file);
496 if (access(datfile, R_OK) < 0)
499 DPRINTF(2, (stderr, "%s", "false (no \".dat\" file)\n"));
506 DPRINTF(2, (stderr, "%s", "true\n"));
510 static bool path_is_absolute(const char *const path)
517 if (isalpha(path[0]) && path[1] == ':' && path[2] == '/')
526 * Add a file to the file list.
528 static int add_file(int percent, const char *file, const char *dir,
529 FILEDESC **head, FILEDESC **tail, FILEDESC *parent)
543 const size_t do_len = (strlen(dir) + strlen(file) + 2);
544 path = do_malloc(do_len + 1);
545 snprintf(path, do_len, "%s/%s", dir, file);
548 !is_existant(path)) /* If doesn't exist, don't do anything. */
553 const int isdir = is_dir(path);
554 if ((isdir > 0 && parent) || (isdir < 0))
557 return false; /* don't recurse */
560 DPRINTF(1, (stderr, "trying to add file \"%s\"\n", path));
565 ((fd = open(path, O_RDONLY | O_BINARY)) < 0)) ||
566 !path_is_absolute(path))
568 debugprint("sarahhhhh fd=%d path=<%s> dir=<%s> file=<%s> percent=%d\n",
569 fd, path, dir, file, percent);
571 if (!dir && (!strchr(file, '/')))
573 if (((sp = strrchr(file, '-')) != NULL) && (strcmp(sp, "-o") == 0))
575 #define CALL__add_file(dir) add_file(percent, file, dir, head, tail, parent)
576 #define COND_CALL__add_file(loc_dir, dir) \
577 ((!strcmp((loc_dir), (dir))) ? 0 : CALL__add_file(dir))
578 /* BSD-style '-o' offensive file suffix */
580 found = CALL__add_file(LOCOFFDIR) ||
581 COND_CALL__add_file(LOCOFFDIR, OFFDIR);
582 /* put the suffix back in for better identification later */
587 (CALL__add_file(LOCFORTDIR) || CALL__add_file(LOCOFFDIR) ||
588 COND_CALL__add_file(LOCFORTDIR, FORTDIR) ||
589 COND_CALL__add_file(LOCOFFDIR, OFFDIR));
591 found = (CALL__add_file(LOCOFFDIR) ||
592 COND_CALL__add_file(LOCOFFDIR, OFFDIR));
594 found = (CALL__add_file(LOCFORTDIR) ||
595 COND_CALL__add_file(LOCFORTDIR, FORTDIR));
596 #undef COND_CALL__add_file
597 #undef CALL__add_file
599 if (!found && !parent && !dir)
600 { /* don't display an error when trying language specific files */
607 strncpy(llang, env_lang, sizeof(llang));
608 llang[sizeof(llang) - 1] = '\0';
611 /* the language string can be like "es:fr_BE:ga" */
612 while (!ret && lang && (*lang))
614 char *p = strchr(lang, ':');
617 snprintf(langdir, sizeof(langdir), "%s/%s", FORTDIR, lang);
619 if (strncmp(path, lang, 2) == 0)
621 else if (strncmp(path, langdir, strlen(FORTDIR) + 3) == 0)
627 debugprint("moshe\n");
643 DPRINTF(2, (stderr, "path = \"%s\"\n", path));
647 fp->percent = percent;
649 fp->name = strdup(file);
650 fp->path = strdup(path);
653 fp->utf8_charset = false;
654 const size_t do_len = (strlen(path) + 5);
655 char *testpath = do_malloc(do_len + 1);
656 snprintf(testpath, do_len, "%s.u8", path);
657 // fprintf(stderr, "State mal: %s\n", testpath);
658 if (stat(testpath, &statbuf) == 0)
659 fp->utf8_charset = true;
663 // fprintf(stderr, "Is utf8?: %i\n", fp->utf8_charset );
667 if ((isdir && !add_dir(fp)) || (!isdir && !is_fortfile(path, &fp->datfile)))
671 stderr, "fortune:%s not a fortune file or directory\n", path);
684 /* This is a hack to come around another hack - add_dir returns success
685 * if the directory is allowed to be empty, but we can not handle an
686 * empty directory... */
687 if (isdir && fp->num_children == 0)
704 else if (fp->percent == NO_PROB)
723 static int names_compare(const void *a, const void *b)
725 return strcmp(*(const char *const *)a, *(const char *const *)b);
729 * Add the contents of an entire directory.
731 int add_dir(FILEDESC *fp)
734 struct dirent *dirent;
736 size_t i, count_names, max_count_names;
740 if (!(dir = opendir(fp->path)))
742 debugprint("yonah\n");
746 FILEDESC *tailp = NULL;
747 DPRINTF(1, (stderr, "adding dir \"%s\"\n", fp->path));
748 fp->num_children = 0;
749 max_count_names = 200;
751 names = malloc(sizeof(names[0]) * max_count_names);
754 debugprint("zach\n");
755 perror("Out of RAM!");
758 while ((dirent = readdir(dir)))
760 if (dirent->d_name[0] == 0)
762 char *name = strdup(dirent->d_name);
763 if (count_names == max_count_names)
765 max_count_names += 200;
766 names = realloc(names, sizeof(names[0]) * max_count_names);
769 debugprint("rebecca\n");
770 perror("Out of RAM!");
774 names[count_names++] = name;
777 qsort(names, count_names, sizeof(names[0]), names_compare);
779 for (i = 0; i < count_names; ++i)
781 if (add_file(NO_PROB, names[i], fp->path, &fp->child, &tailp, fp))
789 if (fp->num_children == 0)
792 * Only the local fortune dir and the local offensive dir are
793 * allowed to be empty.
794 * - Brian Bassett (brianb@debian.org) 1999/07/31
796 if (strcmp(LOCFORTDIR, fp->path) == 0 ||
797 strcmp(LOCOFFDIR, fp->path) == 0)
802 stderr, "fortune: %s: No fortune files in directory.\n", fp->path);
810 * Form the file list from the file specifications.
813 static int top_level__add_file(const char *dirpath)
815 return add_file(NO_PROB, dirpath, NULL, &File_list, &File_tail, NULL);
818 static int cond_top_level__add_file(
819 const char *dirpath, const char *possible_dup)
821 if (!strcmp(dirpath, possible_dup))
825 return top_level__add_file(dirpath);
828 static int cond_top_level__LOCFORTDIR(void)
830 return cond_top_level__add_file(FORTDIR, LOCFORTDIR);
833 static int cond_top_level__OFFDIR(void)
835 return cond_top_level__add_file(OFFDIR, LOCOFFDIR);
838 static int top_level_LOCFORTDIR(void)
840 return (top_level__add_file(LOCFORTDIR) | cond_top_level__LOCFORTDIR());
843 static int form_file_list(char **files, int file_cnt)
848 char fullpathname[512], locpathname[512];
854 return (top_level__add_file(LOCFORTDIR) |
855 top_level__add_file(LOCOFFDIR) |
856 cond_top_level__LOCFORTDIR() | cond_top_level__OFFDIR());
860 return (top_level__add_file(LOCOFFDIR) | cond_top_level__OFFDIR());
871 strncpy(llang, env_lang, sizeof(llang));
872 llang[sizeof(llang) - 1] = '\0';
875 /* the language string can be like "es:fr_BE:ga" */
876 while (lang && (*lang))
878 p = strchr(lang, ':');
882 /* first try full locale */
884 NO_PROB, lang, NULL, &File_list, &File_tail, NULL);
886 /* if not try language name only (two first chars) */
891 strncpy(ll, lang, 2);
894 NO_PROB, ll, NULL, &File_list, &File_tail, NULL);
897 /* if we have found one we have finished */
903 return top_level_LOCFORTDIR();
907 /* no locales available, use default */
908 return top_level_LOCFORTDIR();
913 for (i = 0; i < file_cnt; i++)
916 if (!isdigit(files[i][0]))
920 const int MAX_PERCENT = 100;
921 bool percent_has_overflowed = false;
923 for (sp = files[i]; isdigit(*sp); sp++)
925 percent = percent * 10 + *sp - '0';
926 percent_has_overflowed = (percent > MAX_PERCENT);
927 if (percent_has_overflowed)
932 if (percent_has_overflowed || (percent > 100))
934 fprintf(stderr, "percentages must be <= 100\n");
936 "Overflow percentage detected at argument \"%s\"!\n",
944 "Overflow percentage detected at argument \"%s\"!\n",
951 fprintf(stderr, "%s", "percentages must be integers\n");
956 * If the number isn't followed by a '%', then
957 * it was not a percentage, just the first part
958 * of a file name which starts with digits.
965 else if (*++sp == '\0')
969 fprintf(stderr, "%s", "percentages must precede files\n");
976 if (strcmp(sp, "all") == 0)
978 snprintf(fullpathname, sizeof(fullpathname), "%s", FORTDIR);
979 snprintf(locpathname, sizeof(locpathname), "%s", LOCFORTDIR);
981 /* if it isn't an absolute path or relative to . or ..
982 make it an absolute path relative to FORTDIR */
985 if (strncmp(sp, "/", 1) != 0 && strncmp(sp, "./", 2) != 0 &&
986 strncmp(sp, "../", 3) != 0)
989 fullpathname, sizeof(fullpathname), "%s/%s", FORTDIR, sp);
991 locpathname, sizeof(locpathname), "%s/%s", LOCFORTDIR, sp);
995 snprintf(fullpathname, sizeof(fullpathname), "%s", sp);
996 snprintf(locpathname, sizeof(locpathname), "%s", sp);
1005 strncpy(llang, env_lang, sizeof(llang));
1006 llang[sizeof(llang) - 1] = '\0';
1009 /* the language string can be like "es:fr_BE:ga" */
1010 while (!ret && lang && (*lang))
1012 char *p = strchr(lang, ':');
1016 /* first try full locale */
1018 langdir, sizeof(langdir), "%s/%s/%s", FORTDIR, lang, sp);
1020 percent, langdir, NULL, &File_list, &File_tail, NULL);
1022 /* if not try language name only (two first chars) */
1027 strncpy(ll, lang, 2);
1030 langdir, sizeof(langdir), "%s/%s/%s", FORTDIR, ll, sp);
1032 percent, langdir, NULL, &File_list, &File_tail, NULL);
1040 percent, fullpathname, NULL, &File_list, &File_tail, NULL);
1042 strncmp(fullpathname, locpathname, sizeof(fullpathname)))
1044 percent, locpathname, NULL, &File_list, &File_tail, NULL);
1048 snprintf(locpathname, sizeof(locpathname), "%s/%s",
1052 percent, locpathname, NULL, &File_list, &File_tail, NULL);
1058 if (strncmp(fullpathname, locpathname, sizeof(fullpathname)) &&
1059 strcmp(sp, "all") == 0)
1062 percent, locpathname, NULL, &File_list, &File_tail, NULL);
1066 percent, fullpathname, NULL, &File_list, &File_tail, NULL))
1073 * This routine evaluates the arguments on the command line
1075 static void getargs(int argc, char **argv)
1077 bool ignore_case = false;
1082 #endif /* NO_REGEX */
1086 #define DEBUG_GETOPT "D"
1088 #define DEBUG_GETOPT
1092 #define OFFENSIVE_GETOPT
1094 #define OFFENSIVE_GETOPT "o"
1097 while ((ch = getopt(argc, argv,
1098 "ac" DEBUG_GETOPT "efilm:n:" OFFENSIVE_GETOPT "suvw")) != EOF)
1101 case 'a': /* any fortune */
1110 Equal_probs = true; /* scatter un-allocted prob equally */
1112 case 'f': /* find fortune files */
1115 case 'l': /* long ones only */
1120 SLEN = atoi(optarg);
1122 #ifndef NO_OFFENSIVE
1123 case 'o': /* offensive ones only */
1127 case 's': /* short ones only */
1131 case 'w': /* give time to read */
1135 case 'i': /* case-insensitive match */
1136 case 'm': /* dump out the fortunes */
1137 (void)fprintf(stderr, "%s",
1138 "fortune: can't match fortunes on this system (Sorry)\n");
1140 #else /* NO_REGEX */
1141 case 'm': /* dump out the fortunes */
1145 case 'i': /* case-insensitive match */
1148 #endif /* NO_REGEX */
1149 case 'u': /* Don't recode the fortune */
1153 (void)printf("%s\n", program_version());
1156 Show_filename = true;
1165 if (!form_file_list(argv, argc))
1169 fprintf(stderr, "%s", "No fortunes found\n");
1171 exit(1); /* errors printed through form_file_list() */
1175 * print_list(File_list, 0); */
1177 /* If (Find_files) print_list() moved to main */
1182 pat = conv_pat(pat);
1183 if (BAD_COMP(RE_COMP(pat)))
1185 fprintf(stderr, "bad pattern: %s\n", pat);
1193 #endif /* NO_REGEX */
1198 * Initialize the fortune probabilities.
1200 static void init_prob(void)
1203 int percent = 0, num_noprob = 0, frac;
1206 * Distribute the residual probability (if any) across all
1207 * files with unspecified probability (i.e., probability of 0)
1210 FILEDESC *last = NULL;
1211 for (fp = File_tail; fp; fp = fp->prev)
1212 if (fp->percent == NO_PROB)
1219 percent += fp->percent;
1220 DPRINTF(1, (stderr, "summing probabilities:%d%% with %d NO_PROB's\n",
1221 percent, num_noprob));
1224 fprintf(stderr, "fortune: probabilities sum to %d%%!\n", percent);
1227 else if (percent < 100 && num_noprob == 0)
1230 "fortune: no place to put residual probability (%d%%)\n", percent);
1233 else if (percent == 100 && num_noprob != 0)
1236 stderr, "fortune: no probability left to put in residual files\n");
1239 Spec_prob = percent; /* this is for -f when % is specified on cmd line */
1240 percent = 100 - percent;
1243 if (num_noprob != 0)
1247 frac = percent / num_noprob;
1248 DPRINTF(1, (stderr, ", frac = %d%%", frac));
1249 for (fp = File_tail; fp != last; fp = fp->prev)
1250 if (fp->percent == NO_PROB)
1256 last->percent = percent;
1257 DPRINTF(1, (stderr, ", residual = %d%%", percent));
1261 DPRINTF(1, (stderr, ", %d%% distributed over remaining fortunes\n",
1265 DPRINTF(1, (stderr, "%s", "\n"));
1269 * print_list(File_list, 0); *//* Causes crash with new %% code */
1275 * Zero out the fields we care about in a tbl structure.
1277 static void zero_tbl(STRFILE *tp)
1280 tp->str_longlen = 0;
1281 tp->str_shortlen = (uint32_t)(-1);
1286 * Merge the tbl data of t2 into t1.
1288 static void sum_tbl(STRFILE *t1, STRFILE *t2)
1290 t1->str_numstr += t2->str_numstr;
1291 if (t1->str_longlen < t2->str_longlen)
1292 t1->str_longlen = t2->str_longlen;
1293 if (t1->str_shortlen > t2->str_shortlen)
1294 t1->str_shortlen = t2->str_shortlen;
1299 * Get the tbl data file the datfile.
1301 static void get_tbl(FILEDESC *fp)
1310 if ((fd = open(fp->datfile, O_RDONLY | O_BINARY)) < 0)
1312 perror(fp->datfile);
1315 if (read(fd, &fp->tbl.str_version, sizeof fp->tbl.str_version) !=
1316 sizeof fp->tbl.str_version)
1318 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1321 if (read(fd, &fp->tbl.str_numstr, sizeof fp->tbl.str_numstr) !=
1322 sizeof fp->tbl.str_numstr)
1324 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1327 if (read(fd, &fp->tbl.str_longlen, sizeof fp->tbl.str_longlen) !=
1328 sizeof fp->tbl.str_longlen)
1330 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1333 if (read(fd, &fp->tbl.str_shortlen, sizeof fp->tbl.str_shortlen) !=
1334 sizeof fp->tbl.str_shortlen)
1336 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1339 if (read(fd, &fp->tbl.str_flags, sizeof fp->tbl.str_flags) !=
1340 sizeof fp->tbl.str_flags)
1342 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1345 if (read(fd, &fp->tbl.stuff, sizeof fp->tbl.stuff) !=
1346 sizeof fp->tbl.stuff)
1348 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1351 fp->tbl.str_version = ntohl(fp->tbl.str_version);
1352 fp->tbl.str_numstr = ntohl(fp->tbl.str_numstr);
1353 fp->tbl.str_longlen = ntohl(fp->tbl.str_longlen);
1354 fp->tbl.str_shortlen = ntohl(fp->tbl.str_shortlen);
1355 fp->tbl.str_flags = ntohl(fp->tbl.str_flags);
1361 for (child = fp->child; child; child = child->next)
1364 sum_tbl(&fp->tbl, &child->tbl);
1367 fp->read_tbl = true;
1372 * Sum up all the noprob probabilities, starting with fp.
1374 static void sum_noprobs(FILEDESC *fp)
1376 static bool did_noprobs = false;
1380 zero_tbl(&Noprob_tbl);
1384 /* This conditional should help us return correct values for -f
1385 * when a percentage is specified */
1386 if (fp->percent == NO_PROB)
1387 sum_tbl(&Noprob_tbl, &fp->tbl);
1395 * Pick a child from a chosen parent.
1397 static FILEDESC *pick_child(FILEDESC *parent)
1404 choice = my_random(parent->num_children);
1405 DPRINTF(1, (stderr, " choice = %d (of %d)\n", choice,
1406 parent->num_children));
1407 for (fp = parent->child; choice--; fp = fp->next)
1409 DPRINTF(1, (stderr, " using %s\n", fp->name));
1415 choice = (int)(my_random(parent->tbl.str_numstr));
1416 DPRINTF(1, (stderr, " choice = %d (of %ld)\n", choice,
1417 parent->tbl.str_numstr));
1418 for (fp = parent->child; choice >= (int)fp->tbl.str_numstr;
1421 choice -= fp->tbl.str_numstr;
1422 DPRINTF(1, (stderr, "\tskip %s, %ld (choice = %d)\n", fp->name,
1423 fp->tbl.str_numstr, choice));
1426 1, (stderr, " using %s, %ld\n", fp->name, fp->tbl.str_numstr));
1433 * Open up the dat file if we need to.
1435 static void open_dat(FILEDESC *fp)
1437 if (fp->datfd < 0 &&
1438 (fp->datfd = open(fp->datfile, O_RDONLY | O_BINARY)) < 0)
1446 * Get the position from the pos file, if there is one. If not,
1447 * return a random number.
1449 static void get_pos(FILEDESC *fp)
1451 assert(fp->read_tbl);
1452 if (fp->pos == POS_UNKNOWN)
1454 fp->pos = (int32_t)(my_random(fp->tbl.str_numstr));
1456 if (++(fp->pos) >= (int32_t)fp->tbl.str_numstr)
1457 fp->pos -= fp->tbl.str_numstr;
1458 DPRINTF(1, (stderr, "pos for %s is %ld\n", fp->name, fp->pos));
1463 * Get the fortune data file's seek pointer for the next fortune.
1465 static void get_fort(void)
1470 if (!File_list->next || File_list->percent == NO_PROB)
1474 choice = my_random(100);
1475 DPRINTF(1, (stderr, "choice = %d\n", choice));
1476 for (fp = File_list; fp->percent != NO_PROB; fp = fp->next)
1477 if (choice < fp->percent)
1481 choice -= fp->percent;
1482 DPRINTF(1, (stderr, " skip \"%s\", %d%% (choice = %d)\n",
1483 fp->name, fp->percent, choice));
1485 DPRINTF(1, (stderr, "using \"%s\", %d%% (choice = %d)\n", fp->name,
1486 fp->percent, choice));
1488 if (fp->percent != NO_PROB)
1495 choice = (int)(my_random(Noprob_tbl.str_numstr));
1496 DPRINTF(1, (stderr, "choice = %d (of %ld) \n", choice,
1497 Noprob_tbl.str_numstr));
1498 while (choice >= (int)fp->tbl.str_numstr)
1500 choice -= (int)fp->tbl.str_numstr;
1502 DPRINTF(1, (stderr, " skip \"%s\", %ld (choice = %d)\n",
1503 fp->name, fp->tbl.str_numstr, choice));
1506 (stderr, "using \"%s\", %ld\n", fp->name, fp->tbl.str_numstr));
1510 if (fp->tbl.str_numstr == 0)
1512 fprintf(stderr, "%s", "fortune: no fortune found\n");
1517 DPRINTF(1, (stderr, "%s", "picking child\n"));
1518 fp = pick_child(fp);
1524 (off_t)(sizeof fp->tbl + (size_t)fp->pos * sizeof Seekpts[0]), 0);
1525 if ((read(fp->datfd, &Seekpts[0], sizeof Seekpts[0]) < 0) ||
1526 (read(fp->datfd, &Seekpts[1], sizeof Seekpts[1]) < 0))
1530 Seekpts[0] = (int32_t)ntohl((uint32_t)Seekpts[0]);
1531 Seekpts[1] = (int32_t)ntohl((uint32_t)Seekpts[1]);
1536 * Assocatiate a FILE * with the given FILEDESC.
1538 static void open_fp(FILEDESC *fp)
1540 if (!fp->inf && !(fp->inf = fdopen(fp->fd, "r")))
1550 * Return the maximum fortune len in the file list.
1552 static int maxlen_in_list(FILEDESC *list)
1555 int len, maxlen = 0;
1557 for (fp = list; fp; fp = fp->next)
1561 if ((len = maxlen_in_list(fp->child)) > maxlen)
1567 if ((int)fp->tbl.str_longlen > maxlen)
1569 maxlen = (int)fp->tbl.str_longlen;
1578 * Print out the matches from the files in the list.
1580 static void matches_in_list(FILEDESC *list)
1583 unsigned char *p; /* -allover */
1584 unsigned char ch; /* -allover */
1589 for (fp = list; fp; fp = fp->next)
1593 matches_in_list(fp->child);
1596 DPRINTF(1, (stderr, "searching in %s\n", fp->path));
1600 while (fgets((char *)sp, Fort_len, fp->inf))
1602 if (!STR_ENDSTRING(sp, fp->tbl))
1604 sp += strlen((const char *)sp);
1609 nchar = (int)(sp - Fortbuf);
1611 if (fp->utf8_charset && (!No_recode))
1614 output = recode_string(request, (const char *)Fortbuf);
1616 output = strdup((const char *)Fortbuf);
1621 output = (char *)Fortbuf;
1623 /* Should maybe rot13 Fortbuf -allover */
1625 if (fp->tbl.str_flags & STR_ROTATED)
1627 for (p = (unsigned char *)output; (ch = *p); ++p)
1629 if (isupper(ch) && isascii(ch))
1630 *p = 'A' + (ch - 'A' + 13) % 26;
1631 else if (islower(ch) && isascii(ch))
1632 *p = 'a' + (ch - 'a' + 13) % 26;
1636 DPRINTF(1, (stdout, "nchar = %d\n", nchar));
1637 if ((nchar < SLEN || !Short_only) &&
1638 (nchar > SLEN || !Long_only) && RE_EXEC(output))
1643 stderr, "(%s)\n%c\n", fp->name, fp->tbl.str_delim);
1647 fputs(output, stdout);
1648 printf("%c\n", fp->tbl.str_delim);
1651 if (fp->utf8_charset && (!No_recode))
1665 * Find all the fortunes which match the pattern we've been given.
1667 static int find_matches(void)
1669 Fort_len = maxlen_in_list(File_list);
1670 DPRINTF(2, (stderr, "Maximum length is %d\n", Fort_len));
1671 /* extra length, "%\n" is appended */
1672 Fortbuf = do_malloc((unsigned int)Fort_len + 10);
1675 matches_in_list(File_list);
1679 #endif /* NO_REGEX */
1681 static void display(FILEDESC *fp)
1684 unsigned char line[BUFSIZ];
1687 fseek(fp->inf, (long)Seekpts[0], SEEK_SET);
1689 printf("(%s)\n%%\n", fp->name);
1690 for (Fort_len = 0; fgets((char *)line, sizeof line, fp->inf) &&
1691 !STR_ENDSTRING(line, fp->tbl);
1694 if (fp->tbl.str_flags & STR_ROTATED)
1696 for (p = (char *)line; (ch = *p); ++p)
1698 if (isupper(ch) && isascii(ch))
1699 *p = 'A' + (ch - 'A' + 13) % 26;
1700 else if (islower(ch) && isascii(ch))
1701 *p = 'a' + (ch - 'a' + 13) % 26;
1704 if (fp->utf8_charset && (!No_recode))
1708 output = recode_string(request, (const char *)line);
1710 output = strdup((const char *)line);
1712 fputs(output, stdout);
1716 fputs((char *)line, stdout);
1723 * Return the length of the fortune.
1725 static int fortlen(void)
1730 if (!(Fortfile->tbl.str_flags & (STR_RANDOM | STR_ORDERED)))
1731 nchar = (Seekpts[1] - Seekpts[0]) - 2; /* for %^J delimiter */
1735 fseek(Fortfile->inf, (long)Seekpts[0], SEEK_SET);
1737 while (fgets(line, sizeof line, Fortfile->inf) &&
1738 !STR_ENDSTRING(line, Fortfile->tbl))
1739 nchar += strlen(line);
1745 static int mymax(int i, int j) { return (i >= j ? i : j); }
1747 static void free_desc(FILEDESC *ptr)
1751 free_desc(ptr->child);
1761 FILEDESC *next = ptr->next;
1767 int main(int ac, char *av[])
1771 env_lang = getenv("LC_ALL");
1773 env_lang = getenv("LC_MESSAGES");
1775 env_lang = getenv("LANGUAGE");
1777 env_lang = getenv("LANG");
1785 #ifndef DONT_CALL_GETARGS
1790 outer = recode_new_outer(true);
1791 request = recode_new_request(outer);
1794 setlocale(LC_ALL, "");
1798 ctype = nl_langinfo(CODESET);
1799 if (!ctype || !*ctype)
1803 else if (strcmp(ctype, "ANSI_X3.4-1968") == 0)
1805 ctype = "ISO-8859-1";
1810 const size_t do_len = strlen(ctype) + 7 + 1;
1811 char *crequest = do_malloc(do_len + 1);
1812 snprintf(crequest, do_len, "UTF-8..%s", ctype);
1813 recode_scan_request(request, crequest);
1820 exit_code = (find_matches() != 0);
1828 sum_noprobs(File_list);
1831 print_list(File_list, 0);
1835 srandom((unsigned int)(time((time_t *)NULL) + getpid()));
1839 } while ((Short_only && fortlen() > SLEN) ||
1840 (Long_only && fortlen() <= SLEN));
1847 sleep((unsigned int)mymax(Fort_len / CPERS, MINW));
1852 recode_delete_request(request);
1853 recode_delete_outer(outer);
1856 /* Free the File_list */
1857 free_desc(File_list);