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) \
123 #define DPRINTF(l, x)
134 char *datfile, *posfile;
140 struct fd *child, *parent;
141 struct fd *next, *prev;
144 static const char *env_lang = NULL;
146 static bool Found_one = false; /* did we find a match? */
147 static bool Find_files = false; /* just find a list of proper fortune files */
148 static bool Wait = false; /* wait desired after fortune */
149 static bool Short_only = false; /* short fortune desired */
150 static bool Long_only = false; /* long fortune desired */
151 static bool Offend = false; /* offensive fortunes only */
152 static bool All_forts = false; /* any fortune allowed */
153 static bool Equal_probs = false; /* scatter un-allocated prob equally */
154 static bool Show_filename = false;
155 static bool No_recode = false; /* Do we want to stop recoding from occuring */
157 static bool ErrorMessage =
158 false; /* Set to true if an error message has been displayed */
162 #define RE_COMP(p) regcomp(&Re_pat, (p), REG_NOSUB)
163 #define BAD_COMP(f) ((f) != 0)
164 #define RE_EXEC(p) (regexec(&Re_pat, (p), 0, NULL, 0) == 0)
166 static regex_t Re_pat;
169 #endif /* POSIX_REGEX */
172 static bool Match = false; /* dump fortunes matching a pattern */
176 static bool Debug = false; /* print debug messages */
179 static unsigned char *Fortbuf = NULL; /* fortune buffer for -m */
181 static int Fort_len = 0, Spec_prob = 0, /* total prob specified on cmd line */
182 Num_files, Num_kids, /* totals of files and children. */
183 SLEN = 160; /* max. characters in a "short" fortune */
185 static int32_t Seekpts[2]; /* seek pointers to fortunes */
187 static FILEDESC *File_list = NULL, /* Head of file list */
188 *File_tail = NULL; /* Tail of file list */
189 static FILEDESC *Fortfile; /* Fortune file to use */
191 static STRFILE Noprob_tbl; /* sum of data for all no prob files */
194 static RECODE_REQUEST request;
195 static RECODE_OUTER outer;
196 static inline char *my_recode_string(const char *s)
198 return recode_string(request, (const char *)s);
201 static inline char *my_recode_string(const char *s) { return strdup(s); }
204 static int add_dir(FILEDESC *);
206 static unsigned long my_random(const unsigned long base)
208 unsigned long long l = 0;
209 char *hard_coded_val = getenv("FORTUNE_MOD_RAND_HARD_CODED_VALS");
212 return ((unsigned long)atol(hard_coded_val) % base);
214 if (getenv("FORTUNE_MOD_USE_SRAND"))
218 FILE *const fp = fopen("/dev/urandom", "rb");
223 if (fread(&l, sizeof(l), 1, fp) != 1)
231 return (((unsigned long)random()) % base);
234 static char *program_version(void)
236 static char buf[BUFSIZ];
237 (void)snprintf(buf, sizeof(buf), "%s version %s", PROGRAM_NAME, VERSION);
241 static void __attribute__((noreturn)) usage(void)
243 (void)fprintf(stderr, "%s\n", program_version());
244 (void)fprintf(stderr, "%s", "fortune [-a");
246 (void)fprintf(stderr, "%s", "D");
248 (void)fprintf(stderr, "%s", "f");
250 (void)fprintf(stderr, "%s", "i");
252 (void)fprintf(stderr, "%s", "l");
254 (void)fprintf(stderr, "%s", "o");
256 (void)fprintf(stderr, "%s", "sw]");
258 (void)fprintf(stderr, "%s", " [-m pattern]");
260 (void)fprintf(stderr, "%s", " [-n number] [ [#%] file/directory/all]\n");
264 #define STR(str) ((!str) ? "NULL" : (str))
268 * Set the global values for number of files/children, to be used
269 * in printing probabilities when listing files
271 static void calc_equal_probs(void)
273 Num_files = Num_kids = 0;
274 FILEDESC *fiddlylist = File_list;
278 Num_kids += fiddlylist->num_children;
279 fiddlylist = fiddlylist->next;
285 * Print out the actual list, recursively.
287 static void print_list(FILEDESC *list, int lev)
291 fprintf(stderr, "%*s", lev * 4, "");
292 if (list->percent == NO_PROB)
296 /* This, with some changes elsewhere, gives proper percentages
297 * for every case fprintf(stderr, "___%%"); */
298 fprintf(stderr, "%5.2f%%",
299 (100.0 - Spec_prob) * list->tbl.str_numstr /
300 Noprob_tbl.str_numstr);
304 fprintf(stderr, "%5.2f%%", 100.0 / Num_files);
308 fprintf(stderr, "%5.2f%%", 100.0 / Num_kids);
313 fprintf(stderr, "%5.2f%%", 1.0 * list->percent);
315 fprintf(stderr, " %s", STR(list->name));
316 DPRINTF(1, (stderr, " (%s, %s, %s)\n", STR(list->path),
317 STR(list->datfile), STR(list->posfile)));
321 print_list(list->child, lev + 1);
330 * Convert the pattern to an ignore-case equivalent.
332 static char *conv_pat(const char *const orig_str)
337 size_t cnt = 1; /* allow for '\0' */
338 for (sp = orig_str; *sp != '\0'; sp++)
340 const size_t prev_cnt = cnt;
351 fprintf(stderr, "%s",
352 "pattern too long for ignoring case; overflow!\n");
356 if (!(new_buf = malloc(cnt)))
358 fprintf(stderr, "%s", "pattern too long for ignoring case\n");
363 const char *orig = orig_str;
364 for (dest_ptr = new_buf; *orig != '\0'; ++orig)
370 *dest_ptr++ = (char)toupper(*orig);
373 else if (isupper(*orig))
377 *dest_ptr++ = (char)tolower(*orig);
392 * Do a malloc, checking for NULL return.
394 static void *do_malloc(const size_t size)
396 void *new_buf = malloc(size);
400 (void)fprintf(stderr, "%s", "fortune: out of memory.\n");
408 * Return a pointer to an initialized new FILEDESC.
410 static FILEDESC *new_fp(void)
414 fp = (FILEDESC *)do_malloc(sizeof *fp);
416 fp->pos = POS_UNKNOWN;
419 fp->percent = NO_PROB;
420 fp->read_tbl = false;
421 fp->tbl.str_version = 0;
422 fp->tbl.str_numstr = 0;
423 fp->tbl.str_longlen = 0;
424 fp->tbl.str_shortlen = 0;
425 fp->tbl.str_flags = 0;
426 fp->tbl.stuff[0] = 0;
427 fp->tbl.stuff[1] = 0;
428 fp->tbl.stuff[2] = 0;
429 fp->tbl.stuff[3] = 0;
440 static inline void debugprint(const char *msg, ...)
445 vfprintf(stderr, msg, ap);
450 #define debugprint(format, ...) \
456 * Return true if the file is a directory, false otherwise.
458 static int is_dir(const char *const file)
462 if (stat(file, &sbuf) < 0)
464 debugprint("is_dir failed for file=<%s>\n", file);
467 const bool ret = (S_ISDIR(sbuf.st_mode) ? true : false);
468 debugprint("is_dir for file=<%s> gave ret=<%d>\n", file, ret);
474 * Return true if the file exists, false otherwise.
476 static int is_existant(char *file)
480 if (stat(file, &staat) == 0)
490 perror("fortune: bad juju in is_existant");
497 * Return true if the file is a fortune database file. We try and
498 * exclude files without reading them if possible to avoid
499 * overhead. Files which start with ".", or which have "illegal"
500 * suffixes, as contained in suflist[], are ruled out.
502 static int is_fortfile(const char *const file, char **datp)
504 const char *sp = strrchr(file, '/');
505 static const char *suflist[] = {/* list of "illegal" suffixes" */
506 "dat", "pos", "c", "h", "p", "i", "f", "pas", "ftn", "ins.c", "ins,pas",
507 "ins.ftn", "sml", NULL};
509 DPRINTF(2, (stderr, "is_fortfile(%s) returns ", file));
521 DPRINTF(2, (stderr, "%s", "false (file starts with '.')\n"));
524 if ((sp = strrchr(sp, '.')))
527 for (int i = 0; suflist[i]; ++i)
529 if (strcmp(sp, suflist[i]) == 0)
531 DPRINTF(2, (stderr, "false (file has suffix \".%s\")\n", sp));
537 const size_t do_len = (strlen(file) + 6);
538 char *const datfile = do_malloc(do_len + 1);
539 snprintf(datfile, do_len, "%s.dat", file);
540 if (access(datfile, R_OK) < 0)
543 DPRINTF(2, (stderr, "%s", "false (no \".dat\" file)\n"));
554 DPRINTF(2, (stderr, "%s", "true\n"));
558 static bool path_is_absolute(const char *const path)
565 if (isalpha(path[0]) && path[1] == ':' && path[2] == '/')
573 static int open4read(const char *const path)
575 return open(path, O_RDONLY | O_BINARY);
580 * Add a file to the file list.
582 #define GCC_SNPRINTF_MARGIN 10
583 static int add_file(int percent, const char *file, const char *dir,
584 FILEDESC **head, FILEDESC **tail, FILEDESC *parent)
598 const size_t do_len =
599 (strlen(dir) + strlen(file) + (2 + GCC_SNPRINTF_MARGIN));
600 path = do_malloc(do_len + 1);
601 snprintf(path, do_len, "%s/%s", dir, file);
604 !is_existant(path)) /* If doesn't exist, don't do anything. */
609 const int isdir = is_dir(path);
610 if ((isdir > 0 && parent) || (isdir < 0))
613 return false; /* don't recurse */
616 DPRINTF(1, (stderr, "trying to add file \"%s\"\n", path));
621 ((fd = open4read(path)) < 0)) ||
622 !path_is_absolute(path))
624 debugprint("check file fd=%d path=<%s> dir=<%s> file=<%s> percent=%d\n",
625 fd, path, dir, file, percent);
627 if (!dir && (!strchr(file, '/')))
629 if (((sp = strrchr(file, '-')) != NULL) && (strcmp(sp, "-o") == 0))
631 #define CALL__add_file(dir) add_file(percent, file, dir, head, tail, parent)
632 #define COND_CALL__add_file(loc_dir, dir) \
633 ((!strcmp((loc_dir), (dir))) ? 0 : CALL__add_file(dir))
634 /* BSD-style '-o' offensive file suffix */
636 found = CALL__add_file(LOCOFFDIR) ||
637 COND_CALL__add_file(LOCOFFDIR, OFFDIR);
638 /* put the suffix back in for better identification later */
644 (CALL__add_file(LOCFORTDIR) || CALL__add_file(LOCOFFDIR) ||
645 COND_CALL__add_file(LOCFORTDIR, FORTDIR) ||
646 COND_CALL__add_file(LOCOFFDIR, OFFDIR));
650 found = (CALL__add_file(LOCOFFDIR) ||
651 COND_CALL__add_file(LOCOFFDIR, OFFDIR));
655 found = (CALL__add_file(LOCFORTDIR) ||
656 COND_CALL__add_file(LOCFORTDIR, FORTDIR));
658 #undef COND_CALL__add_file
659 #undef CALL__add_file
661 if (!found && !parent && !dir)
662 { /* don't display an error when trying language specific files */
669 strncpy(llang, env_lang, sizeof(llang));
670 llang[sizeof(llang) - 1] = '\0';
673 /* the language string can be like "es:fr_BE:ga" */
674 while (!ret && lang && (*lang))
676 char *p = strchr(lang, ':');
681 snprintf(langdir, sizeof(langdir), "%s/%s", FORTDIR, lang);
683 if (strncmp(path, lang, 2) == 0)
687 else if (strncmp(path, langdir, strlen(FORTDIR) + 3) == 0)
709 DPRINTF(2, (stderr, "path = \"%s\"\n", path));
713 fp->percent = percent;
715 fp->name = strdup(file);
716 fp->path = strdup(path);
719 fp->utf8_charset = false;
720 const size_t do_len = (strlen(path) + 5);
721 char *testpath = do_malloc(do_len + 1);
722 snprintf(testpath, do_len, "%s.u8", path);
723 // fprintf(stderr, "State mal: %s\n", testpath);
724 if (stat(testpath, &statbuf) == 0)
726 fp->utf8_charset = true;
731 // fprintf(stderr, "Is utf8?: %i\n", fp->utf8_charset );
735 if ((isdir && !add_dir(fp)) || (!isdir && !is_fortfile(path, &fp->datfile)))
740 stderr, "fortune:%s not a fortune file or directory\n", path);
756 /* This is a hack to come around another hack - add_dir returns success
757 * if the directory is allowed to be empty, but we can not handle an
758 * empty directory... */
759 if (isdir && fp->num_children == 0)
780 else if (fp->percent == NO_PROB)
799 static int names_compare(const void *a, const void *b)
801 return strcmp(*(const char *const *)a, *(const char *const *)b);
805 * Add the contents of an entire directory.
807 static int add_dir(FILEDESC *const fp)
810 struct dirent *dirent;
812 size_t i, count_names, max_count_names;
816 if (!(dir = opendir(fp->path)))
821 FILEDESC *tailp = NULL;
822 DPRINTF(1, (stderr, "adding dir \"%s\"\n", fp->path));
823 fp->num_children = 0;
824 max_count_names = 200;
826 names = malloc(sizeof(names[0]) * max_count_names);
829 perror("Out of RAM!");
832 while ((dirent = readdir(dir)))
834 if (dirent->d_name[0] == 0)
838 char *name = strdup(dirent->d_name);
839 if (count_names == max_count_names)
841 max_count_names += 200;
842 names = realloc(names, sizeof(names[0]) * max_count_names);
845 perror("Out of RAM!");
849 names[count_names++] = name;
852 qsort(names, count_names, sizeof(names[0]), names_compare);
854 for (i = 0; i < count_names; ++i)
856 if (add_file(NO_PROB, names[i], fp->path, &fp->child, &tailp, fp))
864 if (fp->num_children == 0)
867 * Only the local fortune dir and the local offensive dir are
868 * allowed to be empty.
869 * - Brian Bassett (brianb@debian.org) 1999/07/31
871 if (strcmp(LOCFORTDIR, fp->path) == 0 ||
872 strcmp(LOCOFFDIR, fp->path) == 0)
877 stderr, "fortune: %s: No fortune files in directory.\n", fp->path);
885 * Form the file list from the file specifications.
888 static int top_level__add_file(const char *dirpath)
890 return add_file(NO_PROB, dirpath, NULL, &File_list, &File_tail, NULL);
893 static int cond_top_level__add_file(
894 const char *dirpath, const char *possible_dup)
896 if (!strcmp(dirpath, possible_dup))
900 return top_level__add_file(dirpath);
903 static int cond_top_level__LOCFORTDIR(void)
905 return cond_top_level__add_file(FORTDIR, LOCFORTDIR);
908 static int cond_top_level__OFFDIR(void)
910 return cond_top_level__add_file(OFFDIR, LOCOFFDIR);
913 static int top_level_LOCFORTDIR(void)
915 return (top_level__add_file(LOCFORTDIR) | cond_top_level__LOCFORTDIR());
918 static int form_file_list(char **files, int file_cnt)
923 char fullpathname[512], locpathname[512];
929 return (top_level__add_file(LOCFORTDIR) |
930 top_level__add_file(LOCOFFDIR) |
931 cond_top_level__LOCFORTDIR() | cond_top_level__OFFDIR());
935 return (top_level__add_file(LOCOFFDIR) | cond_top_level__OFFDIR());
946 strncpy(llang, env_lang, sizeof(llang));
947 llang[sizeof(llang) - 1] = '\0';
950 /* the language string can be like "es:fr_BE:ga" */
951 while (lang && (*lang))
953 p = strchr(lang, ':');
959 /* first try full locale */
961 NO_PROB, lang, NULL, &File_list, &File_tail, NULL);
963 /* if not try language name only (two first chars) */
968 strncpy(ll, lang, 2);
971 NO_PROB, ll, NULL, &File_list, &File_tail, NULL);
974 /* if we have found one we have finished */
982 return top_level_LOCFORTDIR();
986 /* no locales available, use default */
987 return top_level_LOCFORTDIR();
992 for (i = 0; i < file_cnt; i++)
995 if (!isdigit(files[i][0]))
1001 const int MAX_PERCENT = 100;
1002 bool percent_has_overflowed = false;
1004 for (sp = files[i]; isdigit(*sp); sp++)
1006 percent = percent * 10 + *sp - '0';
1007 percent_has_overflowed = (percent > MAX_PERCENT);
1008 if (percent_has_overflowed)
1013 if (percent_has_overflowed || (percent > 100))
1015 fprintf(stderr, "percentages must be <= 100\n");
1017 "Overflow percentage detected at argument \"%s\"!\n",
1019 ErrorMessage = true;
1025 "Overflow percentage detected at argument \"%s\"!\n",
1027 ErrorMessage = true;
1032 fprintf(stderr, "%s", "percentages must be integers\n");
1033 ErrorMessage = true;
1037 * If the number isn't followed by a '%', then
1038 * it was not a percentage, just the first part
1039 * of a file name which starts with digits.
1046 else if (*++sp == '\0')
1048 if (++i >= file_cnt)
1050 fprintf(stderr, "%s", "percentages must precede files\n");
1051 ErrorMessage = true;
1057 if (strcmp(sp, "all") == 0)
1059 snprintf(fullpathname, sizeof(fullpathname), "%s", FORTDIR);
1060 snprintf(locpathname, sizeof(locpathname), "%s", LOCFORTDIR);
1062 /* if it isn't an absolute path or relative to . or ..
1063 make it an absolute path relative to FORTDIR */
1066 if (strncmp(sp, "/", 1) != 0 && strncmp(sp, "./", 2) != 0 &&
1067 strncmp(sp, "../", 3) != 0)
1070 fullpathname, sizeof(fullpathname), "%s/%s", FORTDIR, sp);
1072 locpathname, sizeof(locpathname), "%s/%s", LOCFORTDIR, sp);
1076 snprintf(fullpathname, sizeof(fullpathname), "%s", sp);
1077 snprintf(locpathname, sizeof(locpathname), "%s", sp);
1086 strncpy(llang, env_lang, sizeof(llang));
1087 llang[sizeof(llang) - 1] = '\0';
1090 /* the language string can be like "es:fr_BE:ga" */
1091 while (!ret && lang && (*lang))
1093 char *p = strchr(lang, ':');
1099 /* first try full locale */
1101 langdir, sizeof(langdir), "%s/%s/%s", FORTDIR, lang, sp);
1103 percent, langdir, NULL, &File_list, &File_tail, NULL);
1105 /* if not try language name only (two first chars) */
1110 strncpy(ll, lang, 2);
1113 langdir, sizeof(langdir), "%s/%s/%s", FORTDIR, ll, sp);
1115 percent, langdir, NULL, &File_list, &File_tail, NULL);
1124 percent, fullpathname, NULL, &File_list, &File_tail, NULL);
1127 strncmp(fullpathname, locpathname, sizeof(fullpathname)))
1130 percent, locpathname, NULL, &File_list, &File_tail, NULL);
1134 snprintf(locpathname, sizeof(locpathname), "%s/%s",
1138 percent, locpathname, NULL, &File_list, &File_tail, NULL);
1144 if (strncmp(fullpathname, locpathname, sizeof(fullpathname)) &&
1145 strcmp(sp, "all") == 0)
1148 percent, locpathname, NULL, &File_list, &File_tail, NULL);
1152 percent, fullpathname, NULL, &File_list, &File_tail, NULL))
1161 * This routine evaluates the arguments on the command line
1163 static void getargs(int argc, char **argv)
1165 bool ignore_case = false;
1174 #define DEBUG_GETOPT "D"
1176 #define DEBUG_GETOPT
1180 #define OFFENSIVE_GETOPT
1182 #define OFFENSIVE_GETOPT "o"
1185 while ((ch = getopt(argc, argv,
1186 "ac" DEBUG_GETOPT "efilm:n:" OFFENSIVE_GETOPT "suvw")) != EOF)
1190 case 'a': /* any fortune */
1199 Equal_probs = true; /* scatter un-allocted prob equally */
1201 case 'f': /* find fortune files */
1204 case 'l': /* long ones only */
1209 SLEN = atoi(optarg);
1211 #ifndef NO_OFFENSIVE
1212 case 'o': /* offensive ones only */
1216 case 's': /* short ones only */
1220 case 'w': /* give time to read */
1224 case 'i': /* case-insensitive match */
1225 case 'm': /* dump out the fortunes */
1226 (void)fprintf(stderr, "%s",
1227 "fortune: can't match fortunes on this system "
1230 #else /* NO_REGEX */
1231 case 'm': /* dump out the fortunes */
1235 case 'i': /* case-insensitive match */
1238 #endif /* NO_REGEX */
1239 case 'u': /* Don't recode the fortune */
1243 (void)printf("%s\n", program_version());
1246 Show_filename = true;
1256 if (!form_file_list(argv, argc))
1260 fprintf(stderr, "%s", "No fortunes found\n");
1262 exit(1); /* errors printed through form_file_list() */
1267 print_list(File_list, 0); /* Causes crash with new %% code */
1272 /* If (Find_files) print_list() moved to main */
1278 pat = conv_pat(pat);
1280 if (BAD_COMP(RE_COMP(pat)))
1282 fprintf(stderr, "bad pattern: %s\n", pat);
1295 * Initialize the fortune probabilities.
1297 static void init_prob(void)
1300 int percent = 0, num_noprob = 0, frac;
1303 * Distribute the residual probability (if any) across all
1304 * files with unspecified probability (i.e., probability of 0)
1307 FILEDESC *last = NULL;
1308 for (fp = File_tail; fp; fp = fp->prev)
1310 if (fp->percent == NO_PROB)
1320 percent += fp->percent;
1323 DPRINTF(1, (stderr, "summing probabilities:%d%% with %d NO_PROB's\n",
1324 percent, num_noprob));
1327 fprintf(stderr, "fortune: probabilities sum to %d%%!\n", percent);
1330 else if (percent < 100 && num_noprob == 0)
1333 "fortune: no place to put residual probability "
1338 else if (percent == 100 && num_noprob != 0)
1340 fprintf(stderr, "fortune: no probability left to put in "
1341 "residual files\n");
1344 Spec_prob = percent; /* this is for -f when % is specified on
1346 percent = 100 - percent;
1349 if (num_noprob != 0)
1353 frac = percent / num_noprob;
1354 DPRINTF(1, (stderr, ", frac = %d%%", frac));
1355 for (fp = File_tail; fp != last; fp = fp->prev)
1357 if (fp->percent == NO_PROB)
1364 last->percent = percent;
1365 DPRINTF(1, (stderr, ", residual = %d%%", percent));
1369 DPRINTF(1, (stderr, ", %d%% distributed over remaining fortunes\n",
1373 DPRINTF(1, (stderr, "%s", "\n"));
1379 print_list(File_list, 0); /* Causes crash with new %% code */
1388 * Zero out the fields we care about in a tbl structure.
1390 static void zero_tbl(STRFILE *tp)
1393 tp->str_longlen = 0;
1394 tp->str_shortlen = (uint32_t)(-1);
1399 * Merge the tbl data of t2 into t1.
1401 static void sum_tbl(STRFILE *t1, STRFILE *t2)
1403 t1->str_numstr += t2->str_numstr;
1404 if (t1->str_longlen < t2->str_longlen)
1406 t1->str_longlen = t2->str_longlen;
1408 if (t1->str_shortlen > t2->str_shortlen)
1410 t1->str_shortlen = t2->str_shortlen;
1416 * Get the tbl data file the datfile.
1418 static void get_tbl(FILEDESC *fp)
1429 if ((fd = open4read(fp->datfile)) < 0)
1431 perror(fp->datfile);
1434 if (read(fd, &fp->tbl.str_version, sizeof fp->tbl.str_version) !=
1435 sizeof fp->tbl.str_version)
1437 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1440 if (read(fd, &fp->tbl.str_numstr, sizeof fp->tbl.str_numstr) !=
1441 sizeof fp->tbl.str_numstr)
1443 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1446 if (read(fd, &fp->tbl.str_longlen, sizeof fp->tbl.str_longlen) !=
1447 sizeof fp->tbl.str_longlen)
1449 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1452 if (read(fd, &fp->tbl.str_shortlen, sizeof fp->tbl.str_shortlen) !=
1453 sizeof fp->tbl.str_shortlen)
1455 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1458 if (read(fd, &fp->tbl.str_flags, sizeof fp->tbl.str_flags) !=
1459 sizeof fp->tbl.str_flags)
1461 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1464 if (read(fd, &fp->tbl.stuff, sizeof fp->tbl.stuff) !=
1465 sizeof fp->tbl.stuff)
1467 fprintf(stderr, "fortune: %s corrupted\n", fp->path);
1470 fp->tbl.str_version = ntohl(fp->tbl.str_version);
1471 fp->tbl.str_numstr = ntohl(fp->tbl.str_numstr);
1472 fp->tbl.str_longlen = ntohl(fp->tbl.str_longlen);
1473 fp->tbl.str_shortlen = ntohl(fp->tbl.str_shortlen);
1474 fp->tbl.str_flags = ntohl(fp->tbl.str_flags);
1480 for (child = fp->child; child; child = child->next)
1483 sum_tbl(&fp->tbl, &child->tbl);
1486 fp->read_tbl = true;
1491 * Sum up all the noprob probabilities, starting with fp.
1493 static void sum_noprobs(FILEDESC *fp)
1495 static bool did_noprobs = false;
1501 zero_tbl(&Noprob_tbl);
1505 /* This conditional should help us return correct values for
1506 * -f when a percentage is specified */
1507 if (fp->percent == NO_PROB)
1509 sum_tbl(&Noprob_tbl, &fp->tbl);
1518 * Pick a child from a chosen parent.
1520 static FILEDESC *pick_child(FILEDESC *parent)
1527 choice = (int)my_random((unsigned long)parent->num_children);
1528 DPRINTF(1, (stderr, " choice = %d (of %d)\n", choice,
1529 parent->num_children));
1530 for (fp = parent->child; choice--; fp = fp->next)
1534 DPRINTF(1, (stderr, " using %s\n", fp->name));
1540 choice = (int)(my_random(parent->tbl.str_numstr));
1541 DPRINTF(1, (stderr, " choice = %d (of %ld)\n", choice,
1542 parent->tbl.str_numstr));
1543 for (fp = parent->child; choice >= (int)fp->tbl.str_numstr;
1546 choice -= fp->tbl.str_numstr;
1547 DPRINTF(1, (stderr, "\tskip %s, %ld (choice = %d)\n", fp->name,
1548 fp->tbl.str_numstr, choice));
1551 1, (stderr, " using %s, %ld\n", fp->name, fp->tbl.str_numstr));
1558 * Open up the dat file if we need to.
1560 static void open_dat(FILEDESC *fp)
1562 if (fp->datfd < 0 && (fp->datfd = open4read(fp->datfile)) < 0)
1570 * Get the position from the pos file, if there is one. If
1571 * not, return a random number.
1573 static void get_pos(FILEDESC *fp)
1575 assert(fp->read_tbl);
1576 if (fp->pos == POS_UNKNOWN)
1578 fp->pos = (int32_t)(my_random(fp->tbl.str_numstr));
1580 if (++(fp->pos) >= (int32_t)fp->tbl.str_numstr)
1582 fp->pos -= fp->tbl.str_numstr;
1584 DPRINTF(1, (stderr, "pos for %s is %ld\n", fp->name, fp->pos));
1589 * Get the fortune data file's seek pointer for the next
1592 static void get_fort(void)
1597 if (!File_list->next || File_list->percent == NO_PROB)
1603 choice = (int)my_random(100);
1604 DPRINTF(1, (stderr, "choice = %d\n", choice));
1605 for (fp = File_list; fp->percent != NO_PROB; fp = fp->next)
1607 if (choice < fp->percent)
1613 choice -= fp->percent;
1614 DPRINTF(1, (stderr, " skip \"%s\", %d%% (choice = %d)\n",
1615 fp->name, fp->percent, choice));
1618 DPRINTF(1, (stderr, "using \"%s\", %d%% (choice = %d)\n", fp->name,
1619 fp->percent, choice));
1621 if (fp->percent != NO_PROB)
1630 choice = (int)(my_random(Noprob_tbl.str_numstr));
1631 DPRINTF(1, (stderr, "choice = %d (of %ld) \n", choice,
1632 Noprob_tbl.str_numstr));
1633 while (choice >= (int)fp->tbl.str_numstr)
1635 choice -= (int)fp->tbl.str_numstr;
1637 DPRINTF(1, (stderr, " skip \"%s\", %ld (choice = %d)\n",
1638 fp->name, fp->tbl.str_numstr, choice));
1641 (stderr, "using \"%s\", %ld\n", fp->name, fp->tbl.str_numstr));
1645 if (fp->tbl.str_numstr == 0)
1647 fprintf(stderr, "%s", "fortune: no fortune found\n");
1652 DPRINTF(1, (stderr, "%s", "picking child\n"));
1653 fp = pick_child(fp);
1659 (off_t)(sizeof fp->tbl + (size_t)fp->pos * sizeof Seekpts[0]), 0);
1660 if ((read(fp->datfd, &Seekpts[0], sizeof Seekpts[0]) < 0) ||
1661 (read(fp->datfd, &Seekpts[1], sizeof Seekpts[1]) < 0))
1665 Seekpts[0] = (int32_t)ntohl((uint32_t)Seekpts[0]);
1666 Seekpts[1] = (int32_t)ntohl((uint32_t)Seekpts[1]);
1671 * Assocatiate a FILE * with the given FILEDESC.
1673 static void open_fp(FILEDESC *fp)
1675 if (!fp->inf && !(fp->inf = fdopen(fp->fd, "r")))
1685 * Return the maximum fortune len in the file list.
1687 static int maxlen_in_list(FILEDESC *list)
1690 int len, maxlen = 0;
1692 for (fp = list; fp; fp = fp->next)
1696 if ((len = maxlen_in_list(fp->child)) > maxlen)
1704 if ((int)fp->tbl.str_longlen > maxlen)
1706 maxlen = (int)fp->tbl.str_longlen;
1715 * Print out the matches from the files in the list.
1717 static void matches_in_list(FILEDESC *list)
1720 unsigned char *p; /* -allover */
1721 unsigned char ch; /* -allover */
1726 for (fp = list; fp; fp = fp->next)
1730 matches_in_list(fp->child);
1733 DPRINTF(1, (stderr, "searching in %s\n", fp->path));
1737 while (fgets((char *)sp, Fort_len, fp->inf))
1739 if (!STR_ENDSTRING(sp, fp->tbl))
1741 sp += strlen((const char *)sp);
1746 nchar = (int)(sp - Fortbuf);
1748 if (fp->utf8_charset && (!No_recode))
1750 output = my_recode_string((const char *)Fortbuf);
1754 output = (char *)Fortbuf;
1756 /* Should maybe rot13 Fortbuf -allover */
1758 if (fp->tbl.str_flags & STR_ROTATED)
1760 for (p = (unsigned char *)output; (ch = *p); ++p)
1762 if (isupper(ch) && isascii(ch))
1764 *p = 'A' + (ch - 'A' + 13) % 26;
1766 else if (islower(ch) && isascii(ch))
1768 *p = 'a' + (ch - 'a' + 13) % 26;
1773 DPRINTF(1, (stdout, "nchar = %d\n", nchar));
1774 if ((nchar < SLEN || !Short_only) &&
1775 (nchar > SLEN || !Long_only) && RE_EXEC(output))
1780 stderr, "(%s)\n%c\n", fp->name, fp->tbl.str_delim);
1784 fputs(output, stdout);
1785 printf("%c\n", fp->tbl.str_delim);
1788 if (fp->utf8_charset && (!No_recode))
1802 * Find all the fortunes which match the pattern we've been
1805 static int find_matches(void)
1807 Fort_len = maxlen_in_list(File_list);
1808 DPRINTF(2, (stderr, "Maximum length is %d\n", Fort_len));
1809 /* extra length, "%\n" is appended */
1810 Fortbuf = do_malloc((unsigned int)Fort_len + 10);
1813 matches_in_list(File_list);
1819 static void display(FILEDESC *fp)
1822 unsigned char line[BUFSIZ];
1825 fseek(fp->inf, (long)Seekpts[0], SEEK_SET);
1828 printf("(%s)\n%%\n", fp->name);
1830 for (Fort_len = 0; fgets((char *)line, sizeof line, fp->inf) &&
1831 !STR_ENDSTRING(line, fp->tbl);
1834 if (fp->tbl.str_flags & STR_ROTATED)
1836 for (p = (char *)line; (ch = *p); ++p)
1838 if (isupper(ch) && isascii(ch))
1840 *p = 'A' + (ch - 'A' + 13) % 26;
1842 else if (islower(ch) && isascii(ch))
1844 *p = 'a' + (ch - 'a' + 13) % 26;
1848 if (fp->utf8_charset && (!No_recode))
1850 char *output = my_recode_string((const char *)line);
1851 fputs(output, stdout);
1855 fputs((char *)line, stdout);
1862 * Return the length of the fortune.
1864 static int fortlen(void)
1869 if (!(Fortfile->tbl.str_flags & (STR_RANDOM | STR_ORDERED)))
1871 nchar = (Seekpts[1] - Seekpts[0]) - 2; /* for %^J delimiter */
1876 fseek(Fortfile->inf, (long)Seekpts[0], SEEK_SET);
1878 while (fgets(line, sizeof line, Fortfile->inf) &&
1879 !STR_ENDSTRING(line, Fortfile->tbl))
1881 nchar += strlen(line);
1888 static int mymax(int i, int j) { return (i >= j ? i : j); }
1890 static void free_desc(FILEDESC *ptr)
1894 free_desc(ptr->child);
1904 FILEDESC *next = ptr->next;
1910 int main(int argc, char *argv[])
1917 env_lang = getenv("LC_ALL");
1920 env_lang = getenv("LC_MESSAGES");
1924 env_lang = getenv("LANGUAGE");
1928 env_lang = getenv("LANG");
1937 getargs(argc, argv);
1939 outer = recode_new_outer(true);
1940 request = recode_new_request(outer);
1943 setlocale(LC_ALL, "");
1949 ctype = nl_langinfo(CODESET);
1950 if (!ctype || !*ctype)
1954 else if (strcmp(ctype, "ANSI_X3.4-1968") == 0)
1956 ctype = "ISO-8859-1";
1959 const size_t do_len = strlen(ctype) + (7 + 1 + GCC_SNPRINTF_MARGIN);
1960 char *crequest = do_malloc(do_len + 1);
1961 snprintf(crequest, do_len, "UTF-8..%s", ctype);
1962 recode_scan_request(request, crequest);
1969 exit_code = (find_matches() != 0);
1978 sum_noprobs(File_list);
1983 print_list(File_list, 0);
1991 } while ((Short_only && fortlen() > SLEN) ||
1992 (Long_only && fortlen() <= SLEN));
1999 sleep((unsigned int)mymax(Fort_len / CPERS, MINW));
2004 recode_delete_request(request);
2005 recode_delete_outer(outer);
2008 /* Free the File_list */
2009 free_desc(File_list);