chiark / gitweb /
Fix mime_content_type() to not be so lazy; now it copes with arbitrary
[disorder] / lib / mime.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2005, 2007 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 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 /** @file lib/mime.c
21  * @brief Support for MIME and allied protocols
22  */
23
24 #include <config.h>
25 #include "types.h"
26
27 #include <string.h>
28 #include <ctype.h>
29
30 #include <stdio.h>
31
32 #include "mem.h"
33 #include "mime.h"
34 #include "vector.h"
35 #include "hex.h"
36 #include "log.h"
37 #include "base64.h"
38 #include "kvp.h"
39
40 /** @brief Match whitespace characters */
41 static int whitespace(int c) {
42   switch(c) {
43   case ' ':
44   case '\t':
45   case '\r':
46   case '\n':
47     return 1;
48   default:
49     return 0;
50   }
51 }
52
53 /** @brief Match RFC2045 tspecial characters */
54 static int tspecial(int c) {
55   switch(c) {
56   case '(':
57   case ')':
58   case '<':
59   case '>':
60   case '@':
61   case ',':
62   case ';':
63   case ':':
64   case '\\':
65   case '"':
66   case '/':
67   case '[':
68   case ']':
69   case '?':
70   case '=':
71     return 1;
72   default:
73     return 0;
74   }
75 }
76
77 /** @brief Match RFC2616 separator characters */
78 static int http_separator(int c) {
79   switch(c) {
80   case '(':
81   case ')':
82   case '<':
83   case '>':
84   case '@':
85   case ',':
86   case ';':
87   case ':':
88   case '\\':
89   case '"':
90   case '/':
91   case '[':
92   case ']':
93   case '?':
94   case '=':
95   case '{':
96   case '}':
97   case ' ':
98   case '\t':
99     return 1;
100   default:
101     return 0;
102   }
103 }
104
105 /** @brief Match CRLF */
106 static int iscrlf(const char *ptr) {
107   return ptr[0] == '\r' && ptr[1] == '\n';
108 }
109
110 /** @brief Skip whitespace
111  * @param s Pointer into string
112  * @param rfc822_comments If true, skip RFC822 nested comments
113  * @return Pointer into string after whitespace
114  */
115 static const char *skipwhite(const char *s, int rfc822_comments) {
116   int c, depth;
117   
118   for(;;) {
119     switch(c = *s) {
120     case ' ':
121     case '\t':
122     case '\r':
123     case '\n':
124       ++s;
125       break;
126     case '(':
127       if(!rfc822_comments)
128         return s;
129       ++s;
130       depth = 1;
131       while(*s && depth) {
132         c = *s++;
133         switch(c) {
134         case '(': ++depth; break;
135         case ')': --depth; break;
136         case '\\':
137           if(!*s) return 0;
138           ++s;
139           break;
140         }
141       }
142       if(depth) return 0;
143       break;
144     default:
145       return s;
146     }
147   }
148 }
149
150 /** @brief Test for a word character
151  * @param c Character to test
152  * @param special tspecial() (MIME/RFC2405) or http_separator() (HTTP/RFC2616)
153  * @return 1 if @p c is a word character, else 0
154  */
155 static int iswordchar(int c, int (*special)(int)) {
156   return !(c <= ' ' || c > '~' || special(c));
157 }
158
159 /** @brief Parse an RFC1521/RFC2616 word
160  * @param s Pointer to start of word
161  * @param valuep Where to store value
162  * @param special tspecial() (MIME/RFC2405) or http_separator() (HTTP/RFC2616)
163  * @return Pointer just after end of word or NULL if there's no word
164  *
165  * A word is a token or a quoted-string.
166  */
167 static const char *parseword(const char *s, char **valuep,
168                              int (*special)(int)) {
169   struct dynstr value[1];
170   int c;
171
172   dynstr_init(value);
173   if(*s == '"') {
174     ++s;
175     while((c = *s++) != '"') {
176       switch(c) {
177       case '\\':
178         if(!(c = *s++)) return 0;
179       default:
180         dynstr_append(value, c);
181         break;
182       }
183     }
184     if(!c) return 0;
185   } else {
186     if(!iswordchar((unsigned char)*s, special))
187       return NULL;
188     dynstr_init(value);
189     while(iswordchar((unsigned char)*s, special))
190       dynstr_append(value, *s++);
191   }
192   dynstr_terminate(value);
193   *valuep = value->vec;
194   return s;
195 }
196
197 /** @brief Parse an RFC1521/RFC2616 token
198  * @param s Pointer to start of token
199  * @param valuep Where to store value
200  * @param special tspecial() (MIME/RFC2405) or http_separator() (HTTP/RFC2616)
201  * @return Pointer just after end of token or NULL if there's no token
202  */
203 static const char *parsetoken(const char *s, char **valuep,
204                               int (*special)(int)) {
205   if(*s == '"') return 0;
206   return parseword(s, valuep, special);
207 }
208
209 /** @brief Parse a MIME content-type field
210  * @param s Start of field
211  * @param typep Where to store type
212  * @param parametersp Where to store parameter list
213  * @return 0 on success, non-0 on error
214  *
215  * See <a href="http://tools.ietf.org/html/rfc2045#section-5">RFC 2045 s5</a>.
216  */
217 int mime_content_type(const char *s,
218                       char **typep,
219                       struct kvp **parametersp) {
220   struct dynstr type, parametername;
221   struct kvp *parameters = 0;
222   char *parametervalue;
223
224   dynstr_init(&type);
225   if(!(s = skipwhite(s, 1))) return -1;
226   if(!*s) return -1;
227   while(*s && !tspecial(*s) && !whitespace(*s))
228     dynstr_append(&type, tolower((unsigned char)*s++));
229   if(!(s = skipwhite(s, 1))) return -1;
230   if(*s++ != '/') return -1;
231   dynstr_append(&type, '/');
232   if(!(s = skipwhite(s, 1))) return -1;
233   while(*s && !tspecial(*s) && !whitespace(*s))
234     dynstr_append(&type, tolower((unsigned char)*s++));
235   if(!(s = skipwhite(s, 1))) return -1;
236
237   while(*s == ';') {
238     dynstr_init(&parametername);
239     ++s;
240     if(!(s = skipwhite(s, 1))) return -1;
241     if(!*s) return -1;
242     while(*s && !tspecial(*s) && !whitespace(*s))
243       dynstr_append(&parametername, tolower((unsigned char)*s++));
244     if(!(s = skipwhite(s, 1))) return -1;
245     if(*s++ != '=') return -1;
246     if(!(s = skipwhite(s, 1))) return -1;
247     if(!(s = parseword(s, &parametervalue, tspecial))) return -1;
248     if(!(s = skipwhite(s, 1))) return -1;
249     dynstr_terminate(&parametername);
250     kvp_set(&parameters, parametername.vec, parametervalue);
251   }
252   dynstr_terminate(&type);
253   *typep = type.vec;
254   *parametersp = parameters;
255   return 0;
256 }
257
258 /** @brief Parse a MIME message
259  * @param s Start of message
260  * @param callback Called for each header field
261  * @param u Passed to callback
262  * @return Pointer to decoded body (might be in original string), or NULL on error
263  *
264  * This does an RFC 822-style parse and honors Content-Transfer-Encoding as
265  * described in <a href="http://tools.ietf.org/html/rfc2045#section-6">RFC 2045
266  * s6</a>.  @p callback is called for each header field encountered, in order,
267  * with ASCII characters in the header name forced to lower case.
268  */
269 const char *mime_parse(const char *s,
270                        int (*callback)(const char *name, const char *value,
271                                        void *u),
272                        void *u) {
273   struct dynstr name, value;
274   char *cte = 0, *p;
275   
276   while(*s && !iscrlf(s)) {
277     dynstr_init(&name);
278     dynstr_init(&value);
279     while(*s && !tspecial(*s) && !whitespace(*s))
280       dynstr_append(&name, tolower((unsigned char)*s++));
281     if(!(s = skipwhite(s, 1))) return 0;
282     if(*s != ':') return 0;
283     ++s;
284     while(*s && !(*s == '\n' && !(s[1] == ' ' || s[1] == '\t')))
285       dynstr_append(&value, *s++);
286     if(*s) ++s;
287     dynstr_terminate(&name);
288     dynstr_terminate(&value);
289     if(!strcmp(name.vec, "content-transfer-encoding")) {
290       cte = xstrdup(value.vec);
291       for(p = cte; *p; p++)
292         *p = tolower((unsigned char)*p);
293     }
294     if(callback(name.vec, value.vec, u)) return 0;
295   }
296   if(*s) s += 2;
297   if(cte) {
298     if(!strcmp(cte, "base64")) return mime_base64(s, 0);
299     if(!strcmp(cte, "quoted-printable")) return mime_qp(s);
300   }
301   return s;
302 }
303
304 /** @brief Match the boundary string */
305 static int isboundary(const char *ptr, const char *boundary, size_t bl) {
306   return (ptr[0] == '-'
307           && ptr[1] == '-'
308           && !strncmp(ptr + 2, boundary, bl)
309           && (iscrlf(ptr + bl + 2)
310               || (ptr[bl + 2] == '-'
311                   && ptr[bl + 3] == '-'
312                   && (iscrlf(ptr + bl + 4) || *(ptr + bl + 4) == 0))));
313 }
314
315 /** @brief Match the final boundary string */
316 static int isfinal(const char *ptr, const char *boundary, size_t bl) {
317   return (ptr[0] == '-'
318           && ptr[1] == '-'
319           && !strncmp(ptr + 2, boundary, bl)
320           && ptr[bl + 2] == '-'
321           && ptr[bl + 3] == '-'
322           && (iscrlf(ptr + bl + 4) || *(ptr + bl + 4) == 0));
323 }
324
325 /** @brief Parse a multipart MIME body
326  * @param s Start of message
327  * @param callback Callback for each part
328  * @param boundary Boundary string
329  * @param u Passed to callback
330  * @return 0 on success, non-0 on error
331  * 
332  * See <a href="http://tools.ietf.org/html/rfc2046#section-5.1">RFC 2046
333  * s5.1</a>.  @p callback is called for each part (not yet decoded in any way)
334  * in succession; you should probably call mime_parse() for each part.
335  */
336 int mime_multipart(const char *s,
337                    int (*callback)(const char *s, void *u),
338                    const char *boundary,
339                    void *u) {
340   size_t bl = strlen(boundary);
341   const char *start, *e;
342   int ret;
343
344   /* We must start with a boundary string */
345   if(!isboundary(s, boundary, bl))
346     return -1;
347   /* Keep going until we hit a final boundary */
348   while(!isfinal(s, boundary, bl)) {
349     s = strstr(s, "\r\n") + 2;
350     start = s;
351     while(!isboundary(s, boundary, bl)) {
352       if(!(e = strstr(s, "\r\n")))
353         return -1;
354       s = e + 2;
355     }
356     if((ret = callback(xstrndup(start,
357                                 s == start ? 0 : s - start - 2),
358                        u)))
359       return ret;
360   }
361   return 0;
362 }
363
364 /** @brief Parse an RFC2388-style content-disposition field
365  * @param s Start of field
366  * @param dispositionp Where to store disposition
367  * @param parameternamep Where to store parameter name
368  * @param parametervaluep Wher to store parameter value
369  * @return 0 on success, non-0 on error
370  *
371  * See <a href="http://tools.ietf.org/html/rfc2388#section-3">RFC 2388 s3</a>
372  * and <a href="http://tools.ietf.org/html/rfc2183">RFC 2183</a>.
373  */
374 int mime_rfc2388_content_disposition(const char *s,
375                                      char **dispositionp,
376                                      char **parameternamep,
377                                      char **parametervaluep) {
378   struct dynstr disposition, parametername;
379
380   dynstr_init(&disposition);
381   if(!(s = skipwhite(s, 1))) return -1;
382   if(!*s) return -1;
383   while(*s && !tspecial(*s) && !whitespace(*s))
384     dynstr_append(&disposition, tolower((unsigned char)*s++));
385   if(!(s = skipwhite(s, 1))) return -1;
386
387   if(*s == ';') {
388     dynstr_init(&parametername);
389     ++s;
390     if(!(s = skipwhite(s, 1))) return -1;
391     if(!*s) return -1;
392     while(*s && !tspecial(*s) && !whitespace(*s))
393       dynstr_append(&parametername, tolower((unsigned char)*s++));
394     if(!(s = skipwhite(s, 1))) return -1;
395     if(*s++ != '=') return -1;
396     if(!(s = skipwhite(s, 1))) return -1;
397     if(!(s = parseword(s, parametervaluep, tspecial))) return -1;
398     if(!(s = skipwhite(s, 1))) return -1;
399     dynstr_terminate(&parametername);
400     *parameternamep = parametername.vec;
401   } else
402     *parametervaluep = *parameternamep = 0;
403   dynstr_terminate(&disposition);
404   *dispositionp = disposition.vec;
405   return 0;
406 }
407
408 /** @brief Convert MIME quoted-printable
409  * @param s Quoted-printable data
410  * @return Decoded data
411  *
412  * See <a href="http://tools.ietf.org/html/rfc2045#section-6.7">RFC 2045
413  * s6.7</a>.
414  */
415 char *mime_qp(const char *s) {
416   struct dynstr d;
417   int c, a, b;
418   const char *t;
419
420   dynstr_init(&d);
421   while((c = *s++)) {
422     switch(c) {
423     case '=':
424       if((a = unhexdigitq(s[0])) != -1
425          && (b = unhexdigitq(s[1])) != -1) {
426         dynstr_append(&d, a * 16 + b);
427         s += 2;
428       } else {
429         t = s;
430         while(*t == ' ' || *t == '\t') ++t;
431         if(iscrlf(t)) {
432           /* soft line break */
433           s = t + 2;
434         } else
435           return 0;
436       }
437       break;
438     case ' ':
439     case '\t':
440       t = s;
441       while(*t == ' ' || *t == '\t') ++t;
442       if(iscrlf(t))
443         /* trailing space is always eliminated */
444         s = t;
445       else
446         dynstr_append(&d, c);
447       break;
448     default:
449       dynstr_append(&d, c);
450       break;
451     }
452   }
453   dynstr_terminate(&d);
454   return d.vec;
455 }
456
457 /** @brief Parse a RFC2109 Cookie: header
458  * @param s Header field value
459  * @param cd Where to store result
460  * @return 0 on success, non-0 on error
461  *
462  * See <a href="http://tools.ietf.org/html/rfc2109">RFC 2109</a>.
463  */
464 int parse_cookie(const char *s,
465                  struct cookiedata *cd) {
466   char *n = 0, *v = 0;
467
468   memset(cd, 0, sizeof *cd);
469   s = skipwhite(s, 0);
470   while(*s) {
471     /* Skip separators */
472     if(*s == ';' || *s == ',') {
473       ++s;
474       s = skipwhite(s, 0);
475       continue;
476     }
477     if(!(s = parsetoken(s, &n, http_separator))) return -1;
478     s = skipwhite(s, 0);
479     if(*s++ != '=') return -1;
480     s = skipwhite(s, 0);
481     if(!(s = parseword(s, &v, http_separator))) return -1;
482     if(n[0] == '$') {
483       /* Some bit of meta-information */
484       if(!strcmp(n, "$Version"))
485         cd->version = v;
486       else if(!strcmp(n, "$Path")) {
487         if(cd->ncookies > 0 && cd->cookies[cd->ncookies-1].path == 0)
488           cd->cookies[cd->ncookies-1].path = v;
489         else {
490           error(0, "redundant $Path in Cookie: header");
491           return -1;
492         }
493       } else if(!strcmp(n, "$Domain")) {
494         if(cd->ncookies > 0 && cd->cookies[cd->ncookies-1].domain == 0)
495           cd->cookies[cd->ncookies-1].domain = v;
496         else {
497           error(0, "redundant $Domain in Cookie: header");
498           return -1;
499         }
500       }
501     } else {
502       /* It's a new cookie */
503       cd->cookies = xrealloc(cd->cookies,
504                              (cd->ncookies + 1) * sizeof (struct cookie));
505       cd->cookies[cd->ncookies].name = n;
506       cd->cookies[cd->ncookies].value = v;
507       cd->cookies[cd->ncookies].path = 0;
508       cd->cookies[cd->ncookies].domain = 0;
509       ++cd->ncookies;
510     }
511     s = skipwhite(s, 0);
512     if(*s && (*s != ',' && *s != ';')) {
513       error(0, "missing separator in Cookie: header");
514       return -1;
515     }
516   }
517   return 0;
518 }
519
520 /** @brief Find a named cookie
521  * @param cd Parse cookie data
522  * @param name Name of cookie
523  * @return Cookie structure or NULL if not found
524  */
525 const struct cookie *find_cookie(const struct cookiedata *cd,
526                                  const char *name) {
527   int n;
528
529   for(n = 0; n < cd->ncookies; ++n)
530     if(!strcmp(cd->cookies[n].name, name))
531       return &cd->cookies[n];
532   return 0;
533 }
534
535 /** @brief RFC822 quoting
536  * @param s String to quote
537  * @param force If non-0, always quote
538  * @return Possibly quoted string
539  */
540 char *quote822(const char *s, int force) {
541   const char *t;
542   struct dynstr d[1];
543   int c;
544
545   if(!force) {
546     /* See if we need to quote */
547     for(t = s; (c = (unsigned char)*t); ++t) {
548       if(tspecial(c) || http_separator(c) || whitespace(c))
549         break;
550     }
551     if(*t)
552       force = 1;
553   }
554
555   if(!force)
556     return xstrdup(s);
557
558   dynstr_init(d);
559   dynstr_append(d, '"');
560   for(t = s; (c = (unsigned char)*t); ++t) {
561     if(c == '"' || c == '\\')
562       dynstr_append(d, '\\');
563     dynstr_append(d, c);
564   }
565   dynstr_append(d, '"');
566   dynstr_terminate(d);
567   return d->vec;
568 }
569
570 /** @brief Return true if @p ptr points at trailing space */
571 static int is_trailing_space(const char *ptr) {
572   if(*ptr == ' ' || *ptr == '\t') {
573     while(*ptr == ' ' || *ptr == '\t')
574       ++ptr;
575     return *ptr == '\n' || *ptr == 0;
576   } else
577     return 0;
578 }
579
580 /** @brief Encoding text as quoted-printable
581  * @param text String to encode
582  * @return Encoded string
583  *
584  * See <a href="http://tools.ietf.org/html/rfc2045#section-6.7">RFC2045
585  * s6.7</a>.
586  */
587 char *mime_to_qp(const char *text) {
588   struct dynstr d[1];
589   int linelength = 0;                   /* length of current line */
590   char buffer[10];
591
592   dynstr_init(d);
593   /* The rules are:
594    * 1. Anything except newline can be replaced with =%02X
595    * 2. Newline, 33-60 and 62-126 stand for themselves (i.e. not '=')
596    * 3. Non-trailing space/tab stand for themselves.
597    * 4. Output lines are limited to 76 chars, with =<newline> being used
598    *    as a soft line break
599    * 5. Newlines aren't counted towards the 76 char limit.
600    */
601   while(*text) {
602     const int c = (unsigned char)*text;
603     if(c == '\n') {
604       /* Newline stands as itself */
605       dynstr_append(d, '\n');
606       linelength = 0;
607     } else if((c >= 33 && c <= 126 && c != '=')
608               || ((c == ' ' || c == '\t')
609                   && !is_trailing_space(text))) {
610       /* Things that can stand for themselves  */
611       dynstr_append(d, c);
612       ++linelength;
613     } else {
614       /* Anything else that needs encoding */
615       snprintf(buffer, sizeof buffer, "=%02X", c);
616       dynstr_append_string(d, buffer);
617       linelength += 3;
618     }
619     ++text;
620     if(linelength > 73 && *text && *text != '\n') {
621       /* Next character might overflow 76 character limit if encoded, so we
622        * insert a soft break */
623       dynstr_append_string(d, "=\n");
624       linelength = 0;
625     }
626   }
627   /* Ensure there is a final newline */
628   if(linelength)
629     dynstr_append(d, '\n');
630   /* That's all */
631   dynstr_terminate(d);
632   return d->vec;
633 }
634
635 /** @brief Encode text
636  * @param text Underlying UTF-8 text
637  * @param charsetp Where to store charset string
638  * @param encodingp Where to store encoding string
639  * @return Encoded text (might be @ref text)
640  */
641 const char *mime_encode_text(const char *text,
642                              const char **charsetp,
643                              const char **encodingp) {
644   const char *ptr;
645
646   /* See if there are in fact any non-ASCII characters */
647   for(ptr = text; *ptr; ++ptr)
648     if((unsigned char)*ptr >= 128)
649       break;
650   if(!*ptr) {
651     /* Plain old ASCII, no encoding required */
652     *charsetp = "us-ascii";
653     *encodingp = "7bit";
654     return text;
655   }
656   *charsetp = "utf-8";
657   *encodingp = "quoted-printable";
658   return mime_to_qp(text);
659 }
660
661 /*
662 Local Variables:
663 c-basic-offset:2
664 comment-column:40
665 fill-column:79
666 End:
667 */