2 * This file is part of DisOrder.
3 * Copyright (C) 2004-2008 Richard Kettlewell
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
42 #include "configuration.h"
48 #include "inputline.h"
75 static hash *cgi_macros;
77 /** @brief Parse of a template */
79 /** @brief Next element */
80 struct cgi_element *next;
82 /** @brief Element type */
84 #define ELEMENT_TEXT 0
85 #define ELEMENT_EXPANSION 1
87 /** @brief Line number at start of element */
90 /** @brief Plain text */
93 /** @brief Expansion name */
96 /** @brief Argument count */
99 /** @brief Argument values (NOT recursively expanded) */
103 #define RELIST(x) struct re *x, **x##_tail = &x
105 static int have_read_options;
106 static struct kvp *labels;
107 static struct column *columns;
109 static void include_options(const char *name);
110 static void cgi_expand_parsed(const char *name,
111 struct cgi_element *head,
112 const struct cgi_expansion *expansions,
117 static void cgi_parse_get(void) {
120 if(!(q = getenv("QUERY_STRING"))) fatal(0, "QUERY_STRING not set");
121 cgi_args = kvp_urldecode(q, strlen(q));
124 static void cgi_input(char **ptrp, size_t *np) {
130 if(!(cl = getenv("CONTENT_LENGTH"))) fatal(0, "CONTENT_LENGTH not set");
132 q = xmalloc_noptr(n + 1);
134 r = read(0, q + m, n - m);
138 fatal(0, "unexpected end of file reading request body");
141 default: fatal(errno, "error reading request body");
144 if(memchr(q, 0, n)) fatal(0, "null character in request body");
150 static int cgi_field_callback(const char *name, const char *value,
152 char *disposition, *pname, *pvalue;
155 if(!strcmp(name, "content-disposition")) {
156 if(mime_rfc2388_content_disposition(value,
160 fatal(0, "error parsing Content-Disposition field");
161 if(!strcmp(disposition, "form-data")
163 && !strcmp(pname, "name")) {
165 fatal(0, "duplicate Content-Disposition field");
172 static int cgi_part_callback(const char *s,
173 void attribute((unused)) *u) {
177 if(!(s = mime_parse(s, cgi_field_callback, &name)))
178 fatal(0, "error parsing part header");
179 if(!name) fatal(0, "no name found");
180 k = xmalloc(sizeof *k);
188 static void cgi_parse_multipart(const char *boundary) {
192 if(mime_multipart(q, cgi_part_callback, boundary, 0))
193 fatal(0, "invalid multipart object");
196 static void cgi_parse_post(void) {
197 const char *ct, *boundary;
202 if(!(ct = getenv("CONTENT_TYPE")))
203 ct = "application/x-www-form-urlencoded";
204 if(mime_content_type(ct, &type, &k))
205 fatal(0, "invalid content type '%s'", ct);
206 if(!strcmp(type, "application/x-www-form-urlencoded")) {
208 cgi_args = kvp_urldecode(q, n);
211 if(!strcmp(type, "multipart/form-data")) {
212 if(!(boundary = kvp_get(k, "boundary")))
213 fatal(0, "no boundary parameter found");
214 cgi_parse_multipart(boundary);
217 fatal(0, "unrecognized content type '%s'", type);
220 void cgi_parse(void) {
224 if(!(p = getenv("REQUEST_METHOD"))) fatal(0, "REQUEST_METHOD not set");
225 if(!strcmp(p, "GET"))
227 else if(!strcmp(p, "POST"))
230 fatal(0, "unknown request method %s", p);
231 for(k = cgi_args; k; k = k->next)
232 if(!utf8_valid(k->name, strlen(k->name))
233 || !utf8_valid(k->value, strlen(k->value)))
234 fatal(0, "invalid UTF-8 sequence in cgi argument");
237 const char *cgi_get(const char *name) {
238 return kvp_get(cgi_args, name);
241 void cgi_output(cgi_sink *output, const char *fmt, ...) {
247 n = byte_vasprintf(&r, fmt, ap);
249 fatal(errno, "error calling byte_vasprintf");
251 r = cgi_sgmlquote(r, 0);
252 output->sink->write(output->sink, r, strlen(r));
256 void cgi_header(struct sink *output, const char *name, const char *value) {
257 sink_printf(output, "%s: %s\r\n", name, value);
260 void cgi_body(struct sink *output) {
261 sink_printf(output, "\r\n");
264 char *cgi_sgmlquote(const char *s, int raw) {
265 uint32_t *ucs, *p, c;
270 if(!(ucs = utf8_to_utf32(s, strlen(s), 0))) exit(EXIT_FAILURE);
272 ucs = xmalloc_noptr((strlen(s) + 1) * sizeof(uint32_t));
273 for(n = 0; s[n]; ++n)
274 ucs[n] = (unsigned char)s[n];
279 /* estimate the length we'll need */
280 for(p = ucs; (c = *p); ++p) {
283 if(c > 127 || c < 32) {
294 /* format the string */
295 b = bp = xmalloc_noptr(n);
296 for(p = ucs; (c = *p); ++p) {
299 if(*p > 127 || *p < 32) {
304 bp += sprintf(bp, "&#%lu;", (unsigned long)c);
314 void cgi_attr(struct sink *output, const char *name, const char *value) {
315 if(!value[strspn(value, "abcdefghijklmnopqrstuvwxyz"
316 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
318 sink_printf(output, "%s=%s", name, value);
320 sink_printf(output, "%s=\"%s\"", name, cgi_sgmlquote(value, 0));
323 void cgi_opentag(struct sink *output, const char *name, ...) {
327 sink_printf(output, "<%s", name);
329 while((n = va_arg(ap, const char *))) {
330 sink_printf(output, " ");
331 v = va_arg(ap, const char *);
333 cgi_attr(output, n, v);
335 sink_printf(output, n);
337 sink_printf(output, ">");
340 void cgi_closetag(struct sink *output, const char *name) {
341 sink_printf(output, "</%s>", name);
344 static int template_open(const char *name,
346 const char **filenamep) {
351 dirs[0] = pkgconfdir;
352 dirs[1] = pkgdatadir;
354 if((fd = open(name, O_RDONLY)) < 0) fatal(0, "cannot open %s", name);
357 for(n = 0; n < config->templates.n + (int)(sizeof dirs / sizeof *dirs); ++n) {
358 byte_xasprintf(&fullpath, "%s/%s%s",
359 n < config->templates.n ? config->templates.s[n]
360 : dirs[n - config->templates.n],
362 if((fd = open(fullpath, O_RDONLY)) >= 0) break;
364 if(fd < 0) error(0, "cannot find %s%s in template path", name, ext);
365 *filenamep = fullpath;
370 static int valid_template_name(const char *name) {
371 if(strchr(name, '/') || name[0] == '.')
376 void cgi_expand(const char *template,
377 const struct cgi_expansion *expansions,
387 if(!valid_template_name(template))
388 fatal(0, "invalid template name '%s'", template);
389 if((fd = template_open(template, ".html", &template)) < 0)
390 exitfn(EXIT_FAILURE);
391 if(fstat(fd, &sb) < 0) fatal(errno, "cannot stat %s", template);
393 b = xmalloc_noptr(sb.st_size + 1);
394 while(m < sb.st_size) {
395 n = read(fd, b + m, sb.st_size - m);
397 else if(n == 0) fatal(0, "unexpected EOF reading %s", template);
398 else if(errno != EINTR) fatal(errno, "error reading %s", template);
402 cgi_expand_string(template, b, expansions, nexpansions, output, u);
405 /** @brief Return a linked list of the parse of @p template */
406 static struct cgi_element *cgi_parse_string(const char *name,
407 const char *template) {
408 int braces, line = 1, sline;
412 struct cgi_element *head = 0, **tailp = &head, *e;
415 if(*template != '@') {
418 /* Gather up text without any expansions in. */
419 while(*template && *template != '@') {
420 if(*template == '\n')
422 dynstr_append(&d, *template++);
424 dynstr_terminate(&d);
425 e = xmalloc(sizeof *e);
428 e->type = ELEMENT_TEXT;
439 while(*template != '@') {
440 /* Skip whitespace */
441 while(isspace((unsigned char)*template))
444 if(*template == '{') {
447 while(*template && (*template != '}' || braces > 0)) {
449 case '{': ++braces; break;
450 case '}': --braces; break;
451 case '\n': ++line; break;
453 dynstr_append(&d, *template++);
455 if(!*template) fatal(0, "%s:%d: unterminated expansion '%.*s'",
456 name, sline, (int)(template - p), p);
458 if(isspace((unsigned char)*template)) {
459 /* We have @{...}<WHITESPACE><SOMETHING> */
460 for(p = template; isspace((unsigned char)*p); ++p)
462 /* Now we are looking at <SOMETHING>. If it's "{" then that
463 * must be the next argument. Otherwise we infer that this
464 * is really the end of the expansion. */
466 goto finished_expansion;
469 /* unbracketed arg */
471 && *template != '@' && *template != '{' && *template != ':') {
472 if(*template == '\n') ++line;
473 dynstr_append(&d, *template++);
477 if(!*template) fatal(0, "%s:%d: unterminated expansion '%.*s'",
478 name, sline, (int)(template - p), p);
479 /* trailing whitespace is not significant in unquoted args */
480 while(d.nvec && (isspace((unsigned char)d.vec[d.nvec - 1])))
483 dynstr_terminate(&d);
484 vector_append(&v, d.vec);
488 vector_terminate(&v);
489 /* @@ terminates this file */
492 e = xmalloc(sizeof *e);
495 e->type = ELEMENT_EXPANSION;
497 e->nargs = v.nvec - 1;
505 void cgi_expand_string(const char *name,
506 const char *template,
507 const struct cgi_expansion *expansions,
511 cgi_expand_parsed(name, cgi_parse_string(name, template),
512 expansions, nexpansions, output, u);
515 static void cgi_expand_parsed(const char *name,
516 struct cgi_element *head,
517 const struct cgi_expansion *expansions,
524 cgi_sink parameter_output;
525 const struct cgi_macro *macro;
527 struct cgi_element *e;
529 for(e = head; e; e = e->next) {
532 output->sink->write(output->sink, e->text, strlen(e->text));
534 case ELEMENT_EXPANSION:
535 if((n = table_find(expansions,
536 offsetof(struct cgi_expansion, name),
537 sizeof (struct cgi_expansion),
540 /* We found a built-in */
541 if(e->nargs < expansions[n].minargs)
542 fatal(0, "%s:%d: insufficient arguments to @%s@ (min %d, got %d)",
543 name, e->line, e->name, expansions[n].minargs, e->nargs);
544 if(e->nargs > expansions[n].maxargs)
545 fatal(0, "%s:%d: too many arguments to @%s@ (max %d, got %d)",
546 name, e->line, e->name, expansions[n].maxargs, e->nargs);
547 /* for ordinary expansions, recursively expand the arguments */
548 if(!(expansions[n].flags & EXP_MAGIC)) {
549 for(m = 0; m < e->nargs; ++m) {
551 byte_xasprintf(&argname, "<%s:%d arg #%d>", name, e->line, m);
552 parameter_output.quote = 0;
553 parameter_output.sink = sink_dynstr(&d);
554 cgi_expand_string(argname, e->args[m],
555 expansions, nexpansions,
556 ¶meter_output, u);
557 dynstr_terminate(&d);
561 expansions[n].handler(e->nargs, e->args, output, u);
562 } else if(cgi_macros && (macro = hash_find(cgi_macros, e->name))) {
563 /* We found a macro */
564 if(e->nargs != macro->nargs)
565 fatal(0, "%s:%d: wrong number of arguments to @%s@ (need %d, got %d)",
566 name, e->line, e->name, macro->nargs, e->nargs);
567 /* We must substitute in argument values */
569 cgi_expand_string(e->name,
576 /* Totally undefined */
577 fatal(0, "%s:%d: unknown expansion '%s'", name, e->line, e->name);
584 char *cgi_makeurl(const char *url, ...) {
586 struct kvp *kvp, *k, **kk = &kvp;
591 dynstr_append_string(&d, url);
593 while((n = va_arg(ap, const char *))) {
594 v = va_arg(ap, const char *);
595 *kk = k = xmalloc(sizeof *k);
602 dynstr_append(&d, '?');
603 dynstr_append_string(&d, kvp_urlencode(kvp, 0));
605 dynstr_terminate(&d);
609 void cgi_set_option(const char *name, const char *value) {
610 struct kvp *k = xmalloc(sizeof *k);
618 static void option_label(int attribute((unused)) nvec,
620 cgi_set_option(vec[0], vec[1]);
623 static void option_include(int attribute((unused)) nvec,
625 include_options(vec[0]);
628 static void option_columns(int nvec,
630 struct column *c = xmalloc(sizeof *c);
634 c->ncolumns = nvec - 1;
635 c->columns = &vec[1];
639 static struct option {
641 int minargs, maxargs;
642 void (*handler)(int nvec, char **vec);
644 { "columns", 1, INT_MAX, option_columns },
645 { "include", 1, 1, option_include },
646 { "label", 2, 2, option_label },
649 struct read_options_state {
654 static void read_options_error(const char *msg,
656 struct read_options_state *cs = u;
658 error(0, "%s:%d: %s", cs->name, cs->line, msg);
661 static void include_options(const char *name) {
666 struct read_options_state cs;
668 if((fd = template_open(name, "", &cs.name)) < 0) return;
669 if(!(fp = fdopen(fd, "r"))) fatal(errno, "error calling fdopen");
671 while(!inputline(cs.name, fp, &buffer, '\n')) {
673 if(!(vec = split(buffer, &n, SPLIT_COMMENTS|SPLIT_QUOTES,
674 read_options_error, &cs)))
677 if((i = TABLE_FIND(options, struct option, name, vec[0])) == -1) {
678 error(0, "%s:%d: unknown option '%s'", cs.name, cs.line, vec[0]);
683 if(n < options[i].minargs) {
684 error(0, "%s:%d: too few arguments to '%s'", cs.name, cs.line, vec[-1]);
687 if(n > options[i].maxargs) {
688 error(0, "%s:%d: too many arguments to '%s'", cs.name, cs.line, vec[-1]);
691 options[i].handler(n, vec);
696 static void read_options(void) {
697 if(!have_read_options) {
698 have_read_options = 1;
699 include_options("options");
703 const char *cgi_label(const char *key) {
707 if(!(label = kvp_get(labels, key))) {
709 if(!strncmp(key, "images.", 7)) {
710 static const char *url_static;
711 /* images.X defaults to <url.static>X.png */
714 url_static = cgi_label("url.static");
715 byte_xasprintf((char **)&label, "%s%s.png", url_static, key + 7);
716 } else if((label = strchr(key, '.')))
717 /* X.Y defaults to Y */
720 /* otherwise default to label name */
726 int cgi_label_exists(const char *key) {
728 return kvp_get(labels, key) ? 1 : 0;
731 char **cgi_columns(const char *name, int *ncolumns) {
735 for(c = columns; c && strcmp(name, c->name); c = c->next)
739 *ncolumns = c->ncolumns;
748 void cgi_define(const char *name,
755 cgi_macros = hash_new(sizeof(struct cgi_macro));
759 hash_add(cgi_macros, name, &m, HASH_INSERT_OR_REPLACE);