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"
83 #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 const char *env_lang = NULL;
144 static bool Found_one = false; /* 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 */
160 #define RE_COMP(p) regcomp(&Re_pat, (p), REG_NOSUB)
161 #define BAD_COMP(f) ((f) != 0)
162 #define RE_EXEC(p) (regexec(&Re_pat, (p), 0, NULL, 0) == 0)
164 static regex_t Re_pat;
167 #endif /* POSIX_REGEX */
170 static bool Match = false; /* dump fortunes matching a pattern */
174 static bool Debug = false; /* print debug messages */
177 static unsigned char *Fortbuf = NULL; /* fortune buffer for -m */
179 static int Fort_len = 0, Spec_prob = 0, /* total prob specified on cmd line */
180 Num_files, Num_kids, /* totals of files and children. */
181 SLEN = 160; /* max. characters in a "short" fortune */
183 static int32_t Seekpts[2]; /* seek pointers to fortunes */
185 static FILEDESC *File_list = NULL, /* Head of file list */
186 *File_tail = NULL; /* Tail of file list */
187 static FILEDESC *Fortfile; /* Fortune file to use */
189 static STRFILE Noprob_tbl; /* sum of data for all no prob files */
192 static RECODE_REQUEST request;
193 static RECODE_OUTER outer;
194 static inline char *my_recode_string(const char *s)
196 return recode_string(request, (const char *)s);
199 static inline char *my_recode_string(const char *s) { return strdup(s); }
202 static int add_dir(FILEDESC *);
204 static unsigned long my_random(const unsigned long base)
206 unsigned long long l = 0;
207 char *hard_coded_val = getenv("FORTUNE_MOD_RAND_HARD_CODED_VALS");
210 return ((unsigned long)atol(hard_coded_val) % base);
212 if (getenv("FORTUNE_MOD_USE_SRAND"))
216 FILE *const fp = fopen("/dev/urandom", "rb");
221 if (fread(&l, sizeof(l), 1, fp) != 1)
229 return random() % base;
232 static char *program_version(void)
234 static char buf[BUFSIZ];
235 (void)snprintf(buf, sizeof(buf), "%s version %s", PROGRAM_NAME, VERSION);
239 static void __attribute__((noreturn)) usage(void)
241 (void)fprintf(stderr, "%s\n", program_version());
242 (void)fprintf(stderr, "%s", "fortune [-a");
244 (void)fprintf(stderr, "%s", "D");
246 (void)fprintf(stderr, "%s", "f");
248 (void)fprintf(stderr, "%s", "i");
250 (void)fprintf(stderr, "%s", "l");
252 (void)fprintf(stderr, "%s", "o");
254 (void)fprintf(stderr, "%s", "sw]");
256 (void)fprintf(stderr, "%s", " [-m pattern]");
258 (void)fprintf(stderr, "%s", " [-n number] [ [#%] file/directory/all]\n");
262 #define STR(str) ((!str) ? "NULL" : (str))
266 * Set the global values for number of files/children, to be used
267 * in printing probabilities when listing files
269 static void calc_equal_probs(void)
271 Num_files = Num_kids = 0;
272 FILEDESC *fiddlylist = File_list;
276 Num_kids += fiddlylist->num_children;
277 fiddlylist = fiddlylist->next;
283 * Print out the actual list, recursively.
285 static void print_list(FILEDESC *list, int lev)
289 fprintf(stderr, "%*s", lev * 4, "");
290 if (list->percent == NO_PROB)
292 /* This, with some changes elsewhere, gives proper percentages
293 * for every case fprintf(stderr, "___%%"); */
294 fprintf(stderr, "%5.2f%%",
295 (100.0 - Spec_prob) * list->tbl.str_numstr /
296 Noprob_tbl.str_numstr);
298 fprintf(stderr, "%5.2f%%", 100.0 / Num_files);
300 fprintf(stderr, "%5.2f%%", 100.0 / Num_kids);
302 fprintf(stderr, "%5.2f%%", 1.0 * list->percent);
303 fprintf(stderr, " %s", STR(list->name));
304 DPRINTF(1, (stderr, " (%s, %s, %s)\n", STR(list->path),
305 STR(list->datfile), STR(list->posfile)));
308 print_list(list->child, lev + 1);
316 * Convert the pattern to an ignore-case equivalent.
318 static char *conv_pat(const char *const orig_str)
323 size_t cnt = 1; /* allow for '\0' */
324 for (sp = orig_str; *sp != '\0'; sp++)
326 const size_t prev_cnt = cnt;
333 fprintf(stderr, "%s",
334 "pattern too long for ignoring case; overflow!\n");
338 if (!(new_buf = malloc(cnt)))
340 fprintf(stderr, "%s", "pattern too long for ignoring case\n");
345 const char *orig = orig_str;
346 for (dest_ptr = new_buf; *orig != '\0'; ++orig)
352 *dest_ptr++ = (char)toupper(*orig);
355 else if (isupper(*orig))
359 *dest_ptr++ = (char)tolower(*orig);
372 * Do a malloc, checking for NULL return.
374 static void *do_malloc(const size_t size)
376 void *new_buf = malloc(size);
380 (void)fprintf(stderr, "%s", "fortune: out of memory.\n");
388 * Return a pointer to an initialized new FILEDESC.
390 static FILEDESC *new_fp(void)
394 fp = (FILEDESC *)do_malloc(sizeof *fp);
396 fp->pos = POS_UNKNOWN;
399 fp->percent = NO_PROB;
400 fp->read_tbl = false;
401 fp->tbl.str_version = 0;
402 fp->tbl.str_numstr = 0;
403 fp->tbl.str_longlen = 0;
404 fp->tbl.str_shortlen = 0;
405 fp->tbl.str_flags = 0;
406 fp->tbl.stuff[0] = 0;
407 fp->tbl.stuff[1] = 0;
408 fp->tbl.stuff[2] = 0;
409 fp->tbl.stuff[3] = 0;
420 static inline void debugprint(const char *msg, ...)
425 vfprintf(stderr, msg, ap);
430 #define debugprint(format, ...) \
436 * Return true if the file is a directory, false otherwise.
438 static int is_dir(const char *const file)
442 if (stat(file, &sbuf) < 0)
444 debugprint("is_dir failed for file=<%s>\n", file);
447 const bool ret = (S_ISDIR(sbuf.st_mode) ? true : false);
448 debugprint("is_dir for file=<%s> gave ret=<%d>\n", file, ret);
454 * Return true if the file exists, false otherwise.
456 static int is_existant(char *file)
460 if (stat(file, &staat) == 0)
468 perror("fortune: bad juju in is_existant");
475 * Return true if the file is a fortune database file. We try and
476 * exclude files without reading them if possible to avoid
477 * overhead. Files which start with ".", or which have "illegal"
478 * suffixes, as contained in suflist[], are ruled out.
480 static int is_fortfile(const char *const file, char **datp)
482 const char *sp = strrchr(file, '/');
483 static const char *suflist[] = {/* list of "illegal" suffixes" */
484 "dat", "pos", "c", "h", "p", "i", "f", "pas", "ftn", "ins.c", "ins,pas",
485 "ins.ftn", "sml", NULL};
487 DPRINTF(2, (stderr, "is_fortfile(%s) returns ", file));
495 DPRINTF(2, (stderr, "%s", "false (file starts with '.')\n"));
498 if ((sp = strrchr(sp, '.')))
501 for (int i = 0; suflist[i]; ++i)
502 if (strcmp(sp, suflist[i]) == 0)
504 DPRINTF(2, (stderr, "false (file has suffix \".%s\")\n", sp));
509 const size_t do_len = (strlen(file) + 6);
510 char *const datfile = do_malloc(do_len + 1);
511 snprintf(datfile, do_len, "%s.dat", file);
512 if (access(datfile, R_OK) < 0)
515 DPRINTF(2, (stderr, "%s", "false (no \".dat\" file)\n"));
522 DPRINTF(2, (stderr, "%s", "true\n"));
526 static bool path_is_absolute(const char *const path)
533 if (isalpha(path[0]) && path[1] == ':' && path[2] == '/')
541 static int open4read(const char const *path)
543 return open(path, O_RDONLY | O_BINARY);
548 * Add a file to the file list.
550 static int add_file(int percent, const char *file, const char *dir,
551 FILEDESC **head, FILEDESC **tail, FILEDESC *parent)
565 const size_t do_len = (strlen(dir) + strlen(file) + 2);
566 path = do_malloc(do_len + 1);
567 snprintf(path, do_len, "%s/%s", dir, file);
570 !is_existant(path)) /* If doesn't exist, don't do anything. */
575 const int isdir = is_dir(path);
576 if ((isdir > 0 && parent) || (isdir < 0))
579 return false; /* don't recurse */
582 DPRINTF(1, (stderr, "trying to add file \"%s\"\n", path));
587 ((fd = open4read(path)) < 0)) ||
588 !path_is_absolute(path))
590 debugprint("check file fd=%d path=<%s> dir=<%s> file=<%s> percent=%d\n",
591 fd, path, dir, file, percent);
593 if (!dir && (!strchr(file, '/')))
595 if (((sp = strrchr(file, '-')) != NULL) && (strcmp(sp, "-o") == 0))
597 #define CALL__add_file(dir) add_file(percent, file, dir, head, tail, parent)
598 #define COND_CALL__add_file(loc_dir, dir) \
599 ((!strcmp((loc_dir), (dir))) ? 0 : CALL__add_file(dir))
600 /* BSD-style '-o' offensive file suffix */
602 found = CALL__add_file(LOCOFFDIR) ||
603 COND_CALL__add_file(LOCOFFDIR, OFFDIR);
604 /* put the suffix back in for better identification later */
609 (CALL__add_file(LOCFORTDIR) || CALL__add_file(LOCOFFDIR) ||
610 COND_CALL__add_file(LOCFORTDIR, FORTDIR) ||
611 COND_CALL__add_file(LOCOFFDIR, OFFDIR));
613 found = (CALL__add_file(LOCOFFDIR) ||
614 COND_CALL__add_file(LOCOFFDIR, OFFDIR));
616 found = (CALL__add_file(LOCFORTDIR) ||
617 COND_CALL__add_file(LOCFORTDIR, FORTDIR));
618 #undef COND_CALL__add_file
619 #undef CALL__add_file
621 if (!found && !parent && !dir)
622 { /* don't display an error when trying language specific files */
629 strncpy(llang, env_lang, sizeof(llang));
630 llang[sizeof(llang) - 1] = '\0';
633 /* the language string can be like "es:fr_BE:ga" */
634 while (!ret && lang && (*lang))
636 char *p = strchr(lang, ':');
639 snprintf(langdir, sizeof(langdir), "%s/%s", FORTDIR, lang);
641 if (strncmp(path, lang, 2) == 0)
643 else if (strncmp(path, langdir, strlen(FORTDIR) + 3) == 0)
663 DPRINTF(2, (stderr, "path = \"%s\"\n", path));
667 fp->percent = percent;
669 fp->name = strdup(file);
670 fp->path = strdup(path);
673 fp->utf8_charset = false;
674 const size_t do_len = (strlen(path) + 5);
675 char *testpath = do_malloc(do_len + 1);
676 snprintf(testpath, do_len, "%s.u8", path);
677 // fprintf(stderr, "State mal: %s\n", testpath);
678 if (stat(testpath, &statbuf) == 0)
679 fp->utf8_charset = true;
683 // fprintf(stderr, "Is utf8?: %i\n", fp->utf8_charset );
687 if ((isdir && !add_dir(fp)) || (!isdir && !is_fortfile(path, &fp->datfile)))
691 stderr, "fortune:%s not a fortune file or directory\n", path);
704 /* This is a hack to come around another hack - add_dir returns success
705 * if the directory is allowed to be empty, but we can not handle an
706 * empty directory... */
707 if (isdir && fp->num_children == 0)
724 else if (fp->percent == NO_PROB)
743 static int names_compare(const void *a, const void *b)
745 return strcmp(*(const char *const *)a, *(const char *const *)b);
749 * Add the contents of an entire directory.
751 static int add_dir(FILEDESC *const fp)
754 struct dirent *dirent;
756 size_t i, count_names, max_count_names;
760 if (!(dir = opendir(fp->path)))
765 FILEDESC *tailp = NULL;
766 DPRINTF(1, (stderr, "adding dir \"%s\"\n", fp->path));
767 fp->num_children = 0;
768 max_count_names = 200;
770 names = malloc(sizeof(names[0]) * max_count_names);
773 perror("Out of RAM!");
776 while ((dirent = readdir(dir)))
778 if (dirent->d_name[0] == 0)
780 char *name = strdup(dirent->d_name);
781 if (count_names == max_count_names)
783 max_count_names += 200;
784 names = realloc(names, sizeof(names[0]) * max_count_names);
787 perror("Out of RAM!");
791 names[count_names++] = name;
794 qsort(names, count_names, sizeof(names[0]), names_compare);
796 for (i = 0; i < count_names; ++i)
798 if (add_file(NO_PROB, names[i], fp->path, &fp->child, &tailp, fp))
806 if (fp->num_children == 0)
809 * Only the local fortune dir and the local offensive dir are
810 * allowed to be empty.
811 * - Brian Bassett (brianb@debian.org) 1999/07/31
813 if (strcmp(LOCFORTDIR, fp->path) == 0 ||
814 strcmp(LOCOFFDIR, fp->path) == 0)
819 stderr, "fortune: %s: No fortune files in directory.\n", fp->path);
827 * Form the file list from the file specifications.
830 static int top_level__add_file(const char *dirpath)
832 return add_file(NO_PROB, dirpath, NULL, &File_list, &File_tail, NULL);
835 static int cond_top_level__add_file(
836 const char *dirpath, const char *possible_dup)
838 if (!strcmp(dirpath, possible_dup))
842 return top_level__add_file(dirpath);
845 static int cond_top_level__LOCFORTDIR(void)
847 return cond_top_level__add_file(FORTDIR, LOCFORTDIR);
850 static int cond_top_level__OFFDIR(void)
852 return cond_top_level__add_file(OFFDIR, LOCOFFDIR);
855 static int top_level_LOCFORTDIR(void)
857 return (top_level__add_file(LOCFORTDIR) | cond_top_level__LOCFORTDIR());
860 static int form_file_list(char **files, int file_cnt)
865 char fullpathname[512], locpathname[512];
871 return (top_level__add_file(LOCFORTDIR) |
872 top_level__add_file(LOCOFFDIR) |
873 cond_top_level__LOCFORTDIR() | cond_top_level__OFFDIR());
877 return (top_level__add_file(LOCOFFDIR) | cond_top_level__OFFDIR());
888 strncpy(llang, env_lang, sizeof(llang));
889 llang[sizeof(llang) - 1] = '\0';
892 /* the language string can be like "es:fr_BE:ga" */
893 while (lang && (*lang))
895 p = strchr(lang, ':');
899 /* first try full locale */
901 NO_PROB, lang, NULL, &File_list, &File_tail, NULL);
903 /* if not try language name only (two first chars) */
908 strncpy(ll, lang, 2);
911 NO_PROB, ll, NULL, &File_list, &File_tail, NULL);
914 /* if we have found one we have finished */
920 return top_level_LOCFORTDIR();
924 /* no locales available, use default */
925 return top_level_LOCFORTDIR();
930 for (i = 0; i < file_cnt; i++)
933 if (!isdigit(files[i][0]))
937 const int MAX_PERCENT = 100;
938 bool percent_has_overflowed = false;
940 for (sp = files[i]; isdigit(*sp); sp++)
942 percent = percent * 10 + *sp - '0';
943 percent_has_overflowed = (percent > MAX_PERCENT);
944 if (percent_has_overflowed)
949 if (percent_has_overflowed || (percent > 100))
951 fprintf(stderr, "percentages must be <= 100\n");
953 "Overflow percentage detected at argument \"%s\"!\n",
961 "Overflow percentage detected at argument \"%s\"!\n",
968 fprintf(stderr, "%s", "percentages must be integers\n");
973 * If the number isn't followed by a '%', then
974 * it was not a percentage, just the first part
975 * of a file name which starts with digits.
982 else if (*++sp == '\0')
986 fprintf(stderr, "%s", "percentages must precede files\n");
993 if (strcmp(sp, "all") == 0)
995 snprintf(fullpathname, sizeof(fullpathname), "%s", FORTDIR);
996 snprintf(locpathname, sizeof(locpathname), "%s", LOCFORTDIR);
998 /* if it isn't an absolute path or relative to . or ..
999 make it an absolute path relative to FORTDIR */
1002 if (strncmp(sp, "/", 1) != 0 && strncmp(sp, "./", 2) != 0 &&
1003 strncmp(sp, "../", 3) != 0)
1006 fullpathname, sizeof(fullpathname), "%s/%s", FORTDIR, sp);
1008 locpathname, sizeof(locpathname), "%s/%s", LOCFORTDIR, sp);
1012 snprintf(fullpathname, sizeof(fullpathname), "%s", sp);
1013 snprintf(locpathname, sizeof(locpathname), "%s", sp);
1022 strncpy(llang, env_lang, sizeof(llang));
1023 llang[sizeof(llang) - 1] = '\0';
1026 /* the language string can be like "es:fr_BE:ga" */
1027 while (!ret && lang && (*lang))
1029 char *p = strchr(lang, ':');
1033 /* first try full locale */
1035 langdir, sizeof(langdir), "%s/%s/%s", FORTDIR, lang, sp);
1037 percent, langdir, NULL, &File_list, &File_tail, NULL);
1039 /* if not try language name only (two first chars) */
1044 strncpy(ll, lang, 2);
1047 langdir, sizeof(langdir), "%s/%s/%s", FORTDIR, ll, sp);
1049 percent, langdir, NULL, &File_list, &File_tail, NULL);
1057 percent, fullpathname, NULL, &File_list, &File_tail, NULL);
1059 strncmp(fullpathname, locpathname, sizeof(fullpathname)))
1061 percent, locpathname, NULL, &File_list, &File_tail, NULL);
1065 snprintf(locpathname, sizeof(locpathname), "%s/%s",
1069 percent, locpathname, NULL, &File_list, &File_tail, NULL);
1075 if (strncmp(fullpathname, locpathname, sizeof(fullpathname)) &&
1076 strcmp(sp, "all") == 0)
1079 percent, locpathname, NULL, &File_list, &File_tail, NULL);
1083 percent, fullpathname, NULL, &File_list, &File_tail, NULL))
1090 * This routine evaluates the arguments on the command line
1092 static void getargs(int argc, char **argv)
1094 bool ignore_case = false;
1103 #define DEBUG_GETOPT "D"
1105 #define DEBUG_GETOPT
1109 #define OFFENSIVE_GETOPT
1111 #define OFFENSIVE_GETOPT "o"
1114 while ((ch = getopt(argc, argv,
1115 "ac" DEBUG_GETOPT "efilm:n:" OFFENSIVE_GETOPT "suvw")) != EOF)
1118 case 'a': /* any fortune */
1127 Equal_probs = true; /* scatter un-allocted prob equally */
1129 case 'f': /* find fortune files */
1132 case 'l': /* long ones only */
1137 SLEN = atoi(optarg);
1139 #ifndef NO_OFFENSIVE
1140 case 'o': /* offensive ones only */
1144 case 's': /* short ones only */
1148 case 'w': /* give time to read */
1152 case 'i': /* case-insensitive match */
1153 case 'm': /* dump out the fortunes */
1154 (void)fprintf(stderr, "%s",
1155 "fortune: can't match fortunes on this system (Sorry)\n");
1157 #else /* NO_REGEX */
1158 case 'm': /* dump out the fortunes */
1162 case 'i': /* case-insensitive match */
1165 #endif /* NO_REGEX */
1166 case 'u': /* Don't recode the fortune */
1170 (void)printf("%s\n", program_version());
1173 Show_filename = true;
1182 if (!form_file_list(argv, argc))
1186 fprintf(stderr, "%s", "No fortunes found\n");
1188 exit(1); /* errors printed through form_file_list() */
1193 print_list(File_list, 0); /* Causes crash with new %% code */
1198 /* If (Find_files) print_list() moved to main */
1203 pat = conv_pat(pat);
1204 if (BAD_COMP(RE_COMP(pat)))
1206 fprintf(stderr, "bad pattern: %s\n", pat);
1219 * Initialize the fortune probabilities.
1221 static void init_prob(void)
1224 int percent = 0, num_noprob = 0, frac;
1227 * Distribute the residual probability (if any) across all
1228 * files with unspecified probability (i.e., probability of 0)
1231 FILEDESC *last = NULL;
1232 for (fp = File_tail; fp; fp = fp->prev)
1233 if (fp->percent == NO_PROB)
1240 percent += fp->percent;
1241 DPRINTF(1, (stderr, "summing probabilities:%d%% with %d NO_PROB's\n",
1242 percent, num_noprob));
1245 fprintf(stderr, "fortune: probabilities sum to %d%%!\n", percent);
1248 else if (percent < 100 && num_noprob == 0)
1251 "fortune: no place to put residual probability (%d%%)\n", percent);
1254 else if (percent == 100 && num_noprob != 0)
1257 stderr, "fortune: no probability left to put in residual files\n");
1260 Spec_prob = percent; /* this is for -f when % is specified on cmd line */
1261 percent = 100 - percent;
1264 if (num_noprob != 0)
1268 frac = percent / num_noprob;
1269 DPRINTF(1, (stderr, ", frac = %d%%", frac));
1270 for (fp = File_tail; fp != last; fp = fp->prev)
1271 if (fp->percent == NO_PROB)
1277 last->percent = percent;
1278 DPRINTF(1, (stderr, ", residual = %d%%", percent));
1282 DPRINTF(1, (stderr, ", %d%% distributed over remaining fortunes\n",
1286 DPRINTF(1, (stderr, "%s", "\n"));
1291 print_list(File_list, 0); /* Causes crash with new %% code */
1299 * Zero out the fields we care about in a tbl structure.
1301 static void zero_tbl(STRFILE *tp)
1304 tp->str_longlen = 0;
1305 tp->str_shortlen = (uint32_t)(-1);
1310 * Merge the tbl data of t2 into t1.
1312 static void sum_tbl(STRFILE *t1, STRFILE *t2)
1314 t1->str_numstr += t2->str_numstr;
1315 if (t1->str_longlen < t2->str_longlen)
1316 t1->str_longlen = t2->str_longlen;
1317 if (t1->str_shortlen > t2->str_shortlen)
1318 t1->str_shortlen = t2->str_shortlen;
1323 * Get the tbl data file the datfile.
1325 static void get_tbl(FILEDESC *fp)
1334 if ((fd = open4read(fp->datfile)) < 0)
1336 perror(fp->datfile);
1339 if (read(fd, &fp->tbl.str_version, sizeof fp->tbl.str_version) !=
1340 sizeof fp->tbl.str_version)
1342 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1345 if (read(fd, &fp->tbl.str_numstr, sizeof fp->tbl.str_numstr) !=
1346 sizeof fp->tbl.str_numstr)
1348 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1351 if (read(fd, &fp->tbl.str_longlen, sizeof fp->tbl.str_longlen) !=
1352 sizeof fp->tbl.str_longlen)
1354 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1357 if (read(fd, &fp->tbl.str_shortlen, sizeof fp->tbl.str_shortlen) !=
1358 sizeof fp->tbl.str_shortlen)
1360 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1363 if (read(fd, &fp->tbl.str_flags, sizeof fp->tbl.str_flags) !=
1364 sizeof fp->tbl.str_flags)
1366 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1369 if (read(fd, &fp->tbl.stuff, sizeof fp->tbl.stuff) !=
1370 sizeof fp->tbl.stuff)
1372 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1375 fp->tbl.str_version = ntohl(fp->tbl.str_version);
1376 fp->tbl.str_numstr = ntohl(fp->tbl.str_numstr);
1377 fp->tbl.str_longlen = ntohl(fp->tbl.str_longlen);
1378 fp->tbl.str_shortlen = ntohl(fp->tbl.str_shortlen);
1379 fp->tbl.str_flags = ntohl(fp->tbl.str_flags);
1385 for (child = fp->child; child; child = child->next)
1388 sum_tbl(&fp->tbl, &child->tbl);
1391 fp->read_tbl = true;
1396 * Sum up all the noprob probabilities, starting with fp.
1398 static void sum_noprobs(FILEDESC *fp)
1400 static bool did_noprobs = false;
1404 zero_tbl(&Noprob_tbl);
1408 /* This conditional should help us return correct values for -f
1409 * when a percentage is specified */
1410 if (fp->percent == NO_PROB)
1411 sum_tbl(&Noprob_tbl, &fp->tbl);
1419 * Pick a child from a chosen parent.
1421 static FILEDESC *pick_child(FILEDESC *parent)
1428 choice = my_random(parent->num_children);
1429 DPRINTF(1, (stderr, " choice = %d (of %d)\n", choice,
1430 parent->num_children));
1431 for (fp = parent->child; choice--; fp = fp->next)
1433 DPRINTF(1, (stderr, " using %s\n", fp->name));
1439 choice = (int)(my_random(parent->tbl.str_numstr));
1440 DPRINTF(1, (stderr, " choice = %d (of %ld)\n", choice,
1441 parent->tbl.str_numstr));
1442 for (fp = parent->child; choice >= (int)fp->tbl.str_numstr;
1445 choice -= fp->tbl.str_numstr;
1446 DPRINTF(1, (stderr, "\tskip %s, %ld (choice = %d)\n", fp->name,
1447 fp->tbl.str_numstr, choice));
1450 1, (stderr, " using %s, %ld\n", fp->name, fp->tbl.str_numstr));
1457 * Open up the dat file if we need to.
1459 static void open_dat(FILEDESC *fp)
1461 if (fp->datfd < 0 && (fp->datfd = open4read(fp->datfile)) < 0)
1469 * Get the position from the pos file, if there is one. If not,
1470 * return a random number.
1472 static void get_pos(FILEDESC *fp)
1474 assert(fp->read_tbl);
1475 if (fp->pos == POS_UNKNOWN)
1477 fp->pos = (int32_t)(my_random(fp->tbl.str_numstr));
1479 if (++(fp->pos) >= (int32_t)fp->tbl.str_numstr)
1480 fp->pos -= fp->tbl.str_numstr;
1481 DPRINTF(1, (stderr, "pos for %s is %ld\n", fp->name, fp->pos));
1486 * Get the fortune data file's seek pointer for the next fortune.
1488 static void get_fort(void)
1493 if (!File_list->next || File_list->percent == NO_PROB)
1497 choice = my_random(100);
1498 DPRINTF(1, (stderr, "choice = %d\n", choice));
1499 for (fp = File_list; fp->percent != NO_PROB; fp = fp->next)
1500 if (choice < fp->percent)
1504 choice -= fp->percent;
1505 DPRINTF(1, (stderr, " skip \"%s\", %d%% (choice = %d)\n",
1506 fp->name, fp->percent, choice));
1508 DPRINTF(1, (stderr, "using \"%s\", %d%% (choice = %d)\n", fp->name,
1509 fp->percent, choice));
1511 if (fp->percent != NO_PROB)
1518 choice = (int)(my_random(Noprob_tbl.str_numstr));
1519 DPRINTF(1, (stderr, "choice = %d (of %ld) \n", choice,
1520 Noprob_tbl.str_numstr));
1521 while (choice >= (int)fp->tbl.str_numstr)
1523 choice -= (int)fp->tbl.str_numstr;
1525 DPRINTF(1, (stderr, " skip \"%s\", %ld (choice = %d)\n",
1526 fp->name, fp->tbl.str_numstr, choice));
1529 (stderr, "using \"%s\", %ld\n", fp->name, fp->tbl.str_numstr));
1533 if (fp->tbl.str_numstr == 0)
1535 fprintf(stderr, "%s", "fortune: no fortune found\n");
1540 DPRINTF(1, (stderr, "%s", "picking child\n"));
1541 fp = pick_child(fp);
1547 (off_t)(sizeof fp->tbl + (size_t)fp->pos * sizeof Seekpts[0]), 0);
1548 if ((read(fp->datfd, &Seekpts[0], sizeof Seekpts[0]) < 0) ||
1549 (read(fp->datfd, &Seekpts[1], sizeof Seekpts[1]) < 0))
1553 Seekpts[0] = (int32_t)ntohl((uint32_t)Seekpts[0]);
1554 Seekpts[1] = (int32_t)ntohl((uint32_t)Seekpts[1]);
1559 * Assocatiate a FILE * with the given FILEDESC.
1561 static void open_fp(FILEDESC *fp)
1563 if (!fp->inf && !(fp->inf = fdopen(fp->fd, "r")))
1573 * Return the maximum fortune len in the file list.
1575 static int maxlen_in_list(FILEDESC *list)
1578 int len, maxlen = 0;
1580 for (fp = list; fp; fp = fp->next)
1584 if ((len = maxlen_in_list(fp->child)) > maxlen)
1590 if ((int)fp->tbl.str_longlen > maxlen)
1592 maxlen = (int)fp->tbl.str_longlen;
1601 * Print out the matches from the files in the list.
1603 static void matches_in_list(FILEDESC *list)
1606 unsigned char *p; /* -allover */
1607 unsigned char ch; /* -allover */
1612 for (fp = list; fp; fp = fp->next)
1616 matches_in_list(fp->child);
1619 DPRINTF(1, (stderr, "searching in %s\n", fp->path));
1623 while (fgets((char *)sp, Fort_len, fp->inf))
1625 if (!STR_ENDSTRING(sp, fp->tbl))
1627 sp += strlen((const char *)sp);
1632 nchar = (int)(sp - Fortbuf);
1634 if (fp->utf8_charset && (!No_recode))
1636 output = my_recode_string((const char *)Fortbuf);
1640 output = (char *)Fortbuf;
1642 /* Should maybe rot13 Fortbuf -allover */
1644 if (fp->tbl.str_flags & STR_ROTATED)
1646 for (p = (unsigned char *)output; (ch = *p); ++p)
1648 if (isupper(ch) && isascii(ch))
1649 *p = 'A' + (ch - 'A' + 13) % 26;
1650 else if (islower(ch) && isascii(ch))
1651 *p = 'a' + (ch - 'a' + 13) % 26;
1655 DPRINTF(1, (stdout, "nchar = %d\n", nchar));
1656 if ((nchar < SLEN || !Short_only) &&
1657 (nchar > SLEN || !Long_only) && RE_EXEC(output))
1662 stderr, "(%s)\n%c\n", fp->name, fp->tbl.str_delim);
1666 fputs(output, stdout);
1667 printf("%c\n", fp->tbl.str_delim);
1670 if (fp->utf8_charset && (!No_recode))
1684 * Find all the fortunes which match the pattern we've been given.
1686 static int find_matches(void)
1688 Fort_len = maxlen_in_list(File_list);
1689 DPRINTF(2, (stderr, "Maximum length is %d\n", Fort_len));
1690 /* extra length, "%\n" is appended */
1691 Fortbuf = do_malloc((unsigned int)Fort_len + 10);
1694 matches_in_list(File_list);
1700 static void display(FILEDESC *fp)
1703 unsigned char line[BUFSIZ];
1706 fseek(fp->inf, (long)Seekpts[0], SEEK_SET);
1708 printf("(%s)\n%%\n", fp->name);
1709 for (Fort_len = 0; fgets((char *)line, sizeof line, fp->inf) &&
1710 !STR_ENDSTRING(line, fp->tbl);
1713 if (fp->tbl.str_flags & STR_ROTATED)
1715 for (p = (char *)line; (ch = *p); ++p)
1717 if (isupper(ch) && isascii(ch))
1718 *p = 'A' + (ch - 'A' + 13) % 26;
1719 else if (islower(ch) && isascii(ch))
1720 *p = 'a' + (ch - 'a' + 13) % 26;
1723 if (fp->utf8_charset && (!No_recode))
1725 char *output = my_recode_string((const char *)line);
1726 fputs(output, stdout);
1730 fputs((char *)line, stdout);
1737 * Return the length of the fortune.
1739 static int fortlen(void)
1744 if (!(Fortfile->tbl.str_flags & (STR_RANDOM | STR_ORDERED)))
1745 nchar = (Seekpts[1] - Seekpts[0]) - 2; /* for %^J delimiter */
1749 fseek(Fortfile->inf, (long)Seekpts[0], SEEK_SET);
1751 while (fgets(line, sizeof line, Fortfile->inf) &&
1752 !STR_ENDSTRING(line, Fortfile->tbl))
1753 nchar += strlen(line);
1759 static int mymax(int i, int j) { return (i >= j ? i : j); }
1761 static void free_desc(FILEDESC *ptr)
1765 free_desc(ptr->child);
1775 FILEDESC *next = ptr->next;
1781 int main(int argc, char *argv[])
1788 env_lang = getenv("LC_ALL");
1790 env_lang = getenv("LC_MESSAGES");
1792 env_lang = getenv("LANGUAGE");
1794 env_lang = getenv("LANG");
1802 #ifndef DONT_CALL_GETARGS
1803 getargs(argc, argv);
1807 outer = recode_new_outer(true);
1808 request = recode_new_request(outer);
1811 setlocale(LC_ALL, "");
1817 ctype = nl_langinfo(CODESET);
1818 if (!ctype || !*ctype)
1822 else if (strcmp(ctype, "ANSI_X3.4-1968") == 0)
1824 ctype = "ISO-8859-1";
1827 const size_t do_len = strlen(ctype) + 7 + 1;
1828 char *crequest = do_malloc(do_len + 1);
1829 snprintf(crequest, do_len, "UTF-8..%s", ctype);
1830 recode_scan_request(request, crequest);
1837 exit_code = (find_matches() != 0);
1846 sum_noprobs(File_list);
1849 print_list(File_list, 0);
1857 } while ((Short_only && fortlen() > SLEN) ||
1858 (Long_only && fortlen() <= SLEN));
1865 sleep((unsigned int)mymax(Fort_len / CPERS, MINW));
1870 recode_delete_request(request);
1871 recode_delete_outer(outer);
1874 /* Free the File_list */
1875 free_desc(File_list);