]> granicus.if.org Git - fortune-mod/blobdiff - fortune-mod/fortune/fortune.c
Re-implement BSD-style -o suffix support
[fortune-mod] / fortune-mod / fortune / fortune.c
index 200d190ac6efeaaa5a0caa1c2d67f99eb666f810..d68e523bd83f2ad2266cc0af83d28f2d620268d5 100644 (file)
@@ -79,6 +79,7 @@
 
 #define PROGRAM_NAME "fortune-mod"
 
+#include "config.h"
 #include "fortune-mod-common.h"
 
 #include <dirent.h>
 #include <assert.h>
 #include <errno.h>
 #include <locale.h>
+
 #ifndef _WIN32
+
 #include <langinfo.h>
 #define O_BINARY 0
+
+#ifdef HAVE_RECODE_H
 #define WITH_RECODE
 #endif
+
+#endif
+
 #ifdef WITH_RECODE
 #include <recode.h>
 #endif
 #ifdef HAVE_REGEX_H
 #include <regex.h>
 #endif
-#ifdef HAVE_REGEXP_H
-#include <regexp.h>
-#endif
-#ifdef HAVE_RX_H
-#include <rx.h>
-#endif
-
-#include "config.h"
 
 #define MINW 6   /* minimum wait if desired */
 #define CPERS 20 /* # of chars for each sec */
 #ifdef DEBUG
 #define DPRINTF(l, x)                                                          \
     if (Debug >= l)                                                            \
-        fprintf x;
+    {                                                                          \
+        fprintf x;                                                             \
+    }
 #else
 #define DPRINTF(l, x)
 #endif
@@ -139,9 +141,8 @@ typedef struct fd
     struct fd *next, *prev;
 } FILEDESC;
 
-static char *env_lang;
+static const char *env_lang = NULL;
 
-static bool Found_one;           /* did we find a match? */
 static bool Find_files = false;  /* just find a list of proper fortune files */
 static bool Wait = false;        /* wait desired after fortune */
 static bool Short_only = false;  /* short fortune desired */
@@ -155,13 +156,23 @@ static bool No_recode = false; /* Do we want to stop recoding from occuring */
 static bool ErrorMessage =
     false; /* Set to true if an error message has been displayed */
 
-#ifndef NO_REGEX
-static bool Match = false; /* dump fortunes matching a pattern */
+#ifdef POSIX_REGEX
+#define WITH_REGEX
+#define RE_COMP(p) regcomp(&Re_pat, (p), REG_NOSUB)
+#define BAD_COMP(f) ((f) != 0)
+#define RE_EXEC(p) (regexec(&Re_pat, (p), 0, NULL, 0) == 0)
+
+static regex_t Re_pat;
+#else
+#define NO_REGEX
+#endif /* POSIX_REGEX */
 
+#ifdef WITH_REGEX
+static bool Match = false; /* dump fortunes matching a pattern */
 #endif
+
 #ifdef DEBUG
 static bool Debug = false; /* print debug messages */
-
 #endif
 
 static unsigned char *Fortbuf = NULL; /* fortune buffer for -m */
@@ -178,24 +189,20 @@ static FILEDESC *Fortfile;         /* Fortune file to use */
 
 static STRFILE Noprob_tbl; /* sum of data for all no prob files */
 
-#ifdef POSIX_REGEX
-#define RE_COMP(p) regcomp(&Re_pat, (p), REG_NOSUB)
-#define BAD_COMP(f) ((f) != 0)
-#define RE_EXEC(p) (regexec(&Re_pat, (p), 0, NULL, 0) == 0)
-
-static regex_t Re_pat;
-#else
-#define NO_REGEX
-#endif /* POSIX_REGEX */
-
 #ifdef WITH_RECODE
 static RECODE_REQUEST request;
 static RECODE_OUTER outer;
+static inline char *my_recode_string(const char *s)
+{
+    return recode_string(request, (const char *)s);
+}
+#else
+static inline char *my_recode_string(const char *s) { return strdup(s); }
 #endif
 
-int add_dir(FILEDESC *);
+static int add_dir(FILEDESC *);
 
-static unsigned long my_random(unsigned long base)
+static unsigned long my_random(const unsigned long base)
 {
     unsigned long long l = 0;
     char *hard_coded_val = getenv("FORTUNE_MOD_RAND_HARD_CODED_VALS");
@@ -220,7 +227,7 @@ static unsigned long my_random(unsigned long base)
     fclose(fp);
     return l % base;
 fallback:
-    return random() % base;
+    return (((unsigned long)random()) % base);
 }
 
 static char *program_version(void)
@@ -238,17 +245,17 @@ static void __attribute__((noreturn)) usage(void)
     (void)fprintf(stderr, "%s", "D");
 #endif /* DEBUG */
     (void)fprintf(stderr, "%s", "f");
-#ifndef NO_REGEX
+#ifdef WITH_REGEX
     (void)fprintf(stderr, "%s", "i");
-#endif /* NO_REGEX */
+#endif
     (void)fprintf(stderr, "%s", "l");
 #ifndef NO_OFFENSIVE
     (void)fprintf(stderr, "%s", "o");
 #endif
     (void)fprintf(stderr, "%s", "sw]");
-#ifndef NO_REGEX
+#ifdef WITH_REGEX
     (void)fprintf(stderr, "%s", " [-m pattern]");
-#endif /* NO_REGEX */
+#endif
     (void)fprintf(stderr, "%s", " [-n number] [ [#%] file/directory/all]\n");
     exit(1);
 }
@@ -282,80 +289,108 @@ static void print_list(FILEDESC *list, int lev)
     {
         fprintf(stderr, "%*s", lev * 4, "");
         if (list->percent == NO_PROB)
+        {
             if (!Equal_probs)
+            {
                 /* This, with some changes elsewhere, gives proper percentages
                  * for every case fprintf(stderr, "___%%"); */
                 fprintf(stderr, "%5.2f%%",
                     (100.0 - Spec_prob) * list->tbl.str_numstr /
                         Noprob_tbl.str_numstr);
+            }
             else if (lev == 0)
+            {
                 fprintf(stderr, "%5.2f%%", 100.0 / Num_files);
+            }
             else
+            {
                 fprintf(stderr, "%5.2f%%", 100.0 / Num_kids);
+            }
+        }
         else
+        {
             fprintf(stderr, "%5.2f%%", 1.0 * list->percent);
+        }
         fprintf(stderr, " %s", STR(list->name));
         DPRINTF(1, (stderr, " (%s, %s, %s)\n", STR(list->path),
                        STR(list->datfile), STR(list->posfile)));
         putc('\n', stderr);
         if (list->child)
+        {
             print_list(list->child, lev + 1);
+        }
         list = list->next;
     }
 }
 
-#ifndef NO_REGEX
+#ifdef WITH_REGEX
 /*
  * conv_pat:
  *      Convert the pattern to an ignore-case equivalent.
  */
-static char *conv_pat(char *orig)
+static char *conv_pat(const char *const orig_str)
 {
-    char *sp;
-    unsigned int cnt;
+    const char *sp;
     char *new_buf;
 
-    cnt = 1; /* allow for '\0' */
-    for (sp = orig; *sp != '\0'; sp++)
+    size_t cnt = 1; /* allow for '\0' */
+    for (sp = orig_str; *sp != '\0'; sp++)
+    {
+        const size_t prev_cnt = cnt;
         if (isalpha(*sp))
+        {
             cnt += 4;
+        }
         else
-            cnt++;
+        {
+            ++cnt;
+        }
+        if (prev_cnt >= cnt)
+        {
+            fprintf(stderr, "%s",
+                "pattern too long for ignoring case; overflow!\n");
+            exit(1);
+        }
+    }
     if (!(new_buf = malloc(cnt)))
     {
         fprintf(stderr, "%s", "pattern too long for ignoring case\n");
         exit(1);
     }
 
-    for (sp = new_buf; *orig != '\0'; orig++)
+    char *dest_ptr;
+    const char *orig = orig_str;
+    for (dest_ptr = new_buf; *orig != '\0'; ++orig)
     {
         if (islower(*orig))
         {
-            *sp++ = '[';
-            *sp++ = *orig;
-            *sp++ = (char)toupper(*orig);
-            *sp++ = ']';
+            *dest_ptr++ = '[';
+            *dest_ptr++ = *orig;
+            *dest_ptr++ = (char)toupper(*orig);
+            *dest_ptr++ = ']';
         }
         else if (isupper(*orig))
         {
-            *sp++ = '[';
-            *sp++ = *orig;
-            *sp++ = (char)tolower(*orig);
-            *sp++ = ']';
+            *dest_ptr++ = '[';
+            *dest_ptr++ = *orig;
+            *dest_ptr++ = (char)tolower(*orig);
+            *dest_ptr++ = ']';
         }
         else
-            *sp++ = *orig;
+        {
+            *dest_ptr++ = *orig;
+        }
     }
-    *sp = '\0';
+    *dest_ptr = '\0';
     return new_buf;
 }
-#endif /* NO_REGEX */
+#endif
 
 /*
  * do_malloc:
  *      Do a malloc, checking for NULL return.
  */
-static void *do_malloc(size_t size)
+static void *do_malloc(const size_t size)
 {
     void *new_buf = malloc(size);
 
@@ -375,7 +410,7 @@ static FILEDESC *new_fp(void)
 {
     FILEDESC *fp;
 
-    fp = (FILEDESC *)do_malloc(sizeof *fp);
+    fp = do_malloc(sizeof *fp);
     fp->datfd = -1;
     fp->pos = POS_UNKNOWN;
     fp->inf = NULL;
@@ -442,7 +477,9 @@ static int is_existant(char *file)
     struct stat staat;
 
     if (stat(file, &staat) == 0)
+    {
         return true;
+    }
     switch (errno)
     {
     case ENOENT:
@@ -471,9 +508,13 @@ static int is_fortfile(const char *const file, char **datp)
     DPRINTF(2, (stderr, "is_fortfile(%s) returns ", file));
 
     if (!sp)
+    {
         sp = file;
+    }
     else
+    {
         sp++;
+    }
     if (*sp == '.')
     {
         DPRINTF(2, (stderr, "%s", "false (file starts with '.')\n"));
@@ -483,11 +524,13 @@ static int is_fortfile(const char *const file, char **datp)
     {
         sp++;
         for (int i = 0; suflist[i]; ++i)
+        {
             if (strcmp(sp, suflist[i]) == 0)
             {
                 DPRINTF(2, (stderr, "false (file has suffix \".%s\")\n", sp));
                 return false;
             }
+        }
     }
 
     const size_t do_len = (strlen(file) + 6);
@@ -500,9 +543,13 @@ static int is_fortfile(const char *const file, char **datp)
         return false;
     }
     if (datp)
+    {
         *datp = datfile;
+    }
     else
+    {
         free(datfile);
+    }
     DPRINTF(2, (stderr, "%s", "true\n"));
     return true;
 }
@@ -521,10 +568,17 @@ static bool path_is_absolute(const char *const path)
 #endif
     return false;
 }
+
+static int open4read(const char *const path)
+{
+    return open(path, O_RDONLY | O_BINARY);
+}
+
 /*
  * add_file:
  *      Add a file to the file list.
  */
+#define GCC_SNPRINTF_MARGIN 10
 static int add_file(int percent, const char *file, const char *dir,
     FILEDESC **head, FILEDESC **tail, FILEDESC *parent)
 {
@@ -540,7 +594,8 @@ static int add_file(int percent, const char *file, const char *dir,
     }
     else
     {
-        const size_t do_len = (strlen(dir) + strlen(file) + 2);
+        const size_t do_len =
+            (strlen(dir) + strlen(file) + (2 + GCC_SNPRINTF_MARGIN));
         path = do_malloc(do_len + 1);
         snprintf(path, do_len, "%s/%s", dir, file);
     }
@@ -562,40 +617,12 @@ static int add_file(int percent, const char *file, const char *dir,
 #ifdef _WIN32
             (!isdir) &&
 #endif
-            ((fd = open(path, O_RDONLY | O_BINARY)) < 0)) ||
+            ((fd = open4read(path)) < 0)) ||
         !path_is_absolute(path))
     {
-        debugprint("sarahhhhh fd=%d path=<%s> dir=<%s> file=<%s> percent=%d\n",
+        debugprint("check file fd=%d path=<%s> dir=<%s> file=<%s> percent=%d\n",
             fd, path, dir, file, percent);
         bool found = false;
-        if (!dir && (!strchr(file, '/')))
-        {
-            if (((sp = strrchr(file, '-')) != NULL) && (strcmp(sp, "-o") == 0))
-            {
-#define CALL__add_file(dir) add_file(percent, file, dir, head, tail, parent)
-#define COND_CALL__add_file(loc_dir, dir)                                      \
-    ((!strcmp((loc_dir), (dir))) ? 0 : CALL__add_file(dir))
-                /* BSD-style '-o' offensive file suffix */
-                *sp = '\0';
-                found = CALL__add_file(LOCOFFDIR) ||
-                        COND_CALL__add_file(LOCOFFDIR, OFFDIR);
-                /* put the suffix back in for better identification later */
-                *sp = '-';
-            }
-            else if (All_forts)
-                found =
-                    (CALL__add_file(LOCFORTDIR) || CALL__add_file(LOCOFFDIR) ||
-                        COND_CALL__add_file(LOCFORTDIR, FORTDIR) ||
-                        COND_CALL__add_file(LOCOFFDIR, OFFDIR));
-            else if (Offend)
-                found = (CALL__add_file(LOCOFFDIR) ||
-                         COND_CALL__add_file(LOCOFFDIR, OFFDIR));
-            else
-                found = (CALL__add_file(LOCFORTDIR) ||
-                         COND_CALL__add_file(LOCFORTDIR, FORTDIR));
-#undef COND_CALL__add_file
-#undef CALL__add_file
-        }
         if (!found && !parent && !dir)
         { /* don't display an error when trying language specific files */
             if (env_lang)
@@ -613,24 +640,28 @@ static int add_file(int percent, const char *file, const char *dir,
                 {
                     char *p = strchr(lang, ':');
                     if (p)
+                    {
                         *p++ = '\0';
+                    }
                     snprintf(langdir, sizeof(langdir), "%s/%s", FORTDIR, lang);
 
                     if (strncmp(path, lang, 2) == 0)
+                    {
                         ret = 1;
+                    }
                     else if (strncmp(path, langdir, strlen(FORTDIR) + 3) == 0)
+                    {
                         ret = 1;
+                    }
                     lang = p;
                 }
                 if (!ret)
                 {
-                    debugprint("moshe\n");
                     perror(path);
                 }
             }
             else
             {
-                debugprint("abe\n");
                 perror(path);
             }
         }
@@ -656,7 +687,9 @@ static int add_file(int percent, const char *file, const char *dir,
     snprintf(testpath, do_len, "%s.u8", path);
     //    fprintf(stderr, "State mal: %s\n", testpath);
     if (stat(testpath, &statbuf) == 0)
+    {
         fp->utf8_charset = true;
+    }
 
     free(testpath);
     testpath = NULL;
@@ -667,8 +700,10 @@ static int add_file(int percent, const char *file, const char *dir,
     if ((isdir && !add_dir(fp)) || (!isdir && !is_fortfile(path, &fp->datfile)))
     {
         if (!parent)
+        {
             fprintf(
                 stderr, "fortune:%s not a fortune file or directory\n", path);
+        }
         free(path);
         path = NULL;
         free(fp->datfile);
@@ -676,7 +711,9 @@ static int add_file(int percent, const char *file, const char *dir,
         free(fp->name);
         free(fp->path);
         if (fp->fd >= 0)
+        {
             close(fp->fd);
+        }
         free(fp);
         return false;
     }
@@ -693,14 +730,18 @@ static int add_file(int percent, const char *file, const char *dir,
         free(fp->name);
         free(fp->path);
         if (fp->fd >= 0)
+        {
             close(fp->fd);
+        }
         free(fp);
         return true;
     }
     /* End hack. */
 
     if (!(*head))
+    {
         *head = *tail = fp;
+    }
     else if (fp->percent == NO_PROB)
     {
         (*tail)->next = fp;
@@ -728,7 +769,7 @@ static int names_compare(const void *a, const void *b)
  * add_dir:
  *      Add the contents of an entire directory.
  */
-int add_dir(FILEDESC *fp)
+static int add_dir(FILEDESC *const fp)
 {
     DIR *dir;
     struct dirent *dirent;
@@ -739,7 +780,6 @@ int add_dir(FILEDESC *fp)
     fp->fd = -1;
     if (!(dir = opendir(fp->path)))
     {
-        debugprint("yonah\n");
         perror(fp->path);
         return false;
     }
@@ -751,14 +791,15 @@ int add_dir(FILEDESC *fp)
     names = malloc(sizeof(names[0]) * max_count_names);
     if (!names)
     {
-        debugprint("zach\n");
         perror("Out of RAM!");
         exit(-1);
     }
     while ((dirent = readdir(dir)))
     {
         if (dirent->d_name[0] == 0)
+        {
             continue;
+        }
         char *name = strdup(dirent->d_name);
         if (count_names == max_count_names)
         {
@@ -766,7 +807,6 @@ int add_dir(FILEDESC *fp)
             names = realloc(names, sizeof(names[0]) * max_count_names);
             if (!names)
             {
-                debugprint("rebecca\n");
                 perror("Out of RAM!");
                 exit(-1);
             }
@@ -877,7 +917,9 @@ static int form_file_list(char **files, int file_cnt)
                 {
                     p = strchr(lang, ':');
                     if (p)
+                    {
                         *p++ = '\0';
+                    }
 
                     /* first try full locale */
                     ret = add_file(
@@ -896,7 +938,9 @@ static int form_file_list(char **files, int file_cnt)
 
                     /* if we have found one we have finished */
                     if (ret)
+                    {
                         return ret;
+                    }
                     lang = p;
                 }
                 /* default */
@@ -914,15 +958,37 @@ static int form_file_list(char **files, int file_cnt)
     {
         percent = NO_PROB;
         if (!isdigit(files[i][0]))
+        {
             sp = files[i];
+        }
         else
         {
+            const int MAX_PERCENT = 100;
+            bool percent_has_overflowed = false;
             percent = 0;
             for (sp = files[i]; isdigit(*sp); sp++)
+            {
                 percent = percent * 10 + *sp - '0';
-            if (percent > 100)
+                percent_has_overflowed = (percent > MAX_PERCENT);
+                if (percent_has_overflowed)
+                {
+                    break;
+                }
+            }
+            if (percent_has_overflowed || (percent > 100))
             {
                 fprintf(stderr, "percentages must be <= 100\n");
+                fprintf(stderr,
+                    "Overflow percentage detected at argument \"%s\"!\n",
+                    files[i]);
+                ErrorMessage = true;
+                return false;
+            }
+            if (percent < 0)
+            {
+                fprintf(stderr,
+                    "Overflow percentage detected at argument \"%s\"!\n",
+                    files[i]);
                 ErrorMessage = true;
                 return false;
             }
@@ -953,10 +1019,23 @@ static int form_file_list(char **files, int file_cnt)
                 sp = files[i];
             }
         }
+
+        /* BSD-style '-o' offensive file suffix */
+        bool offensive = false;
+        const size_t sp_len = strlen(sp);
+        if (sp_len >= 3 && sp[sp_len - 2] == '-' && sp[sp_len - 1] == 'o')
+        {
+            sp[sp_len - 2] = '\0';
+            offensive = true;
+        }
+
+        const char* fulldir = offensive ? OFFDIR : FORTDIR;
+        const char* locdir = offensive ? LOCOFFDIR : LOCFORTDIR;
+
         if (strcmp(sp, "all") == 0)
         {
-            snprintf(fullpathname, sizeof(fullpathname), "%s", FORTDIR);
-            snprintf(locpathname, sizeof(locpathname), "%s", LOCFORTDIR);
+            snprintf(fullpathname, sizeof(fullpathname), "%s", fulldir);
+            snprintf(locpathname, sizeof(locpathname), "%s", locdir);
         }
         /* if it isn't an absolute path or relative to . or ..
            make it an absolute path relative to FORTDIR */
@@ -966,9 +1045,9 @@ static int form_file_list(char **files, int file_cnt)
                 strncmp(sp, "../", 3) != 0)
             {
                 snprintf(
-                    fullpathname, sizeof(fullpathname), "%s/%s", FORTDIR, sp);
+                    fullpathname, sizeof(fullpathname), "%s/%s", fulldir, sp);
                 snprintf(
-                    locpathname, sizeof(locpathname), "%s/%s", LOCFORTDIR, sp);
+                    locpathname, sizeof(locpathname), "%s/%s", locdir, sp);
             }
             else
             {
@@ -991,11 +1070,13 @@ static int form_file_list(char **files, int file_cnt)
             {
                 char *p = strchr(lang, ':');
                 if (p)
+                {
                     *p++ = '\0';
+                }
 
                 /* first try full locale */
                 snprintf(
-                    langdir, sizeof(langdir), "%s/%s/%s", FORTDIR, lang, sp);
+                    langdir, sizeof(langdir), "%s/%s/%s", fulldir, lang, sp);
                 ret = add_file(
                     percent, langdir, NULL, &File_list, &File_tail, NULL);
 
@@ -1007,7 +1088,7 @@ static int form_file_list(char **files, int file_cnt)
                     strncpy(ll, lang, 2);
                     ll[2] = '\0';
                     snprintf(
-                        langdir, sizeof(langdir), "%s/%s/%s", FORTDIR, ll, sp);
+                        langdir, sizeof(langdir), "%s/%s/%s", fulldir, ll, sp);
                     ret = add_file(
                         percent, langdir, NULL, &File_list, &File_tail, NULL);
                 }
@@ -1016,15 +1097,29 @@ static int form_file_list(char **files, int file_cnt)
             }
             /* default */
             if (!ret)
+            {
                 ret = add_file(
                     percent, fullpathname, NULL, &File_list, &File_tail, NULL);
+            }
             if (!ret &&
                 strncmp(fullpathname, locpathname, sizeof(fullpathname)))
+            {
                 ret = add_file(
                     percent, locpathname, NULL, &File_list, &File_tail, NULL);
-
+            }
+            if (strncmp(fullpathname, locpathname, sizeof(fullpathname)) &&
+                strcmp(sp, "all") == 0)
+            {
+                add_file(
+                    percent, locpathname, NULL, &File_list, &File_tail, NULL);
+            }
             if (!ret)
             {
+                if (offensive)
+                {
+                    // restore -o suffix
+                    sp[sp_len - 2] = '-';
+                }
                 snprintf(locpathname, sizeof(locpathname), "%s/%s",
                     getenv("PWD"), sp);
 
@@ -1035,16 +1130,12 @@ static int form_file_list(char **files, int file_cnt)
             {
                 return false;
             }
-            if (strncmp(fullpathname, locpathname, sizeof(fullpathname)) &&
-                strcmp(sp, "all") == 0)
-            {
-                add_file(
-                    percent, locpathname, NULL, &File_list, &File_tail, NULL);
-            }
         }
         else if (!add_file(
                      percent, fullpathname, NULL, &File_list, &File_tail, NULL))
+        {
             return false;
+        }
     }
     return true;
 }
@@ -1054,12 +1145,11 @@ static int form_file_list(char **files, int file_cnt)
  */
 static void getargs(int argc, char **argv)
 {
-    int ignore_case = false;
-
-#ifndef NO_REGEX
+#ifdef WITH_REGEX
+    bool ignore_case = false;
     char *pat = NULL;
+#endif
 
-#endif /* NO_REGEX */
     int ch;
 
 #ifdef DEBUG
@@ -1075,7 +1165,8 @@ static void getargs(int argc, char **argv)
 #endif
 
     while ((ch = getopt(argc, argv,
-                "ac" DEBUG_GETOPT "efilm:n:" OFFENSIVE_GETOPT "suvw")) != EOF)
+                "ac" DEBUG_GETOPT "efhilm:n:" OFFENSIVE_GETOPT "suvw")) != EOF)
+    {
         switch (ch)
         {
         case 'a': /* any fortune */
@@ -1115,7 +1206,8 @@ static void getargs(int argc, char **argv)
         case 'i': /* case-insensitive match */
         case 'm': /* dump out the fortunes */
             (void)fprintf(stderr, "%s",
-                "fortune: can't match fortunes on this system (Sorry)\n");
+                "fortune: can't match fortunes on this system "
+                "(Sorry)\n");
             exit(0);
 #else             /* NO_REGEX */
         case 'm': /* dump out the fortunes */
@@ -1123,7 +1215,7 @@ static void getargs(int argc, char **argv)
             pat = optarg;
             break;
         case 'i': /* case-insensitive match */
-            ignore_case++;
+            ignore_case = true;
             break;
 #endif            /* NO_REGEX */
         case 'u': /* Don't recode the fortune */
@@ -1135,10 +1227,12 @@ static void getargs(int argc, char **argv)
         case 'c':
             Show_filename = true;
             break;
+        case 'h':
         case '?':
         default:
             usage();
         }
+    }
     argc -= optind;
     argv += optind;
 
@@ -1151,15 +1245,21 @@ static void getargs(int argc, char **argv)
         exit(1); /* errors printed through form_file_list() */
     }
 #ifdef DEBUG
-/*      if (Debug >= 1)
- * print_list(File_list, 0); */
-#endif /* DEBUG */
+#if 0
+      if (Debug >= 1)
+ print_list(File_list, 0); /* Causes crash with new %% code */
+
+#endif
+#endif
+
 /* If (Find_files) print_list() moved to main */
-#ifndef NO_REGEX
+#ifdef WITH_REGEX
     if (pat)
     {
         if (ignore_case)
+        {
             pat = conv_pat(pat);
+        }
         if (BAD_COMP(RE_COMP(pat)))
         {
             fprintf(stderr, "bad pattern: %s\n", pat);
@@ -1170,7 +1270,7 @@ static void getargs(int argc, char **argv)
             free(pat);
         }
     }
-#endif /* NO_REGEX */
+#endif
 }
 
 /*
@@ -1189,14 +1289,20 @@ static void init_prob(void)
      */
     FILEDESC *last = NULL;
     for (fp = File_tail; fp; fp = fp->prev)
+    {
         if (fp->percent == NO_PROB)
         {
             num_noprob++;
             if (Equal_probs)
+            {
                 last = fp;
+            }
         }
         else
+        {
             percent += fp->percent;
+        }
+    }
     DPRINTF(1, (stderr, "summing probabilities:%d%% with %d NO_PROB's\n",
                    percent, num_noprob));
     if (percent > 100)
@@ -1207,16 +1313,19 @@ static void init_prob(void)
     else if (percent < 100 && num_noprob == 0)
     {
         fprintf(stderr,
-            "fortune: no place to put residual probability (%d%%)\n", percent);
+            "fortune: no place to put residual probability "
+            "(%d%%)\n",
+            percent);
         exit(1);
     }
     else if (percent == 100 && num_noprob != 0)
     {
-        fprintf(
-            stderr, "fortune: no probability left to put in residual files\n");
+        fprintf(stderr, "fortune: no probability left to put in "
+                        "residual files\n");
         exit(1);
     }
-    Spec_prob = percent; /* this is for -f when % is specified on cmd line */
+    Spec_prob = percent; /* this is for -f when % is specified on
+                            cmd line */
     percent = 100 - percent;
     if (Equal_probs)
     {
@@ -1227,11 +1336,13 @@ static void init_prob(void)
                 frac = percent / num_noprob;
                 DPRINTF(1, (stderr, ", frac = %d%%", frac));
                 for (fp = File_tail; fp != last; fp = fp->prev)
+                {
                     if (fp->percent == NO_PROB)
                     {
                         fp->percent = frac;
                         percent -= frac;
                     }
+                }
             }
             last->percent = percent;
             DPRINTF(1, (stderr, ", residual = %d%%", percent));
@@ -1245,8 +1356,13 @@ static void init_prob(void)
     DPRINTF(1, (stderr, "%s", "\n"));
 
 #ifdef DEBUG
-/*      if (Debug >= 1)
- * print_list(File_list, 0); *//* Causes crash with new %% code */
+#if 0
+      if (Debug >= 1)
+    {
+ print_list(File_list, 0); /* Causes crash with new %% code */
+    }
+
+#endif
 #endif
 }
 
@@ -1269,9 +1385,13 @@ static void sum_tbl(STRFILE *t1, STRFILE *t2)
 {
     t1->str_numstr += t2->str_numstr;
     if (t1->str_longlen < t2->str_longlen)
+    {
         t1->str_longlen = t2->str_longlen;
+    }
     if (t1->str_shortlen > t2->str_shortlen)
+    {
         t1->str_shortlen = t2->str_shortlen;
+    }
 }
 
 /*
@@ -1284,10 +1404,12 @@ static void get_tbl(FILEDESC *fp)
     FILEDESC *child;
 
     if (fp->read_tbl)
+    {
         return;
+    }
     if (!(fp->child))
     {
-        if ((fd = open(fp->datfile, O_RDONLY | O_BINARY)) < 0)
+        if ((fd = open4read(fp->datfile)) < 0)
         {
             perror(fp->datfile);
             exit(1);
@@ -1356,15 +1478,19 @@ static void sum_noprobs(FILEDESC *fp)
     static bool did_noprobs = false;
 
     if (did_noprobs)
+    {
         return;
+    }
     zero_tbl(&Noprob_tbl);
     while (fp)
     {
         get_tbl(fp);
-        /* This conditional should help us return correct values for -f
-         * when a percentage is specified */
+        /* This conditional should help us return correct values for
+         * -f when a percentage is specified */
         if (fp->percent == NO_PROB)
+        {
             sum_tbl(&Noprob_tbl, &fp->tbl);
+        }
         fp = fp->next;
     }
     did_noprobs = true;
@@ -1381,11 +1507,13 @@ static FILEDESC *pick_child(FILEDESC *parent)
 
     if (Equal_probs)
     {
-        choice = my_random(parent->num_children);
+        choice = (int)my_random((unsigned long)parent->num_children);
         DPRINTF(1, (stderr, "    choice = %d (of %d)\n", choice,
                        parent->num_children));
         for (fp = parent->child; choice--; fp = fp->next)
+        {
             continue;
+        }
         DPRINTF(1, (stderr, "    using %s\n", fp->name));
         return fp;
     }
@@ -1414,8 +1542,7 @@ static FILEDESC *pick_child(FILEDESC *parent)
  */
 static void open_dat(FILEDESC *fp)
 {
-    if (fp->datfd < 0 &&
-        (fp->datfd = open(fp->datfile, O_RDONLY | O_BINARY)) < 0)
+    if (fp->datfd < 0 && (fp->datfd = open4read(fp->datfile)) < 0)
     {
         exit(1);
     }
@@ -1423,8 +1550,8 @@ static void open_dat(FILEDESC *fp)
 
 /*
  * get_pos:
- *      Get the position from the pos file, if there is one.  If not,
- *      return a random number.
+ *      Get the position from the pos file, if there is one.  If
+ * not, return a random number.
  */
 static void get_pos(FILEDESC *fp)
 {
@@ -1434,13 +1561,16 @@ static void get_pos(FILEDESC *fp)
         fp->pos = (int32_t)(my_random(fp->tbl.str_numstr));
     }
     if (++(fp->pos) >= (int32_t)fp->tbl.str_numstr)
+    {
         fp->pos -= fp->tbl.str_numstr;
+    }
     DPRINTF(1, (stderr, "pos for %s is %ld\n", fp->name, fp->pos));
 }
 
 /*
  * get_fort:
- *      Get the fortune data file's seek pointer for the next fortune.
+ *      Get the fortune data file's seek pointer for the next
+ * fortune.
  */
 static void get_fort(void)
 {
@@ -1448,25 +1578,33 @@ static void get_fort(void)
     int choice;
 
     if (!File_list->next || File_list->percent == NO_PROB)
+    {
         fp = File_list;
+    }
     else
     {
-        choice = my_random(100);
+        choice = (int)my_random(100);
         DPRINTF(1, (stderr, "choice = %d\n", choice));
         for (fp = File_list; fp->percent != NO_PROB; fp = fp->next)
+        {
             if (choice < fp->percent)
+            {
                 break;
+            }
             else
             {
                 choice -= fp->percent;
                 DPRINTF(1, (stderr, "    skip \"%s\", %d%% (choice = %d)\n",
                                fp->name, fp->percent, choice));
             }
+        }
         DPRINTF(1, (stderr, "using \"%s\", %d%% (choice = %d)\n", fp->name,
                        fp->percent, choice));
     }
     if (fp->percent != NO_PROB)
+    {
         get_tbl(fp);
+    }
     else
     {
         if (fp->next)
@@ -1524,7 +1662,7 @@ static void open_fp(FILEDESC *fp)
     }
 }
 
-#ifndef NO_REGEX
+#ifdef WITH_REGEX
 /*
  * maxlen_in_list
  *      Return the maximum fortune len in the file list.
@@ -1539,7 +1677,9 @@ static int maxlen_in_list(FILEDESC *list)
         if (fp->child)
         {
             if ((len = maxlen_in_list(fp->child)) > maxlen)
+            {
                 maxlen = len;
+            }
         }
         else
         {
@@ -1557,7 +1697,7 @@ static int maxlen_in_list(FILEDESC *list)
  * matches_in_list
  *      Print out the matches from the files in the list.
  */
-static void matches_in_list(FILEDESC *list)
+static void matches_in_list(FILEDESC *list, bool *const Found_one_ptr)
 {
     unsigned char *sp;
     unsigned char *p; /* -allover */
@@ -1570,7 +1710,7 @@ static void matches_in_list(FILEDESC *list)
     {
         if (fp->child)
         {
-            matches_in_list(fp->child);
+            matches_in_list(fp->child, Found_one_ptr);
             continue;
         }
         DPRINTF(1, (stderr, "searching in %s\n", fp->path));
@@ -1590,11 +1730,7 @@ static void matches_in_list(FILEDESC *list)
 
                 if (fp->utf8_charset && (!No_recode))
                 {
-#ifdef WITH_RECODE
-                    output = recode_string(request, (const char *)Fortbuf);
-#else
-                    output = strdup((const char *)Fortbuf);
-#endif
+                    output = my_recode_string((const char *)Fortbuf);
                 }
                 else
                 {
@@ -1607,9 +1743,13 @@ static void matches_in_list(FILEDESC *list)
                     for (p = (unsigned char *)output; (ch = *p); ++p)
                     {
                         if (isupper(ch) && isascii(ch))
+                        {
                             *p = 'A' + (ch - 'A' + 13) % 26;
+                        }
                         else if (islower(ch) && isascii(ch))
+                        {
                             *p = 'a' + (ch - 'a' + 13) % 26;
+                        }
                     }
                 }
 
@@ -1621,7 +1761,7 @@ static void matches_in_list(FILEDESC *list)
                     {
                         fprintf(
                             stderr, "(%s)\n%c\n", fp->name, fp->tbl.str_delim);
-                        Found_one = true;
+                        (*Found_one_ptr) = true;
                         in_file = true;
                     }
                     fputs(output, stdout);
@@ -1642,21 +1782,22 @@ static void matches_in_list(FILEDESC *list)
 
 /*
  * find_matches:
- *      Find all the fortunes which match the pattern we've been given.
+ *      Find all the fortunes which match the pattern we've been
+ * given.
  */
-static int find_matches(void)
+static bool find_matches(void)
 {
     Fort_len = maxlen_in_list(File_list);
     DPRINTF(2, (stderr, "Maximum length is %d\n", Fort_len));
     /* extra length, "%\n" is appended */
     Fortbuf = do_malloc((unsigned int)Fort_len + 10);
 
-    Found_one = false;
-    matches_in_list(File_list);
+    bool Found_one = false;
+    matches_in_list(File_list, &Found_one);
     return Found_one;
     /* NOTREACHED */
 }
-#endif /* NO_REGEX */
+#endif
 
 static void display(FILEDESC *fp)
 {
@@ -1666,7 +1807,9 @@ static void display(FILEDESC *fp)
     open_fp(fp);
     fseek(fp->inf, (long)Seekpts[0], SEEK_SET);
     if (Show_filename)
+    {
         printf("(%s)\n%%\n", fp->name);
+    }
     for (Fort_len = 0; fgets((char *)line, sizeof line, fp->inf) &&
                        !STR_ENDSTRING(line, fp->tbl);
          Fort_len++)
@@ -1676,19 +1819,18 @@ static void display(FILEDESC *fp)
             for (p = (char *)line; (ch = *p); ++p)
             {
                 if (isupper(ch) && isascii(ch))
+                {
                     *p = 'A' + (ch - 'A' + 13) % 26;
+                }
                 else if (islower(ch) && isascii(ch))
+                {
                     *p = 'a' + (ch - 'a' + 13) % 26;
+                }
             }
         }
         if (fp->utf8_charset && (!No_recode))
         {
-            char *output;
-#ifdef WITH_RECODE
-            output = recode_string(request, (const char *)line);
-#else
-            output = strdup((const char *)line);
-#endif
+            char *output = my_recode_string((const char *)line);
             fputs(output, stdout);
             free(output);
         }
@@ -1708,7 +1850,9 @@ static int fortlen(void)
     char line[BUFSIZ];
 
     if (!(Fortfile->tbl.str_flags & (STR_RANDOM | STR_ORDERED)))
+    {
         nchar = (Seekpts[1] - Seekpts[0]) - 2; /* for %^J delimiter */
+    }
     else
     {
         open_fp(Fortfile);
@@ -1716,7 +1860,9 @@ static int fortlen(void)
         nchar = 0;
         while (fgets(line, sizeof line, Fortfile->inf) &&
                !STR_ENDSTRING(line, Fortfile->tbl))
+        {
             nchar += strlen(line);
+        }
     }
     Fort_len = nchar;
     return nchar;
@@ -1744,17 +1890,26 @@ static void free_desc(FILEDESC *ptr)
     }
 }
 
-int main(int ac, char *av[])
+int main(int argc, char *argv[])
 {
+#ifdef WITH_RECODE
     const char *ctype;
+#endif
+
     int exit_code = 0;
     env_lang = getenv("LC_ALL");
     if (!env_lang)
+    {
         env_lang = getenv("LC_MESSAGES");
+    }
     if (!env_lang)
+    {
         env_lang = getenv("LANGUAGE");
+    }
     if (!env_lang)
+    {
         env_lang = getenv("LANG");
+    }
 #ifdef _WIN32
     if (!env_lang)
     {
@@ -1762,16 +1917,15 @@ int main(int ac, char *av[])
     }
 #endif
 
-#ifndef DONT_CALL_GETARGS
-    getargs(ac, av);
-#endif
-
+    getargs(argc, argv);
 #ifdef WITH_RECODE
     outer = recode_new_outer(true);
     request = recode_new_request(outer);
 #endif
 
     setlocale(LC_ALL, "");
+
+#ifdef WITH_RECODE
 #ifdef _WIN32
     ctype = "C";
 #else
@@ -1785,34 +1939,35 @@ int main(int ac, char *av[])
         ctype = "ISO-8859-1";
     }
 #endif
-
-#ifdef WITH_RECODE
-    const size_t do_len = strlen(ctype) + 7 + 1;
+    const size_t do_len = strlen(ctype) + (7 + 1 + GCC_SNPRINTF_MARGIN);
     char *crequest = do_malloc(do_len + 1);
     snprintf(crequest, do_len, "UTF-8..%s", ctype);
     recode_scan_request(request, crequest);
     free(crequest);
 #endif
 
-#ifndef NO_REGEX
+#ifdef WITH_REGEX
     if (Match)
     {
-        exit_code = (find_matches() != 0);
+        exit_code = find_matches();
         regfree(&Re_pat);
         goto cleanup;
     }
 #endif
+
     init_prob();
     if (Find_files)
     {
         sum_noprobs(File_list);
         if (Equal_probs)
+        {
             calc_equal_probs();
+        }
         print_list(File_list, 0);
     }
     else
     {
-        srandom((unsigned int)(time((time_t *)NULL) + getpid()));
+        call_srandom();
         do
         {
             get_fort();
@@ -1827,7 +1982,10 @@ int main(int ac, char *av[])
             sleep((unsigned int)mymax(Fort_len / CPERS, MINW));
         }
     }
+#ifdef WITH_REGEX
 cleanup:
+#endif
+
 #ifdef WITH_RECODE
     recode_delete_request(request);
     recode_delete_outer(outer);