chiark / gitweb /
restore db4.3 support (broken in previous commit)
[disorder] / lib / cgi.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004, 2005, 2007, 2008 Richard Kettlewell
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 3 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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU 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, see <http://www.gnu.org/licenses/>.
17  */
18 /** @file lib/cgi.c
19  * @brief CGI tools
20  */
21
22 #include "common.h"
23
24 #include <unistd.h>
25 #include <errno.h>
26
27 #include "cgi.h"
28 #include "mem.h"
29 #include "log.h"
30 #include "vector.h"
31 #include "hash.h"
32 #include "kvp.h"
33 #include "mime.h"
34 #include "unicode.h"
35 #include "sink.h"
36
37 /** @brief Hash of arguments */
38 static hash *cgi_args;
39
40 /** @brief Get CGI arguments from a GET request's query string */
41 static struct kvp *cgi__init_get(void) {
42   const char *q;
43
44   if((q = getenv("QUERY_STRING")))
45     return kvp_urldecode(q, strlen(q));
46   error(0, "QUERY_STRING not set, assuming empty");
47   return NULL;
48 }
49
50 /** @brief Read the HTTP request body */
51 static void cgi__input(char **ptrp, size_t *np) {
52   const char *cl;
53   char *q;
54   size_t n, m = 0;
55   int r;
56
57   if(!(cl = getenv("CONTENT_LENGTH")))
58     fatal(0, "CONTENT_LENGTH not set");
59   n = atol(cl);
60   /* We check for overflow and also limit the input to 16MB. Lower
61    * would probably do.  */
62   if(!(n+1) || n > 16 * 1024 * 1024)
63     fatal(0, "input is much too large");
64   q = xmalloc_noptr(n + 1);
65   while(m < n) {
66     r = read(0, q + m, n - m);
67     if(r > 0)
68       m += r;
69     else if(r == 0)
70       fatal(0, "unexpected end of file reading request body");
71     else switch(errno) {
72     case EINTR: break;
73     default: fatal(errno, "error reading request body");
74     }
75   }
76   if(memchr(q, 0, n))
77     fatal(0, "null character in request body");
78   q[n + 1] = 0;
79   *ptrp = q;
80   if(np)
81     *np = n;
82 }
83
84 /** @brief Called for each part header field (see cgi__part_callback()) */
85 static int cgi__field_callback(const char *name, const char *value,
86                                void *u) {
87   char *disposition, *pname, *pvalue;
88   char **namep = u;
89
90   if(!strcmp(name, "content-disposition")) {
91     if(mime_rfc2388_content_disposition(value,
92                                         &disposition,
93                                         &pname,
94                                         &pvalue))
95       fatal(0, "error parsing Content-Disposition field");
96     if(!strcmp(disposition, "form-data")
97        && pname
98        && !strcmp(pname, "name")) {
99       if(*namep)
100         fatal(0, "duplicate Content-Disposition field");
101       *namep = pvalue;
102     }
103   }
104   return 0;
105 }
106
107 /** @brief Called for each part (see cgi__init_multipart()) */
108 static int cgi__part_callback(const char *s,
109                               void *u) {
110   char *name = 0;
111   struct kvp *k, **head = u;
112   
113   if(!(s = mime_parse(s, cgi__field_callback, &name)))
114     fatal(0, "error parsing part header");
115   if(!name)
116     fatal(0, "no name found");
117   k = xmalloc(sizeof *k);
118   k->next = *head;
119   k->name = name;
120   k->value = s;
121   *head = k;
122   return 0;
123 }
124
125 /** @brief Initialize CGI arguments from a multipart/form-data request body */
126 static struct kvp *cgi__init_multipart(const char *boundary) {
127   char *q;
128   struct kvp *head = 0;
129   
130   cgi__input(&q, 0);
131   if(mime_multipart(q, cgi__part_callback, boundary, &head))
132     fatal(0, "invalid multipart object");
133   return head;
134 }
135
136 /** @brief Initialize CGI arguments from a POST request */
137 static struct kvp *cgi__init_post(void) {
138   const char *ct, *boundary;
139   char *q, *type;
140   size_t n;
141   struct kvp *k;
142
143   if(!(ct = getenv("CONTENT_TYPE")))
144     ct = "application/x-www-form-urlencoded";
145   if(mime_content_type(ct, &type, &k))
146     fatal(0, "invalid content type '%s'", ct);
147   if(!strcmp(type, "application/x-www-form-urlencoded")) {
148     cgi__input(&q, &n);
149     return kvp_urldecode(q, n);
150   }
151   if(!strcmp(type, "multipart/form-data")) {
152     if(!(boundary = kvp_get(k, "boundary")))
153       fatal(0, "no boundary parameter found");
154     return cgi__init_multipart(boundary);
155   }
156   fatal(0, "unrecognized content type '%s'", type);
157 }
158
159 /** @brief Initialize CGI arguments
160  *
161  * Must be called before other cgi_ functions are used.
162  *
163  * This function can be called more than once, in which case it
164  * revisits the environment and (perhaps) standard input.  This is
165  * only intended to be used for testing, actual CGI applications
166  * should call it exactly once.
167  */
168 void cgi_init(void) {
169   const char *p;
170   struct kvp *k;
171
172   cgi_args = hash_new(sizeof (char *));
173   if(!(p = getenv("REQUEST_METHOD")))
174     error(0, "REQUEST_METHOD not set, assuming GET");
175   if(!p || !strcmp(p, "GET"))
176     k = cgi__init_get();
177   else if(!strcmp(p, "POST"))
178     k = cgi__init_post();
179   else
180     fatal(0, "unknown request method %s", p);
181   /* Validate the arguments and put them in a hash */
182   for(; k; k = k->next) {
183     if(!utf8_valid(k->name, strlen(k->name))
184        || !utf8_valid(k->value, strlen(k->value)))
185       error(0, "invalid UTF-8 sequence in cgi argument %s", k->name);
186     else
187       hash_add(cgi_args, k->name, &k->value, HASH_INSERT_OR_REPLACE);
188     /* We just drop bogus arguments. */
189   }
190 }
191
192 /** @brief Get a CGI argument by name
193  *
194  * cgi_init() must be called first.  Names and values are all valid
195  * UTF-8 strings (and this is enforced at initialization time).
196  */
197 const char *cgi_get(const char *name) {
198   const char **v = hash_find(cgi_args, name);
199
200   return v ? *v : NULL;
201 }
202
203 /** @brief Set a CGI argument */
204 void cgi_set(const char *name, const char *value) {
205   value = xstrdup(value);
206   hash_add(cgi_args, name, &value, HASH_INSERT_OR_REPLACE);
207 }
208
209 /** @brief Clear CGI arguments */
210 void cgi_clear(void) {
211   cgi_args = hash_new(sizeof (char *));
212 }
213
214 /** @brief Add SGML-style quoting
215  * @param src String to quote (UTF-8)
216  * @return Quoted string
217  *
218  * Quotes characters for insertion into HTML output.  Anything that is
219  * not a printable ASCII character will be converted to a numeric
220  * character references, as will '"', '&', '<' and '>' (since those
221  * have special meanings).
222  *
223  * Quoting everything down to ASCII means we don't care what the
224  * content encoding really is (as long as it's not anything insane
225  * like EBCDIC).
226  */
227 char *cgi_sgmlquote(const char *src) {
228   uint32_t *ucs, c;
229   int n;
230   struct dynstr d[1];
231   struct sink *s;
232
233   if(!(ucs = utf8_to_utf32(src, strlen(src), 0)))
234     exit(1);
235   dynstr_init(d);
236   s = sink_dynstr(d);
237   n = 1;
238   /* format the string */
239   while((c = *ucs++)) {
240     switch(c) {
241     default:
242       if(c > 126 || c < 32) {
243       case '"':
244       case '&':
245       case '<':
246       case '>':
247         /* For simplicity we always use numeric character references
248          * even if a named reference is available. */
249         sink_printf(s, "&#%"PRIu32";", c);
250         break;
251       } else
252         sink_writec(s, (char)c);
253     }
254   }
255   dynstr_terminate(d);
256   return d->vec;
257 }
258
259 /** @brief Write a CGI attribute
260  * @param output Where to send output
261  * @param name Attribute name
262  * @param value Attribute value
263  */
264 void cgi_attr(struct sink *output, const char *name, const char *value) {
265   /* Try to avoid needless quoting */
266   if(!value[strspn(value, "abcdefghijklmnopqrstuvwxyz"
267                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
268                    "0123456789")])
269     sink_printf(output, "%s=%s", name, value);
270   else
271     sink_printf(output, "%s=\"%s\"", name, cgi_sgmlquote(value));
272 }
273
274 /** @brief Write an open tag
275  * @param output Where to send output
276  * @param name Element name
277  * @param ... Attribute name/value pairs
278  *
279  * The name/value pair list is terminated by a single (char *)0.
280  */
281 void cgi_opentag(struct sink *output, const char *name, ...) {
282   va_list ap;
283   const char *n, *v;
284    
285   sink_printf(output, "<%s", name);
286   va_start(ap, name);
287   while((n = va_arg(ap, const char *))) {
288     sink_printf(output, " ");
289     v = va_arg(ap, const char *);
290     if(v)
291       cgi_attr(output, n, v);
292     else
293       sink_printf(output, n);
294   }
295   va_end(ap);
296   sink_printf(output, ">");
297 }
298
299 /** @brief Write a close tag
300  * @param output Where to send output
301  * @param name Element name
302  */
303 void cgi_closetag(struct sink *output, const char *name) {
304   sink_printf(output, "</%s>", name);
305 }
306
307 /** @brief Construct a URL
308  * @param url Base URL
309  * @param ... Name/value pairs for constructed query string
310  * @return Constructed URL
311  *
312  * The name/value pair list is terminated by a single (char *)0.
313  */
314 char *cgi_makeurl(const char *url, ...) {
315   va_list ap;
316   struct kvp *kvp, *k, **kk = &kvp;
317   struct dynstr d;
318   const char *n, *v;
319   
320   dynstr_init(&d);
321   dynstr_append_string(&d, url);
322   va_start(ap, url);
323   while((n = va_arg(ap, const char *))) {
324     v = va_arg(ap, const char *);
325     *kk = k = xmalloc(sizeof *k);
326     kk = &k->next;
327     k->name = n;
328     k->value = v;
329   }
330   va_end(ap);
331   *kk = 0;
332   if(kvp) {
333     dynstr_append(&d, '?');
334     dynstr_append_string(&d, kvp_urlencode(kvp, 0));
335   }
336   dynstr_terminate(&d);
337   return d.vec;
338 }
339
340 /** @brief Construct a URL from current parameters
341  * @param url Base URL
342  * @return Constructed URL
343  */
344 char *cgi_thisurl(const char *url) {
345   struct dynstr d[1];
346   char **keys = hash_keys(cgi_args);
347   int n;
348
349   dynstr_init(d);
350   dynstr_append_string(d, url);
351   for(n = 0; keys[n]; ++n) {
352     dynstr_append(d, n ? '&' : '?');
353     dynstr_append_string(d, urlencodestring(keys[n]));
354     dynstr_append(d, '=');
355     dynstr_append_string(d, urlencodestring(cgi_get(keys[n])));
356   }
357   dynstr_terminate(d);
358   return d->vec;
359 }
360
361 /*
362 Local Variables:
363 c-basic-offset:2
364 comment-column:40
365 fill-column:79
366 indent-tabs-mode:nil
367 End:
368 */