[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.46

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