chiark / gitweb /
First cut at macro definition. Does not expand args yet.
[disorder] / server / cgi.c
CommitLineData
460b9539 1/*
2 * This file is part of DisOrder.
5aff007d 3 * Copyright (C) 2004-2008 Richard Kettlewell
460b9539 4 *
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.
9 *
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.
14 *
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
18 * USA
19 */
20
21#include <config.h>
22#include "types.h"
23
24#include <string.h>
25#include <stdio.h>
26#include <unistd.h>
27#include <stdlib.h>
28#include <errno.h>
29#include <sys/stat.h>
30#include <stddef.h>
31#include <fcntl.h>
32#include <unistd.h>
33#include <pcre.h>
34#include <limits.h>
35#include <fnmatch.h>
36#include <ctype.h>
37
38#include "mem.h"
39#include "log.h"
40#include "hex.h"
41#include "charset.h"
42#include "configuration.h"
43#include "table.h"
44#include "syscalls.h"
45#include "kvp.h"
46#include "vector.h"
47#include "split.h"
48#include "inputline.h"
49#include "regsub.h"
50#include "defs.h"
51#include "sink.h"
52#include "cgi.h"
53#include "printf.h"
54#include "mime.h"
18cda350 55#include "unicode.h"
3dddcfa4 56#include "hash.h"
460b9539 57
58struct kvp *cgi_args;
59
60/* options */
61struct column {
62 struct column *next;
63 char *name;
64 int ncolumns;
65 char **columns;
66};
67
3dddcfa4
RK
68/* macros */
69struct cgi_macro {
70 int nargs;
71 char **args;
72 const char *value;
73};
74
75static hash *cgi_macros;
76
460b9539 77#define RELIST(x) struct re *x, **x##_tail = &x
78
79static int have_read_options;
80static struct kvp *labels;
81static struct column *columns;
82
83static void include_options(const char *name);
84
85static void cgi_parse_get(void) {
86 const char *q;
87
88 if(!(q = getenv("QUERY_STRING"))) fatal(0, "QUERY_STRING not set");
89 cgi_args = kvp_urldecode(q, strlen(q));
90}
91
92static void cgi_input(char **ptrp, size_t *np) {
93 const char *cl;
94 char *q;
95 size_t n, m = 0;
96 int r;
97
98 if(!(cl = getenv("CONTENT_LENGTH"))) fatal(0, "CONTENT_LENGTH not set");
99 n = atol(cl);
100 q = xmalloc_noptr(n + 1);
101 while(m < n) {
102 r = read(0, q + m, n - m);
103 if(r > 0)
104 m += r;
105 else if(r == 0)
106 fatal(0, "unexpected end of file reading request body");
107 else switch(errno) {
108 case EINTR: break;
109 default: fatal(errno, "error reading request body");
110 }
111 }
112 if(memchr(q, 0, n)) fatal(0, "null character in request body");
113 q[n + 1] = 0;
114 *ptrp = q;
115 if(np) *np = n;
116}
117
118static int cgi_field_callback(const char *name, const char *value,
119 void *u) {
120 char *disposition, *pname, *pvalue;
121 char **namep = u;
122
123 if(!strcmp(name, "content-disposition")) {
124 if(mime_rfc2388_content_disposition(value,
125 &disposition,
126 &pname,
127 &pvalue))
128 fatal(0, "error parsing Content-Disposition field");
129 if(!strcmp(disposition, "form-data")
130 && pname
131 && !strcmp(pname, "name")) {
132 if(*namep)
133 fatal(0, "duplicate Content-Disposition field");
134 *namep = pvalue;
135 }
136 }
137 return 0;
138}
139
140static int cgi_part_callback(const char *s,
141 void attribute((unused)) *u) {
142 char *name = 0;
143 struct kvp *k;
144
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);
149 k->next = cgi_args;
150 k->name = name;
151 k->value = s;
152 cgi_args = k;
153 return 0;
154}
155
156static void cgi_parse_multipart(const char *boundary) {
157 char *q;
158
159 cgi_input(&q, 0);
160 if(mime_multipart(q, cgi_part_callback, boundary, 0))
161 fatal(0, "invalid multipart object");
162}
163
164static void cgi_parse_post(void) {
9bce81d1 165 const char *ct, *boundary;
166 char *q, *type;
460b9539 167 size_t n;
9bce81d1 168 struct kvp *k;
460b9539 169
170 if(!(ct = getenv("CONTENT_TYPE")))
171 ct = "application/x-www-form-urlencoded";
9bce81d1 172 if(mime_content_type(ct, &type, &k))
460b9539 173 fatal(0, "invalid content type '%s'", ct);
174 if(!strcmp(type, "application/x-www-form-urlencoded")) {
175 cgi_input(&q, &n);
176 cgi_args = kvp_urldecode(q, n);
177 return;
178 }
179 if(!strcmp(type, "multipart/form-data")) {
9bce81d1 180 if(!(boundary = kvp_get(k, "boundary")))
181 fatal(0, "no boundary parameter found");
182 cgi_parse_multipart(boundary);
460b9539 183 return;
184 }
185 fatal(0, "unrecognized content type '%s'", type);
186}
187
188void cgi_parse(void) {
189 const char *p;
190 struct kvp *k;
191
192 if(!(p = getenv("REQUEST_METHOD"))) fatal(0, "REQUEST_METHOD not set");
193 if(!strcmp(p, "GET"))
194 cgi_parse_get();
195 else if(!strcmp(p, "POST"))
196 cgi_parse_post();
197 else
198 fatal(0, "unknown request method %s", p);
199 for(k = cgi_args; k; k = k->next)
18cda350
RK
200 if(!utf8_valid(k->name, strlen(k->name))
201 || !utf8_valid(k->value, strlen(k->value)))
460b9539 202 fatal(0, "invalid UTF-8 sequence in cgi argument");
203}
204
205const char *cgi_get(const char *name) {
206 return kvp_get(cgi_args, name);
207}
208
209void cgi_output(cgi_sink *output, const char *fmt, ...) {
210 va_list ap;
211 int n;
212 char *r;
213
214 va_start(ap, fmt);
215 n = byte_vasprintf(&r, fmt, ap);
216 if(n < 0)
217 fatal(errno, "error calling byte_vasprintf");
218 if(output->quote)
219 r = cgi_sgmlquote(r, 0);
220 output->sink->write(output->sink, r, strlen(r));
221 va_end(ap);
222}
223
224void cgi_header(struct sink *output, const char *name, const char *value) {
225 sink_printf(output, "%s: %s\r\n", name, value);
226}
227
228void cgi_body(struct sink *output) {
229 sink_printf(output, "\r\n");
230}
231
232char *cgi_sgmlquote(const char *s, int raw) {
233 uint32_t *ucs, *p, c;
234 char *b, *bp;
235 int n;
236
237 if(!raw) {
caecd4f4 238 if(!(ucs = utf8_to_utf32(s, strlen(s), 0))) exit(EXIT_FAILURE);
460b9539 239 } else {
240 ucs = xmalloc_noptr((strlen(s) + 1) * sizeof(uint32_t));
241 for(n = 0; s[n]; ++n)
242 ucs[n] = (unsigned char)s[n];
243 ucs[n] = 0;
244 }
245
246 n = 1;
247 /* estimate the length we'll need */
248 for(p = ucs; (c = *p); ++p) {
249 switch(c) {
250 default:
251 if(c > 127 || c < 32) {
252 case '"':
253 case '&':
254 case '<':
255 case '>':
256 n += 12;
257 break;
258 } else
259 n++;
260 }
261 }
262 /* format the string */
263 b = bp = xmalloc_noptr(n);
264 for(p = ucs; (c = *p); ++p) {
265 switch(c) {
266 default:
267 if(*p > 127 || *p < 32) {
268 case '"':
269 case '&':
270 case '<':
271 case '>':
272 bp += sprintf(bp, "&#%lu;", (unsigned long)c);
273 break;
274 } else
275 *bp++ = c;
276 }
277 }
278 *bp = 0;
279 return b;
280}
281
282void cgi_attr(struct sink *output, const char *name, const char *value) {
283 if(!value[strspn(value, "abcdefghijklmnopqrstuvwxyz"
284 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
285 "0123456789")])
286 sink_printf(output, "%s=%s", name, value);
287 else
288 sink_printf(output, "%s=\"%s\"", name, cgi_sgmlquote(value, 0));
289}
290
291void cgi_opentag(struct sink *output, const char *name, ...) {
292 va_list ap;
293 const char *n, *v;
294
295 sink_printf(output, "<%s", name);
296 va_start(ap, name);
297 while((n = va_arg(ap, const char *))) {
298 sink_printf(output, " ");
299 v = va_arg(ap, const char *);
300 if(v)
301 cgi_attr(output, n, v);
302 else
303 sink_printf(output, n);
304 }
305 sink_printf(output, ">");
306}
307
308void cgi_closetag(struct sink *output, const char *name) {
309 sink_printf(output, "</%s>", name);
310}
311
312static int template_open(const char *name,
313 const char *ext,
314 const char **filenamep) {
315 const char *dirs[2];
316 int fd = -1, n;
317 char *fullpath;
318
319 dirs[0] = pkgconfdir;
320 dirs[1] = pkgdatadir;
321 if(name[0] == '/') {
322 if((fd = open(name, O_RDONLY)) < 0) fatal(0, "cannot open %s", name);
323 *filenamep = name;
324 } else {
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],
329 name, ext);
330 if((fd = open(fullpath, O_RDONLY)) >= 0) break;
331 }
332 if(fd < 0) error(0, "cannot find %s%s in template path", name, ext);
333 *filenamep = fullpath;
334 }
335 return fd;
336}
337
338static int valid_template_name(const char *name) {
339 if(strchr(name, '/') || name[0] == '.')
340 return 0;
341 return 1;
342}
343
344void cgi_expand(const char *template,
345 const struct cgi_expansion *expansions,
346 size_t nexpansions,
347 cgi_sink *output,
348 void *u) {
349 int fd = -1;
350 int n;
351 off_t m;
352 char *b;
353 struct stat sb;
354
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);
360 m = 0;
361 b = xmalloc_noptr(sb.st_size + 1);
362 while(m < sb.st_size) {
363 n = read(fd, b + m, sb.st_size - m);
364 if(n > 0) m += n;
365 else if(n == 0) fatal(0, "unexpected EOF reading %s", template);
366 else if(errno != EINTR) fatal(errno, "error reading %s", template);
367 }
368 b[sb.st_size] = 0;
369 xclose(fd);
370 cgi_expand_string(template, b, expansions, nexpansions, output, u);
371}
372
373void cgi_expand_string(const char *name,
374 const char *template,
375 const struct cgi_expansion *expansions,
376 size_t nexpansions,
377 cgi_sink *output,
378 void *u) {
379 int braces, n, m, line = 1, sline;
380 char *argname;
381 const char *p;
382 struct vector v;
383 struct dynstr d;
384 cgi_sink parameter_output;
3dddcfa4 385 const struct cgi_macro *macro;
460b9539 386
387 while(*template) {
388 if(*template != '@') {
389 p = template;
390 while(*p && *p != '@') {
391 if(*p == '\n') ++line;
392 ++p;
393 }
394 output->sink->write(output->sink, template, p - template);
395 template = p;
396 continue;
397 }
398 vector_init(&v);
399 braces = 0;
400 ++template;
401 sline = line;
402 while(*template != '@') {
f6b388d0
RK
403 /* Skip whitespace */
404 while(isspace((unsigned char)*template))
405 ++template;
460b9539 406 dynstr_init(&d);
407 if(*template == '{') {
408 /* bracketed arg */
409 ++template;
410 while(*template && (*template != '}' || braces > 0)) {
411 switch(*template) {
412 case '{': ++braces; break;
413 case '}': --braces; break;
414 case '\n': ++line; break;
415 }
416 dynstr_append(&d, *template++);
417 }
418 if(!*template) fatal(0, "%s:%d: unterminated expansion", name, sline);
419 ++template;
f6b388d0
RK
420 if(isspace((unsigned char)*template)) {
421 /* We have @{...}<WHITESPACE><SOMETHING> */
422 for(p = template; isspace((unsigned char)*p); ++p)
423 ;
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. */
427 if(*p != '{')
428 goto finished_expansion;
429 }
460b9539 430 } else {
431 /* unbracketed arg */
460b9539 432 while(*template
433 && *template != '@' && *template != '{' && *template != ':') {
434 if(*template == '\n') ++line;
435 dynstr_append(&d, *template++);
436 }
437 if(*template == ':')
438 ++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])))
442 --d.nvec;
443 }
444 dynstr_terminate(&d);
445 vector_append(&v, d.vec);
446 }
447 ++template;
f6b388d0 448finished_expansion:
460b9539 449 vector_terminate(&v);
450 /* @@ terminates this file */
451 if(v.nvec == 0)
452 break;
453 if((n = table_find(expansions,
454 offsetof(struct cgi_expansion, name),
455 sizeof (struct cgi_expansion),
456 nexpansions,
3dddcfa4
RK
457 v.vec[0])) >= 0) {
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) {
468 dynstr_init(&d);
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 &parameter_output, u);
475 dynstr_terminate(&d);
476 v.vec[m] = d.vec;
477 }
460b9539 478 }
3dddcfa4
RK
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 */
486 /* TODO */
487 cgi_expand_string(v.vec[0],
488 macro->value,
489 expansions,
490 nexpansions,
491 output,
492 u);
493 } else {
494 /* Totally undefined */
495 fatal(0, "%s:%d: unknown expansion '%s'", name, line, v.vec[0]);
460b9539 496 }
460b9539 497 }
498}
499
500char *cgi_makeurl(const char *url, ...) {
501 va_list ap;
502 struct kvp *kvp, *k, **kk = &kvp;
503 struct dynstr d;
504 const char *n, *v;
505
506 dynstr_init(&d);
507 dynstr_append_string(&d, url);
508 va_start(ap, url);
509 while((n = va_arg(ap, const char *))) {
510 v = va_arg(ap, const char *);
511 *kk = k = xmalloc(sizeof *k);
512 kk = &k->next;
513 k->name = n;
514 k->value = v;
515 }
516 *kk = 0;
517 if(kvp) {
518 dynstr_append(&d, '?');
519 dynstr_append_string(&d, kvp_urlencode(kvp, 0));
520 }
521 dynstr_terminate(&d);
522 return d.vec;
523}
524
525void cgi_set_option(const char *name, const char *value) {
526 struct kvp *k = xmalloc(sizeof *k);
527
528 k->next = labels;
529 k->name = name;
530 k->value = value;
531 labels = k;
532}
533
534static void option_label(int attribute((unused)) nvec,
535 char **vec) {
536 cgi_set_option(vec[0], vec[1]);
537}
538
539static void option_include(int attribute((unused)) nvec,
540 char **vec) {
541 include_options(vec[0]);
542}
543
544static void option_columns(int nvec,
545 char **vec) {
546 struct column *c = xmalloc(sizeof *c);
547
548 c->next = columns;
549 c->name = vec[0];
550 c->ncolumns = nvec - 1;
551 c->columns = &vec[1];
552 columns = c;
553}
554
555static struct option {
556 const char *name;
557 int minargs, maxargs;
558 void (*handler)(int nvec, char **vec);
559} options[] = {
560 { "columns", 1, INT_MAX, option_columns },
561 { "include", 1, 1, option_include },
562 { "label", 2, 2, option_label },
563};
564
565struct read_options_state {
566 const char *name;
567 int line;
568};
569
570static void read_options_error(const char *msg,
571 void *u) {
572 struct read_options_state *cs = u;
573
574 error(0, "%s:%d: %s", cs->name, cs->line, msg);
575}
576
577static void include_options(const char *name) {
578 int n, i;
579 int fd;
580 FILE *fp;
581 char **vec, *buffer;
582 struct read_options_state cs;
583
584 if((fd = template_open(name, "", &cs.name)) < 0) return;
585 if(!(fp = fdopen(fd, "r"))) fatal(errno, "error calling fdopen");
586 cs.line = 0;
587 while(!inputline(cs.name, fp, &buffer, '\n')) {
588 ++cs.line;
589 if(!(vec = split(buffer, &n, SPLIT_COMMENTS|SPLIT_QUOTES,
590 read_options_error, &cs)))
591 continue;
592 if(!n) continue;
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]);
595 continue;
596 }
597 ++vec;
598 --n;
599 if(n < options[i].minargs) {
600 error(0, "%s:%d: too few arguments to '%s'", cs.name, cs.line, vec[-1]);
601 continue;
602 }
603 if(n > options[i].maxargs) {
604 error(0, "%s:%d: too many arguments to '%s'", cs.name, cs.line, vec[-1]);
605 continue;
606 }
607 options[i].handler(n, vec);
608 }
609 fclose(fp);
610}
611
612static void read_options(void) {
613 if(!have_read_options) {
614 have_read_options = 1;
615 include_options("options");
616 }
617}
618
619const char *cgi_label(const char *key) {
620 const char *label;
621
622 read_options();
623 if(!(label = kvp_get(labels, key))) {
5e34540b 624 /* No label found */
625 if(!strncmp(key, "images.", 7)) {
626 static const char *url_static;
627 /* images.X defaults to <url.static>X.png */
628
629 if(!url_static)
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 */
460b9539 634 ++label;
635 else
5e34540b 636 /* otherwise default to label name */
460b9539 637 label = key;
638 }
639 return label;
640}
641
8f9616f1
RK
642int cgi_label_exists(const char *key) {
643 read_options();
644 return kvp_get(labels, key) ? 1 : 0;
645}
646
460b9539 647char **cgi_columns(const char *name, int *ncolumns) {
648 struct column *c;
649
650 read_options();
651 for(c = columns; c && strcmp(name, c->name); c = c->next)
652 ;
653 if(c) {
654 if(ncolumns)
655 *ncolumns = c->ncolumns;
656 return c->columns;
657 } else {
658 if(ncolumns)
659 *ncolumns = 0;
660 return 0;
661 }
662}
663
3dddcfa4
RK
664void cgi_define(const char *name,
665 int nargs,
666 char **args,
667 const char *value) {
668 struct cgi_macro m;
669
670 if(!cgi_macros)
671 cgi_macros = hash_new(sizeof(struct cgi_macro));
672 m.nargs = nargs;
673 m.args = args;
674 m.value = value;
675 hash_add(cgi_macros, name, &m, HASH_INSERT_OR_REPLACE);
676}
677
460b9539 678/*
679Local Variables:
680c-basic-offset:2
681comment-column:40
682End:
683*/