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);
111 static void cgi_parse_get(void) {
114 if(!(q = getenv("QUERY_STRING"))) fatal(0, "QUERY_STRING not set");
115 cgi_args = kvp_urldecode(q, strlen(q));
118 static void cgi_input(char **ptrp, size_t *np) {
124 if(!(cl = getenv("CONTENT_LENGTH"))) fatal(0, "CONTENT_LENGTH not set");
126 q = xmalloc_noptr(n + 1);
128 r = read(0, q + m, n - m);
132 fatal(0, "unexpected end of file reading request body");
135 default: fatal(errno, "error reading request body");
138 if(memchr(q, 0, n)) fatal(0, "null character in request body");
144 static int cgi_field_callback(const char *name, const char *value,
146 char *disposition, *pname, *pvalue;
149 if(!strcmp(name, "content-disposition")) {
150 if(mime_rfc2388_content_disposition(value,
154 fatal(0, "error parsing Content-Disposition field");
155 if(!strcmp(disposition, "form-data")
157 && !strcmp(pname, "name")) {
159 fatal(0, "duplicate Content-Disposition field");
166 static int cgi_part_callback(const char *s,
167 void attribute((unused)) *u) {
171 if(!(s = mime_parse(s, cgi_field_callback, &name)))
172 fatal(0, "error parsing part header");
173 if(!name) fatal(0, "no name found");
174 k = xmalloc(sizeof *k);
182 static void cgi_parse_multipart(const char *boundary) {
186 if(mime_multipart(q, cgi_part_callback, boundary, 0))
187 fatal(0, "invalid multipart object");
190 static void cgi_parse_post(void) {
191 const char *ct, *boundary;
196 if(!(ct = getenv("CONTENT_TYPE")))
197 ct = "application/x-www-form-urlencoded";
198 if(mime_content_type(ct, &type, &k))
199 fatal(0, "invalid content type '%s'", ct);
200 if(!strcmp(type, "application/x-www-form-urlencoded")) {
202 cgi_args = kvp_urldecode(q, n);
205 if(!strcmp(type, "multipart/form-data")) {
206 if(!(boundary = kvp_get(k, "boundary")))
207 fatal(0, "no boundary parameter found");
208 cgi_parse_multipart(boundary);
211 fatal(0, "unrecognized content type '%s'", type);
214 void cgi_parse(void) {
218 if(!(p = getenv("REQUEST_METHOD"))) fatal(0, "REQUEST_METHOD not set");
219 if(!strcmp(p, "GET"))
221 else if(!strcmp(p, "POST"))
224 fatal(0, "unknown request method %s", p);
225 for(k = cgi_args; k; k = k->next)
226 if(!utf8_valid(k->name, strlen(k->name))
227 || !utf8_valid(k->value, strlen(k->value)))
228 fatal(0, "invalid UTF-8 sequence in cgi argument");
231 const char *cgi_get(const char *name) {
232 return kvp_get(cgi_args, name);
235 void cgi_output(cgi_sink *output, const char *fmt, ...) {
241 n = byte_vasprintf(&r, fmt, ap);
243 fatal(errno, "error calling byte_vasprintf");
245 r = cgi_sgmlquote(r, 0);
246 output->sink->write(output->sink, r, strlen(r));
250 void cgi_header(struct sink *output, const char *name, const char *value) {
251 sink_printf(output, "%s: %s\r\n", name, value);
254 void cgi_body(struct sink *output) {
255 sink_printf(output, "\r\n");
258 char *cgi_sgmlquote(const char *s, int raw) {
259 uint32_t *ucs, *p, c;
264 if(!(ucs = utf8_to_utf32(s, strlen(s), 0))) exit(EXIT_FAILURE);
266 ucs = xmalloc_noptr((strlen(s) + 1) * sizeof(uint32_t));
267 for(n = 0; s[n]; ++n)
268 ucs[n] = (unsigned char)s[n];
273 /* estimate the length we'll need */
274 for(p = ucs; (c = *p); ++p) {
277 if(c > 127 || c < 32) {
288 /* format the string */
289 b = bp = xmalloc_noptr(n);
290 for(p = ucs; (c = *p); ++p) {
293 if(*p > 127 || *p < 32) {
298 bp += sprintf(bp, "&#%lu;", (unsigned long)c);
308 void cgi_attr(struct sink *output, const char *name, const char *value) {
309 if(!value[strspn(value, "abcdefghijklmnopqrstuvwxyz"
310 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
312 sink_printf(output, "%s=%s", name, value);
314 sink_printf(output, "%s=\"%s\"", name, cgi_sgmlquote(value, 0));
317 void cgi_opentag(struct sink *output, const char *name, ...) {
321 sink_printf(output, "<%s", name);
323 while((n = va_arg(ap, const char *))) {
324 sink_printf(output, " ");
325 v = va_arg(ap, const char *);
327 cgi_attr(output, n, v);
329 sink_printf(output, n);
331 sink_printf(output, ">");
334 void cgi_closetag(struct sink *output, const char *name) {
335 sink_printf(output, "</%s>", name);
338 static int template_open(const char *name,
340 const char **filenamep) {
345 dirs[0] = pkgconfdir;
346 dirs[1] = pkgdatadir;
348 if((fd = open(name, O_RDONLY)) < 0) fatal(0, "cannot open %s", name);
351 for(n = 0; n < config->templates.n + (int)(sizeof dirs / sizeof *dirs); ++n) {
352 byte_xasprintf(&fullpath, "%s/%s%s",
353 n < config->templates.n ? config->templates.s[n]
354 : dirs[n - config->templates.n],
356 if((fd = open(fullpath, O_RDONLY)) >= 0) break;
358 if(fd < 0) error(0, "cannot find %s%s in template path", name, ext);
359 *filenamep = fullpath;
364 static int valid_template_name(const char *name) {
365 if(strchr(name, '/') || name[0] == '.')
370 void cgi_expand(const char *template,
371 const struct cgi_expansion *expansions,
381 if(!valid_template_name(template))
382 fatal(0, "invalid template name '%s'", template);
383 if((fd = template_open(template, ".html", &template)) < 0)
384 exitfn(EXIT_FAILURE);
385 if(fstat(fd, &sb) < 0) fatal(errno, "cannot stat %s", template);
387 b = xmalloc_noptr(sb.st_size + 1);
388 while(m < sb.st_size) {
389 n = read(fd, b + m, sb.st_size - m);
391 else if(n == 0) fatal(0, "unexpected EOF reading %s", template);
392 else if(errno != EINTR) fatal(errno, "error reading %s", template);
396 cgi_expand_string(template, b, expansions, nexpansions, output, u);
399 /** @brief Return a linked list of the parse of @p template */
400 static struct cgi_element *cgi_parse_string(const char *name,
401 const char *template) {
402 int braces, line = 1, sline;
406 struct cgi_element *head = 0, **tailp = &head, *e;
409 if(*template != '@') {
412 /* Gather up text without any expansions in. */
413 while(*template && *template != '@') {
414 if(*template == '\n')
416 dynstr_append(&d, *template++);
418 dynstr_terminate(&d);
419 e = xmalloc(sizeof *e);
422 e->type = ELEMENT_TEXT;
433 while(*template != '@') {
434 /* Skip whitespace */
435 while(isspace((unsigned char)*template))
438 if(*template == '{') {
441 while(*template && (*template != '}' || braces > 0)) {
443 case '{': ++braces; break;
444 case '}': --braces; break;
445 case '\n': ++line; break;
447 dynstr_append(&d, *template++);
449 if(!*template) fatal(0, "%s:%d: unterminated expansion '%.*s'",
450 name, sline, (int)(template - p), p);
452 if(isspace((unsigned char)*template)) {
453 /* We have @{...}<WHITESPACE><SOMETHING> */
454 for(p = template; isspace((unsigned char)*p); ++p)
456 /* Now we are looking at <SOMETHING>. If it's "{" then that
457 * must be the next argument. Otherwise we infer that this
458 * is really the end of the expansion. */
460 goto finished_expansion;
463 /* unbracketed arg */
465 && *template != '@' && *template != '{' && *template != ':') {
466 if(*template == '\n') ++line;
467 dynstr_append(&d, *template++);
471 if(!*template) fatal(0, "%s:%d: unterminated expansion '%.*s'",
472 name, sline, (int)(template - p), p);
473 /* trailing whitespace is not significant in unquoted args */
474 while(d.nvec && (isspace((unsigned char)d.vec[d.nvec - 1])))
477 dynstr_terminate(&d);
478 vector_append(&v, d.vec);
482 vector_terminate(&v);
483 /* @@ terminates this file */
486 e = xmalloc(sizeof *e);
489 e->type = ELEMENT_EXPANSION;
491 e->nargs = v.nvec - 1;
499 void cgi_expand_string(const char *name,
500 const char *template,
501 const struct cgi_expansion *expansions,
508 cgi_sink parameter_output;
509 const struct cgi_macro *macro;
511 struct cgi_element *e;
513 for(e = cgi_parse_string(name, template); e; e = e->next) {
516 output->sink->write(output->sink, e->text, strlen(e->text));
518 case ELEMENT_EXPANSION:
519 if((n = table_find(expansions,
520 offsetof(struct cgi_expansion, name),
521 sizeof (struct cgi_expansion),
524 /* We found a built-in */
525 if(e->nargs < expansions[n].minargs)
526 fatal(0, "%s:%d: insufficient arguments to @%s@ (min %d, got %d)",
527 name, e->line, e->name, expansions[n].minargs, e->nargs);
528 if(e->nargs > expansions[n].maxargs)
529 fatal(0, "%s:%d: too many arguments to @%s@ (max %d, got %d)",
530 name, e->line, e->name, expansions[n].maxargs, e->nargs);
531 /* for ordinary expansions, recursively expand the arguments */
532 if(!(expansions[n].flags & EXP_MAGIC)) {
533 for(m = 0; m < e->nargs; ++m) {
535 byte_xasprintf(&argname, "<%s:%d arg #%d>", name, e->line, m);
536 parameter_output.quote = 0;
537 parameter_output.sink = sink_dynstr(&d);
538 cgi_expand_string(argname, e->args[m],
539 expansions, nexpansions,
540 ¶meter_output, u);
541 dynstr_terminate(&d);
545 expansions[n].handler(e->nargs, e->args, output, u);
546 } else if(cgi_macros && (macro = hash_find(cgi_macros, e->name))) {
547 /* We found a macro */
548 if(e->nargs != macro->nargs)
549 fatal(0, "%s:%d: wrong number of arguments to @%s@ (need %d, got %d)",
550 name, e->line, e->name, macro->nargs, e->nargs);
551 /* We must substitute in argument values */
553 cgi_expand_string(e->name,
560 /* Totally undefined */
561 fatal(0, "%s:%d: unknown expansion '%s'", name, e->line, e->name);
568 char *cgi_makeurl(const char *url, ...) {
570 struct kvp *kvp, *k, **kk = &kvp;
575 dynstr_append_string(&d, url);
577 while((n = va_arg(ap, const char *))) {
578 v = va_arg(ap, const char *);
579 *kk = k = xmalloc(sizeof *k);
586 dynstr_append(&d, '?');
587 dynstr_append_string(&d, kvp_urlencode(kvp, 0));
589 dynstr_terminate(&d);
593 void cgi_set_option(const char *name, const char *value) {
594 struct kvp *k = xmalloc(sizeof *k);
602 static void option_label(int attribute((unused)) nvec,
604 cgi_set_option(vec[0], vec[1]);
607 static void option_include(int attribute((unused)) nvec,
609 include_options(vec[0]);
612 static void option_columns(int nvec,
614 struct column *c = xmalloc(sizeof *c);
618 c->ncolumns = nvec - 1;
619 c->columns = &vec[1];
623 static struct option {
625 int minargs, maxargs;
626 void (*handler)(int nvec, char **vec);
628 { "columns", 1, INT_MAX, option_columns },
629 { "include", 1, 1, option_include },
630 { "label", 2, 2, option_label },
633 struct read_options_state {
638 static void read_options_error(const char *msg,
640 struct read_options_state *cs = u;
642 error(0, "%s:%d: %s", cs->name, cs->line, msg);
645 static void include_options(const char *name) {
650 struct read_options_state cs;
652 if((fd = template_open(name, "", &cs.name)) < 0) return;
653 if(!(fp = fdopen(fd, "r"))) fatal(errno, "error calling fdopen");
655 while(!inputline(cs.name, fp, &buffer, '\n')) {
657 if(!(vec = split(buffer, &n, SPLIT_COMMENTS|SPLIT_QUOTES,
658 read_options_error, &cs)))
661 if((i = TABLE_FIND(options, struct option, name, vec[0])) == -1) {
662 error(0, "%s:%d: unknown option '%s'", cs.name, cs.line, vec[0]);
667 if(n < options[i].minargs) {
668 error(0, "%s:%d: too few arguments to '%s'", cs.name, cs.line, vec[-1]);
671 if(n > options[i].maxargs) {
672 error(0, "%s:%d: too many arguments to '%s'", cs.name, cs.line, vec[-1]);
675 options[i].handler(n, vec);
680 static void read_options(void) {
681 if(!have_read_options) {
682 have_read_options = 1;
683 include_options("options");
687 const char *cgi_label(const char *key) {
691 if(!(label = kvp_get(labels, key))) {
693 if(!strncmp(key, "images.", 7)) {
694 static const char *url_static;
695 /* images.X defaults to <url.static>X.png */
698 url_static = cgi_label("url.static");
699 byte_xasprintf((char **)&label, "%s%s.png", url_static, key + 7);
700 } else if((label = strchr(key, '.')))
701 /* X.Y defaults to Y */
704 /* otherwise default to label name */
710 int cgi_label_exists(const char *key) {
712 return kvp_get(labels, key) ? 1 : 0;
715 char **cgi_columns(const char *name, int *ncolumns) {
719 for(c = columns; c && strcmp(name, c->name); c = c->next)
723 *ncolumns = c->ncolumns;
732 void cgi_define(const char *name,
739 cgi_macros = hash_new(sizeof(struct cgi_macro));
743 hash_add(cgi_macros, name, &m, HASH_INSERT_OR_REPLACE);