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"
113 #define MINW 6 /* minimum wait if desired */
114 #define CPERS 20 /* # of chars for each sec */
116 #define POS_UNKNOWN ((int32_t)-1) /* pos for file unknown */
117 #define NO_PROB (-1) /* no prob specified for file */
120 #define DPRINTF(l, x) \
124 #define DPRINTF(l, x)
135 char *datfile, *posfile;
141 struct fd *child, *parent;
142 struct fd *next, *prev;
145 static char *env_lang;
147 static bool Found_one; /* did we find a match? */
148 static bool Find_files = FALSE; /* just find a list of proper fortune files */
149 static bool Wait = FALSE; /* wait desired after fortune */
150 static bool Short_only = FALSE; /* short fortune desired */
151 static bool Long_only = FALSE; /* long fortune desired */
152 static bool Offend = FALSE; /* offensive fortunes only */
153 static bool All_forts = FALSE; /* any fortune allowed */
154 static bool Equal_probs = FALSE; /* scatter un-allocated prob equally */
155 static bool Show_filename = FALSE;
156 static bool No_recode = FALSE; /* Do we want to stop recoding from occuring */
158 static bool ErrorMessage =
159 FALSE; /* Set to true if an error message has been displayed */
162 static bool Match = FALSE; /* dump fortunes matching a pattern */
166 static bool Debug = FALSE; /* print debug messages */
170 static unsigned char *Fortbuf = NULL; /* fortune buffer for -m */
172 static int Fort_len = 0, Spec_prob = 0, /* total prob specified on cmd line */
173 Num_files, Num_kids, /* totals of files and children. */
174 SLEN = 160; /* max. characters in a "short" fortune */
176 static int32_t Seekpts[2]; /* seek pointers to fortunes */
178 static FILEDESC *File_list = NULL, /* Head of file list */
179 *File_tail = NULL; /* Tail of file list */
180 static FILEDESC *Fortfile; /* Fortune file to use */
182 static STRFILE Noprob_tbl; /* sum of data for all no prob files */
185 #define RE_COMP(p) regcomp(&Re_pat, (p), REG_NOSUB)
186 #define BAD_COMP(f) ((f) != 0)
187 #define RE_EXEC(p) (regexec(&Re_pat, (p), 0, NULL, 0) == 0)
189 static regex_t Re_pat;
192 #endif /* POSIX_REGEX */
195 static RECODE_REQUEST request;
196 static RECODE_OUTER outer;
199 int add_dir(FILEDESC *);
201 static unsigned long my_random(unsigned long base)
203 unsigned long long l = 0;
204 char *hard_coded_val = getenv("FORTUNE_MOD_RAND_HARD_CODED_VALS");
207 return ((unsigned long)atol(hard_coded_val) % base);
209 if (getenv("FORTUNE_MOD_USE_SRAND"))
213 FILE *const fp = fopen("/dev/urandom", "rb");
218 if (fread(&l, sizeof(l), 1, fp) != 1)
226 return random() % base;
229 static char *program_version(void)
231 static char buf[BUFSIZ];
232 (void)sprintf(buf, "%s version %s", PROGRAM_NAME, VERSION);
236 static void __attribute__((noreturn)) usage(void)
238 (void)fprintf(stderr, "%s\n", program_version());
239 (void)fprintf(stderr, "fortune [-a");
241 (void)fprintf(stderr, "D");
243 (void)fprintf(stderr, "f");
245 (void)fprintf(stderr, "i");
246 #endif /* NO_REGEX */
247 (void)fprintf(stderr, "l");
249 (void)fprintf(stderr, "o");
251 (void)fprintf(stderr, "sw]");
253 (void)fprintf(stderr, " [-m pattern]");
254 #endif /* NO_REGEX */
255 (void)fprintf(stderr, " [-n number] [ [#%%] file/directory/all]\n");
259 #define STR(str) ((str) == NULL ? "NULL" : (str))
263 * Set the global values for number of files/children, to be used
264 * in printing probabilities when listing files
266 static void calc_equal_probs(void)
268 Num_files = Num_kids = 0;
269 FILEDESC *fiddlylist = File_list;
270 while (fiddlylist != NULL)
273 Num_kids += fiddlylist->num_children;
274 fiddlylist = fiddlylist->next;
280 * Print out the actual list, recursively.
282 static void print_list(FILEDESC *list, int lev)
286 fprintf(stderr, "%*s", lev * 4, "");
287 if (list->percent == NO_PROB)
289 /* This, with some changes elsewhere, gives proper percentages
290 * for every case fprintf(stderr, "___%%"); */
291 fprintf(stderr, "%5.2f%%",
292 (100.0 - Spec_prob) * list->tbl.str_numstr /
293 Noprob_tbl.str_numstr);
295 fprintf(stderr, "%5.2f%%", 100.0 / Num_files);
297 fprintf(stderr, "%5.2f%%", 100.0 / Num_kids);
299 fprintf(stderr, "%5.2f%%", 1.0 * list->percent);
300 fprintf(stderr, " %s", STR(list->name));
301 DPRINTF(1, (stderr, " (%s, %s, %s)\n", STR(list->path),
302 STR(list->datfile), STR(list->posfile)));
304 if (list->child != NULL)
305 print_list(list->child, lev + 1);
313 * Convert the pattern to an ignore-case equivalent.
315 static char *conv_pat(char *orig)
321 cnt = 1; /* allow for '\0' */
322 for (sp = orig; *sp != '\0'; sp++)
327 if ((new = malloc(cnt)) == NULL)
329 fprintf(stderr, "pattern too long for ignoring case\n");
333 for (sp = new; *orig != '\0'; orig++)
339 *sp++ = (char)toupper(*orig);
342 else if (isupper(*orig))
346 *sp++ = (char)tolower(*orig);
355 #endif /* NO_REGEX */
359 * Do a malloc, checking for NULL return.
361 static void *do_malloc(size_t size)
363 void *new_buf = malloc(size);
367 (void)fprintf(stderr, "fortune: out of memory.\n");
375 * Return a pointer to an initialized new FILEDESC.
377 static FILEDESC *new_fp(void)
381 fp = (FILEDESC *)do_malloc(sizeof *fp);
383 fp->pos = POS_UNKNOWN;
386 fp->percent = NO_PROB;
387 fp->read_tbl = FALSE;
388 fp->tbl.str_version = 0;
389 fp->tbl.str_numstr = 0;
390 fp->tbl.str_longlen = 0;
391 fp->tbl.str_shortlen = 0;
392 fp->tbl.str_flags = 0;
393 fp->tbl.stuff[0] = 0;
394 fp->tbl.stuff[1] = 0;
395 fp->tbl.stuff[2] = 0;
396 fp->tbl.stuff[3] = 0;
407 static inline void debugprint(const char *msg, ...)
412 vfprintf(stderr, msg, ap);
417 #define debugprint(format, ...) \
423 * Return TRUE if the file is a directory, FALSE otherwise.
425 static int is_dir(const char *const file)
429 if (stat(file, &sbuf) < 0)
431 debugprint("is_dir failed for file=<%s>\n", file);
434 const bool ret = ((sbuf.st_mode & S_IFDIR) ? true : false);
435 debugprint("is_dir for file=<%s> gave ret=<%d>\n", file, ret);
441 * Return TRUE if the file exists, FALSE otherwise.
443 static int is_existant(char *file)
447 if (stat(file, &staat) == 0)
455 perror("fortune: bad juju in is_existant");
462 * Return TRUE if the file is a fortune database file. We try and
463 * exclude files without reading them if possible to avoid
464 * overhead. Files which start with ".", or which have "illegal"
465 * suffixes, as contained in suflist[], are ruled out.
467 static int is_fortfile(const char *const file, char **datp)
469 const char *sp = strrchr(file, '/');
470 static const char *suflist[] = {/* list of "illegal" suffixes" */
471 "dat", "pos", "c", "h", "p", "i", "f", "pas", "ftn", "ins.c", "ins,pas",
472 "ins.ftn", "sml", NULL};
474 DPRINTF(2, (stderr, "is_fortfile(%s) returns ", file));
482 DPRINTF(2, (stderr, "FALSE (file starts with '.')\n"));
485 if ((sp = strrchr(sp, '.')) != NULL)
488 for (int i = 0; suflist[i] != NULL; i++)
489 if (strcmp(sp, suflist[i]) == 0)
491 DPRINTF(2, (stderr, "FALSE (file has suffix \".%s\")\n", sp));
496 char *const datfile = do_malloc((unsigned int)(strlen(file) + 6));
497 sprintf(datfile, "%s.dat", file);
498 if (access(datfile, R_OK) < 0)
501 DPRINTF(2, (stderr, "FALSE (no \".dat\" file)\n"));
508 DPRINTF(2, (stderr, "TRUE\n"));
512 static bool path_is_absolute(const char *const path)
519 if (isalpha(path[0]) && path[1] == ':' && path[2] == '/')
528 * Add a file to the file list.
530 static int add_file(int percent, const char *file, const char *dir,
531 FILEDESC **head, FILEDESC **tail, FILEDESC *parent)
535 char *path, *testpath;
546 path = do_malloc((unsigned int)(strlen(dir) + strlen(file) + 2));
547 sprintf(path, "%s/%s", dir, file);
550 !is_existant(path)) /* If doesn't exist, don't do anything. */
555 const int isdir = is_dir(path);
556 if ((isdir > 0 && parent != NULL) || (isdir < 0))
559 return FALSE; /* don't recurse */
562 DPRINTF(1, (stderr, "trying to add file \"%s\"\n", path));
567 ((fd = open(path, O_RDONLY | O_BINARY)) < 0)) ||
568 !path_is_absolute(path))
570 debugprint("sarahhhhh fd=%d path=<%s> dir=<%s> file=<%s> percent=%d\n",
571 fd, path, dir, file, percent);
573 if (dir == NULL && (strchr(file, '/') == NULL))
575 if (((sp = strrchr(file, '-')) != NULL) && (strcmp(sp, "-o") == 0))
577 #define CALL__add_file(dir) add_file(percent, file, dir, head, tail, parent)
578 #define COND_CALL__add_file(loc_dir, dir) \
579 ((!strcmp((loc_dir), (dir))) ? 0 : CALL__add_file(dir))
580 /* BSD-style '-o' offensive file suffix */
582 found = CALL__add_file(LOCOFFDIR) ||
583 COND_CALL__add_file(LOCOFFDIR, OFFDIR);
584 /* put the suffix back in for better identification later */
589 (CALL__add_file(LOCFORTDIR) || CALL__add_file(LOCOFFDIR) ||
590 COND_CALL__add_file(LOCFORTDIR, FORTDIR) ||
591 COND_CALL__add_file(LOCOFFDIR, OFFDIR));
593 found = (CALL__add_file(LOCOFFDIR) ||
594 COND_CALL__add_file(LOCOFFDIR, OFFDIR));
596 found = (CALL__add_file(LOCFORTDIR) ||
597 COND_CALL__add_file(LOCFORTDIR, FORTDIR));
598 #undef COND_CALL__add_file
599 #undef CALL__add_file
601 if (!found && parent == NULL && dir == NULL)
602 { /* don't display an error when trying language specific files */
609 strncpy(llang, env_lang, sizeof(llang));
610 llang[sizeof(llang) - 1] = '\0';
613 /* the language string can be like "es:fr_BE:ga" */
614 while (!ret && lang && (*lang))
616 char *p = strchr(lang, ':');
619 snprintf(langdir, sizeof(langdir), "%s/%s", FORTDIR, lang);
621 if (strncmp(path, lang, 2) == 0)
623 else if (strncmp(path, langdir, strlen(FORTDIR) + 3) == 0)
629 debugprint("moshe\n");
645 DPRINTF(2, (stderr, "path = \"%s\"\n", path));
649 fp->percent = percent;
651 fp->name = strdup(file);
652 fp->path = strdup(path);
655 fp->utf8_charset = FALSE;
656 testpath = do_malloc(strlen(path) + 4UL);
657 sprintf(testpath, "%s.u8", path);
658 // fprintf(stderr, "State mal: %s\n", testpath);
659 if (stat(testpath, &statbuf) == 0)
660 fp->utf8_charset = TRUE;
664 // fprintf(stderr, "Is utf8?: %i\n", fp->utf8_charset );
668 if ((isdir && !add_dir(fp)) || (!isdir && !is_fortfile(path, &fp->datfile)))
672 stderr, "fortune:%s not a fortune file or directory\n", path);
685 /* This is a hack to come around another hack - add_dir returns success
686 * if the directory is allowed to be empty, but we can not handle an
687 * empty directory... */
688 if (isdir && fp->num_children == 0)
705 else if (fp->percent == NO_PROB)
724 static int names_compare(const void *a, const void *b)
726 return strcmp(*(const char *const *)a, *(const char *const *)b);
730 * Add the contents of an entire directory.
732 int add_dir(FILEDESC *fp)
735 struct dirent *dirent;
737 size_t i, count_names, max_count_names;
741 if ((dir = opendir(fp->path)) == NULL)
743 debugprint("yonah\n");
747 FILEDESC *tailp = NULL;
748 DPRINTF(1, (stderr, "adding dir \"%s\"\n", fp->path));
749 fp->num_children = 0;
750 max_count_names = 200;
752 names = malloc(sizeof(names[0]) * max_count_names);
755 debugprint("zach\n");
756 perror("Out of RAM!");
759 while ((dirent = readdir(dir)) != NULL)
761 if (dirent->d_name[0] == 0)
763 char *name = strdup(dirent->d_name);
764 if (count_names == max_count_names)
766 max_count_names += 200;
767 names = realloc(names, sizeof(names[0]) * max_count_names);
770 debugprint("rebecca\n");
771 perror("Out of RAM!");
775 names[count_names++] = name;
778 qsort(names, count_names, sizeof(names[0]), names_compare);
780 for (i = 0; i < count_names; ++i)
782 if (add_file(NO_PROB, names[i], fp->path, &fp->child, &tailp, fp))
790 if (fp->num_children == 0)
793 * Only the local fortune dir and the local offensive dir are
794 * allowed to be empty.
795 * - Brian Bassett (brianb@debian.org) 1999/07/31
797 if (strcmp(LOCFORTDIR, fp->path) == 0 ||
798 strcmp(LOCOFFDIR, fp->path) == 0)
803 stderr, "fortune: %s: No fortune files in directory.\n", fp->path);
811 * Form the file list from the file specifications.
814 static int top_level__add_file(const char *dirpath)
816 return add_file(NO_PROB, dirpath, NULL, &File_list, &File_tail, NULL);
819 static int cond_top_level__add_file(
820 const char *dirpath, const char *possible_dup)
822 if (!strcmp(dirpath, possible_dup))
826 return top_level__add_file(dirpath);
829 static int cond_top_level__LOCFORTDIR(void)
831 return cond_top_level__add_file(FORTDIR, LOCFORTDIR);
834 static int cond_top_level__OFFDIR(void)
836 return cond_top_level__add_file(OFFDIR, LOCOFFDIR);
839 static int top_level_LOCFORTDIR(void)
841 return (top_level__add_file(LOCFORTDIR) | cond_top_level__LOCFORTDIR());
844 static int form_file_list(char **files, int file_cnt)
849 char fullpathname[512], locpathname[512];
855 return (top_level__add_file(LOCFORTDIR) |
856 top_level__add_file(LOCOFFDIR) |
857 cond_top_level__LOCFORTDIR() | cond_top_level__OFFDIR());
861 return (top_level__add_file(LOCOFFDIR) | cond_top_level__OFFDIR());
872 strncpy(llang, env_lang, sizeof(llang));
873 llang[sizeof(llang) - 1] = '\0';
876 /* the language string can be like "es:fr_BE:ga" */
877 while (lang && (*lang))
879 p = strchr(lang, ':');
883 /* first try full locale */
885 NO_PROB, lang, NULL, &File_list, &File_tail, NULL);
887 /* if not try language name only (two first chars) */
892 strncpy(ll, lang, 2);
895 NO_PROB, ll, NULL, &File_list, &File_tail, NULL);
898 /* if we have found one we have finished */
904 return top_level_LOCFORTDIR();
908 /* no locales available, use default */
909 return top_level_LOCFORTDIR();
914 for (i = 0; i < file_cnt; i++)
917 if (!isdigit(files[i][0]))
922 for (sp = files[i]; isdigit(*sp); sp++)
923 percent = percent * 10 + *sp - '0';
926 fprintf(stderr, "percentages must be <= 100\n");
932 fprintf(stderr, "percentages must be integers\n");
937 * If the number isn't followed by a '%', then
938 * it was not a percentage, just the first part
939 * of a file name which starts with digits.
946 else if (*++sp == '\0')
950 fprintf(stderr, "percentages must precede files\n");
957 if (strcmp(sp, "all") == 0)
959 snprintf(fullpathname, sizeof(fullpathname), "%s", FORTDIR);
960 snprintf(locpathname, sizeof(locpathname), "%s", LOCFORTDIR);
962 /* if it isn't an absolute path or relative to . or ..
963 make it an absolute path relative to FORTDIR */
966 if (strncmp(sp, "/", 1) != 0 && strncmp(sp, "./", 2) != 0 &&
967 strncmp(sp, "../", 3) != 0)
970 fullpathname, sizeof(fullpathname), "%s/%s", FORTDIR, sp);
972 locpathname, sizeof(locpathname), "%s/%s", LOCFORTDIR, sp);
976 snprintf(fullpathname, sizeof(fullpathname), "%s", sp);
977 snprintf(locpathname, sizeof(locpathname), "%s", sp);
986 strncpy(llang, env_lang, sizeof(llang));
987 llang[sizeof(llang) - 1] = '\0';
990 /* the language string can be like "es:fr_BE:ga" */
991 while (!ret && lang && (*lang))
993 char *p = strchr(lang, ':');
997 /* first try full locale */
999 langdir, sizeof(langdir), "%s/%s/%s", FORTDIR, lang, sp);
1001 percent, langdir, NULL, &File_list, &File_tail, NULL);
1003 /* if not try language name only (two first chars) */
1008 strncpy(ll, lang, 2);
1011 langdir, sizeof(langdir), "%s/%s/%s", FORTDIR, ll, sp);
1013 percent, langdir, NULL, &File_list, &File_tail, NULL);
1021 percent, fullpathname, NULL, &File_list, &File_tail, NULL);
1023 strncmp(fullpathname, locpathname, sizeof(fullpathname)))
1025 percent, locpathname, NULL, &File_list, &File_tail, NULL);
1029 snprintf(locpathname, sizeof(locpathname), "%s/%s",
1033 percent, locpathname, NULL, &File_list, &File_tail, NULL);
1039 if (strncmp(fullpathname, locpathname, sizeof(fullpathname)) &&
1040 strcmp(sp, "all") == 0)
1043 percent, locpathname, NULL, &File_list, &File_tail, NULL);
1047 percent, fullpathname, NULL, &File_list, &File_tail, NULL))
1054 * This routine evaluates the arguments on the command line
1056 static void getargs(int argc, char **argv)
1058 int ignore_case = FALSE;
1063 #endif /* NO_REGEX */
1067 #define DEBUG_GETOPT "D"
1069 #define DEBUG_GETOPT
1073 #define OFFENSIVE_GETOPT
1075 #define OFFENSIVE_GETOPT "o"
1078 while ((ch = getopt(argc, argv,
1079 "ac" DEBUG_GETOPT "efilm:n:" OFFENSIVE_GETOPT "suvw")) != EOF)
1082 case 'a': /* any fortune */
1091 Equal_probs = TRUE; /* scatter un-allocted prob equally */
1093 case 'f': /* find fortune files */
1096 case 'l': /* long ones only */
1101 SLEN = atoi(optarg);
1103 #ifndef NO_OFFENSIVE
1104 case 'o': /* offensive ones only */
1108 case 's': /* short ones only */
1112 case 'w': /* give time to read */
1116 case 'i': /* case-insensitive match */
1117 case 'm': /* dump out the fortunes */
1118 (void)fprintf(stderr,
1119 "fortune: can't match fortunes on this system (Sorry)\n");
1121 #else /* NO_REGEX */
1122 case 'm': /* dump out the fortunes */
1126 case 'i': /* case-insensitive match */
1129 #endif /* NO_REGEX */
1130 case 'u': /* Don't recode the fortune */
1134 (void)printf("%s\n", program_version());
1137 Show_filename = TRUE;
1146 if (!form_file_list(argv, argc))
1149 fprintf(stderr, "No fortunes found\n");
1150 exit(1); /* errors printed through form_file_list() */
1154 * print_list(File_list, 0); */
1156 /* If (Find_files) print_list() moved to main */
1161 pat = conv_pat(pat);
1162 if (BAD_COMP(RE_COMP(pat)))
1164 fprintf(stderr, "bad pattern: %s\n", pat);
1172 #endif /* NO_REGEX */
1177 * Initialize the fortune probabilities.
1179 static void init_prob(void)
1182 int percent = 0, num_noprob = 0, frac;
1185 * Distribute the residual probability (if any) across all
1186 * files with unspecified probability (i.e., probability of 0)
1189 FILEDESC *last = NULL;
1190 for (fp = File_tail; fp != NULL; fp = fp->prev)
1191 if (fp->percent == NO_PROB)
1198 percent += fp->percent;
1199 DPRINTF(1, (stderr, "summing probabilities:%d%% with %d NO_PROB's\n",
1200 percent, num_noprob));
1203 fprintf(stderr, "fortune: probabilities sum to %d%%!\n", percent);
1206 else if (percent < 100 && num_noprob == 0)
1209 "fortune: no place to put residual probability (%d%%)\n", percent);
1212 else if (percent == 100 && num_noprob != 0)
1215 stderr, "fortune: no probability left to put in residual files\n");
1218 Spec_prob = percent; /* this is for -f when % is specified on cmd line */
1219 percent = 100 - percent;
1222 if (num_noprob != 0)
1226 frac = percent / num_noprob;
1227 DPRINTF(1, (stderr, ", frac = %d%%", frac));
1228 for (fp = File_tail; fp != last; fp = fp->prev)
1229 if (fp->percent == NO_PROB)
1235 last->percent = percent;
1236 DPRINTF(1, (stderr, ", residual = %d%%", percent));
1240 DPRINTF(1, (stderr, ", %d%% distributed over remaining fortunes\n",
1244 DPRINTF(1, (stderr, "\n"));
1248 * print_list(File_list, 0); *//* Causes crash with new %% code */
1254 * Zero out the fields we care about in a tbl structure.
1256 static void zero_tbl(STRFILE *tp)
1259 tp->str_longlen = 0;
1260 tp->str_shortlen = (uint32_t)(-1);
1265 * Merge the tbl data of t2 into t1.
1267 static void sum_tbl(STRFILE *t1, STRFILE *t2)
1269 t1->str_numstr += t2->str_numstr;
1270 if (t1->str_longlen < t2->str_longlen)
1271 t1->str_longlen = t2->str_longlen;
1272 if (t1->str_shortlen > t2->str_shortlen)
1273 t1->str_shortlen = t2->str_shortlen;
1278 * Get the tbl data file the datfile.
1280 static void get_tbl(FILEDESC *fp)
1287 if (fp->child == NULL)
1289 if ((fd = open(fp->datfile, O_RDONLY | O_BINARY)) < 0)
1291 perror(fp->datfile);
1294 if (read(fd, &fp->tbl.str_version, sizeof fp->tbl.str_version) !=
1295 sizeof fp->tbl.str_version)
1297 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1300 if (read(fd, &fp->tbl.str_numstr, sizeof fp->tbl.str_numstr) !=
1301 sizeof fp->tbl.str_numstr)
1303 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1306 if (read(fd, &fp->tbl.str_longlen, sizeof fp->tbl.str_longlen) !=
1307 sizeof fp->tbl.str_longlen)
1309 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1312 if (read(fd, &fp->tbl.str_shortlen, sizeof fp->tbl.str_shortlen) !=
1313 sizeof fp->tbl.str_shortlen)
1315 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1318 if (read(fd, &fp->tbl.str_flags, sizeof fp->tbl.str_flags) !=
1319 sizeof fp->tbl.str_flags)
1321 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1324 if (read(fd, &fp->tbl.stuff, sizeof fp->tbl.stuff) !=
1325 sizeof fp->tbl.stuff)
1327 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1330 fp->tbl.str_version = ntohl(fp->tbl.str_version);
1331 fp->tbl.str_numstr = ntohl(fp->tbl.str_numstr);
1332 fp->tbl.str_longlen = ntohl(fp->tbl.str_longlen);
1333 fp->tbl.str_shortlen = ntohl(fp->tbl.str_shortlen);
1334 fp->tbl.str_flags = ntohl(fp->tbl.str_flags);
1340 for (child = fp->child; child != NULL; child = child->next)
1343 sum_tbl(&fp->tbl, &child->tbl);
1346 fp->read_tbl = TRUE;
1351 * Sum up all the noprob probabilities, starting with fp.
1353 static void sum_noprobs(FILEDESC *fp)
1355 static bool did_noprobs = FALSE;
1359 zero_tbl(&Noprob_tbl);
1363 /* This conditional should help us return correct values for -f
1364 * when a percentage is specified */
1365 if (fp->percent == NO_PROB)
1366 sum_tbl(&Noprob_tbl, &fp->tbl);
1374 * Pick a child from a chosen parent.
1376 static FILEDESC *pick_child(FILEDESC *parent)
1383 choice = my_random(parent->num_children);
1384 DPRINTF(1, (stderr, " choice = %d (of %d)\n", choice,
1385 parent->num_children));
1386 for (fp = parent->child; choice--; fp = fp->next)
1388 DPRINTF(1, (stderr, " using %s\n", fp->name));
1394 choice = (int)(my_random(parent->tbl.str_numstr));
1395 DPRINTF(1, (stderr, " choice = %d (of %ld)\n", choice,
1396 parent->tbl.str_numstr));
1397 for (fp = parent->child; choice >= (int)fp->tbl.str_numstr;
1400 choice -= fp->tbl.str_numstr;
1401 DPRINTF(1, (stderr, "\tskip %s, %ld (choice = %d)\n", fp->name,
1402 fp->tbl.str_numstr, choice));
1405 1, (stderr, " using %s, %ld\n", fp->name, fp->tbl.str_numstr));
1412 * Open up the dat file if we need to.
1414 static void open_dat(FILEDESC *fp)
1416 if (fp->datfd < 0 &&
1417 (fp->datfd = open(fp->datfile, O_RDONLY | O_BINARY)) < 0)
1425 * Get the position from the pos file, if there is one. If not,
1426 * return a random number.
1428 static void get_pos(FILEDESC *fp)
1430 assert(fp->read_tbl);
1431 if (fp->pos == POS_UNKNOWN)
1433 fp->pos = (int32_t)(my_random(fp->tbl.str_numstr));
1435 if (++(fp->pos) >= (int32_t)fp->tbl.str_numstr)
1436 fp->pos -= fp->tbl.str_numstr;
1437 DPRINTF(1, (stderr, "pos for %s is %ld\n", fp->name, fp->pos));
1442 * Get the fortune data file's seek pointer for the next fortune.
1444 static void get_fort(void)
1449 if (File_list->next == NULL || File_list->percent == NO_PROB)
1453 choice = my_random(100);
1454 DPRINTF(1, (stderr, "choice = %d\n", choice));
1455 for (fp = File_list; fp->percent != NO_PROB; fp = fp->next)
1456 if (choice < fp->percent)
1460 choice -= fp->percent;
1461 DPRINTF(1, (stderr, " skip \"%s\", %d%% (choice = %d)\n",
1462 fp->name, fp->percent, choice));
1464 DPRINTF(1, (stderr, "using \"%s\", %d%% (choice = %d)\n", fp->name,
1465 fp->percent, choice));
1467 if (fp->percent != NO_PROB)
1471 if (fp->next != NULL)
1474 choice = (int)(my_random(Noprob_tbl.str_numstr));
1475 DPRINTF(1, (stderr, "choice = %d (of %ld) \n", choice,
1476 Noprob_tbl.str_numstr));
1477 while (choice >= (int)fp->tbl.str_numstr)
1479 choice -= (int)fp->tbl.str_numstr;
1481 DPRINTF(1, (stderr, " skip \"%s\", %ld (choice = %d)\n",
1482 fp->name, fp->tbl.str_numstr, choice));
1485 (stderr, "using \"%s\", %ld\n", fp->name, fp->tbl.str_numstr));
1489 if (fp->tbl.str_numstr == 0)
1491 fprintf(stderr, "fortune: no fortune found\n");
1494 if (fp->child != NULL)
1496 DPRINTF(1, (stderr, "picking child\n"));
1497 fp = pick_child(fp);
1503 (off_t)(sizeof fp->tbl + (size_t)fp->pos * sizeof Seekpts[0]), 0);
1504 if ((read(fp->datfd, &Seekpts[0], sizeof Seekpts[0]) < 0) ||
1505 (read(fp->datfd, &Seekpts[1], sizeof Seekpts[1]) < 0))
1509 Seekpts[0] = (int32_t)ntohl((uint32_t)Seekpts[0]);
1510 Seekpts[1] = (int32_t)ntohl((uint32_t)Seekpts[1]);
1515 * Assocatiate a FILE * with the given FILEDESC.
1517 static void open_fp(FILEDESC *fp)
1519 if (fp->inf == NULL && (fp->inf = fdopen(fp->fd, "r")) == NULL)
1529 * Return the maximum fortune len in the file list.
1531 static int maxlen_in_list(FILEDESC *list)
1534 int len, maxlen = 0;
1536 for (fp = list; fp != NULL; fp = fp->next)
1538 if (fp->child != NULL)
1540 if ((len = maxlen_in_list(fp->child)) > maxlen)
1546 if ((int)fp->tbl.str_longlen > maxlen)
1548 maxlen = (int)fp->tbl.str_longlen;
1557 * Print out the matches from the files in the list.
1559 static void matches_in_list(FILEDESC *list)
1562 unsigned char *p; /* -allover */
1563 unsigned char ch; /* -allover */
1568 for (fp = list; fp != NULL; fp = fp->next)
1570 if (fp->child != NULL)
1572 matches_in_list(fp->child);
1575 DPRINTF(1, (stderr, "searching in %s\n", fp->path));
1579 while (fgets((char *)sp, Fort_len, fp->inf) != NULL)
1581 if (!STR_ENDSTRING(sp, fp->tbl))
1583 sp += strlen((const char *)sp);
1588 nchar = (int)(sp - Fortbuf);
1590 if (fp->utf8_charset && (!No_recode))
1593 output = recode_string(request, (const char *)Fortbuf);
1595 output = strdup(Fortbuf);
1600 output = (char *)Fortbuf;
1602 /* Should maybe rot13 Fortbuf -allover */
1604 if (fp->tbl.str_flags & STR_ROTATED)
1606 for (p = (unsigned char *)output; (ch = *p); ++p)
1608 if (isupper(ch) && isascii(ch))
1609 *p = 'A' + (ch - 'A' + 13) % 26;
1610 else if (islower(ch) && isascii(ch))
1611 *p = 'a' + (ch - 'a' + 13) % 26;
1615 DPRINTF(1, (stdout, "nchar = %d\n", nchar));
1616 if ((nchar < SLEN || !Short_only) &&
1617 (nchar > SLEN || !Long_only) && RE_EXEC(output))
1622 stderr, "(%s)\n%c\n", fp->name, fp->tbl.str_delim);
1626 fputs(output, stdout);
1627 printf("%c\n", fp->tbl.str_delim);
1630 if (fp->utf8_charset && (!No_recode))
1641 * Find all the fortunes which match the pattern we've been given.
1643 static int find_matches(void)
1645 Fort_len = maxlen_in_list(File_list);
1646 DPRINTF(2, (stderr, "Maximum length is %d\n", Fort_len));
1647 /* extra length, "%\n" is appended */
1648 Fortbuf = do_malloc((unsigned int)Fort_len + 10);
1651 matches_in_list(File_list);
1655 #endif /* NO_REGEX */
1657 static void display(FILEDESC *fp)
1660 unsigned char line[BUFSIZ];
1663 fseek(fp->inf, (long)Seekpts[0], 0);
1665 printf("(%s)\n%%\n", fp->name);
1666 for (Fort_len = 0; fgets((char *)line, sizeof line, fp->inf) != NULL &&
1667 !STR_ENDSTRING(line, fp->tbl);
1670 if (fp->tbl.str_flags & STR_ROTATED)
1672 for (p = (char *)line; (ch = *p); ++p)
1674 if (isupper(ch) && isascii(ch))
1675 *p = 'A' + (ch - 'A' + 13) % 26;
1676 else if (islower(ch) && isascii(ch))
1677 *p = 'a' + (ch - 'a' + 13) % 26;
1680 if (fp->utf8_charset && (!No_recode))
1684 output = recode_string(request, (const char *)line);
1686 output = strdup(line);
1688 fputs(output, stdout);
1692 fputs((char *)line, stdout);
1699 * Return the length of the fortune.
1701 static int fortlen(void)
1706 if (!(Fortfile->tbl.str_flags & (STR_RANDOM | STR_ORDERED)))
1707 nchar = (Seekpts[1] - Seekpts[0]) - 2; /* for %^J delimiter */
1711 fseek(Fortfile->inf, (long)Seekpts[0], 0);
1713 while (fgets(line, sizeof line, Fortfile->inf) != NULL &&
1714 !STR_ENDSTRING(line, Fortfile->tbl))
1715 nchar += strlen(line);
1721 static int mymax(int i, int j) { return (i >= j ? i : j); }
1723 static void free_desc(FILEDESC *ptr)
1727 free_desc(ptr->child);
1737 FILEDESC *next = ptr->next;
1743 int main(int ac, char *av[])
1748 env_lang = getenv("LC_ALL");
1750 env_lang = getenv("LC_MESSAGES");
1752 env_lang = getenv("LANGUAGE");
1754 env_lang = getenv("LANG");
1762 #ifndef DONT_CALL_GETARGS
1767 outer = recode_new_outer(true);
1768 request = recode_new_request(outer);
1771 setlocale(LC_ALL, "");
1775 ctype = nl_langinfo(CODESET);
1776 if (!ctype || !*ctype)
1780 else if (strcmp(ctype, "ANSI_X3.4-1968") == 0)
1782 ctype = "ISO-8859-1";
1787 crequest = malloc(strlen(ctype) + 7 + 1);
1788 sprintf(crequest, "UTF-8..%s", ctype);
1789 recode_scan_request(request, crequest);
1796 exit_code = (find_matches() != 0);
1804 sum_noprobs(File_list);
1807 print_list(File_list, 0);
1811 srandom((unsigned int)(time((time_t *)NULL) + getpid()));
1815 } while ((Short_only && fortlen() > SLEN) ||
1816 (Long_only && fortlen() <= SLEN));
1823 sleep((unsigned int)mymax(Fort_len / CPERS, MINW));
1828 recode_delete_request(request);
1829 recode_delete_outer(outer);
1832 /* Free the File_list */
1833 free_desc(File_list);