[BACK]Return to cgi.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / mandoc

Annotation of src/usr.bin/mandoc/cgi.c, Revision 1.118

1.118   ! schwarze    1: /* $OpenBSD: cgi.c,v 1.117 2022/07/05 14:03:35 schwarze Exp $ */
1.1       schwarze    2: /*
1.117     schwarze    3:  * Copyright (c) 2014-2019, 2021, 2022 Ingo Schwarze <schwarze@usta.de>
1.1       schwarze    4:  * Copyright (c) 2011, 2012 Kristaps Dzonsons <kristaps@bsd.lv>
1.116     schwarze    5:  * Copyright (c) 2022 Anna Vyalkova <cyber@sysrq.in>
1.1       schwarze    6:  *
                      7:  * Permission to use, copy, modify, and distribute this software for any
                      8:  * purpose with or without fee is hereby granted, provided that the above
                      9:  * copyright notice and this permission notice appear in all copies.
                     10:  *
1.44      schwarze   11:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
1.1       schwarze   12:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
1.44      schwarze   13:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
1.1       schwarze   14:  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     15:  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
                     16:  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
                     17:  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1.110     schwarze   18:  *
                     19:  * Implementation of the man.cgi(8) program.
1.1       schwarze   20:  */
1.33      schwarze   21: #include <sys/types.h>
                     22: #include <sys/time.h>
                     23:
1.1       schwarze   24: #include <ctype.h>
1.67      schwarze   25: #include <err.h>
1.1       schwarze   26: #include <errno.h>
                     27: #include <fcntl.h>
                     28: #include <limits.h>
1.32      schwarze   29: #include <stdint.h>
1.1       schwarze   30: #include <stdio.h>
                     31: #include <stdlib.h>
                     32: #include <string.h>
                     33: #include <unistd.h>
                     34:
1.47      schwarze   35: #include "mandoc_aux.h"
1.1       schwarze   36: #include "mandoc.h"
1.47      schwarze   37: #include "roff.h"
1.50      schwarze   38: #include "mdoc.h"
1.51      schwarze   39: #include "man.h"
1.100     schwarze   40: #include "mandoc_parse.h"
1.1       schwarze   41: #include "main.h"
1.44      schwarze   42: #include "manconf.h"
1.1       schwarze   43: #include "mansearch.h"
1.7       schwarze   44: #include "cgi.h"
1.1       schwarze   45:
                     46: /*
                     47:  * A query as passed to the search function.
                     48:  */
                     49: struct query {
1.23      schwarze   50:        char            *manpath; /* desired manual directory */
                     51:        char            *arch; /* architecture */
                     52:        char            *sec; /* manual section */
1.25      schwarze   53:        char            *query; /* unparsed query expression */
1.5       schwarze   54:        int              equal; /* match whole names, not substrings */
1.1       schwarze   55: };
                     56:
                     57: struct req {
                     58:        struct query      q;
                     59:        char            **p; /* array of available manpaths */
                     60:        size_t            psz; /* number of available manpaths */
1.60      schwarze   61:        int               isquery; /* QUERY_STRING used, not PATH_INFO */
1.1       schwarze   62: };
                     63:
1.70      schwarze   64: enum   focus {
                     65:        FOCUS_NONE = 0,
                     66:        FOCUS_QUERY
                     67: };
                     68:
1.1       schwarze   69: static void             html_print(const char *);
                     70: static void             html_putchar(char);
1.43      schwarze   71: static int              http_decode(char *);
1.110     schwarze   72: static void             http_encode(const char *);
1.68      schwarze   73: static void             parse_manpath_conf(struct req *);
1.110     schwarze   74: static void             parse_path_info(struct req *, const char *);
1.68      schwarze   75: static void             parse_query_string(struct req *, const char *);
1.12      schwarze   76: static void             pg_error_badrequest(const char *);
                     77: static void             pg_error_internal(void);
                     78: static void             pg_index(const struct req *);
1.106     schwarze   79: static void             pg_noresult(const struct req *, int, const char *,
                     80:                                const char *);
1.87      schwarze   81: static void             pg_redirect(const struct req *, const char *);
1.6       schwarze   82: static void             pg_search(const struct req *);
1.12      schwarze   83: static void             pg_searchres(const struct req *,
                     84:                                struct manpage *, size_t);
1.19      schwarze   85: static void             pg_show(struct req *, const char *);
1.117     schwarze   86: static int              resp_begin_html(int, const char *, const char *);
1.1       schwarze   87: static void             resp_begin_http(int, const char *);
1.68      schwarze   88: static void             resp_catman(const struct req *, const char *);
1.117     schwarze   89: static int              resp_copy(const char *, const char *);
1.1       schwarze   90: static void             resp_end_html(void);
1.68      schwarze   91: static void             resp_format(const struct req *, const char *);
1.70      schwarze   92: static void             resp_searchform(const struct req *, enum focus);
1.10      schwarze   93: static void             resp_show(const struct req *, const char *);
1.25      schwarze   94: static void             set_query_attr(char **, char **);
1.97      schwarze   95: static int              validate_arch(const char *);
1.25      schwarze   96: static int              validate_filename(const char *);
                     97: static int              validate_manpath(const struct req *, const char *);
                     98: static int              validate_urifrag(const char *);
1.1       schwarze   99:
1.58      schwarze  100: static const char       *scriptname = SCRIPT_NAME;
1.1       schwarze  101:
1.10      schwarze  102: static const int sec_prios[] = {1, 4, 5, 8, 6, 3, 7, 2, 9};
1.8       schwarze  103: static const char *const sec_numbers[] = {
                    104:     "0", "1", "2", "3", "3p", "4", "5", "6", "7", "8", "9"
                    105: };
                    106: static const char *const sec_names[] = {
                    107:     "All Sections",
                    108:     "1 - General Commands",
                    109:     "2 - System Calls",
1.34      schwarze  110:     "3 - Library Functions",
                    111:     "3p - Perl Library",
                    112:     "4 - Device Drivers",
1.8       schwarze  113:     "5 - File Formats",
                    114:     "6 - Games",
1.34      schwarze  115:     "7 - Miscellaneous Information",
                    116:     "8 - System Manager\'s Manual",
                    117:     "9 - Kernel Developer\'s Manual"
1.8       schwarze  118: };
                    119: static const int sec_MAX = sizeof(sec_names) / sizeof(char *);
                    120:
                    121: static const char *const arch_names[] = {
1.111     schwarze  122:     "amd64",       "alpha",       "armv7",       "arm64",
                    123:     "hppa",        "i386",        "landisk",     "loongson",
                    124:     "luna88k",     "macppc",      "mips64",      "octeon",
1.113     visa      125:     "powerpc64",   "riscv64",     "sparc64",
1.111     schwarze  126:
1.76      schwarze  127:     "amiga",       "arc",         "armish",      "arm32",
                    128:     "atari",       "aviion",      "beagle",      "cats",
                    129:     "hppa64",      "hp300",
1.64      schwarze  130:     "ia64",        "mac68k",      "mvme68k",     "mvme88k",
                    131:     "mvmeppc",     "palm",        "pc532",       "pegasos",
1.113     visa      132:     "pmax",        "powerpc",     "sgi",         "socppc",
                    133:     "solbourne",   "sparc",
1.79      schwarze  134:     "sun3",        "vax",         "wgrisc",      "x68k",
                    135:     "zaurus"
1.8       schwarze  136: };
                    137: static const int arch_MAX = sizeof(arch_names) / sizeof(char *);
                    138:
1.1       schwarze  139: /*
                    140:  * Print a character, escaping HTML along the way.
                    141:  * This will pass non-ASCII straight to output: be warned!
                    142:  */
                    143: static void
                    144: html_putchar(char c)
                    145: {
                    146:
                    147:        switch (c) {
1.93      schwarze  148:        case '"':
1.80      bentley   149:                printf("&quot;");
1.1       schwarze  150:                break;
1.93      schwarze  151:        case '&':
1.1       schwarze  152:                printf("&amp;");
                    153:                break;
1.93      schwarze  154:        case '>':
1.1       schwarze  155:                printf("&gt;");
                    156:                break;
1.93      schwarze  157:        case '<':
1.1       schwarze  158:                printf("&lt;");
                    159:                break;
                    160:        default:
                    161:                putchar((unsigned char)c);
                    162:                break;
                    163:        }
                    164: }
                    165:
                    166: /*
                    167:  * Call through to html_putchar().
                    168:  * Accepts NULL strings.
                    169:  */
                    170: static void
                    171: html_print(const char *p)
                    172: {
1.43      schwarze  173:
1.1       schwarze  174:        if (NULL == p)
                    175:                return;
                    176:        while ('\0' != *p)
                    177:                html_putchar(*p++);
                    178: }
                    179:
                    180: /*
1.23      schwarze  181:  * Transfer the responsibility for the allocated string *val
                    182:  * to the query structure.
1.1       schwarze  183:  */
                    184: static void
1.23      schwarze  185: set_query_attr(char **attr, char **val)
1.1       schwarze  186: {
                    187:
1.23      schwarze  188:        free(*attr);
                    189:        if (**val == '\0') {
                    190:                *attr = NULL;
                    191:                free(*val);
                    192:        } else
                    193:                *attr = *val;
                    194:        *val = NULL;
                    195: }
                    196:
                    197: /*
                    198:  * Parse the QUERY_STRING for key-value pairs
                    199:  * and store the values into the query structure.
                    200:  */
                    201: static void
1.68      schwarze  202: parse_query_string(struct req *req, const char *qs)
1.23      schwarze  203: {
                    204:        char            *key, *val;
                    205:        size_t           keysz, valsz;
                    206:
1.60      schwarze  207:        req->isquery    = 1;
1.23      schwarze  208:        req->q.manpath  = NULL;
                    209:        req->q.arch     = NULL;
                    210:        req->q.sec      = NULL;
1.25      schwarze  211:        req->q.query    = NULL;
1.23      schwarze  212:        req->q.equal    = 1;
                    213:
                    214:        key = val = NULL;
                    215:        while (*qs != '\0') {
1.1       schwarze  216:
1.23      schwarze  217:                /* Parse one key. */
                    218:
                    219:                keysz = strcspn(qs, "=;&");
                    220:                key = mandoc_strndup(qs, keysz);
                    221:                qs += keysz;
                    222:                if (*qs != '=')
                    223:                        goto next;
                    224:
                    225:                /* Parse one value. */
                    226:
                    227:                valsz = strcspn(++qs, ";&");
                    228:                val = mandoc_strndup(qs, valsz);
                    229:                qs += valsz;
                    230:
                    231:                /* Decode and catch encoding errors. */
1.1       schwarze  232:
1.23      schwarze  233:                if ( ! (http_decode(key) && http_decode(val)))
                    234:                        goto next;
1.1       schwarze  235:
1.23      schwarze  236:                /* Handle key-value pairs. */
1.1       schwarze  237:
1.23      schwarze  238:                if ( ! strcmp(key, "query"))
1.25      schwarze  239:                        set_query_attr(&req->q.query, &val);
1.1       schwarze  240:
1.23      schwarze  241:                else if ( ! strcmp(key, "apropos"))
                    242:                        req->q.equal = !strcmp(val, "0");
                    243:
                    244:                else if ( ! strcmp(key, "manpath")) {
1.13      schwarze  245: #ifdef COMPAT_OLDURI
1.23      schwarze  246:                        if ( ! strncmp(val, "OpenBSD ", 8)) {
1.13      schwarze  247:                                val[7] = '-';
                    248:                                if ('C' == val[8])
                    249:                                        val[8] = 'c';
                    250:                        }
                    251: #endif
1.23      schwarze  252:                        set_query_attr(&req->q.manpath, &val);
                    253:                }
                    254:
                    255:                else if ( ! (strcmp(key, "sec")
1.13      schwarze  256: #ifdef COMPAT_OLDURI
1.23      schwarze  257:                    && strcmp(key, "sektion")
1.13      schwarze  258: #endif
1.23      schwarze  259:                    )) {
                    260:                        if ( ! strcmp(val, "0"))
                    261:                                *val = '\0';
                    262:                        set_query_attr(&req->q.sec, &val);
1.5       schwarze  263:                }
1.23      schwarze  264:
                    265:                else if ( ! strcmp(key, "arch")) {
                    266:                        if ( ! strcmp(val, "default"))
                    267:                                *val = '\0';
                    268:                        set_query_attr(&req->q.arch, &val);
                    269:                }
                    270:
                    271:                /*
                    272:                 * The key must be freed in any case.
                    273:                 * The val may have been handed over to the query
                    274:                 * structure, in which case it is now NULL.
                    275:                 */
                    276: next:
                    277:                free(key);
                    278:                key = NULL;
                    279:                free(val);
                    280:                val = NULL;
                    281:
                    282:                if (*qs != '\0')
                    283:                        qs++;
1.1       schwarze  284:        }
                    285: }
                    286:
                    287: /*
                    288:  * HTTP-decode a string.  The standard explanation is that this turns
                    289:  * "%4e+foo" into "n foo" in the regular way.  This is done in-place
                    290:  * over the allocated string.
                    291:  */
                    292: static int
                    293: http_decode(char *p)
                    294: {
                    295:        char             hex[3];
1.3       tedu      296:        char            *q;
1.1       schwarze  297:        int              c;
                    298:
                    299:        hex[2] = '\0';
                    300:
1.3       tedu      301:        q = p;
                    302:        for ( ; '\0' != *p; p++, q++) {
1.1       schwarze  303:                if ('%' == *p) {
                    304:                        if ('\0' == (hex[0] = *(p + 1)))
1.48      schwarze  305:                                return 0;
1.1       schwarze  306:                        if ('\0' == (hex[1] = *(p + 2)))
1.48      schwarze  307:                                return 0;
1.1       schwarze  308:                        if (1 != sscanf(hex, "%x", &c))
1.48      schwarze  309:                                return 0;
1.1       schwarze  310:                        if ('\0' == c)
1.48      schwarze  311:                                return 0;
1.1       schwarze  312:
1.3       tedu      313:                        *q = (char)c;
                    314:                        p += 2;
1.1       schwarze  315:                } else
1.3       tedu      316:                        *q = '+' == *p ? ' ' : *p;
1.1       schwarze  317:        }
                    318:
1.3       tedu      319:        *q = '\0';
1.48      schwarze  320:        return 1;
1.1       schwarze  321: }
                    322:
                    323: static void
1.97      schwarze  324: http_encode(const char *p)
                    325: {
                    326:        for (; *p != '\0'; p++) {
                    327:                if (isalnum((unsigned char)*p) == 0 &&
                    328:                    strchr("-._~", *p) == NULL)
1.104     schwarze  329:                        printf("%%%2.2X", (unsigned char)*p);
1.97      schwarze  330:                else
                    331:                        putchar(*p);
                    332:        }
                    333: }
                    334:
                    335: static void
1.1       schwarze  336: resp_begin_http(int code, const char *msg)
                    337: {
                    338:
                    339:        if (200 != code)
1.2       tedu      340:                printf("Status: %d %s\r\n", code, msg);
1.1       schwarze  341:
1.2       tedu      342:        printf("Content-Type: text/html; charset=utf-8\r\n"
                    343:             "Cache-Control: no-cache\r\n"
1.107     bentley   344:             "Content-Security-Policy: default-src 'none'; "
                    345:             "style-src 'self' 'unsafe-inline'\r\n"
1.2       tedu      346:             "Pragma: no-cache\r\n"
                    347:             "\r\n");
1.1       schwarze  348:
                    349:        fflush(stdout);
                    350: }
                    351:
1.117     schwarze  352: static int
                    353: resp_copy(const char *element, const char *filename)
1.53      schwarze  354: {
                    355:        char     buf[4096];
                    356:        ssize_t  sz;
                    357:        int      fd;
                    358:
1.117     schwarze  359:        if ((fd = open(filename, O_RDONLY)) == -1)
                    360:                return 0;
                    361:
                    362:        if (element != NULL)
                    363:                printf("<%s>\n", element);
                    364:        fflush(stdout);
                    365:        while ((sz = read(fd, buf, sizeof(buf))) > 0)
                    366:                write(STDOUT_FILENO, buf, sz);
                    367:        close(fd);
                    368:        return 1;
1.53      schwarze  369: }
                    370:
1.117     schwarze  371: static int
1.88      schwarze  372: resp_begin_html(int code, const char *msg, const char *file)
1.1       schwarze  373: {
1.114     schwarze  374:        const char      *name, *sec, *cp;
                    375:        int              namesz, secsz;
1.1       schwarze  376:
                    377:        resp_begin_http(code, msg);
                    378:
1.37      schwarze  379:        printf("<!DOCTYPE html>\n"
1.65      schwarze  380:               "<html>\n"
                    381:               "<head>\n"
1.82      schwarze  382:               "  <meta charset=\"UTF-8\"/>\n"
1.95      schwarze  383:               "  <meta name=\"viewport\""
                    384:                      " content=\"width=device-width, initial-scale=1.0\">\n"
1.82      schwarze  385:               "  <link rel=\"stylesheet\" href=\"%s/mandoc.css\""
1.65      schwarze  386:               " type=\"text/css\" media=\"all\">\n"
1.88      schwarze  387:               "  <title>",
                    388:               CSS_DIR);
                    389:        if (file != NULL) {
1.114     schwarze  390:                cp = strrchr(file, '/');
                    391:                name = cp == NULL ? file : cp + 1;
                    392:                cp = strrchr(name, '.');
                    393:                namesz = cp == NULL ? strlen(name) : cp - name;
                    394:                sec = NULL;
                    395:                if (cp != NULL && cp[1] != '0') {
                    396:                        sec = cp + 1;
                    397:                        secsz = strlen(sec);
                    398:                } else if (name - file > 1) {
                    399:                        for (cp = name - 2; cp >= file; cp--) {
                    400:                                if (*cp < '1' || *cp > '9')
                    401:                                        continue;
                    402:                                sec = cp;
                    403:                                secsz = name - cp - 1;
                    404:                                break;
                    405:                        }
                    406:                }
                    407:                printf("%.*s", namesz, name);
                    408:                if (sec != NULL)
                    409:                        printf("(%.*s)", secsz, sec);
                    410:                fputs(" - ", stdout);
1.88      schwarze  411:        }
                    412:        printf("%s</title>\n"
1.65      schwarze  413:               "</head>\n"
1.81      schwarze  414:               "<body>\n",
1.88      schwarze  415:               CUSTOMIZE_TITLE);
1.53      schwarze  416:
1.117     schwarze  417:        return resp_copy("header", MAN_DIR "/header.html");
1.1       schwarze  418: }
                    419:
                    420: static void
                    421: resp_end_html(void)
                    422: {
1.117     schwarze  423:        if (resp_copy("footer", MAN_DIR "/footer.html"))
                    424:                puts("</footer>");
1.53      schwarze  425:
1.65      schwarze  426:        puts("</body>\n"
                    427:             "</html>");
1.1       schwarze  428: }
                    429:
                    430: static void
1.70      schwarze  431: resp_searchform(const struct req *req, enum focus focus)
1.1       schwarze  432: {
                    433:        int              i;
                    434:
1.117     schwarze  435:        printf("<form role=\"search\" action=\"/%s\" method=\"get\" "
1.109     schwarze  436:               "autocomplete=\"off\" autocapitalize=\"none\">\n"
1.82      schwarze  437:               "  <fieldset>\n"
                    438:               "    <legend>Manual Page Search Parameters</legend>\n",
1.1       schwarze  439:               scriptname);
1.8       schwarze  440:
                    441:        /* Write query input box. */
                    442:
1.96      schwarze  443:        printf("    <input type=\"search\" name=\"query\" value=\"");
1.70      schwarze  444:        if (req->q.query != NULL)
1.25      schwarze  445:                html_print(req->q.query);
1.70      schwarze  446:        printf( "\" size=\"40\"");
                    447:        if (focus == FOCUS_QUERY)
                    448:                printf(" autofocus");
                    449:        puts(">");
1.8       schwarze  450:
1.71      schwarze  451:        /* Write submission buttons. */
1.8       schwarze  452:
1.82      schwarze  453:        printf( "    <button type=\"submit\" name=\"apropos\" value=\"0\">"
1.71      schwarze  454:                "man</button>\n"
1.82      schwarze  455:                "    <button type=\"submit\" name=\"apropos\" value=\"1\">"
                    456:                "apropos</button>\n"
                    457:                "    <br/>\n");
1.8       schwarze  458:
                    459:        /* Write section selector. */
                    460:
1.118   ! schwarze  461:        puts("    <select name=\"sec\" aria-label=\"Manual section\">");
1.8       schwarze  462:        for (i = 0; i < sec_MAX; i++) {
1.82      schwarze  463:                printf("      <option value=\"%s\"", sec_numbers[i]);
1.8       schwarze  464:                if (NULL != req->q.sec &&
                    465:                    0 == strcmp(sec_numbers[i], req->q.sec))
1.65      schwarze  466:                        printf(" selected=\"selected\"");
                    467:                printf(">%s</option>\n", sec_names[i]);
1.8       schwarze  468:        }
1.82      schwarze  469:        puts("    </select>");
1.8       schwarze  470:
                    471:        /* Write architecture selector. */
                    472:
1.116     schwarze  473:        printf( "    <select name=\"arch\" aria-label=\"CPU architecture\">\n"
1.82      schwarze  474:                "      <option value=\"default\"");
1.21      schwarze  475:        if (NULL == req->q.arch)
1.65      schwarze  476:                printf(" selected=\"selected\"");
                    477:        puts(">All Architectures</option>");
1.8       schwarze  478:        for (i = 0; i < arch_MAX; i++) {
1.96      schwarze  479:                printf("      <option");
1.8       schwarze  480:                if (NULL != req->q.arch &&
                    481:                    0 == strcmp(arch_names[i], req->q.arch))
1.65      schwarze  482:                        printf(" selected=\"selected\"");
                    483:                printf(">%s</option>\n", arch_names[i]);
1.8       schwarze  484:        }
1.82      schwarze  485:        puts("    </select>");
1.8       schwarze  486:
                    487:        /* Write manpath selector. */
                    488:
1.1       schwarze  489:        if (req->psz > 1) {
1.82      schwarze  490:                puts("    <select name=\"manpath\">");
1.1       schwarze  491:                for (i = 0; i < (int)req->psz; i++) {
1.96      schwarze  492:                        printf("      <option");
1.41      schwarze  493:                        if (strcmp(req->q.manpath, req->p[i]) == 0)
1.96      schwarze  494:                                printf(" selected=\"selected\"");
                    495:                        printf(">");
1.1       schwarze  496:                        html_print(req->p[i]);
1.65      schwarze  497:                        puts("</option>");
1.1       schwarze  498:                }
1.82      schwarze  499:                puts("    </select>");
1.1       schwarze  500:        }
1.8       schwarze  501:
1.82      schwarze  502:        puts("  </fieldset>\n"
1.117     schwarze  503:             "</form>");
1.1       schwarze  504: }
                    505:
1.16      schwarze  506: static int
1.20      schwarze  507: validate_urifrag(const char *frag)
                    508: {
                    509:
                    510:        while ('\0' != *frag) {
                    511:                if ( ! (isalnum((unsigned char)*frag) ||
                    512:                    '-' == *frag || '.' == *frag ||
                    513:                    '/' == *frag || '_' == *frag))
1.48      schwarze  514:                        return 0;
1.20      schwarze  515:                frag++;
                    516:        }
1.48      schwarze  517:        return 1;
1.20      schwarze  518: }
                    519:
                    520: static int
1.17      schwarze  521: validate_manpath(const struct req *req, const char* manpath)
                    522: {
                    523:        size_t   i;
                    524:
                    525:        for (i = 0; i < req->psz; i++)
                    526:                if ( ! strcmp(manpath, req->p[i]))
1.48      schwarze  527:                        return 1;
1.17      schwarze  528:
1.48      schwarze  529:        return 0;
1.17      schwarze  530: }
                    531:
                    532: static int
1.97      schwarze  533: validate_arch(const char *arch)
                    534: {
                    535:        int      i;
                    536:
                    537:        for (i = 0; i < arch_MAX; i++)
                    538:                if (strcmp(arch, arch_names[i]) == 0)
                    539:                        return 1;
                    540:
                    541:        return 0;
                    542: }
                    543:
                    544: static int
1.16      schwarze  545: validate_filename(const char *file)
                    546: {
                    547:
                    548:        if ('.' == file[0] && '/' == file[1])
                    549:                file += 2;
                    550:
1.48      schwarze  551:        return ! (strstr(file, "../") || strstr(file, "/..") ||
                    552:            (strncmp(file, "man", 3) && strncmp(file, "cat", 3)));
1.16      schwarze  553: }
                    554:
1.1       schwarze  555: static void
1.12      schwarze  556: pg_index(const struct req *req)
1.1       schwarze  557: {
1.117     schwarze  558:        if (resp_begin_html(200, NULL, NULL) == 0)
                    559:                puts("<header>");
1.70      schwarze  560:        resp_searchform(req, FOCUS_QUERY);
1.117     schwarze  561:        printf("</header>\n"
                    562:               "<main>\n"
1.118   ! schwarze  563:               "<p role=\"doc-notice\" aria-label=\"Usage\">\n"
1.26      schwarze  564:               "This web interface is documented in the\n"
1.116     schwarze  565:               "<a class=\"Xr\" href=\"/%s%sman.cgi.8\""
                    566:               " aria-label=\"man dot CGI, section 8\">man.cgi(8)</a>\n"
1.26      schwarze  567:               "manual, and the\n"
1.116     schwarze  568:               "<a class=\"Xr\" href=\"/%s%sapropos.1\""
                    569:               " aria-label=\"apropos, section 1\">apropos(1)</a>\n"
1.9       schwarze  570:               "manual explains the query syntax.\n"
1.116     schwarze  571:               "</p>\n"
                    572:               "</main>\n",
1.58      schwarze  573:               scriptname, *scriptname == '\0' ? "" : "/",
                    574:               scriptname, *scriptname == '\0' ? "" : "/");
1.1       schwarze  575:        resp_end_html();
                    576: }
                    577:
                    578: static void
1.106     schwarze  579: pg_noresult(const struct req *req, int code, const char *http_msg,
                    580:     const char *user_msg)
1.1       schwarze  581: {
1.117     schwarze  582:        if (resp_begin_html(code, http_msg, NULL) == 0)
                    583:                puts("<header>");
1.70      schwarze  584:        resp_searchform(req, FOCUS_QUERY);
1.117     schwarze  585:        puts("</header>");
1.116     schwarze  586:        puts("<main>");
1.118   ! schwarze  587:        puts("<p role=\"doc-notice\" aria-label=\"No result\">");
1.106     schwarze  588:        puts(user_msg);
1.65      schwarze  589:        puts("</p>");
1.116     schwarze  590:        puts("</main>");
1.1       schwarze  591:        resp_end_html();
                    592: }
                    593:
                    594: static void
1.12      schwarze  595: pg_error_badrequest(const char *msg)
1.1       schwarze  596: {
1.117     schwarze  597:        if (resp_begin_html(400, "Bad Request", NULL))
                    598:                puts("</header>");
1.116     schwarze  599:        puts("<main>\n"
                    600:             "<h1>Bad Request</h1>\n"
                    601:             "<p role=\"doc-notice\" aria-label=\"Bad Request\">");
1.1       schwarze  602:        puts(msg);
                    603:        printf("Try again from the\n"
1.65      schwarze  604:               "<a href=\"/%s\">main page</a>.\n"
1.116     schwarze  605:               "</p>\n"
1.117     schwarze  606:               "</main>\n", scriptname);
1.1       schwarze  607:        resp_end_html();
                    608: }
                    609:
                    610: static void
1.12      schwarze  611: pg_error_internal(void)
1.1       schwarze  612: {
1.117     schwarze  613:        if (resp_begin_html(500, "Internal Server Error", NULL))
                    614:                puts("</header>");
1.116     schwarze  615:        puts("<main><p role=\"doc-notice\">Internal Server Error</p></main>");
1.1       schwarze  616:        resp_end_html();
                    617: }
                    618:
                    619: static void
1.87      schwarze  620: pg_redirect(const struct req *req, const char *name)
                    621: {
1.91      schwarze  622:        printf("Status: 303 See Other\r\n"
                    623:            "Location: /");
1.87      schwarze  624:        if (*scriptname != '\0')
                    625:                printf("%s/", scriptname);
                    626:        if (strcmp(req->q.manpath, req->p[0]))
                    627:                printf("%s/", req->q.manpath);
                    628:        if (req->q.arch != NULL)
                    629:                printf("%s/", req->q.arch);
1.97      schwarze  630:        http_encode(name);
                    631:        if (req->q.sec != NULL) {
                    632:                putchar('.');
                    633:                http_encode(req->q.sec);
                    634:        }
1.87      schwarze  635:        printf("\r\nContent-Type: text/html; charset=utf-8\r\n\r\n");
                    636: }
                    637:
                    638: static void
1.12      schwarze  639: pg_searchres(const struct req *req, struct manpage *r, size_t sz)
1.1       schwarze  640: {
1.21      schwarze  641:        char            *arch, *archend;
1.59      schwarze  642:        const char      *sec;
                    643:        size_t           i, iuse;
1.21      schwarze  644:        int              archprio, archpriouse;
1.10      schwarze  645:        int              prio, priouse;
1.117     schwarze  646:        int              have_header;
1.1       schwarze  647:
1.16      schwarze  648:        for (i = 0; i < sz; i++) {
                    649:                if (validate_filename(r[i].file))
                    650:                        continue;
1.67      schwarze  651:                warnx("invalid filename %s in %s database",
1.16      schwarze  652:                    r[i].file, req->q.manpath);
                    653:                pg_error_internal();
                    654:                return;
                    655:        }
                    656:
1.60      schwarze  657:        if (req->isquery && sz == 1) {
1.1       schwarze  658:                /*
                    659:                 * If we have just one result, then jump there now
                    660:                 * without any delay.
                    661:                 */
1.91      schwarze  662:                printf("Status: 303 See Other\r\n"
                    663:                    "Location: /");
                    664:                if (*scriptname != '\0')
                    665:                        printf("%s/", scriptname);
                    666:                if (strcmp(req->q.manpath, req->p[0]))
                    667:                        printf("%s/", req->q.manpath);
                    668:                printf("%s\r\n"
                    669:                    "Content-Type: text/html; charset=utf-8\r\n\r\n",
                    670:                    r[0].file);
1.1       schwarze  671:                return;
                    672:        }
                    673:
1.10      schwarze  674:        /*
                    675:         * In man(1) mode, show one of the pages
                    676:         * even if more than one is found.
                    677:         */
                    678:
1.88      schwarze  679:        iuse = 0;
1.62      schwarze  680:        if (req->q.equal || sz == 1) {
1.59      schwarze  681:                priouse = 20;
1.21      schwarze  682:                archpriouse = 3;
1.10      schwarze  683:                for (i = 0; i < sz; i++) {
1.59      schwarze  684:                        sec = r[i].file;
                    685:                        sec += strcspn(sec, "123456789");
                    686:                        if (sec[0] == '\0')
1.10      schwarze  687:                                continue;
1.59      schwarze  688:                        prio = sec_prios[sec[0] - '1'];
                    689:                        if (sec[1] != '/')
                    690:                                prio += 10;
                    691:                        if (req->q.arch == NULL) {
1.21      schwarze  692:                                archprio =
1.59      schwarze  693:                                    ((arch = strchr(sec + 1, '/'))
                    694:                                        == NULL) ? 3 :
                    695:                                    ((archend = strchr(arch + 1, '/'))
                    696:                                        == NULL) ? 0 :
1.21      schwarze  697:                                    strncmp(arch, "amd64/",
                    698:                                        archend - arch) ? 2 : 1;
                    699:                                if (archprio < archpriouse) {
                    700:                                        archpriouse = archprio;
                    701:                                        priouse = prio;
                    702:                                        iuse = i;
                    703:                                        continue;
                    704:                                }
                    705:                                if (archprio > archpriouse)
                    706:                                        continue;
                    707:                        }
1.10      schwarze  708:                        if (prio >= priouse)
                    709:                                continue;
                    710:                        priouse = prio;
                    711:                        iuse = i;
                    712:                }
1.117     schwarze  713:                have_header = resp_begin_html(200, NULL, r[iuse].file);
1.88      schwarze  714:        } else
1.117     schwarze  715:                have_header = resp_begin_html(200, NULL, NULL);
1.88      schwarze  716:
1.117     schwarze  717:        if (have_header == 0)
                    718:                puts("<header>");
1.88      schwarze  719:        resp_searchform(req,
                    720:            req->q.equal || sz == 1 ? FOCUS_NONE : FOCUS_QUERY);
1.117     schwarze  721:        puts("</header>");
1.88      schwarze  722:
                    723:        if (sz > 1) {
1.116     schwarze  724:                puts("<nav>");
1.88      schwarze  725:                puts("<table class=\"results\">");
                    726:                for (i = 0; i < sz; i++) {
                    727:                        printf("  <tr>\n"
                    728:                               "    <td>"
1.89      schwarze  729:                               "<a class=\"Xr\" href=\"/");
                    730:                        if (*scriptname != '\0')
                    731:                                printf("%s/", scriptname);
                    732:                        if (strcmp(req->q.manpath, req->p[0]))
                    733:                                printf("%s/", req->q.manpath);
                    734:                        printf("%s\">", r[i].file);
1.88      schwarze  735:                        html_print(r[i].names);
                    736:                        printf("</a></td>\n"
                    737:                               "    <td><span class=\"Nd\">");
                    738:                        html_print(r[i].output);
                    739:                        puts("</span></td>\n"
                    740:                             "  </tr>");
                    741:                }
                    742:                puts("</table>");
1.116     schwarze  743:                puts("</nav>");
1.88      schwarze  744:        }
                    745:
                    746:        if (req->q.equal || sz == 1) {
                    747:                puts("<hr>");
1.10      schwarze  748:                resp_show(req, r[iuse].file);
                    749:        }
                    750:
1.1       schwarze  751:        resp_end_html();
                    752: }
                    753:
                    754: static void
1.68      schwarze  755: resp_catman(const struct req *req, const char *file)
1.1       schwarze  756: {
                    757:        FILE            *f;
1.54      schwarze  758:        char            *p;
                    759:        size_t           sz;
                    760:        ssize_t          len;
1.1       schwarze  761:        int              i;
                    762:        int              italic, bold;
                    763:
1.54      schwarze  764:        if ((f = fopen(file, "r")) == NULL) {
1.116     schwarze  765:                puts("<p role=\"doc-notice\">\n"
                    766:                     "  You specified an invalid manual file.\n"
                    767:                     "</p>");
1.1       schwarze  768:                return;
                    769:        }
                    770:
1.65      schwarze  771:        puts("<div class=\"catman\">\n"
                    772:             "<pre>");
1.1       schwarze  773:
1.54      schwarze  774:        p = NULL;
                    775:        sz = 0;
                    776:
                    777:        while ((len = getline(&p, &sz, f)) != -1) {
1.1       schwarze  778:                bold = italic = 0;
1.54      schwarze  779:                for (i = 0; i < len - 1; i++) {
1.43      schwarze  780:                        /*
1.1       schwarze  781:                         * This means that the catpage is out of state.
                    782:                         * Ignore it and keep going (although the
                    783:                         * catpage is bogus).
                    784:                         */
                    785:
                    786:                        if ('\b' == p[i] || '\n' == p[i])
                    787:                                continue;
                    788:
                    789:                        /*
                    790:                         * Print a regular character.
                    791:                         * Close out any bold/italic scopes.
                    792:                         * If we're in back-space mode, make sure we'll
                    793:                         * have something to enter when we backspace.
                    794:                         */
                    795:
                    796:                        if ('\b' != p[i + 1]) {
                    797:                                if (italic)
1.65      schwarze  798:                                        printf("</i>");
1.1       schwarze  799:                                if (bold)
1.65      schwarze  800:                                        printf("</b>");
1.1       schwarze  801:                                italic = bold = 0;
                    802:                                html_putchar(p[i]);
                    803:                                continue;
1.54      schwarze  804:                        } else if (i + 2 >= len)
1.1       schwarze  805:                                continue;
                    806:
                    807:                        /* Italic mode. */
                    808:
                    809:                        if ('_' == p[i]) {
                    810:                                if (bold)
1.65      schwarze  811:                                        printf("</b>");
1.1       schwarze  812:                                if ( ! italic)
1.65      schwarze  813:                                        printf("<i>");
1.1       schwarze  814:                                bold = 0;
                    815:                                italic = 1;
                    816:                                i += 2;
                    817:                                html_putchar(p[i]);
                    818:                                continue;
                    819:                        }
                    820:
1.43      schwarze  821:                        /*
1.1       schwarze  822:                         * Handle funny behaviour troff-isms.
                    823:                         * These grok'd from the original man2html.c.
                    824:                         */
                    825:
                    826:                        if (('+' == p[i] && 'o' == p[i + 2]) ||
                    827:                                        ('o' == p[i] && '+' == p[i + 2]) ||
                    828:                                        ('|' == p[i] && '=' == p[i + 2]) ||
                    829:                                        ('=' == p[i] && '|' == p[i + 2]) ||
                    830:                                        ('*' == p[i] && '=' == p[i + 2]) ||
                    831:                                        ('=' == p[i] && '*' == p[i + 2]) ||
                    832:                                        ('*' == p[i] && '|' == p[i + 2]) ||
                    833:                                        ('|' == p[i] && '*' == p[i + 2]))  {
                    834:                                if (italic)
1.65      schwarze  835:                                        printf("</i>");
1.1       schwarze  836:                                if (bold)
1.65      schwarze  837:                                        printf("</b>");
1.1       schwarze  838:                                italic = bold = 0;
                    839:                                putchar('*');
                    840:                                i += 2;
                    841:                                continue;
                    842:                        } else if (('|' == p[i] && '-' == p[i + 2]) ||
                    843:                                        ('-' == p[i] && '|' == p[i + 1]) ||
                    844:                                        ('+' == p[i] && '-' == p[i + 1]) ||
                    845:                                        ('-' == p[i] && '+' == p[i + 1]) ||
                    846:                                        ('+' == p[i] && '|' == p[i + 1]) ||
                    847:                                        ('|' == p[i] && '+' == p[i + 1]))  {
                    848:                                if (italic)
1.65      schwarze  849:                                        printf("</i>");
1.1       schwarze  850:                                if (bold)
1.65      schwarze  851:                                        printf("</b>");
1.1       schwarze  852:                                italic = bold = 0;
                    853:                                putchar('+');
                    854:                                i += 2;
                    855:                                continue;
                    856:                        }
                    857:
                    858:                        /* Bold mode. */
1.43      schwarze  859:
1.1       schwarze  860:                        if (italic)
1.65      schwarze  861:                                printf("</i>");
1.1       schwarze  862:                        if ( ! bold)
1.65      schwarze  863:                                printf("<b>");
1.1       schwarze  864:                        bold = 1;
                    865:                        italic = 0;
                    866:                        i += 2;
                    867:                        html_putchar(p[i]);
                    868:                }
                    869:
1.43      schwarze  870:                /*
1.1       schwarze  871:                 * Clean up the last character.
1.43      schwarze  872:                 * We can get to a newline; don't print that.
1.1       schwarze  873:                 */
                    874:
                    875:                if (italic)
1.65      schwarze  876:                        printf("</i>");
1.1       schwarze  877:                if (bold)
1.65      schwarze  878:                        printf("</b>");
1.1       schwarze  879:
1.54      schwarze  880:                if (i == len - 1 && p[i] != '\n')
1.1       schwarze  881:                        html_putchar(p[i]);
                    882:
                    883:                putchar('\n');
                    884:        }
1.54      schwarze  885:        free(p);
1.1       schwarze  886:
1.65      schwarze  887:        puts("</pre>\n"
                    888:             "</div>");
1.1       schwarze  889:
                    890:        fclose(f);
                    891: }
                    892:
                    893: static void
1.68      schwarze  894: resp_format(const struct req *req, const char *file)
1.1       schwarze  895: {
1.45      schwarze  896:        struct manoutput conf;
1.1       schwarze  897:        struct mparse   *mp;
1.102     schwarze  898:        struct roff_meta *meta;
1.1       schwarze  899:        void            *vp;
1.30      schwarze  900:        int              fd;
                    901:        int              usepath;
1.1       schwarze  902:
1.115     deraadt   903:        if (-1 == (fd = open(file, O_RDONLY))) {
1.116     schwarze  904:                puts("<p role=\"doc-notice\">\n"
                    905:                     "  You specified an invalid manual file.\n"
                    906:                     "</p>");
1.1       schwarze  907:                return;
                    908:        }
                    909:
1.49      schwarze  910:        mchars_alloc();
1.102     schwarze  911:        mp = mparse_alloc(MPARSE_SO | MPARSE_UTF8 | MPARSE_LATIN1 |
                    912:            MPARSE_VALIDATE, MANDOC_OS_OTHER, req->q.manpath);
1.42      schwarze  913:        mparse_readfd(mp, fd, file);
1.1       schwarze  914:        close(fd);
1.102     schwarze  915:        meta = mparse_result(mp);
1.1       schwarze  916:
1.45      schwarze  917:        memset(&conf, 0, sizeof(conf));
                    918:        conf.fragment = 1;
1.84      schwarze  919:        conf.style = mandoc_strdup(CSS_DIR "/mandoc.css");
1.30      schwarze  920:        usepath = strcmp(req->q.manpath, req->p[0]);
1.90      schwarze  921:        mandoc_asprintf(&conf.man, "/%s%s%s%s%%N.%%S",
                    922:            scriptname, *scriptname == '\0' ? "" : "/",
1.61      schwarze  923:            usepath ? req->q.manpath : "", usepath ? "/" : "");
1.1       schwarze  924:
1.49      schwarze  925:        vp = html_alloc(&conf);
1.102     schwarze  926:        if (meta->macroset == MACROSET_MDOC)
                    927:                html_mdoc(vp, meta);
                    928:        else
                    929:                html_man(vp, meta);
1.1       schwarze  930:
                    931:        html_free(vp);
                    932:        mparse_free(mp);
1.49      schwarze  933:        mchars_free();
1.45      schwarze  934:        free(conf.man);
1.84      schwarze  935:        free(conf.style);
1.1       schwarze  936: }
                    937:
                    938: static void
1.10      schwarze  939: resp_show(const struct req *req, const char *file)
                    940: {
1.16      schwarze  941:
                    942:        if ('.' == file[0] && '/' == file[1])
1.11      schwarze  943:                file += 2;
1.10      schwarze  944:
                    945:        if ('c' == *file)
1.68      schwarze  946:                resp_catman(req, file);
1.10      schwarze  947:        else
1.68      schwarze  948:                resp_format(req, file);
1.10      schwarze  949: }
                    950:
                    951: static void
1.24      schwarze  952: pg_show(struct req *req, const char *fullpath)
1.1       schwarze  953: {
1.24      schwarze  954:        char            *manpath;
                    955:        const char      *file;
1.1       schwarze  956:
1.24      schwarze  957:        if ((file = strchr(fullpath, '/')) == NULL) {
1.12      schwarze  958:                pg_error_badrequest(
1.1       schwarze  959:                    "You did not specify a page to show.");
                    960:                return;
1.43      schwarze  961:        }
1.24      schwarze  962:        manpath = mandoc_strndup(fullpath, file - fullpath);
                    963:        file++;
1.1       schwarze  964:
1.24      schwarze  965:        if ( ! validate_manpath(req, manpath)) {
1.17      schwarze  966:                pg_error_badrequest(
                    967:                    "You specified an invalid manpath.");
1.24      schwarze  968:                free(manpath);
1.17      schwarze  969:                return;
                    970:        }
                    971:
1.1       schwarze  972:        /*
                    973:         * Begin by chdir()ing into the manpath.
                    974:         * This way we can pick up the database files, which are
                    975:         * relative to the manpath root.
                    976:         */
                    977:
1.24      schwarze  978:        if (chdir(manpath) == -1) {
1.67      schwarze  979:                warn("chdir %s", manpath);
1.17      schwarze  980:                pg_error_internal();
1.24      schwarze  981:                free(manpath);
1.16      schwarze  982:                return;
                    983:        }
1.73      schwarze  984:        free(manpath);
1.24      schwarze  985:
                    986:        if ( ! validate_filename(file)) {
1.16      schwarze  987:                pg_error_badrequest(
                    988:                    "You specified an invalid manual file.");
1.1       schwarze  989:                return;
                    990:        }
1.19      schwarze  991:
1.117     schwarze  992:        if (resp_begin_html(200, NULL, file) == 0)
                    993:                puts("<header>");
1.70      schwarze  994:        resp_searchform(req, FOCUS_NONE);
1.117     schwarze  995:        puts("</header>");
1.24      schwarze  996:        resp_show(req, file);
1.10      schwarze  997:        resp_end_html();
1.1       schwarze  998: }
                    999:
                   1000: static void
1.6       schwarze 1001: pg_search(const struct req *req)
1.1       schwarze 1002: {
                   1003:        struct mansearch          search;
                   1004:        struct manpaths           paths;
                   1005:        struct manpage           *res;
1.36      schwarze 1006:        char                    **argv;
                   1007:        char                     *query, *rp, *wp;
1.1       schwarze 1008:        size_t                    ressz;
1.36      schwarze 1009:        int                       argc;
1.1       schwarze 1010:
                   1011:        /*
                   1012:         * Begin by chdir()ing into the root of the manpath.
                   1013:         * This way we can pick up the database files, which are
                   1014:         * relative to the manpath root.
                   1015:         */
                   1016:
1.67      schwarze 1017:        if (chdir(req->q.manpath) == -1) {
                   1018:                warn("chdir %s", req->q.manpath);
1.17      schwarze 1019:                pg_error_internal();
1.1       schwarze 1020:                return;
                   1021:        }
                   1022:
                   1023:        search.arch = req->q.arch;
                   1024:        search.sec = req->q.sec;
1.35      schwarze 1025:        search.outkey = "Nd";
                   1026:        search.argmode = req->q.equal ? ARG_NAME : ARG_EXPR;
1.40      schwarze 1027:        search.firstmatch = 1;
1.1       schwarze 1028:
                   1029:        paths.sz = 1;
                   1030:        paths.paths = mandoc_malloc(sizeof(char *));
                   1031:        paths.paths[0] = mandoc_strdup(".");
                   1032:
                   1033:        /*
1.36      schwarze 1034:         * Break apart at spaces with backslash-escaping.
1.1       schwarze 1035:         */
                   1036:
1.36      schwarze 1037:        argc = 0;
                   1038:        argv = NULL;
                   1039:        rp = query = mandoc_strdup(req->q.query);
                   1040:        for (;;) {
                   1041:                while (isspace((unsigned char)*rp))
                   1042:                        rp++;
                   1043:                if (*rp == '\0')
                   1044:                        break;
                   1045:                argv = mandoc_reallocarray(argv, argc + 1, sizeof(char *));
                   1046:                argv[argc++] = wp = rp;
                   1047:                for (;;) {
                   1048:                        if (isspace((unsigned char)*rp)) {
                   1049:                                *wp = '\0';
                   1050:                                rp++;
                   1051:                                break;
                   1052:                        }
                   1053:                        if (rp[0] == '\\' && rp[1] != '\0')
                   1054:                                rp++;
                   1055:                        if (wp != rp)
                   1056:                                *wp = *rp;
                   1057:                        if (*rp == '\0')
                   1058:                                break;
                   1059:                        wp++;
                   1060:                        rp++;
                   1061:                }
1.1       schwarze 1062:        }
                   1063:
1.87      schwarze 1064:        res = NULL;
                   1065:        ressz = 0;
                   1066:        if (req->isquery && req->q.equal && argc == 1)
                   1067:                pg_redirect(req, argv[0]);
                   1068:        else if (mansearch(&search, &paths, argc, argv, &res, &ressz) == 0)
1.106     schwarze 1069:                pg_noresult(req, 400, "Bad Request",
                   1070:                    "You entered an invalid query.");
1.87      schwarze 1071:        else if (ressz == 0)
1.106     schwarze 1072:                pg_noresult(req, 404, "Not Found", "No results found.");
1.1       schwarze 1073:        else
1.12      schwarze 1074:                pg_searchres(req, res, ressz);
1.1       schwarze 1075:
1.36      schwarze 1076:        free(query);
                   1077:        mansearch_free(res, ressz);
1.1       schwarze 1078:        free(paths.paths[0]);
                   1079:        free(paths.paths);
                   1080: }
                   1081:
                   1082: int
                   1083: main(void)
                   1084: {
1.6       schwarze 1085:        struct req       req;
1.33      schwarze 1086:        struct itimerval itimer;
1.6       schwarze 1087:        const char      *path;
1.23      schwarze 1088:        const char      *querystring;
1.1       schwarze 1089:        int              i;
1.86      schwarze 1090:
                   1091:        /*
                   1092:         * The "rpath" pledge could be revoked after mparse_readfd()
                   1093:         * if the file desciptor to "/footer.html" would be opened
                   1094:         * up front, but it's probably not worth the complication
                   1095:         * of the code it would cause: it would require scattering
                   1096:         * pledge() calls in multiple low-level resp_*() functions.
                   1097:         */
                   1098:
                   1099:        if (pledge("stdio rpath", NULL) == -1) {
                   1100:                warn("pledge");
                   1101:                pg_error_internal();
                   1102:                return EXIT_FAILURE;
                   1103:        }
1.33      schwarze 1104:
                   1105:        /* Poor man's ReDoS mitigation. */
                   1106:
1.38      schwarze 1107:        itimer.it_value.tv_sec = 2;
1.33      schwarze 1108:        itimer.it_value.tv_usec = 0;
1.38      schwarze 1109:        itimer.it_interval.tv_sec = 2;
1.33      schwarze 1110:        itimer.it_interval.tv_usec = 0;
                   1111:        if (setitimer(ITIMER_VIRTUAL, &itimer, NULL) == -1) {
1.67      schwarze 1112:                warn("setitimer");
1.20      schwarze 1113:                pg_error_internal();
1.48      schwarze 1114:                return EXIT_FAILURE;
1.20      schwarze 1115:        }
                   1116:
1.1       schwarze 1117:        /*
1.7       schwarze 1118:         * First we change directory into the MAN_DIR so that
1.1       schwarze 1119:         * subsequent scanning for manpath directories is rooted
                   1120:         * relative to the same position.
                   1121:         */
                   1122:
1.67      schwarze 1123:        if (chdir(MAN_DIR) == -1) {
                   1124:                warn("MAN_DIR: %s", MAN_DIR);
1.12      schwarze 1125:                pg_error_internal();
1.48      schwarze 1126:                return EXIT_FAILURE;
1.43      schwarze 1127:        }
1.1       schwarze 1128:
                   1129:        memset(&req, 0, sizeof(struct req));
1.57      schwarze 1130:        req.q.equal = 1;
1.68      schwarze 1131:        parse_manpath_conf(&req);
1.1       schwarze 1132:
1.56      schwarze 1133:        /* Parse the path info and the query string. */
1.1       schwarze 1134:
1.56      schwarze 1135:        if ((path = getenv("PATH_INFO")) == NULL)
                   1136:                path = "";
                   1137:        else if (*path == '/')
                   1138:                path++;
                   1139:
1.63      schwarze 1140:        if (*path != '\0') {
1.68      schwarze 1141:                parse_path_info(&req, path);
1.92      schwarze 1142:                if (req.q.manpath == NULL || req.q.sec == NULL ||
                   1143:                    *req.q.query == '\0' || access(path, F_OK) == -1)
1.63      schwarze 1144:                        path = "";
1.56      schwarze 1145:        } else if ((querystring = getenv("QUERY_STRING")) != NULL)
1.68      schwarze 1146:                parse_query_string(&req, querystring);
1.17      schwarze 1147:
1.56      schwarze 1148:        /* Validate parsed data and add defaults. */
                   1149:
1.41      schwarze 1150:        if (req.q.manpath == NULL)
                   1151:                req.q.manpath = mandoc_strdup(req.p[0]);
                   1152:        else if ( ! validate_manpath(&req, req.q.manpath)) {
1.17      schwarze 1153:                pg_error_badrequest(
                   1154:                    "You specified an invalid manpath.");
1.48      schwarze 1155:                return EXIT_FAILURE;
1.17      schwarze 1156:        }
1.1       schwarze 1157:
1.97      schwarze 1158:        if (req.q.arch != NULL && validate_arch(req.q.arch) == 0) {
1.20      schwarze 1159:                pg_error_badrequest(
                   1160:                    "You specified an invalid architecture.");
1.48      schwarze 1161:                return EXIT_FAILURE;
1.20      schwarze 1162:        }
                   1163:
1.6       schwarze 1164:        /* Dispatch to the three different pages. */
1.1       schwarze 1165:
1.6       schwarze 1166:        if ('\0' != *path)
                   1167:                pg_show(&req, path);
1.25      schwarze 1168:        else if (NULL != req.q.query)
1.6       schwarze 1169:                pg_search(&req);
                   1170:        else
1.12      schwarze 1171:                pg_index(&req);
1.1       schwarze 1172:
1.23      schwarze 1173:        free(req.q.manpath);
                   1174:        free(req.q.arch);
                   1175:        free(req.q.sec);
1.25      schwarze 1176:        free(req.q.query);
1.1       schwarze 1177:        for (i = 0; i < (int)req.psz; i++)
                   1178:                free(req.p[i]);
                   1179:        free(req.p);
1.48      schwarze 1180:        return EXIT_SUCCESS;
1.56      schwarze 1181: }
                   1182:
                   1183: /*
1.99      schwarze 1184:  * Translate PATH_INFO to a query.
1.56      schwarze 1185:  */
                   1186: static void
1.68      schwarze 1187: parse_path_info(struct req *req, const char *path)
1.56      schwarze 1188: {
1.99      schwarze 1189:        const char      *name, *sec, *end;
1.56      schwarze 1190:
1.60      schwarze 1191:        req->isquery = 0;
1.56      schwarze 1192:        req->q.equal = 1;
1.99      schwarze 1193:        req->q.manpath = NULL;
1.74      schwarze 1194:        req->q.arch = NULL;
1.56      schwarze 1195:
                   1196:        /* Mandatory manual page name. */
1.99      schwarze 1197:        if ((name = strrchr(path, '/')) == NULL)
                   1198:                name = path;
                   1199:        else
                   1200:                name++;
1.56      schwarze 1201:
                   1202:        /* Optional trailing section. */
1.99      schwarze 1203:        sec = strrchr(name, '.');
                   1204:        if (sec != NULL && isdigit((unsigned char)*++sec)) {
                   1205:                req->q.query = mandoc_strndup(name, sec - name - 1);
                   1206:                req->q.sec = mandoc_strdup(sec);
                   1207:        } else {
                   1208:                req->q.query = mandoc_strdup(name);
                   1209:                req->q.sec = NULL;
1.56      schwarze 1210:        }
                   1211:
                   1212:        /* Handle the case of name[.section] only. */
1.99      schwarze 1213:        if (name == path)
1.56      schwarze 1214:                return;
                   1215:
1.74      schwarze 1216:        /* Optional manpath. */
1.99      schwarze 1217:        end = strchr(path, '/');
                   1218:        req->q.manpath = mandoc_strndup(path, end - path);
                   1219:        if (validate_manpath(req, req->q.manpath)) {
                   1220:                path = end + 1;
                   1221:                if (name == path)
                   1222:                        return;
                   1223:        } else {
                   1224:                free(req->q.manpath);
1.74      schwarze 1225:                req->q.manpath = NULL;
1.99      schwarze 1226:        }
1.56      schwarze 1227:
1.74      schwarze 1228:        /* Optional section. */
1.103     schwarze 1229:        if (strncmp(path, "man", 3) == 0 || strncmp(path, "cat", 3) == 0) {
1.99      schwarze 1230:                path += 3;
                   1231:                end = strchr(path, '/');
1.66      schwarze 1232:                free(req->q.sec);
1.99      schwarze 1233:                req->q.sec = mandoc_strndup(path, end - path);
                   1234:                path = end + 1;
                   1235:                if (name == path)
                   1236:                        return;
1.56      schwarze 1237:        }
1.99      schwarze 1238:
                   1239:        /* Optional architecture. */
                   1240:        end = strchr(path, '/');
                   1241:        if (end + 1 != name) {
                   1242:                pg_error_badrequest(
                   1243:                    "You specified too many directory components.");
                   1244:                exit(EXIT_FAILURE);
1.74      schwarze 1245:        }
1.99      schwarze 1246:        req->q.arch = mandoc_strndup(path, end - path);
                   1247:        if (validate_arch(req->q.arch) == 0) {
1.74      schwarze 1248:                pg_error_badrequest(
                   1249:                    "You specified an invalid directory component.");
                   1250:                exit(EXIT_FAILURE);
                   1251:        }
1.1       schwarze 1252: }
                   1253:
                   1254: /*
                   1255:  * Scan for indexable paths.
                   1256:  */
                   1257: static void
1.68      schwarze 1258: parse_manpath_conf(struct req *req)
1.1       schwarze 1259: {
                   1260:        FILE    *fp;
                   1261:        char    *dp;
                   1262:        size_t   dpsz;
1.54      schwarze 1263:        ssize_t  len;
1.1       schwarze 1264:
1.67      schwarze 1265:        if ((fp = fopen("manpath.conf", "r")) == NULL) {
                   1266:                warn("%s/manpath.conf", MAN_DIR);
1.14      schwarze 1267:                pg_error_internal();
                   1268:                exit(EXIT_FAILURE);
                   1269:        }
1.1       schwarze 1270:
1.54      schwarze 1271:        dp = NULL;
                   1272:        dpsz = 0;
                   1273:
                   1274:        while ((len = getline(&dp, &dpsz, fp)) != -1) {
                   1275:                if (dp[len - 1] == '\n')
                   1276:                        dp[--len] = '\0';
1.1       schwarze 1277:                req->p = mandoc_realloc(req->p,
                   1278:                    (req->psz + 1) * sizeof(char *));
1.20      schwarze 1279:                if ( ! validate_urifrag(dp)) {
1.67      schwarze 1280:                        warnx("%s/manpath.conf contains "
                   1281:                            "unsafe path \"%s\"", MAN_DIR, dp);
1.20      schwarze 1282:                        pg_error_internal();
                   1283:                        exit(EXIT_FAILURE);
                   1284:                }
1.67      schwarze 1285:                if (strchr(dp, '/') != NULL) {
                   1286:                        warnx("%s/manpath.conf contains "
                   1287:                            "path with slash \"%s\"", MAN_DIR, dp);
1.20      schwarze 1288:                        pg_error_internal();
                   1289:                        exit(EXIT_FAILURE);
                   1290:                }
                   1291:                req->p[req->psz++] = dp;
1.54      schwarze 1292:                dp = NULL;
                   1293:                dpsz = 0;
1.14      schwarze 1294:        }
1.54      schwarze 1295:        free(dp);
1.14      schwarze 1296:
1.67      schwarze 1297:        if (req->p == NULL) {
                   1298:                warnx("%s/manpath.conf is empty", MAN_DIR);
1.14      schwarze 1299:                pg_error_internal();
                   1300:                exit(EXIT_FAILURE);
1.1       schwarze 1301:        }
                   1302: }