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

Annotation of mandoc/cgi.c, Revision 1.177

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

CVSweb