]>
git.cameronkatri.com Git - mandoc.git/blob - cgi.c
1 /* $Id: cgi.c,v 1.35 2011/12/16 12:06:35 kristaps Exp $ */
3 * Copyright (c) 2011 Kristaps Dzonsons <kristaps@bsd.lv>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 #include <sys/param.h>
38 #include "apropos_db.h"
64 * A query as passed to the search function.
67 const char *arch
; /* architecture */
68 const char *sec
; /* manual section */
69 const char *expr
; /* unparsed expression string */
70 int manroot
; /* manroot index (or -1)*/
71 int whatis
; /* whether whatis mode */
72 int legacy
; /* whether legacy mode */
82 static int atou(const char *, unsigned *);
83 static void catman(const struct req
*, const char *);
84 static int cmp(const void *, const void *);
85 static void format(const struct req
*, const char *);
86 static void html_print(const char *);
87 static void html_putchar(char);
88 static int http_decode(char *);
89 static void http_parse(struct req
*, char *);
90 static int pathstop(DIR *);
91 static void pathgen(DIR *, char *, struct req
*);
92 static void pg_index(const struct req
*, char *);
93 static void pg_search(const struct req
*, char *);
94 static void pg_show(const struct req
*, char *);
95 static void resp_bad(void);
96 static void resp_baddb(void);
97 static void resp_error400(void);
98 static void resp_error404(const char *);
99 static void resp_begin_html(int, const char *);
100 static void resp_begin_http(int, const char *);
101 static void resp_end_html(void);
102 static void resp_index(const struct req
*);
103 static void resp_search(struct res
*, size_t, void *);
104 static void resp_searchform(const struct req
*);
106 static const char *progname
; /* cgi script name */
107 static const char *cache
; /* cache directory */
108 static const char *css
; /* css directory */
109 static const char *host
; /* hostname */
111 static const char * const pages
[PAGE__MAX
] = {
112 "index", /* PAGE_INDEX */
113 "search", /* PAGE_SEARCH */
114 "show", /* PAGE_SHOW */
118 * This is just OpenBSD's strtol(3) suggestion.
119 * I use it instead of strtonum(3) for portability's sake.
122 atou(const char *buf
, unsigned *v
)
128 lval
= strtol(buf
, &ep
, 10);
129 if (buf
[0] == '\0' || *ep
!= '\0')
131 if ((errno
== ERANGE
&& (lval
== LONG_MAX
||
132 lval
== LONG_MIN
)) ||
133 (lval
> UINT_MAX
|| lval
< 0))
136 *v
= (unsigned int)lval
;
141 * Print a character, escaping HTML along the way.
142 * This will pass non-ASCII straight to output: be warned!
162 putchar((unsigned char)c
);
168 * Call through to html_putchar().
169 * Accepts NULL strings.
172 html_print(const char *p
)
182 * Parse out key-value pairs from an HTTP request variable.
183 * This can be either a cookie or a POST/GET string, although man.cgi
184 * uses only GET for simplicity.
187 http_parse(struct req
*req
, char *p
)
189 char *key
, *val
, *manroot
;
193 memset(&req
->q
, 0, sizeof(struct query
));
199 while (p
&& '\0' != *p
) {
206 if (NULL
!= (p
= strchr(p
, '='))) {
210 sz
= strcspn(p
, ";&");
218 sz
= strcspn(p
, ";&");
227 if ('\0' == *key
|| '\0' == *val
)
230 /* Just abort handling. */
232 if ( ! http_decode(key
))
234 if ( ! http_decode(val
))
237 if (0 == strcmp(key
, "expr"))
239 else if (0 == strcmp(key
, "query"))
241 else if (0 == strcmp(key
, "sec"))
243 else if (0 == strcmp(key
, "sektion"))
245 else if (0 == strcmp(key
, "arch"))
247 else if (0 == strcmp(key
, "manpath"))
249 else if (0 == strcmp(key
, "apropos"))
250 legacy
= 0 == strcmp(val
, "0");
251 else if (0 == strcmp(key
, "op"))
252 req
->q
.whatis
= 0 == strcasecmp(val
, "whatis");
255 /* Test for old man.cgi compatibility mode. */
260 } else if (legacy
> 0) {
266 * Section "0" means no section when in legacy mode.
267 * For some man.cgi scripts, "default" arch is none.
270 if (req
->q
.legacy
&& NULL
!= req
->q
.sec
)
271 if (0 == strcmp(req
->q
.sec
, "0"))
273 if (req
->q
.legacy
&& NULL
!= req
->q
.arch
)
274 if (0 == strcmp(req
->q
.arch
, "default"))
277 /* Default to first manroot. */
279 if (NULL
!= manroot
) {
280 for (i
= 0; i
< (int)req
->psz
; i
++)
281 if (0 == strcmp(req
->p
[i
].name
, manroot
))
283 req
->q
.manroot
= i
< (int)req
->psz
? i
: -1;
288 * HTTP-decode a string. The standard explanation is that this turns
289 * "%4e+foo" into "n foo" in the regular way. This is done in-place
290 * over the allocated string.
300 for ( ; '\0' != *p
; p
++) {
302 if ('\0' == (hex
[0] = *(p
+ 1)))
304 if ('\0' == (hex
[1] = *(p
+ 2)))
306 if (1 != sscanf(hex
, "%x", &c
))
312 memmove(p
+ 1, p
+ 3, strlen(p
+ 3) + 1);
314 *p
= '+' == *p
? ' ' : *p
;
322 resp_begin_http(int code
, const char *msg
)
326 printf("Status: %d %s\n", code
, msg
);
328 puts("Content-Type: text/html; charset=utf-8\n"
329 "Cache-Control: no-cache\n"
337 resp_begin_html(int code
, const char *msg
)
340 resp_begin_http(code
, msg
);
342 printf("<!DOCTYPE HTML PUBLIC "
343 " \"-//W3C//DTD HTML 4.01//EN\""
344 " \"http://www.w3.org/TR/html4/strict.dtd\">\n"
347 "<META HTTP-EQUIV=\"Content-Type\""
348 " CONTENT=\"text/html; charset=utf-8\">\n"
349 "<LINK REL=\"stylesheet\" HREF=\"%s/man-cgi.css\""
350 " TYPE=\"text/css\" media=\"all\">\n"
351 "<LINK REL=\"stylesheet\" HREF=\"%s/man.css\""
352 " TYPE=\"text/css\" media=\"all\">\n"
353 "<TITLE>System Manpage Reference</TITLE>\n"
356 "<!-- Begin page content. //-->\n", css
, css
);
368 resp_searchform(const struct req
*req
)
372 puts("<!-- Begin search form. //-->");
373 printf("<DIV ID=\"mancgi\">\n"
374 "<FORM ACTION=\"%s/search.html\" METHOD=\"get\">\n"
376 "<LEGEND>Search Parameters</LEGEND>\n"
377 "<INPUT TYPE=\"submit\" NAME=\"op\""
378 " VALUE=\"Whatis\"> or \n"
379 "<INPUT TYPE=\"submit\" NAME=\"op\""
380 " VALUE=\"apropos\"> for manuals satisfying \n"
381 "<INPUT TYPE=\"text\" NAME=\"expr\" VALUE=\"",
383 html_print(req
->q
.expr
? req
->q
.expr
: "");
384 printf("\">, section "
385 "<INPUT TYPE=\"text\""
386 " SIZE=\"4\" NAME=\"sec\" VALUE=\"");
387 html_print(req
->q
.sec
? req
->q
.sec
: "");
389 "<INPUT TYPE=\"text\""
390 " SIZE=\"8\" NAME=\"arch\" VALUE=\"");
391 html_print(req
->q
.arch
? req
->q
.arch
: "");
394 puts(", <SELECT NAME=\"manpath\">");
395 for (i
= 0; i
< (int)req
->psz
; i
++) {
396 printf("<OPTION %s VALUE=\"",
397 (i
== req
->q
.manroot
) ||
398 (0 == i
&& -1 == req
->q
.manroot
) ?
399 "SELECTED=\"selected\"" : "");
400 html_print(req
->p
[i
].name
);
402 html_print(req
->p
[i
].name
);
408 "<INPUT TYPE=\"reset\" VALUE=\"Reset\">\n"
412 puts("<!-- End search form. //-->");
416 resp_index(const struct req
*req
)
419 resp_begin_html(200, NULL
);
420 resp_searchform(req
);
428 resp_begin_html(400, "Query Malformed");
429 printf("<H1>Malformed Query</H1>\n"
431 "The query your entered was malformed.\n"
432 "Try again from the\n"
433 "<A HREF=\"%s/index.html\">main page</A>.\n"
439 resp_error404(const char *page
)
442 resp_begin_html(404, "Not Found");
443 puts("<H1>Page Not Found</H1>\n"
445 "The page you're looking for, ");
449 "could not be found.\n"
450 "Try searching from the\n"
451 "<A HREF=\"%s/index.html\">main page</A>.\n"
459 resp_begin_html(500, "Internal Server Error");
460 puts("<P>Generic badness happened.</P>");
468 resp_begin_html(500, "Internal Server Error");
469 puts("<P>Your database is broken.</P>");
474 resp_search(struct res
*r
, size_t sz
, void *arg
)
477 const struct req
*req
;
479 req
= (const struct req
*)arg
;
480 assert(req
->q
.manroot
>= 0);
484 * If we have just one result, then jump there now
487 puts("Status: 303 See Other");
488 printf("Location: http://%s%s/show/%d/%u/%u.html\n",
489 host
, progname
, req
->q
.manroot
,
490 r
[0].volume
, r
[0].rec
);
491 puts("Content-Type: text/html; charset=utf-8\n");
495 qsort(r
, sz
, sizeof(struct res
), cmp
);
497 resp_begin_html(200, NULL
);
498 resp_searchform(req
);
500 puts("<DIV CLASS=\"results\">");
504 "No %s results found.\n",
505 req
->q
.whatis
? "whatis" : "apropos");
507 printf("(Try <A HREF=\"%s/search.html?"
508 "op=apropos&expr=", progname
);
509 html_print(req
->q
.expr
? req
->q
.expr
: "");
511 html_print(req
->q
.sec
? req
->q
.sec
: "");
512 printf("&arch=");
513 html_print(req
->q
.arch
? req
->q
.arch
: "");
514 puts("\">apropos</A>?)");
524 for (i
= 0; i
< (int)sz
; i
++) {
526 "<TD CLASS=\"title\">\n"
527 "<A HREF=\"%s/show/%d/%u/%u.html\">",
528 progname
, req
->q
.manroot
,
529 r
[i
].volume
, r
[i
].rec
);
530 html_print(r
[i
].title
);
532 html_print(r
[i
].cat
);
533 if (r
[i
].arch
&& '\0' != *r
[i
].arch
) {
535 html_print(r
[i
].arch
);
539 "<TD CLASS=\"desc\">");
540 html_print(r
[i
].desc
);
552 pg_index(const struct req
*req
, char *path
)
559 catman(const struct req
*req
, const char *file
)
567 if (NULL
== (f
= fopen(file
, "r"))) {
572 resp_begin_html(200, NULL
);
573 resp_searchform(req
);
574 puts("<DIV CLASS=\"catman\">\n"
577 while (NULL
!= (p
= fgetln(f
, &len
))) {
579 for (i
= 0; i
< (int)len
- 1; i
++) {
581 * This means that the catpage is out of state.
582 * Ignore it and keep going (although the
586 if ('\b' == p
[i
] || '\n' == p
[i
])
590 * Print a regular character.
591 * Close out any bold/italic scopes.
592 * If we're in back-space mode, make sure we'll
593 * have something to enter when we backspace.
596 if ('\b' != p
[i
+ 1]) {
604 } else if (i
+ 2 >= (int)len
)
622 * Handle funny behaviour troff-isms.
623 * These grok'd from the original man2html.c.
626 if (('+' == p
[i
] && 'o' == p
[i
+ 2]) ||
627 ('o' == p
[i
] && '+' == p
[i
+ 2]) ||
628 ('|' == p
[i
] && '=' == p
[i
+ 2]) ||
629 ('=' == p
[i
] && '|' == p
[i
+ 2]) ||
630 ('*' == p
[i
] && '=' == p
[i
+ 2]) ||
631 ('=' == p
[i
] && '*' == p
[i
+ 2]) ||
632 ('*' == p
[i
] && '|' == p
[i
+ 2]) ||
633 ('|' == p
[i
] && '*' == p
[i
+ 2])) {
642 } else if (('|' == p
[i
] && '-' == p
[i
+ 2]) ||
643 ('-' == p
[i
] && '|' == p
[i
+ 1]) ||
644 ('+' == p
[i
] && '-' == p
[i
+ 1]) ||
645 ('-' == p
[i
] && '+' == p
[i
+ 1]) ||
646 ('+' == p
[i
] && '|' == p
[i
+ 1]) ||
647 ('|' == p
[i
] && '+' == p
[i
+ 1])) {
671 * Clean up the last character.
672 * We can get to a newline; don't print that.
680 if (i
== (int)len
- 1 && '\n' != p
[i
])
695 format(const struct req
*req
, const char *file
)
703 char opts
[MAXPATHLEN
+ 128];
705 if (-1 == (fd
= open(file
, O_RDONLY
, 0))) {
710 mp
= mparse_alloc(MPARSE_AUTO
, MANDOCLEVEL_FATAL
, NULL
, NULL
);
711 rc
= mparse_readfd(mp
, fd
, file
);
714 if (rc
>= MANDOCLEVEL_FATAL
) {
719 snprintf(opts
, sizeof(opts
), "fragment,"
720 "man=%s/search.html?sec=%%S&expr=%%N,"
721 /*"includes=/cgi-bin/man.cgi/usr/include/%%I"*/,
724 mparse_result(mp
, &mdoc
, &man
);
725 if (NULL
== man
&& NULL
== mdoc
) {
731 resp_begin_html(200, NULL
);
732 resp_searchform(req
);
734 vp
= html_alloc(opts
);
749 pg_show(const struct req
*req
, char *path
)
754 char file
[MAXPATHLEN
];
757 unsigned int vol
, rec
, mr
;
763 /* Parse out mroot, volume, and record from the path. */
765 if (NULL
== path
|| NULL
== (sub
= strchr(path
, '/'))) {
770 if ( ! atou(path
, &mr
)) {
775 if (NULL
== (sub
= strchr(path
, '/'))) {
780 if ( ! atou(path
, &vol
) || ! atou(sub
, &rec
)) {
783 } else if (mr
>= (unsigned int)req
->psz
) {
789 * Begin by chdir()ing into the manroot.
790 * This way we can pick up the database files, which are
791 * relative to the manpath root.
794 if (-1 == chdir(req
->p
[(int)mr
].path
)) {
795 perror(req
->p
[(int)mr
].path
);
800 memset(&ps
, 0, sizeof(struct manpaths
));
801 manpath_manconf(&ps
, "etc/catman.conf");
803 if (vol
>= (unsigned int)ps
.sz
) {
808 sz
= strlcpy(file
, ps
.paths
[vol
], MAXPATHLEN
);
809 assert(sz
< MAXPATHLEN
);
810 strlcat(file
, "/mandoc.index", MAXPATHLEN
);
812 /* Open the index recno(3) database. */
814 idx
= dbopen(file
, O_RDONLY
, 0, DB_RECNO
, NULL
);
824 if (0 != (rc
= (*idx
->get
)(idx
, &key
, &val
, 0))) {
825 rc
< 0 ? resp_baddb() : resp_error400();
827 } else if (0 == val
.size
) {
832 cp
= (char *)val
.data
;
835 if (NULL
== memchr(cp
, '\0', val
.size
- 1))
838 file
[(int)sz
] = '\0';
839 strlcat(file
, "/", MAXPATHLEN
);
840 strlcat(file
, cp
, MAXPATHLEN
);
853 pg_search(const struct req
*req
, char *path
)
858 const char *ep
, *start
;
863 if (req
->q
.manroot
< 0 || 0 == req
->psz
) {
864 resp_search(NULL
, 0, (void *)req
);
868 memset(&opt
, 0, sizeof(struct opts
));
871 opt
.arch
= req
->q
.arch
;
872 opt
.cat
= req
->q
.sec
;
878 * Begin by chdir()ing into the root of the manpath.
879 * This way we can pick up the database files, which are
880 * relative to the manpath root.
883 assert(req
->q
.manroot
< (int)req
->psz
);
884 if (-1 == (chdir(req
->p
[req
->q
.manroot
].path
))) {
885 perror(req
->p
[req
->q
.manroot
].path
);
886 resp_search(NULL
, 0, (void *)req
);
890 memset(&ps
, 0, sizeof(struct manpaths
));
891 manpath_manconf(&ps
, "etc/catman.conf");
894 * Poor man's tokenisation: just break apart by spaces.
895 * Yes, this is half-ass. But it works for now.
898 while (ep
&& isspace((unsigned char)*ep
))
901 while (ep
&& '\0' != *ep
) {
902 cp
= mandoc_realloc(cp
, (sz
+ 1) * sizeof(char *));
904 while ('\0' != *ep
&& ! isspace((unsigned char)*ep
))
906 cp
[sz
] = mandoc_malloc((ep
- start
) + 1);
907 memcpy(cp
[sz
], start
, ep
- start
);
908 cp
[sz
++][ep
- start
] = '\0';
909 while (isspace((unsigned char)*ep
))
914 * Pump down into apropos backend.
915 * The resp_search() function is called with the results.
918 expr
= req
->q
.whatis
?
919 termcomp(sz
, cp
, &tt
) : exprcomp(sz
, cp
, &tt
);
923 (ps
.sz
, ps
.paths
, &opt
,
924 expr
, tt
, (void *)req
, resp_search
);
926 /* ...unless errors occured. */
931 resp_search(NULL
, 0, (void *)req
);
933 for (i
= 0; i
< sz
; i
++)
945 char buf
[MAXPATHLEN
];
948 char *p
, *path
, *subpath
;
950 /* Scan our run-time environment. */
952 if (NULL
== (cache
= getenv("CACHE_DIR")))
953 cache
= "/cache/man.cgi";
955 if (NULL
== (progname
= getenv("SCRIPT_NAME")))
958 if (NULL
== (css
= getenv("CSS_DIR")))
961 if (NULL
== (host
= getenv("HTTP_HOST")))
965 * First we change directory into the cache directory so that
966 * subsequent scanning for manpath directories is rooted
967 * relative to the same position.
970 if (-1 == chdir(cache
)) {
973 return(EXIT_FAILURE
);
974 } else if (NULL
== (cwd
= opendir(cache
))) {
977 return(EXIT_FAILURE
);
980 memset(&req
, 0, sizeof(struct req
));
982 strlcpy(buf
, ".", MAXPATHLEN
);
983 pathgen(cwd
, buf
, &req
);
986 /* Next parse out the query string. */
988 if (NULL
!= (p
= getenv("QUERY_STRING")))
992 * Now juggle paths to extract information.
993 * We want to extract our filetype (the file suffix), the
994 * initial path component, then the trailing component(s).
995 * Start with leading subpath component.
998 subpath
= path
= NULL
;
999 req
.page
= PAGE__MAX
;
1001 if (NULL
== (path
= getenv("PATH_INFO")) || '\0' == *path
)
1002 req
.page
= PAGE_INDEX
;
1004 if (NULL
!= path
&& '/' == *path
&& '\0' == *++path
)
1005 req
.page
= PAGE_INDEX
;
1007 /* Strip file suffix. */
1009 if (NULL
!= path
&& NULL
!= (p
= strrchr(path
, '.')))
1010 if (NULL
!= p
&& NULL
== strchr(p
, '/'))
1013 /* Resolve subpath component. */
1015 if (NULL
!= path
&& NULL
!= (subpath
= strchr(path
, '/')))
1018 /* Map path into one we recognise. */
1020 if (NULL
!= path
&& '\0' != *path
)
1021 for (i
= 0; i
< (int)PAGE__MAX
; i
++)
1022 if (0 == strcmp(pages
[i
], path
)) {
1023 req
.page
= (enum page
)i
;
1031 pg_index(&req
, subpath
);
1034 pg_search(&req
, subpath
);
1037 pg_show(&req
, subpath
);
1040 resp_error404(path
);
1044 for (i
= 0; i
< (int)req
.psz
; i
++) {
1045 free(req
.p
[i
].path
);
1046 free(req
.p
[i
].name
);
1050 return(EXIT_SUCCESS
);
1054 cmp(const void *p1
, const void *p2
)
1057 return(strcasecmp(((const struct res
*)p1
)->title
,
1058 ((const struct res
*)p2
)->title
));
1062 * Check to see if an "etc" path consists of a catman.conf file. If it
1063 * does, that means that the path contains a tree created by catman(8)
1064 * and should be used for indexing.
1071 while (NULL
!= (d
= readdir(dir
)))
1072 if (DT_REG
== d
->d_type
)
1073 if (0 == strcmp(d
->d_name
, "catman.conf"))
1080 * Scan for indexable paths.
1081 * This adds all paths with "etc/catman.conf" to the buffer.
1084 pathgen(DIR *dir
, char *path
, struct req
*req
)
1092 sz
= strlcat(path
, "/", MAXPATHLEN
);
1093 if (sz
>= MAXPATHLEN
) {
1094 fprintf(stderr
, "%s: Path too long", path
);
1099 * First, scan for the "etc" directory.
1100 * If it's found, then see if it should cause us to stop. This
1101 * happens when a catman.conf is found in the directory.
1105 while (0 == rc
&& NULL
!= (d
= readdir(dir
))) {
1106 if (DT_DIR
!= d
->d_type
|| strcmp(d
->d_name
, "etc"))
1109 path
[(int)sz
] = '\0';
1110 ssz
= strlcat(path
, d
->d_name
, MAXPATHLEN
);
1112 if (ssz
>= MAXPATHLEN
) {
1113 fprintf(stderr
, "%s: Path too long", path
);
1115 } else if (NULL
== (cd
= opendir(path
))) {
1125 /* This also strips the trailing slash. */
1126 path
[(int)--sz
] = '\0';
1127 req
->p
= mandoc_realloc
1129 (req
->psz
+ 1) * sizeof(struct paths
));
1131 * Strip out the leading "./" unless we're just a ".",
1132 * in which case use an empty string as our name.
1134 req
->p
[(int)req
->psz
].path
= mandoc_strdup(path
);
1135 req
->p
[(int)req
->psz
].name
=
1136 cp
= mandoc_strdup(path
+ (1 == sz
? 1 : 2));
1139 * The name is just the path with all the slashes taken
1140 * out of it. Simple but effective.
1142 for ( ; '\0' != *cp
; cp
++)
1149 * If no etc/catman.conf was found, recursively enter child
1150 * directory and continue scanning.
1154 while (NULL
!= (d
= readdir(dir
))) {
1155 if (DT_DIR
!= d
->d_type
|| '.' == d
->d_name
[0])
1158 path
[(int)sz
] = '\0';
1159 ssz
= strlcat(path
, d
->d_name
, MAXPATHLEN
);
1161 if (ssz
>= MAXPATHLEN
) {
1162 fprintf(stderr
, "%s: Path too long", path
);
1164 } else if (NULL
== (cd
= opendir(path
))) {
1169 pathgen(cd
, path
, req
);