[BACK]Return to cgi.c CVS log [TXT][DIR] Up to [cvsweb.bsd.lv] / mandoc

Diff for /mandoc/cgi.c between version 1.25 and 1.168

version 1.25, 2011/12/10 22:20:59 version 1.168, 2019/10/01 17:54:14
Line 1 
Line 1 
 /*      $Id$ */  /*      $Id$ */
 /*  /*
  * Copyright (c) 2011 Kristaps Dzonsons <kristaps@bsd.lv>   * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
    * Copyright (c) 2014-2019 Ingo Schwarze <schwarze@usta.de>
  *   *
  * Permission to use, copy, modify, and distribute this software for any   * Permission to use, copy, modify, and distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above   * purpose with or without fee is hereby granted, provided that the above
  * copyright notice and this permission notice appear in all copies.   * copyright notice and this permission notice appear in all copies.
  *   *
  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES   * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF   * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR   * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES   * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN   * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF   * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.   * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */   */
 #ifdef HAVE_CONFIG_H  
 #include "config.h"  #include "config.h"
 #endif  
   
 #include <sys/param.h>  #include <sys/types.h>
 #include <sys/wait.h>  #include <sys/time.h>
   
 #include <assert.h>  
 #include <ctype.h>  #include <ctype.h>
   #if HAVE_ERR
   #include <err.h>
   #endif
 #include <errno.h>  #include <errno.h>
 #include <dirent.h>  
 #include <fcntl.h>  #include <fcntl.h>
 #include <limits.h>  #include <limits.h>
 #include <regex.h>  
 #include <stdio.h>  
 #include <stdarg.h>  
 #include <stdint.h>  #include <stdint.h>
   #include <stdio.h>
 #include <stdlib.h>  #include <stdlib.h>
 #include <string.h>  #include <string.h>
 #include <unistd.h>  #include <unistd.h>
   
 #include "apropos_db.h"  #include "mandoc_aux.h"
 #include "mandoc.h"  #include "mandoc.h"
   #include "roff.h"
 #include "mdoc.h"  #include "mdoc.h"
 #include "man.h"  #include "man.h"
   #include "mandoc_parse.h"
 #include "main.h"  #include "main.h"
 #include "manpath.h"  #include "manconf.h"
   #include "mansearch.h"
   #include "cgi.h"
   
 #ifdef __linux__  
 # include <db_185.h>  
 #else  
 # include <db.h>  
 #endif  
   
 enum    page {  
         PAGE_INDEX,  
         PAGE_SEARCH,  
         PAGE_SHOW,  
         PAGE__MAX  
 };  
   
 struct  paths {  
         char            *name;  
         char            *path;  
 };  
   
 /*  /*
  * A query as passed to the search function.   * A query as passed to the search function.
  */   */
 struct  query {  struct  query {
         const char      *arch; /* architecture */          char            *manpath; /* desired manual directory */
         const char      *sec; /* manual section */          char            *arch; /* architecture */
         const char      *expr; /* unparsed expression string */          char            *sec; /* manual section */
         int              whatis; /* whether whatis mode */          char            *query; /* unparsed query expression */
         int              legacy; /* whether legacy mode */          int              equal; /* match whole names, not substrings */
 };  };
   
 struct  req {  struct  req {
         struct query     q;          struct query      q;
         struct paths    *p;          char            **p; /* array of available manpaths */
         size_t           psz;          size_t            psz; /* number of available manpaths */
         enum page        page;          int               isquery; /* QUERY_STRING used, not PATH_INFO */
 };  };
   
 static  int              atou(const char *, unsigned *);  enum    focus {
 static  void             catman(const char *);          FOCUS_NONE = 0,
 static  int              cmp(const void *, const void *);          FOCUS_QUERY
 static  void             format(const char *);  };
   
 static  void             html_print(const char *);  static  void             html_print(const char *);
 static  void             html_putchar(char);  static  void             html_putchar(char);
 static  int              http_decode(char *);  static  int              http_decode(char *);
 static  void             http_parse(struct query *, char *);  static  void             http_encode(const char *p);
 static  int              pathstop(DIR *);  static  void             parse_manpath_conf(struct req *);
 static  void             pathgen(DIR *, char *, struct req *);  static  void             parse_path_info(struct req *req, const char *path);
 static  void             pg_index(const struct req *, char *);  static  void             parse_query_string(struct req *, const char *);
 static  void             pg_search(const struct req *, char *);  static  void             pg_error_badrequest(const char *);
 static  void             pg_show(const struct req *, char *);  static  void             pg_error_internal(void);
 static  void             resp_bad(void);  static  void             pg_index(const struct req *);
 static  void             resp_baddb(void);  static  void             pg_noresult(const struct req *, int, const char *,
 static  void             resp_error400(void);                                  const char *);
 static  void             resp_error404(const char *);  static  void             pg_redirect(const struct req *, const char *);
 static  void             resp_begin_html(int, const char *);  static  void             pg_search(const struct req *);
   static  void             pg_searchres(const struct req *,
                                   struct manpage *, size_t);
   static  void             pg_show(struct req *, const char *);
   static  void             resp_begin_html(int, const char *, const char *);
 static  void             resp_begin_http(int, const char *);  static  void             resp_begin_http(int, const char *);
   static  void             resp_catman(const struct req *, const char *);
   static  void             resp_copy(const char *);
 static  void             resp_end_html(void);  static  void             resp_end_html(void);
 static  void             resp_index(const struct req *);  static  void             resp_format(const struct req *, const char *);
 static  void             resp_search(struct res *, size_t, void *);  static  void             resp_searchform(const struct req *, enum focus);
 static  void             resp_searchform(const struct req *);  static  void             resp_show(const struct req *, const char *);
   static  void             set_query_attr(char **, char **);
   static  int              validate_arch(const char *);
   static  int              validate_filename(const char *);
   static  int              validate_manpath(const struct req *, const char *);
   static  int              validate_urifrag(const char *);
   
 static  const char       *progname;  static  const char       *scriptname = SCRIPT_NAME;
 static  const char       *cache;  
 static  const char       *host;  
   
 static  const char * const pages[PAGE__MAX] = {  static  const int sec_prios[] = {1, 4, 5, 8, 6, 3, 7, 2, 9};
         "index", /* PAGE_INDEX */  static  const char *const sec_numbers[] = {
         "search", /* PAGE_SEARCH */      "0", "1", "2", "3", "3p", "4", "5", "6", "7", "8", "9"
         "show", /* PAGE_SHOW */  
 };  };
   static  const char *const sec_names[] = {
       "All Sections",
       "1 - General Commands",
       "2 - System Calls",
       "3 - Library Functions",
       "3p - Perl Library",
       "4 - Device Drivers",
       "5 - File Formats",
       "6 - Games",
       "7 - Miscellaneous Information",
       "8 - System Manager\'s Manual",
       "9 - Kernel Developer\'s Manual"
   };
   static  const int sec_MAX = sizeof(sec_names) / sizeof(char *);
   
 /*  static  const char *const arch_names[] = {
  * This is just OpenBSD's strtol(3) suggestion.      "amd64",       "alpha",       "armv7",      "arm64",
  * I use it instead of strtonum(3) for portability's sake.      "hppa",        "i386",        "landisk",
  */      "loongson",    "luna88k",     "macppc",      "mips64",
 static int      "octeon",      "sgi",         "socppc",      "sparc64",
 atou(const char *buf, unsigned *v)      "amiga",       "arc",         "armish",      "arm32",
 {      "atari",       "aviion",      "beagle",      "cats",
         char            *ep;      "hppa64",      "hp300",
         long             lval;      "ia64",        "mac68k",      "mvme68k",     "mvme88k",
       "mvmeppc",     "palm",        "pc532",       "pegasos",
       "pmax",        "powerpc",     "solbourne",   "sparc",
       "sun3",        "vax",         "wgrisc",      "x68k",
       "zaurus"
   };
   static  const int arch_MAX = sizeof(arch_names) / sizeof(char *);
   
         errno = 0;  
         lval = strtol(buf, &ep, 10);  
         if (buf[0] == '\0' || *ep != '\0')  
                 return(0);  
         if ((errno == ERANGE && (lval == LONG_MAX ||  
                                         lval == LONG_MIN)) ||  
                         (lval > UINT_MAX || lval < 0))  
                 return(0);  
   
         *v = (unsigned int)lval;  
         return(1);  
 }  
   
 /*  /*
  * Print a character, escaping HTML along the way.   * Print a character, escaping HTML along the way.
  * This will pass non-ASCII straight to output: be warned!   * This will pass non-ASCII straight to output: be warned!
Line 144  html_putchar(char c)
Line 144  html_putchar(char c)
 {  {
   
         switch (c) {          switch (c) {
         case ('"'):          case '"':
                 printf("&quote;");                  printf("&quot;");
                 break;                  break;
         case ('&'):          case '&':
                 printf("&amp;");                  printf("&amp;");
                 break;                  break;
         case ('>'):          case '>':
                 printf("&gt;");                  printf("&gt;");
                 break;                  break;
         case ('<'):          case '<':
                 printf("&lt;");                  printf("&lt;");
                 break;                  break;
         default:          default:
Line 169  html_putchar(char c)
Line 169  html_putchar(char c)
 static void  static void
 html_print(const char *p)  html_print(const char *p)
 {  {
   
         if (NULL == p)          if (NULL == p)
                 return;                  return;
         while ('\0' != *p)          while ('\0' != *p)
Line 177  html_print(const char *p)
Line 177  html_print(const char *p)
 }  }
   
 /*  /*
  * Parse out key-value pairs from an HTTP request variable.   * Transfer the responsibility for the allocated string *val
  * This can be either a cookie or a POST/GET string, although man.cgi   * to the query structure.
  * uses only GET for simplicity.  
  */   */
 static void  static void
 http_parse(struct query *q, char *p)  set_query_attr(char **attr, char **val)
 {  {
         char            *key, *val;  
         size_t           sz;  
         int              legacy;  
   
         memset(q, 0, sizeof(struct query));          free(*attr);
           if (**val == '\0') {
                   *attr = NULL;
                   free(*val);
           } else
                   *attr = *val;
           *val = NULL;
   }
   
         q->whatis = 1;  /*
         legacy = -1;   * Parse the QUERY_STRING for key-value pairs
    * and store the values into the query structure.
    */
   static void
   parse_query_string(struct req *req, const char *qs)
   {
           char            *key, *val;
           size_t           keysz, valsz;
   
         while (p && '\0' != *p) {          req->isquery    = 1;
                 while (' ' == *p)          req->q.manpath  = NULL;
                         p++;          req->q.arch     = NULL;
           req->q.sec      = NULL;
           req->q.query    = NULL;
           req->q.equal    = 1;
   
                 key = p;          key = val = NULL;
                 val = NULL;          while (*qs != '\0') {
   
                 if (NULL != (p = strchr(p, '='))) {                  /* Parse one key. */
                         *p++ = '\0';  
                         val = p;  
   
                         sz = strcspn(p, ";&");                  keysz = strcspn(qs, "=;&");
                         /* LINTED */                  key = mandoc_strndup(qs, keysz);
                         p += sz;                  qs += keysz;
                   if (*qs != '=')
                           goto next;
   
                         if ('\0' != *p)                  /* Parse one value. */
                                 *p++ = '\0';  
                 } else {  
                         p = key;  
                         sz = strcspn(p, ";&");  
                         /* LINTED */  
                         p += sz;  
   
                         if ('\0' != *p)                  valsz = strcspn(++qs, ";&");
                                 p++;                  val = mandoc_strndup(qs, valsz);
                         continue;                  qs += valsz;
                 }  
   
                 if ('\0' == *key || '\0' == *val)                  /* Decode and catch encoding errors. */
                         continue;  
   
                 /* Just abort handling. */                  if ( ! (http_decode(key) && http_decode(val)))
                           goto next;
   
                 if ( ! http_decode(key))                  /* Handle key-value pairs. */
                         break;  
                 if ( ! http_decode(val))  
                         break;  
   
                 if (0 == strcmp(key, "expr"))                  if ( ! strcmp(key, "query"))
                         q->expr = val;                          set_query_attr(&req->q.query, &val);
                 else if (0 == strcmp(key, "query"))  
                         q->expr = val;  
                 else if (0 == strcmp(key, "sec"))  
                         q->sec = val;  
                 else if (0 == strcmp(key, "sektion"))  
                         q->sec = val;  
                 else if (0 == strcmp(key, "arch"))  
                         q->arch = val;  
                 else if (0 == strcmp(key, "apropos"))  
                         legacy = 0 == strcmp(val, "0");  
                 else if (0 == strcmp(key, "op"))  
                         q->whatis = 0 == strcasecmp(val, "whatis");  
         }  
   
         /* Test for old man.cgi compatibility mode. */                  else if ( ! strcmp(key, "apropos"))
                           req->q.equal = !strcmp(val, "0");
   
         if (legacy == 0) {                  else if ( ! strcmp(key, "manpath")) {
                 q->whatis = 0;  #ifdef COMPAT_OLDURI
                 q->legacy = 1;                          if ( ! strncmp(val, "OpenBSD ", 8)) {
         } else if (legacy > 0) {                                  val[7] = '-';
                 q->legacy = 1;                                  if ('C' == val[8])
                 q->whatis = 1;                                          val[8] = 'c';
         }                          }
   #endif
                           set_query_attr(&req->q.manpath, &val);
                   }
   
         /*                  else if ( ! (strcmp(key, "sec")
          * Section "0" means no section when in legacy mode.  #ifdef COMPAT_OLDURI
          * For some man.cgi scripts, "default" arch is none.                      && strcmp(key, "sektion")
          */  #endif
                       )) {
                           if ( ! strcmp(val, "0"))
                                   *val = '\0';
                           set_query_attr(&req->q.sec, &val);
                   }
   
         if (q->legacy && NULL != q->sec)                  else if ( ! strcmp(key, "arch")) {
                 if (0 == strcmp(q->sec, "0"))                          if ( ! strcmp(val, "default"))
                         q->sec = NULL;                                  *val = '\0';
         if (q->legacy && NULL != q->arch)                          set_query_attr(&req->q.arch, &val);
                 if (0 == strcmp(q->arch, "default"))                  }
                         q->arch = NULL;  
                   /*
                    * The key must be freed in any case.
                    * The val may have been handed over to the query
                    * structure, in which case it is now NULL.
                    */
   next:
                   free(key);
                   key = NULL;
                   free(val);
                   val = NULL;
   
                   if (*qs != '\0')
                           qs++;
           }
 }  }
   
 /*  /*
Line 279  static int
Line 292  static int
 http_decode(char *p)  http_decode(char *p)
 {  {
         char             hex[3];          char             hex[3];
           char            *q;
         int              c;          int              c;
   
         hex[2] = '\0';          hex[2] = '\0';
   
         for ( ; '\0' != *p; p++) {          q = p;
           for ( ; '\0' != *p; p++, q++) {
                 if ('%' == *p) {                  if ('%' == *p) {
                         if ('\0' == (hex[0] = *(p + 1)))                          if ('\0' == (hex[0] = *(p + 1)))
                                 return(0);                                  return 0;
                         if ('\0' == (hex[1] = *(p + 2)))                          if ('\0' == (hex[1] = *(p + 2)))
                                 return(0);                                  return 0;
                         if (1 != sscanf(hex, "%x", &c))                          if (1 != sscanf(hex, "%x", &c))
                                 return(0);                                  return 0;
                         if ('\0' == c)                          if ('\0' == c)
                                 return(0);                                  return 0;
   
                         *p = (char)c;                          *q = (char)c;
                         memmove(p + 1, p + 3, strlen(p + 3) + 1);                          p += 2;
                 } else                  } else
                         *p = '+' == *p ? ' ' : *p;                          *q = '+' == *p ? ' ' : *p;
         }          }
   
         *p = '\0';          *q = '\0';
         return(1);          return 1;
 }  }
   
 static void  static void
   http_encode(const char *p)
   {
           for (; *p != '\0'; p++) {
                   if (isalnum((unsigned char)*p) == 0 &&
                       strchr("-._~", *p) == NULL)
                           printf("%%%2.2X", (unsigned char)*p);
                   else
                           putchar(*p);
           }
   }
   
   static void
 resp_begin_http(int code, const char *msg)  resp_begin_http(int code, const char *msg)
 {  {
   
         if (200 != code)          if (200 != code)
                 printf("Status: %d %s\n", code, msg);                  printf("Status: %d %s\r\n", code, msg);
   
         puts("Content-Type: text/html; charset=utf-8\n"          printf("Content-Type: text/html; charset=utf-8\r\n"
              "Cache-Control: no-cache\n"               "Cache-Control: no-cache\r\n"
              "Pragma: no-cache\n"               "Pragma: no-cache\r\n"
              "");               "\r\n");
   
         fflush(stdout);          fflush(stdout);
 }  }
   
 static void  static void
 resp_begin_html(int code, const char *msg)  resp_copy(const char *filename)
 {  {
           char     buf[4096];
           ssize_t  sz;
           int      fd;
   
           if ((fd = open(filename, O_RDONLY)) != -1) {
                   fflush(stdout);
                   while ((sz = read(fd, buf, sizeof(buf))) > 0)
                           write(STDOUT_FILENO, buf, sz);
                   close(fd);
           }
   }
   
   static void
   resp_begin_html(int code, const char *msg, const char *file)
   {
           char    *cp;
   
         resp_begin_http(code, msg);          resp_begin_http(code, msg);
   
         puts("<!DOCTYPE HTML PUBLIC "          printf("<!DOCTYPE html>\n"
              " \"-//W3C//DTD HTML 4.01//EN\""                 "<html>\n"
              " \"http://www.w3.org/TR/html4/strict.dtd\">\n"                 "<head>\n"
              "<HTML>\n"                 "  <meta charset=\"UTF-8\"/>\n"
              "<HEAD>\n"                 "  <meta name=\"viewport\""
              "<META HTTP-EQUIV=\"Content-Type\""                        " content=\"width=device-width, initial-scale=1.0\">\n"
              " CONTENT=\"text/html; charset=utf-8\">\n"                 "  <link rel=\"stylesheet\" href=\"%s/mandoc.css\""
              "<LINK REL=\"stylesheet\" HREF=\"/man.cgi.css\""                 " type=\"text/css\" media=\"all\">\n"
              " TYPE=\"text/css\" media=\"all\">\n"                 "  <title>",
              "<TITLE>System Manpage Reference</TITLE>\n"                 CSS_DIR);
              "</HEAD>\n"          if (file != NULL) {
              "<BODY>\n"                  if ((cp = strrchr(file, '/')) != NULL)
              "<!-- Begin page content. //-->");                          file = cp + 1;
                   if ((cp = strrchr(file, '.')) != NULL) {
                           printf("%.*s(%s) - ", (int)(cp - file), file, cp + 1);
                   } else
                           printf("%s - ", file);
           }
           printf("%s</title>\n"
                  "</head>\n"
                  "<body>\n",
                  CUSTOMIZE_TITLE);
   
           resp_copy(MAN_DIR "/header.html");
 }  }
   
 static void  static void
 resp_end_html(void)  resp_end_html(void)
 {  {
   
         puts("</BODY>\n"          resp_copy(MAN_DIR "/footer.html");
              "</HTML>");  
           puts("</body>\n"
                "</html>");
 }  }
   
 static void  static void
 resp_searchform(const struct req *req)  resp_searchform(const struct req *req, enum focus focus)
 {  {
           int              i;
   
         puts("<!-- Begin search form. //-->");          printf("<form action=\"/%s\" method=\"get\">\n"
         printf("<FORM ACTION=\"");                 "  <fieldset>\n"
         html_print(progname);                 "    <legend>Manual Page Search Parameters</legend>\n",
         printf("/search.html\" METHOD=\"get\">\n");                 scriptname);
         printf("<FIELDSET>\n"  
                "<LEGEND>Search Parameters</LEGEND>\n"          /* Write query input box. */
                "<INPUT TYPE=\"submit\" NAME=\"op\""  
                " VALUE=\"Whatis\"> or \n"          printf("    <input type=\"search\" name=\"query\" value=\"");
                "<INPUT TYPE=\"submit\" NAME=\"op\""          if (req->q.query != NULL)
                " VALUE=\"apropos\"> for manuals satisfying \n"                  html_print(req->q.query);
                "<INPUT TYPE=\"text\" NAME=\"expr\" VALUE=\"");          printf( "\" size=\"40\"");
         html_print(req->q.expr ? req->q.expr : "");          if (focus == FOCUS_QUERY)
         printf("\">, section "                  printf(" autofocus");
                "<INPUT TYPE=\"text\""          puts(">");
                " SIZE=\"4\" NAME=\"sec\" VALUE=\"");  
         html_print(req->q.sec ? req->q.sec : "");          /* Write submission buttons. */
         printf("\">, arch "  
                "<INPUT TYPE=\"text\""          printf( "    <button type=\"submit\" name=\"apropos\" value=\"0\">"
                " SIZE=\"8\" NAME=\"arch\" VALUE=\"");                  "man</button>\n"
         html_print(req->q.arch ? req->q.arch : "");                  "    <button type=\"submit\" name=\"apropos\" value=\"1\">"
         puts("\">.\n"                  "apropos</button>\n"
              "<INPUT TYPE=\"reset\" VALUE=\"Reset\">\n"                  "    <br/>\n");
              "</FIELDSET>\n"  
              "</FORM>");          /* Write section selector. */
         puts("<!-- End search form. //-->");  
           puts("    <select name=\"sec\">");
           for (i = 0; i < sec_MAX; i++) {
                   printf("      <option value=\"%s\"", sec_numbers[i]);
                   if (NULL != req->q.sec &&
                       0 == strcmp(sec_numbers[i], req->q.sec))
                           printf(" selected=\"selected\"");
                   printf(">%s</option>\n", sec_names[i]);
           }
           puts("    </select>");
   
           /* Write architecture selector. */
   
           printf( "    <select name=\"arch\">\n"
                   "      <option value=\"default\"");
           if (NULL == req->q.arch)
                   printf(" selected=\"selected\"");
           puts(">All Architectures</option>");
           for (i = 0; i < arch_MAX; i++) {
                   printf("      <option");
                   if (NULL != req->q.arch &&
                       0 == strcmp(arch_names[i], req->q.arch))
                           printf(" selected=\"selected\"");
                   printf(">%s</option>\n", arch_names[i]);
           }
           puts("    </select>");
   
           /* Write manpath selector. */
   
           if (req->psz > 1) {
                   puts("    <select name=\"manpath\">");
                   for (i = 0; i < (int)req->psz; i++) {
                           printf("      <option");
                           if (strcmp(req->q.manpath, req->p[i]) == 0)
                                   printf(" selected=\"selected\"");
                           printf(">");
                           html_print(req->p[i]);
                           puts("</option>");
                   }
                   puts("    </select>");
           }
   
           puts("  </fieldset>\n"
                "</form>");
 }  }
   
   static int
   validate_urifrag(const char *frag)
   {
   
           while ('\0' != *frag) {
                   if ( ! (isalnum((unsigned char)*frag) ||
                       '-' == *frag || '.' == *frag ||
                       '/' == *frag || '_' == *frag))
                           return 0;
                   frag++;
           }
           return 1;
   }
   
   static int
   validate_manpath(const struct req *req, const char* manpath)
   {
           size_t   i;
   
           for (i = 0; i < req->psz; i++)
                   if ( ! strcmp(manpath, req->p[i]))
                           return 1;
   
           return 0;
   }
   
   static int
   validate_arch(const char *arch)
   {
           int      i;
   
           for (i = 0; i < arch_MAX; i++)
                   if (strcmp(arch, arch_names[i]) == 0)
                           return 1;
   
           return 0;
   }
   
   static int
   validate_filename(const char *file)
   {
   
           if ('.' == file[0] && '/' == file[1])
                   file += 2;
   
           return ! (strstr(file, "../") || strstr(file, "/..") ||
               (strncmp(file, "man", 3) && strncmp(file, "cat", 3)));
   }
   
 static void  static void
 resp_index(const struct req *req)  pg_index(const struct req *req)
 {  {
   
         resp_begin_html(200, NULL);          resp_begin_html(200, NULL, NULL);
         resp_searchform(req);          resp_searchform(req, FOCUS_QUERY);
           printf("<p>\n"
                  "This web interface is documented in the\n"
                  "<a class=\"Xr\" href=\"/%s%sman.cgi.8\">man.cgi(8)</a>\n"
                  "manual, and the\n"
                  "<a class=\"Xr\" href=\"/%s%sapropos.1\">apropos(1)</a>\n"
                  "manual explains the query syntax.\n"
                  "</p>\n",
                  scriptname, *scriptname == '\0' ? "" : "/",
                  scriptname, *scriptname == '\0' ? "" : "/");
         resp_end_html();          resp_end_html();
 }  }
   
 static void  static void
 resp_error400(void)  pg_noresult(const struct req *req, int code, const char *http_msg,
       const char *user_msg)
 {  {
           resp_begin_html(code, http_msg, NULL);
         resp_begin_html(400, "Query Malformed");          resp_searchform(req, FOCUS_QUERY);
         printf("<H1>Malformed Query</H1>\n"          puts("<p>");
                "<P>\n"          puts(user_msg);
                "The query your entered was malformed.\n"          puts("</p>");
                "Try again from the\n"  
                "<A HREF=\"%s/index.html\">main page</A>.\n"  
                "</P>", progname);  
         resp_end_html();          resp_end_html();
 }  }
   
 static void  static void
 resp_error404(const char *page)  pg_error_badrequest(const char *msg)
 {  {
   
         resp_begin_html(404, "Not Found");          resp_begin_html(400, "Bad Request", NULL);
         puts("<H1>Page Not Found</H1>\n"          puts("<h1>Bad Request</h1>\n"
              "<P>\n"               "<p>\n");
              "The page you're looking for, ");          puts(msg);
         printf("<B>");          printf("Try again from the\n"
         html_print(page);                 "<a href=\"/%s\">main page</a>.\n"
         printf("</B>,\n"                 "</p>", scriptname);
                "could not be found.\n"  
                "Try searching from the\n"  
                "<A HREF=\"%s/index.html\">main page</A>.\n"  
                "</P>", progname);  
         resp_end_html();          resp_end_html();
 }  }
   
 static void  static void
 resp_bad(void)  pg_error_internal(void)
 {  {
         resp_begin_html(500, "Internal Server Error");          resp_begin_html(500, "Internal Server Error", NULL);
         puts("<P>Generic badness happened.</P>");          puts("<p>Internal Server Error</p>");
         resp_end_html();          resp_end_html();
 }  }
   
 static void  static void
 resp_baddb(void)  pg_redirect(const struct req *req, const char *name)
 {  {
           printf("Status: 303 See Other\r\n"
         resp_begin_html(500, "Internal Server Error");              "Location: /");
         puts("<P>Your database is broken.</P>");          if (*scriptname != '\0')
         resp_end_html();                  printf("%s/", scriptname);
           if (strcmp(req->q.manpath, req->p[0]))
                   printf("%s/", req->q.manpath);
           if (req->q.arch != NULL)
                   printf("%s/", req->q.arch);
           http_encode(name);
           if (req->q.sec != NULL) {
                   putchar('.');
                   http_encode(req->q.sec);
           }
           printf("\r\nContent-Type: text/html; charset=utf-8\r\n\r\n");
 }  }
   
 static void  static void
 resp_search(struct res *r, size_t sz, void *arg)  pg_searchres(const struct req *req, struct manpage *r, size_t sz)
 {  {
         int               i;          char            *arch, *archend;
         const struct req *req;          const char      *sec;
           size_t           i, iuse;
           int              archprio, archpriouse;
           int              prio, priouse;
   
         if (1 == sz) {          for (i = 0; i < sz; i++) {
                   if (validate_filename(r[i].file))
                           continue;
                   warnx("invalid filename %s in %s database",
                       r[i].file, req->q.manpath);
                   pg_error_internal();
                   return;
           }
   
           if (req->isquery && sz == 1) {
                 /*                  /*
                  * If we have just one result, then jump there now                   * If we have just one result, then jump there now
                  * without any delay.                   * without any delay.
                  */                   */
                 puts("Status: 303 See Other");                  printf("Status: 303 See Other\r\n"
                 printf("Location: http://%s%s/show/%u/%u.html\n",                      "Location: /");
                                 host, progname,                  if (*scriptname != '\0')
                                 r[0].volume, r[0].rec);                          printf("%s/", scriptname);
                 puts("Content-Type: text/html; charset=utf-8\n");                  if (strcmp(req->q.manpath, req->p[0]))
                           printf("%s/", req->q.manpath);
                   printf("%s\r\n"
                       "Content-Type: text/html; charset=utf-8\r\n\r\n",
                       r[0].file);
                 return;                  return;
         }          }
   
         qsort(r, sz, sizeof(struct res), cmp);          /*
            * In man(1) mode, show one of the pages
            * even if more than one is found.
            */
   
         resp_begin_html(200, NULL);          iuse = 0;
           if (req->q.equal || sz == 1) {
                   priouse = 20;
                   archpriouse = 3;
                   for (i = 0; i < sz; i++) {
                           sec = r[i].file;
                           sec += strcspn(sec, "123456789");
                           if (sec[0] == '\0')
                                   continue;
                           prio = sec_prios[sec[0] - '1'];
                           if (sec[1] != '/')
                                   prio += 10;
                           if (req->q.arch == NULL) {
                                   archprio =
                                       ((arch = strchr(sec + 1, '/'))
                                           == NULL) ? 3 :
                                       ((archend = strchr(arch + 1, '/'))
                                           == NULL) ? 0 :
                                       strncmp(arch, "amd64/",
                                           archend - arch) ? 2 : 1;
                                   if (archprio < archpriouse) {
                                           archpriouse = archprio;
                                           priouse = prio;
                                           iuse = i;
                                           continue;
                                   }
                                   if (archprio > archpriouse)
                                           continue;
                           }
                           if (prio >= priouse)
                                   continue;
                           priouse = prio;
                           iuse = i;
                   }
                   resp_begin_html(200, NULL, r[iuse].file);
           } else
                   resp_begin_html(200, NULL, NULL);
   
         req = (const struct req *)arg;          resp_searchform(req,
         resp_searchform(req);              req->q.equal || sz == 1 ? FOCUS_NONE : FOCUS_QUERY);
   
         if (0 == sz) {          if (sz > 1) {
                 printf("<P>\n"                  puts("<table class=\"results\">");
                        "No %s results found.\n",                  for (i = 0; i < sz; i++) {
                        req->q.whatis ? "whatis" : "apropos");                          printf("  <tr>\n"
                 if (req->q.whatis) {                                 "    <td>"
                         printf("(Try <A HREF=\"");                                 "<a class=\"Xr\" href=\"/");
                         html_print(progname);                          if (*scriptname != '\0')
                         printf("/search.html?op=apropos&amp;expr=");                                  printf("%s/", scriptname);
                         html_print(req->q.expr ? req->q.expr : "");                          if (strcmp(req->q.manpath, req->p[0]))
                         printf("&amp;sec=");                                  printf("%s/", req->q.manpath);
                         html_print(req->q.sec ? req->q.sec : "");                          printf("%s\">", r[i].file);
                         printf("&amp;arch=");                          html_print(r[i].names);
                         html_print(req->q.arch ? req->q.arch : "");                          printf("</a></td>\n"
                         puts("\">apropos</A>?)");                                 "    <td><span class=\"Nd\">");
                           html_print(r[i].output);
                           puts("</span></td>\n"
                                "  </tr>");
                 }                  }
                 puts("</P>");                  puts("</table>");
                 resp_end_html();  
                 return;  
         }          }
   
         puts("<P></P>\n"          if (req->q.equal || sz == 1) {
              "<TABLE>");                  puts("<hr>");
                   resp_show(req, r[iuse].file);
         for (i = 0; i < (int)sz; i++) {  
                 printf("<TR>\n"  
                        "<TD CLASS=\"title\">\n"  
                        "<A HREF=\"");  
                 html_print(progname);  
                 printf("/show/0/%u/%u.html\">", r[i].volume, r[i].rec);  
                 html_print(r[i].title);  
                 putchar('(');  
                 html_print(r[i].cat);  
                 if (r[i].arch && '\0' != *r[i].arch) {  
                         putchar('/');  
                         html_print(r[i].arch);  
                 }  
                 printf(")</A>\n"  
                        "</TD>\n"  
                        "<TD CLASS=\"desc\">");  
                 html_print(r[i].desc);  
                 puts("</TD>\n"  
                      "</TR>");  
         }          }
   
         puts("</TABLE>");  
         resp_end_html();          resp_end_html();
 }  }
   
 /* ARGSUSED */  
 static void  static void
 pg_index(const struct req *req, char *path)  resp_catman(const struct req *req, const char *file)
 {  {
   
         resp_index(req);  
 }  
   
 static void  
 catman(const char *file)  
 {  
         FILE            *f;          FILE            *f;
         size_t           len;  
         int              i;  
         char            *p;          char            *p;
           size_t           sz;
           ssize_t          len;
           int              i;
         int              italic, bold;          int              italic, bold;
   
         if (NULL == (f = fopen(file, "r"))) {          if ((f = fopen(file, "r")) == NULL) {
                 resp_baddb();                  puts("<p>You specified an invalid manual file.</p>");
                 return;                  return;
         }          }
   
         resp_begin_http(200, NULL);          puts("<div class=\"catman\">\n"
         puts("<!DOCTYPE HTML PUBLIC "               "<pre>");
              " \"-//W3C//DTD HTML 4.01//EN\""  
              " \"http://www.w3.org/TR/html4/strict.dtd\">\n"  
              "<HTML>\n"  
              "<HEAD>\n"  
              "<META HTTP-EQUIV=\"Content-Type\""  
              " CONTENT=\"text/html; charset=utf-8\">\n"  
              "<LINK REL=\"stylesheet\" HREF=\"/catman.css\""  
              " TYPE=\"text/css\" media=\"all\">\n"  
              "<TITLE>System Manpage Reference</TITLE>\n"  
              "</HEAD>\n"  
              "<BODY>\n"  
              "<!-- Begin page content. //-->\n"  
              "<PRE>");  
   
         while (NULL != (p = fgetln(f, &len))) {          p = NULL;
           sz = 0;
   
           while ((len = getline(&p, &sz, f)) != -1) {
                 bold = italic = 0;                  bold = italic = 0;
                 for (i = 0; i < (int)len - 1; i++) {                  for (i = 0; i < len - 1; i++) {
                         /*                          /*
                          * This means that the catpage is out of state.                           * This means that the catpage is out of state.
                          * Ignore it and keep going (although the                           * Ignore it and keep going (although the
                          * catpage is bogus).                           * catpage is bogus).
Line 570  catman(const char *file)
Line 751  catman(const char *file)
   
                         if ('\b' != p[i + 1]) {                          if ('\b' != p[i + 1]) {
                                 if (italic)                                  if (italic)
                                         printf("</I>");                                          printf("</i>");
                                 if (bold)                                  if (bold)
                                         printf("</B>");                                          printf("</b>");
                                 italic = bold = 0;                                  italic = bold = 0;
                                 html_putchar(p[i]);                                  html_putchar(p[i]);
                                 continue;                                  continue;
                         } else if (i + 2 >= (int)len)                          } else if (i + 2 >= len)
                                 continue;                                  continue;
   
                         /* Italic mode. */                          /* Italic mode. */
   
                         if ('_' == p[i]) {                          if ('_' == p[i]) {
                                 if (bold)                                  if (bold)
                                         printf("</B>");                                          printf("</b>");
                                 if ( ! italic)                                  if ( ! italic)
                                         printf("<I>");                                          printf("<i>");
                                 bold = 0;                                  bold = 0;
                                 italic = 1;                                  italic = 1;
                                 i += 2;                                  i += 2;
Line 593  catman(const char *file)
Line 774  catman(const char *file)
                                 continue;                                  continue;
                         }                          }
   
                         /*                          /*
                          * Handle funny behaviour troff-isms.                           * Handle funny behaviour troff-isms.
                          * These grok'd from the original man2html.c.                           * These grok'd from the original man2html.c.
                          */                           */
Line 607  catman(const char *file)
Line 788  catman(const char *file)
                                         ('*' == p[i] && '|' == p[i + 2]) ||                                          ('*' == p[i] && '|' == p[i + 2]) ||
                                         ('|' == p[i] && '*' == p[i + 2]))  {                                          ('|' == p[i] && '*' == p[i + 2]))  {
                                 if (italic)                                  if (italic)
                                         printf("</I>");                                          printf("</i>");
                                 if (bold)                                  if (bold)
                                         printf("</B>");                                          printf("</b>");
                                 italic = bold = 0;                                  italic = bold = 0;
                                 putchar('*');                                  putchar('*');
                                 i += 2;                                  i += 2;
Line 621  catman(const char *file)
Line 802  catman(const char *file)
                                         ('+' == p[i] && '|' == p[i + 1]) ||                                          ('+' == p[i] && '|' == p[i + 1]) ||
                                         ('|' == p[i] && '+' == p[i + 1]))  {                                          ('|' == p[i] && '+' == p[i + 1]))  {
                                 if (italic)                                  if (italic)
                                         printf("</I>");                                          printf("</i>");
                                 if (bold)                                  if (bold)
                                         printf("</B>");                                          printf("</b>");
                                 italic = bold = 0;                                  italic = bold = 0;
                                 putchar('+');                                  putchar('+');
                                 i += 2;                                  i += 2;
Line 631  catman(const char *file)
Line 812  catman(const char *file)
                         }                          }
   
                         /* Bold mode. */                          /* Bold mode. */
   
                         if (italic)                          if (italic)
                                 printf("</I>");                                  printf("</i>");
                         if ( ! bold)                          if ( ! bold)
                                 printf("<B>");                                  printf("<b>");
                         bold = 1;                          bold = 1;
                         italic = 0;                          italic = 0;
                         i += 2;                          i += 2;
                         html_putchar(p[i]);                          html_putchar(p[i]);
                 }                  }
   
                 /*                  /*
                  * Clean up the last character.                   * Clean up the last character.
                  * We can get to a newline; don't print that.                   * We can get to a newline; don't print that.
                  */                   */
   
                 if (italic)                  if (italic)
                         printf("</I>");                          printf("</i>");
                 if (bold)                  if (bold)
                         printf("</B>");                          printf("</b>");
   
                 if (i == (int)len - 1 && '\n' != p[i])                  if (i == len - 1 && p[i] != '\n')
                         html_putchar(p[i]);                          html_putchar(p[i]);
   
                 putchar('\n');                  putchar('\n');
         }          }
           free(p);
   
         puts("</PRE>\n"          puts("</pre>\n"
              "</BODY>\n"               "</div>");
              "</HTML>");  
   
         fclose(f);          fclose(f);
 }  }
   
 static void  static void
 format(const char *file)  resp_format(const struct req *req, const char *file)
 {  {
           struct manoutput conf;
         struct mparse   *mp;          struct mparse   *mp;
         int              fd;          struct roff_meta *meta;
         struct mdoc     *mdoc;  
         struct man      *man;  
         void            *vp;          void            *vp;
         enum mandoclevel rc;          int              fd;
         char             opts[MAXPATHLEN + 128];          int              usepath;
   
         if (-1 == (fd = open(file, O_RDONLY, 0))) {          if (-1 == (fd = open(file, O_RDONLY, 0))) {
                 resp_baddb();                  puts("<p>You specified an invalid manual file.</p>");
                 return;                  return;
         }          }
   
         mp = mparse_alloc(MPARSE_AUTO, MANDOCLEVEL_FATAL, NULL, NULL);          mchars_alloc();
         rc = mparse_readfd(mp, fd, file);          mp = mparse_alloc(MPARSE_SO | MPARSE_UTF8 | MPARSE_LATIN1 |
               MPARSE_VALIDATE, MANDOC_OS_OTHER, req->q.manpath);
           mparse_readfd(mp, fd, file);
         close(fd);          close(fd);
           meta = mparse_result(mp);
   
         if (rc >= MANDOCLEVEL_FATAL) {          memset(&conf, 0, sizeof(conf));
                 resp_baddb();          conf.fragment = 1;
                 return;          conf.style = mandoc_strdup(CSS_DIR "/mandoc.css");
         }          usepath = strcmp(req->q.manpath, req->p[0]);
           mandoc_asprintf(&conf.man, "/%s%s%s%s%%N.%%S",
               scriptname, *scriptname == '\0' ? "" : "/",
               usepath ? req->q.manpath : "", usepath ? "/" : "");
   
         snprintf(opts, sizeof(opts), "style=/man.css,"          vp = html_alloc(&conf);
                         "man=%s/search.html?sec=%%S&expr=%%N,"          if (meta->macroset == MACROSET_MDOC)
                         /*"includes=/cgi-bin/man.cgi/usr/include/%%I"*/,                  html_mdoc(vp, meta);
                         progname);          else
                   html_man(vp, meta);
   
         mparse_result(mp, &mdoc, &man);  
         vp = html_alloc(opts);  
   
         if (NULL != mdoc) {  
                 resp_begin_http(200, NULL);  
                 html_mdoc(vp, mdoc);  
         } else if (NULL != man) {  
                 resp_begin_http(200, NULL);  
                 html_man(vp, man);  
         } else  
                 resp_baddb();  
   
         html_free(vp);          html_free(vp);
         mparse_free(mp);          mparse_free(mp);
           mchars_free();
           free(conf.man);
           free(conf.style);
 }  }
   
 static void  static void
 pg_show(const struct req *req, char *path)  resp_show(const struct req *req, const char *file)
 {  {
         struct manpaths  ps;  
         char            *sub;  
         char             file[MAXPATHLEN];  
         const char      *fn, *cp;  
         int              rc;  
         unsigned int     vol, rec, mr;  
         DB              *idx;  
         DBT              key, val;  
   
         idx = NULL;          if ('.' == file[0] && '/' == file[1])
                   file += 2;
   
         /* Parse out mroot, volume, and record from the path. */          if ('c' == *file)
                   resp_catman(req, file);
           else
                   resp_format(req, file);
   }
   
         if (NULL == path || NULL == (sub = strchr(path, '/'))) {  static void
                 resp_error400();  pg_show(struct req *req, const char *fullpath)
   {
           char            *manpath;
           const char      *file;
   
           if ((file = strchr(fullpath, '/')) == NULL) {
                   pg_error_badrequest(
                       "You did not specify a page to show.");
                 return;                  return;
         }  
         *sub++ = '\0';  
         if ( ! atou(path, &mr)) {  
                 resp_error400();  
                 return;  
         }          }
         path = sub;          manpath = mandoc_strndup(fullpath, file - fullpath);
         if (NULL == (sub = strchr(path, '/'))) {          file++;
                 resp_error400();  
           if ( ! validate_manpath(req, manpath)) {
                   pg_error_badrequest(
                       "You specified an invalid manpath.");
                   free(manpath);
                 return;                  return;
         }          }
         *sub++ = '\0';  
         if ( ! atou(path, &vol) || ! atou(sub, &rec)) {  
                 resp_error400();  
                 return;  
         } else if (mr >= (unsigned int)req->psz) {  
                 resp_error400();  
                 return;  
         }  
   
         /*          /*
          * Begin by chdir()ing into the root of the manpath.           * Begin by chdir()ing into the manpath.
          * This way we can pick up the database files, which are           * This way we can pick up the database files, which are
          * relative to the manpath root.           * relative to the manpath root.
          */           */
   
         if (-1 == chdir(req->p[(int)mr].path)) {          if (chdir(manpath) == -1) {
                 perror(req->p[(int)mr].path);                  warn("chdir %s", manpath);
                 resp_baddb();                  pg_error_internal();
                   free(manpath);
                 return;                  return;
         }          }
           free(manpath);
   
         memset(&ps, 0, sizeof(struct manpaths));          if ( ! validate_filename(file)) {
         manpath_manconf("etc/catman.conf", &ps);                  pg_error_badrequest(
                       "You specified an invalid manual file.");
         if (vol >= (unsigned int)ps.sz) {                  return;
                 resp_error400();  
                 goto out;  
         }          }
   
         strlcpy(file, ps.paths[vol], MAXPATHLEN);          resp_begin_html(200, NULL, file);
         strlcat(file, "/mandoc.index", MAXPATHLEN);          resp_searchform(req, FOCUS_NONE);
           resp_show(req, file);
         /* Open the index recno(3) database. */          resp_end_html();
   
         idx = dbopen(file, O_RDONLY, 0, DB_RECNO, NULL);  
         if (NULL == idx) {  
                 perror(file);  
                 resp_baddb();  
                 goto out;  
         }  
   
         key.data = &rec;  
         key.size = 4;  
   
         if (0 != (rc = (*idx->get)(idx, &key, &val, 0))) {  
                 rc < 0 ? resp_baddb() : resp_error400();  
                 goto out;  
         }  
   
         cp = (char *)val.data;  
   
         if (NULL == (fn = memchr(cp, '\0', val.size)))  
                 resp_baddb();  
         else if (++fn - cp >= (int)val.size)  
                 resp_baddb();  
         else if (NULL == memchr(fn, '\0', val.size - (fn - cp)))  
                 resp_baddb();  
         else {  
                 if (0 == strcmp(cp, "cat"))  
                         catman(fn + 1);  
                 else  
                         format(fn + 1);  
         }  
 out:  
         if (idx)  
                 (*idx->close)(idx);  
         manpath_free(&ps);  
 }  }
   
 static void  static void
 pg_search(const struct req *req, char *path)  pg_search(const struct req *req)
 {  {
         size_t            tt;          struct mansearch          search;
         struct manpaths   ps;          struct manpaths           paths;
         int               i, sz, rc;          struct manpage           *res;
         const char       *ep, *start;          char                    **argv;
         char            **cp;          char                     *query, *rp, *wp;
         struct opts       opt;          size_t                    ressz;
         struct expr      *expr;          int                       argc;
   
         if (0 == req->psz) {  
                 resp_search(NULL, 0, (void *)req);  
                 return;  
         }  
   
         memset(&opt, 0, sizeof(struct opts));  
   
         ep       = req->q.expr;  
         opt.arch = req->q.arch;  
         opt.cat  = req->q.sec;  
         rc       = -1;  
         sz       = 0;  
         cp       = NULL;  
   
         /*          /*
          * Begin by chdir()ing into the root of the manpath.           * Begin by chdir()ing into the root of the manpath.
          * This way we can pick up the database files, which are           * This way we can pick up the database files, which are
          * relative to the manpath root.           * relative to the manpath root.
          */           */
   
         if (-1 == (chdir(req->p[0].path))) {          if (chdir(req->q.manpath) == -1) {
                 perror(req->p[0].path);                  warn("chdir %s", req->q.manpath);
                 resp_search(NULL, 0, (void *)req);                  pg_error_internal();
                 return;                  return;
         }          }
   
         memset(&ps, 0, sizeof(struct manpaths));          search.arch = req->q.arch;
         manpath_manconf("etc/catman.conf", &ps);          search.sec = req->q.sec;
           search.outkey = "Nd";
           search.argmode = req->q.equal ? ARG_NAME : ARG_EXPR;
           search.firstmatch = 1;
   
           paths.sz = 1;
           paths.paths = mandoc_malloc(sizeof(char *));
           paths.paths[0] = mandoc_strdup(".");
   
         /*          /*
          * Poor man's tokenisation: just break apart by spaces.           * Break apart at spaces with backslash-escaping.
          * Yes, this is half-ass.  But it works for now.  
          */           */
   
         while (ep && isspace((unsigned char)*ep))          argc = 0;
                 ep++;          argv = NULL;
           rp = query = mandoc_strdup(req->q.query);
         while (ep && '\0' != *ep) {          for (;;) {
                 cp = mandoc_realloc(cp, (sz + 1) * sizeof(char *));                  while (isspace((unsigned char)*rp))
                 start = ep;                          rp++;
                 while ('\0' != *ep && ! isspace((unsigned char)*ep))                  if (*rp == '\0')
                         ep++;                          break;
                 cp[sz] = mandoc_malloc((ep - start) + 1);                  argv = mandoc_reallocarray(argv, argc + 1, sizeof(char *));
                 memcpy(cp[sz], start, ep - start);                  argv[argc++] = wp = rp;
                 cp[sz++][ep - start] = '\0';                  for (;;) {
                 while (isspace((unsigned char)*ep))                          if (isspace((unsigned char)*rp)) {
                         ep++;                                  *wp = '\0';
                                   rp++;
                                   break;
                           }
                           if (rp[0] == '\\' && rp[1] != '\0')
                                   rp++;
                           if (wp != rp)
                                   *wp = *rp;
                           if (*rp == '\0')
                                   break;
                           wp++;
                           rp++;
                   }
         }          }
   
         /*          res = NULL;
          * Pump down into apropos backend.          ressz = 0;
          * The resp_search() function is called with the results.          if (req->isquery && req->q.equal && argc == 1)
          */                  pg_redirect(req, argv[0]);
           else if (mansearch(&search, &paths, argc, argv, &res, &ressz) == 0)
                   pg_noresult(req, 400, "Bad Request",
                       "You entered an invalid query.");
           else if (ressz == 0)
                   pg_noresult(req, 404, "Not Found", "No results found.");
           else
                   pg_searchres(req, res, ressz);
   
         expr = req->q.whatis ?          free(query);
                 termcomp(sz, cp, &tt) : exprcomp(sz, cp, &tt);          mansearch_free(res, ressz);
           free(paths.paths[0]);
         if (NULL != expr)          free(paths.paths);
                 rc = apropos_search  
                         (ps.sz, ps.paths, &opt,  
                          expr, tt, (void *)req, resp_search);  
   
         /* ...unless errors occured. */  
   
         if (0 == rc)  
                 resp_baddb();  
         else if (-1 == rc)  
                 resp_search(NULL, 0, (void *)req);  
   
         for (i = 0; i < sz; i++)  
                 free(cp[i]);  
   
         free(cp);  
         exprfree(expr);  
         manpath_free(&ps);  
 }  }
   
 int  int
 main(void)  main(void)
 {  {
         int              i;  
         char             buf[MAXPATHLEN];  
         DIR             *cwd;  
         struct req       req;          struct req       req;
         char            *p, *path, *subpath;          struct itimerval itimer;
           const char      *path;
           const char      *querystring;
           int              i;
   
         /* Scan our run-time environment. */  #if HAVE_PLEDGE
           /*
            * The "rpath" pledge could be revoked after mparse_readfd()
            * if the file desciptor to "/footer.html" would be opened
            * up front, but it's probably not worth the complication
            * of the code it would cause: it would require scattering
            * pledge() calls in multiple low-level resp_*() functions.
            */
   
         progname = getenv("SCRIPT_NAME");          if (pledge("stdio rpath", NULL) == -1) {
         if (NULL == progname)                  warn("pledge");
                 progname = "";                  pg_error_internal();
                   return EXIT_FAILURE;
           }
   #endif
   
         cache = getenv("CACHE_DIR");          /* Poor man's ReDoS mitigation. */
         if (NULL == cache)  
                 cache = "/cache/man.cgi";  
   
         host = getenv("HTTP_HOST");          itimer.it_value.tv_sec = 2;
         if (NULL == host)          itimer.it_value.tv_usec = 0;
                 host = "localhost";          itimer.it_interval.tv_sec = 2;
           itimer.it_interval.tv_usec = 0;
           if (setitimer(ITIMER_VIRTUAL, &itimer, NULL) == -1) {
                   warn("setitimer");
                   pg_error_internal();
                   return EXIT_FAILURE;
           }
   
         /*          /*
          * First we change directory into the cache directory so that           * First we change directory into the MAN_DIR so that
          * subsequent scanning for manpath directories is rooted           * subsequent scanning for manpath directories is rooted
          * relative to the same position.           * relative to the same position.
          */           */
   
         if (-1 == chdir(cache)) {          if (chdir(MAN_DIR) == -1) {
                 perror(cache);                  warn("MAN_DIR: %s", MAN_DIR);
                 resp_bad();                  pg_error_internal();
                 return(EXIT_FAILURE);                  return EXIT_FAILURE;
         } else if (NULL == (cwd = opendir(cache))) {          }
                 perror(cache);  
                 resp_bad();  
                 return(EXIT_FAILURE);  
         }  
   
         memset(&req, 0, sizeof(struct req));          memset(&req, 0, sizeof(struct req));
           req.q.equal = 1;
           parse_manpath_conf(&req);
   
         strlcpy(buf, ".", MAXPATHLEN);          /* Parse the path info and the query string. */
         pathgen(cwd, buf, &req);  
         closedir(cwd);  
   
         /* Next parse out the query string. */          if ((path = getenv("PATH_INFO")) == NULL)
                   path = "";
           else if (*path == '/')
                   path++;
   
         if (NULL != (p = getenv("QUERY_STRING")))          if (*path != '\0') {
                 http_parse(&req.q, p);                  parse_path_info(&req, path);
                   if (req.q.manpath == NULL || req.q.sec == NULL ||
                       *req.q.query == '\0' || access(path, F_OK) == -1)
                           path = "";
           } else if ((querystring = getenv("QUERY_STRING")) != NULL)
                   parse_query_string(&req, querystring);
   
         /*          /* Validate parsed data and add defaults. */
          * Now juggle paths to extract information.  
          * We want to extract our filetype (the file suffix), the  
          * initial path component, then the trailing component(s).  
          * Start with leading subpath component.  
          */  
   
         subpath = path = NULL;          if (req.q.manpath == NULL)
         req.page = PAGE__MAX;                  req.q.manpath = mandoc_strdup(req.p[0]);
           else if ( ! validate_manpath(&req, req.q.manpath)) {
                   pg_error_badrequest(
                       "You specified an invalid manpath.");
                   return EXIT_FAILURE;
           }
   
         if (NULL == (path = getenv("PATH_INFO")) || '\0' == *path)          if (req.q.arch != NULL && validate_arch(req.q.arch) == 0) {
                 req.page = PAGE_INDEX;                  pg_error_badrequest(
                       "You specified an invalid architecture.");
                   return EXIT_FAILURE;
           }
   
         if (NULL != path && '/' == *path && '\0' == *++path)          /* Dispatch to the three different pages. */
                 req.page = PAGE_INDEX;  
   
         /* Strip file suffix. */          if ('\0' != *path)
                   pg_show(&req, path);
           else if (NULL != req.q.query)
                   pg_search(&req);
           else
                   pg_index(&req);
   
         if (NULL != path && NULL != (p = strrchr(path, '.')))          free(req.q.manpath);
                 if (NULL != p && NULL == strchr(p, '/'))          free(req.q.arch);
                         *p++ = '\0';          free(req.q.sec);
           free(req.q.query);
           for (i = 0; i < (int)req.psz; i++)
                   free(req.p[i]);
           free(req.p);
           return EXIT_SUCCESS;
   }
   
         /* Resolve subpath component. */  /*
    * Translate PATH_INFO to a query.
    */
   static void
   parse_path_info(struct req *req, const char *path)
   {
           const char      *name, *sec, *end;
   
         if (NULL != path && NULL != (subpath = strchr(path, '/')))          req->isquery = 0;
                 *subpath++ = '\0';          req->q.equal = 1;
           req->q.manpath = NULL;
           req->q.arch = NULL;
   
         /* Map path into one we recognise. */          /* Mandatory manual page name. */
           if ((name = strrchr(path, '/')) == NULL)
                   name = path;
           else
                   name++;
   
         if (NULL != path && '\0' != *path)          /* Optional trailing section. */
                 for (i = 0; i < (int)PAGE__MAX; i++)          sec = strrchr(name, '.');
                         if (0 == strcmp(pages[i], path)) {          if (sec != NULL && isdigit((unsigned char)*++sec)) {
                                 req.page = (enum page)i;                  req->q.query = mandoc_strndup(name, sec - name - 1);
                                 break;                  req->q.sec = mandoc_strdup(sec);
                         }          } else {
                   req->q.query = mandoc_strdup(name);
                   req->q.sec = NULL;
           }
   
         /* Route pages. */          /* Handle the case of name[.section] only. */
           if (name == path)
                   return;
   
         switch (req.page) {          /* Optional manpath. */
         case (PAGE_INDEX):          end = strchr(path, '/');
                 pg_index(&req, subpath);          req->q.manpath = mandoc_strndup(path, end - path);
                 break;          if (validate_manpath(req, req->q.manpath)) {
         case (PAGE_SEARCH):                  path = end + 1;
                 pg_search(&req, subpath);                  if (name == path)
                 break;                          return;
         case (PAGE_SHOW):          } else {
                 pg_show(&req, subpath);                  free(req->q.manpath);
                 break;                  req->q.manpath = NULL;
         default:  
                 resp_error404(path);  
                 break;  
         }          }
   
         for (i = 0; i < (int)req.psz; i++) {          /* Optional section. */
                 free(req.p[i].path);          if (strncmp(path, "man", 3) == 0 || strncmp(path, "cat", 3) == 0) {
                 free(req.p[i].name);                  path += 3;
                   end = strchr(path, '/');
                   free(req->q.sec);
                   req->q.sec = mandoc_strndup(path, end - path);
                   path = end + 1;
                   if (name == path)
                           return;
         }          }
   
         free(req.p);          /* Optional architecture. */
         return(EXIT_SUCCESS);          end = strchr(path, '/');
           if (end + 1 != name) {
                   pg_error_badrequest(
                       "You specified too many directory components.");
                   exit(EXIT_FAILURE);
           }
           req->q.arch = mandoc_strndup(path, end - path);
           if (validate_arch(req->q.arch) == 0) {
                   pg_error_badrequest(
                       "You specified an invalid directory component.");
                   exit(EXIT_FAILURE);
           }
 }  }
   
 static int  
 cmp(const void *p1, const void *p2)  
 {  
   
         return(strcasecmp(((const struct res *)p1)->title,  
                                 ((const struct res *)p2)->title));  
 }  
   
 /*  /*
  * Check to see if an "etc" path consists of a catman.conf file.  If it  
  * does, that means that the path contains a tree created by catman(8)  
  * and should be used for indexing.  
  */  
 static int  
 pathstop(DIR *dir)  
 {  
         struct dirent   *d;  
   
         while (NULL != (d = readdir(dir)))  
                 if (DT_REG == d->d_type)  
                         if (0 == strcmp(d->d_name, "catman.conf"))  
                                 return(1);  
   
         return(0);  
 }  
   
 /*  
  * Scan for indexable paths.   * Scan for indexable paths.
  * This adds all paths with "etc/catman.conf" to the buffer.  
  */   */
 static void  static void
 pathgen(DIR *dir, char *path, struct req *req)  parse_manpath_conf(struct req *req)
 {  {
         struct dirent   *d;          FILE    *fp;
         char            *cp;          char    *dp;
         DIR             *cd;          size_t   dpsz;
         int              rc;          ssize_t  len;
         size_t           sz, ssz;  
   
         sz = strlcat(path, "/", MAXPATHLEN);          if ((fp = fopen("manpath.conf", "r")) == NULL) {
         if (sz >= MAXPATHLEN) {                  warn("%s/manpath.conf", MAN_DIR);
                 fprintf(stderr, "%s: Path too long", path);                  pg_error_internal();
                 return;                  exit(EXIT_FAILURE);
         }  
   
         /*  
          * First, scan for the "etc" directory.  
          * If it's found, then see if it should cause us to stop.  This  
          * happens when a catman.conf is found in the directory.  
          */  
   
         rc = 0;  
         while (0 == rc && NULL != (d = readdir(dir))) {  
                 if (DT_DIR != d->d_type || strcmp(d->d_name, "etc"))  
                         continue;  
   
                 path[(int)sz] = '\0';  
                 ssz = strlcat(path, d->d_name, MAXPATHLEN);  
   
                 if (ssz >= MAXPATHLEN) {  
                         fprintf(stderr, "%s: Path too long", path);  
                         return;  
                 } else if (NULL == (cd = opendir(path))) {  
                         perror(path);  
                         return;  
                 }  
   
                 rc = pathstop(cd);  
                 closedir(cd);  
         }          }
   
         if (rc > 0) {          dp = NULL;
                 /* This also strips the trailing slash. */          dpsz = 0;
                 path[(int)sz - 1] = '\0';  
                 req->p = mandoc_realloc  
                         (req->p,  
                          (req->psz + 1) * sizeof(struct paths));  
                 req->p[(int)req->psz].path = mandoc_strdup(path);  
                 /* And this strips out the leading "./". */  
                 req->p[(int)req->psz].name =  
                         cp = mandoc_strdup(path + 2);  
                 req->psz++;  
                 /*  
                  * The name is just the path with all the slashes taken  
                  * out of it.  Simple but effective.  
                  */  
                 for ( ; '\0' != *cp; cp++)  
                         if ('/' == *cp)  
                                 *cp = ' ';  
                 return;  
         }  
   
         /*          while ((len = getline(&dp, &dpsz, fp)) != -1) {
          * If no etc/catman.conf was found, recursively enter child                  if (dp[len - 1] == '\n')
          * directory and continue scanning.                          dp[--len] = '\0';
          */                  req->p = mandoc_realloc(req->p,
                       (req->psz + 1) * sizeof(char *));
         rewinddir(dir);                  if ( ! validate_urifrag(dp)) {
         while (NULL != (d = readdir(dir))) {                          warnx("%s/manpath.conf contains "
                 if (DT_DIR != d->d_type || '.' == d->d_name[0])                              "unsafe path \"%s\"", MAN_DIR, dp);
                         continue;                          pg_error_internal();
                           exit(EXIT_FAILURE);
                 path[(int)sz] = '\0';  
                 ssz = strlcat(path, d->d_name, MAXPATHLEN);  
   
                 if (ssz >= MAXPATHLEN) {  
                         fprintf(stderr, "%s: Path too long", path);  
                         return;  
                 } else if (NULL == (cd = opendir(path))) {  
                         perror(path);  
                         return;  
                 }                  }
                   if (strchr(dp, '/') != NULL) {
                           warnx("%s/manpath.conf contains "
                               "path with slash \"%s\"", MAN_DIR, dp);
                           pg_error_internal();
                           exit(EXIT_FAILURE);
                   }
                   req->p[req->psz++] = dp;
                   dp = NULL;
                   dpsz = 0;
           }
           free(dp);
   
                 pathgen(cd, path, req);          if (req->p == NULL) {
                 closedir(cd);                  warnx("%s/manpath.conf is empty", MAN_DIR);
                   pg_error_internal();
                   exit(EXIT_FAILURE);
         }          }
 }  }

Legend:
Removed from v.1.25  
changed lines
  Added in v.1.168

CVSweb