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 #define RELIST(x) struct re *x, **x##_tail = &x
79 static int have_read_options;
80 static struct kvp *labels;
81 static struct column *columns;
83 static void include_options(const char *name);
85 static void cgi_parse_get(void) {
88 if(!(q = getenv("QUERY_STRING"))) fatal(0, "QUERY_STRING not set");
89 cgi_args = kvp_urldecode(q, strlen(q));
92 static void cgi_input(char **ptrp, size_t *np) {
98 if(!(cl = getenv("CONTENT_LENGTH"))) fatal(0, "CONTENT_LENGTH not set");
100 q = xmalloc_noptr(n + 1);
102 r = read(0, q + m, n - m);
106 fatal(0, "unexpected end of file reading request body");
109 default: fatal(errno, "error reading request body");
112 if(memchr(q, 0, n)) fatal(0, "null character in request body");
118 static int cgi_field_callback(const char *name, const char *value,
120 char *disposition, *pname, *pvalue;
123 if(!strcmp(name, "content-disposition")) {
124 if(mime_rfc2388_content_disposition(value,
128 fatal(0, "error parsing Content-Disposition field");
129 if(!strcmp(disposition, "form-data")
131 && !strcmp(pname, "name")) {
133 fatal(0, "duplicate Content-Disposition field");
140 static int cgi_part_callback(const char *s,
141 void attribute((unused)) *u) {
145 if(!(s = mime_parse(s, cgi_field_callback, &name)))
146 fatal(0, "error parsing part header");
147 if(!name) fatal(0, "no name found");
148 k = xmalloc(sizeof *k);
156 static void cgi_parse_multipart(const char *boundary) {
160 if(mime_multipart(q, cgi_part_callback, boundary, 0))
161 fatal(0, "invalid multipart object");
164 static void cgi_parse_post(void) {
165 const char *ct, *boundary;
170 if(!(ct = getenv("CONTENT_TYPE")))
171 ct = "application/x-www-form-urlencoded";
172 if(mime_content_type(ct, &type, &k))
173 fatal(0, "invalid content type '%s'", ct);
174 if(!strcmp(type, "application/x-www-form-urlencoded")) {
176 cgi_args = kvp_urldecode(q, n);
179 if(!strcmp(type, "multipart/form-data")) {
180 if(!(boundary = kvp_get(k, "boundary")))
181 fatal(0, "no boundary parameter found");
182 cgi_parse_multipart(boundary);
185 fatal(0, "unrecognized content type '%s'", type);
188 void cgi_parse(void) {
192 if(!(p = getenv("REQUEST_METHOD"))) fatal(0, "REQUEST_METHOD not set");
193 if(!strcmp(p, "GET"))
195 else if(!strcmp(p, "POST"))
198 fatal(0, "unknown request method %s", p);
199 for(k = cgi_args; k; k = k->next)
200 if(!utf8_valid(k->name, strlen(k->name))
201 || !utf8_valid(k->value, strlen(k->value)))
202 fatal(0, "invalid UTF-8 sequence in cgi argument");
205 const char *cgi_get(const char *name) {
206 return kvp_get(cgi_args, name);
209 void cgi_output(cgi_sink *output, const char *fmt, ...) {
215 n = byte_vasprintf(&r, fmt, ap);
217 fatal(errno, "error calling byte_vasprintf");
219 r = cgi_sgmlquote(r, 0);
220 output->sink->write(output->sink, r, strlen(r));
224 void cgi_header(struct sink *output, const char *name, const char *value) {
225 sink_printf(output, "%s: %s\r\n", name, value);
228 void cgi_body(struct sink *output) {
229 sink_printf(output, "\r\n");
232 char *cgi_sgmlquote(const char *s, int raw) {
233 uint32_t *ucs, *p, c;
238 if(!(ucs = utf8_to_utf32(s, strlen(s), 0))) exit(EXIT_FAILURE);
240 ucs = xmalloc_noptr((strlen(s) + 1) * sizeof(uint32_t));
241 for(n = 0; s[n]; ++n)
242 ucs[n] = (unsigned char)s[n];
247 /* estimate the length we'll need */
248 for(p = ucs; (c = *p); ++p) {
251 if(c > 127 || c < 32) {
262 /* format the string */
263 b = bp = xmalloc_noptr(n);
264 for(p = ucs; (c = *p); ++p) {
267 if(*p > 127 || *p < 32) {
272 bp += sprintf(bp, "&#%lu;", (unsigned long)c);
282 void cgi_attr(struct sink *output, const char *name, const char *value) {
283 if(!value[strspn(value, "abcdefghijklmnopqrstuvwxyz"
284 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
286 sink_printf(output, "%s=%s", name, value);
288 sink_printf(output, "%s=\"%s\"", name, cgi_sgmlquote(value, 0));
291 void cgi_opentag(struct sink *output, const char *name, ...) {
295 sink_printf(output, "<%s", name);
297 while((n = va_arg(ap, const char *))) {
298 sink_printf(output, " ");
299 v = va_arg(ap, const char *);
301 cgi_attr(output, n, v);
303 sink_printf(output, n);
305 sink_printf(output, ">");
308 void cgi_closetag(struct sink *output, const char *name) {
309 sink_printf(output, "</%s>", name);
312 static int template_open(const char *name,
314 const char **filenamep) {
319 dirs[0] = pkgconfdir;
320 dirs[1] = pkgdatadir;
322 if((fd = open(name, O_RDONLY)) < 0) fatal(0, "cannot open %s", name);
325 for(n = 0; n < config->templates.n + (int)(sizeof dirs / sizeof *dirs); ++n) {
326 byte_xasprintf(&fullpath, "%s/%s%s",
327 n < config->templates.n ? config->templates.s[n]
328 : dirs[n - config->templates.n],
330 if((fd = open(fullpath, O_RDONLY)) >= 0) break;
332 if(fd < 0) error(0, "cannot find %s%s in template path", name, ext);
333 *filenamep = fullpath;
338 static int valid_template_name(const char *name) {
339 if(strchr(name, '/') || name[0] == '.')
344 void cgi_expand(const char *template,
345 const struct cgi_expansion *expansions,
355 if(!valid_template_name(template))
356 fatal(0, "invalid template name '%s'", template);
357 if((fd = template_open(template, ".html", &template)) < 0)
358 exitfn(EXIT_FAILURE);
359 if(fstat(fd, &sb) < 0) fatal(errno, "cannot stat %s", template);
361 b = xmalloc_noptr(sb.st_size + 1);
362 while(m < sb.st_size) {
363 n = read(fd, b + m, sb.st_size - m);
365 else if(n == 0) fatal(0, "unexpected EOF reading %s", template);
366 else if(errno != EINTR) fatal(errno, "error reading %s", template);
370 cgi_expand_string(template, b, expansions, nexpansions, output, u);
373 void cgi_expand_string(const char *name,
374 const char *template,
375 const struct cgi_expansion *expansions,
379 int braces, n, m, line = 1, sline;
384 cgi_sink parameter_output;
385 const struct cgi_macro *macro;
388 if(*template != '@') {
390 while(*p && *p != '@') {
391 if(*p == '\n') ++line;
394 output->sink->write(output->sink, template, p - template);
402 while(*template != '@') {
403 /* Skip whitespace */
404 while(isspace((unsigned char)*template))
407 if(*template == '{') {
410 while(*template && (*template != '}' || braces > 0)) {
412 case '{': ++braces; break;
413 case '}': --braces; break;
414 case '\n': ++line; break;
416 dynstr_append(&d, *template++);
418 if(!*template) fatal(0, "%s:%d: unterminated expansion", name, sline);
420 if(isspace((unsigned char)*template)) {
421 /* We have @{...}<WHITESPACE><SOMETHING> */
422 for(p = template; isspace((unsigned char)*p); ++p)
424 /* Now we are looking at <SOMETHING>. If it's "{" then that
425 * must be the next argument. Otherwise we infer that this
426 * is really the end of the expansion. */
428 goto finished_expansion;
431 /* unbracketed arg */
433 && *template != '@' && *template != '{' && *template != ':') {
434 if(*template == '\n') ++line;
435 dynstr_append(&d, *template++);
439 if(!*template) fatal(0, "%s:%d: unterminated expansion", name, sline);
440 /* trailing whitespace is not significant in unquoted args */
441 while(d.nvec && (isspace((unsigned char)d.vec[d.nvec - 1])))
444 dynstr_terminate(&d);
445 vector_append(&v, d.vec);
449 vector_terminate(&v);
450 /* @@ terminates this file */
453 if((n = table_find(expansions,
454 offsetof(struct cgi_expansion, name),
455 sizeof (struct cgi_expansion),
458 /* We found a built-in */
459 if(v.nvec - 1 < expansions[n].minargs)
460 fatal(0, "%s:%d: insufficient arguments to @%s@ (min %d, got %d)",
461 name, line, v.vec[0], expansions[n].minargs, v.nvec - 1);
462 if(v.nvec - 1 > expansions[n].maxargs)
463 fatal(0, "%s:%d: too many arguments to @%s@ (max %d, got %d)",
464 name, line, v.vec[0], expansions[n].maxargs, v.nvec - 1);
465 /* for ordinary expansions, recursively expand the arguments */
466 if(!(expansions[n].flags & EXP_MAGIC)) {
467 for(m = 1; m < v.nvec; ++m) {
469 byte_xasprintf(&argname, "<%s:%d arg #%d>", name, sline, m);
470 parameter_output.quote = 0;
471 parameter_output.sink = sink_dynstr(&d);
472 cgi_expand_string(argname, v.vec[m],
473 expansions, nexpansions,
474 ¶meter_output, u);
475 dynstr_terminate(&d);
479 expansions[n].handler(v.nvec - 1, v.vec + 1, output, u);
480 } else if(cgi_macros && (macro = hash_find(cgi_macros, v.vec[0]))) {
481 /* We found a macro */
482 if(v.nvec - 1 != macro->nargs)
483 fatal(0, "%s:%d: wrong number of arguments to @%s@ (need %d, got %d)",
484 name, line, v.vec[0], macro->nargs, v.nvec - 1);
485 /* We must substitute in argument values */
487 cgi_expand_string(v.vec[0],
494 /* Totally undefined */
495 fatal(0, "%s:%d: unknown expansion '%s'", name, line, v.vec[0]);
500 char *cgi_makeurl(const char *url, ...) {
502 struct kvp *kvp, *k, **kk = &kvp;
507 dynstr_append_string(&d, url);
509 while((n = va_arg(ap, const char *))) {
510 v = va_arg(ap, const char *);
511 *kk = k = xmalloc(sizeof *k);
518 dynstr_append(&d, '?');
519 dynstr_append_string(&d, kvp_urlencode(kvp, 0));
521 dynstr_terminate(&d);
525 void cgi_set_option(const char *name, const char *value) {
526 struct kvp *k = xmalloc(sizeof *k);
534 static void option_label(int attribute((unused)) nvec,
536 cgi_set_option(vec[0], vec[1]);
539 static void option_include(int attribute((unused)) nvec,
541 include_options(vec[0]);
544 static void option_columns(int nvec,
546 struct column *c = xmalloc(sizeof *c);
550 c->ncolumns = nvec - 1;
551 c->columns = &vec[1];
555 static struct option {
557 int minargs, maxargs;
558 void (*handler)(int nvec, char **vec);
560 { "columns", 1, INT_MAX, option_columns },
561 { "include", 1, 1, option_include },
562 { "label", 2, 2, option_label },
565 struct read_options_state {
570 static void read_options_error(const char *msg,
572 struct read_options_state *cs = u;
574 error(0, "%s:%d: %s", cs->name, cs->line, msg);
577 static void include_options(const char *name) {
582 struct read_options_state cs;
584 if((fd = template_open(name, "", &cs.name)) < 0) return;
585 if(!(fp = fdopen(fd, "r"))) fatal(errno, "error calling fdopen");
587 while(!inputline(cs.name, fp, &buffer, '\n')) {
589 if(!(vec = split(buffer, &n, SPLIT_COMMENTS|SPLIT_QUOTES,
590 read_options_error, &cs)))
593 if((i = TABLE_FIND(options, struct option, name, vec[0])) == -1) {
594 error(0, "%s:%d: unknown option '%s'", cs.name, cs.line, vec[0]);
599 if(n < options[i].minargs) {
600 error(0, "%s:%d: too few arguments to '%s'", cs.name, cs.line, vec[-1]);
603 if(n > options[i].maxargs) {
604 error(0, "%s:%d: too many arguments to '%s'", cs.name, cs.line, vec[-1]);
607 options[i].handler(n, vec);
612 static void read_options(void) {
613 if(!have_read_options) {
614 have_read_options = 1;
615 include_options("options");
619 const char *cgi_label(const char *key) {
623 if(!(label = kvp_get(labels, key))) {
625 if(!strncmp(key, "images.", 7)) {
626 static const char *url_static;
627 /* images.X defaults to <url.static>X.png */
630 url_static = cgi_label("url.static");
631 byte_xasprintf((char **)&label, "%s%s.png", url_static, key + 7);
632 } else if((label = strchr(key, '.')))
633 /* X.Y defaults to Y */
636 /* otherwise default to label name */
642 int cgi_label_exists(const char *key) {
644 return kvp_get(labels, key) ? 1 : 0;
647 char **cgi_columns(const char *name, int *ncolumns) {
651 for(c = columns; c && strcmp(name, c->name); c = c->next)
655 *ncolumns = c->ncolumns;
664 void cgi_define(const char *name,
671 cgi_macros = hash_new(sizeof(struct cgi_macro));
675 hash_add(cgi_macros, name, &m, HASH_INSERT_OR_REPLACE);