2 * This file is part of DisOrder
3 * Copyright (C) 2005, 2007-10, 2013 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 3 of the License, or
8 * (at your option) any later version.
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.
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/>.
19 * @brief Support for MIME and allied protocols
35 /** @brief Match whitespace characters */
36 static int whitespace(int c) {
48 /** @brief Match RFC2045 tspecial characters */
49 int mime_tspecial(int c) {
72 /** @brief Match RFC2616 separator characters */
73 int mime_http_separator(int c) {
100 /** @brief Match CRLF */
101 static int iscrlf(const char *ptr) {
102 return ptr[0] == '\r' && ptr[1] == '\n';
105 /** @brief Skip whitespace
106 * @param s Pointer into string
107 * @param rfc822_comments If true, skip RFC822 nested comments
108 * @return Pointer into string after whitespace
110 static const char *skipwhite(const char *s, int rfc822_comments) {
129 case '(': ++depth; break;
130 case ')': --depth; break;
147 /** @brief Test for a word character
148 * @param c Character to test
149 * @param special mime_tspecial() (MIME/RFC2405) or mime_http_separator() (HTTP/RFC2616)
150 * @return 1 if @p c is a word character, else 0
152 static int iswordchar(int c, int (*special)(int)) {
153 return !(c <= ' ' || c > '~' || special(c));
156 /** @brief Parse an RFC1521/RFC2616 word
157 * @param s Pointer to start of word
158 * @param valuep Where to store value
159 * @param special mime_tspecial() (MIME/RFC2405) or mime_http_separator() (HTTP/RFC2616)
160 * @return Pointer just after end of word or NULL if there's no word
162 * A word is a token or a quoted-string.
164 const char *mime_parse_word(const char *s, char **valuep,
165 int (*special)(int)) {
166 struct dynstr value[1];
172 while((c = *s++) != '"') {
178 dynstr_append(value, c);
185 if(!iswordchar((unsigned char)*s, special))
188 while(iswordchar((unsigned char)*s, special))
189 dynstr_append(value, *s++);
191 dynstr_terminate(value);
192 *valuep = value->vec;
196 /** @brief Parse an RFC1521/RFC2616 token
197 * @param s Pointer to start of token
198 * @param valuep Where to store value
199 * @param special mime_tspecial() (MIME/RFC2405) or mime_http_separator() (HTTP/RFC2616)
200 * @return Pointer just after end of token or NULL if there's no token
202 static const char *parsetoken(const char *s, char **valuep,
203 int (*special)(int)) {
206 return mime_parse_word(s, valuep, special);
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
215 * See <a href="http://tools.ietf.org/html/rfc2045#section-5">RFC 2045 s5</a>.
217 int mime_content_type(const char *s,
219 struct kvp **parametersp) {
220 struct dynstr type, parametername;
221 struct kvp *parameters = 0;
222 char *parametervalue;
225 if(!(s = skipwhite(s, 1)))
229 while(*s && !mime_tspecial(*s) && !whitespace(*s))
230 dynstr_append(&type, tolower((unsigned char)*s++));
231 if(!(s = skipwhite(s, 1)))
235 dynstr_append(&type, '/');
236 if(!(s = skipwhite(s, 1)))
238 while(*s && !mime_tspecial(*s) && !whitespace(*s))
239 dynstr_append(&type, tolower((unsigned char)*s++));
240 if(!(s = skipwhite(s, 1)))
244 dynstr_init(¶metername);
246 if(!(s = skipwhite(s, 1)))
250 while(*s && !mime_tspecial(*s) && !whitespace(*s))
251 dynstr_append(¶metername, tolower((unsigned char)*s++));
252 if(!(s = skipwhite(s, 1)))
256 if(!(s = skipwhite(s, 1)))
258 if(!(s = mime_parse_word(s, ¶metervalue, mime_tspecial)))
260 if(!(s = skipwhite(s, 1)))
262 dynstr_terminate(¶metername);
263 kvp_set(¶meters, parametername.vec, parametervalue);
265 dynstr_terminate(&type);
267 *parametersp = parameters;
271 /** @brief Parse a MIME message
272 * @param s Start of message
273 * @param callback Called for each header field
274 * @param u Passed to callback
275 * @return Pointer to decoded body (might be in original string), or NULL on error
277 * This does an RFC 822-style parse and honors Content-Transfer-Encoding as
278 * described in <a href="http://tools.ietf.org/html/rfc2045#section-6">RFC 2045
279 * s6</a>. @p callback is called for each header field encountered, in order,
280 * with ASCII characters in the header name forced to lower case.
282 const char *mime_parse(const char *s,
283 int (*callback)(const char *name, const char *value,
286 struct dynstr name, value;
289 while(*s && !iscrlf(s)) {
292 while(*s && !mime_tspecial(*s) && !whitespace(*s))
293 dynstr_append(&name, tolower((unsigned char)*s++));
294 if(!(s = skipwhite(s, 1)))
299 while(*s && !(*s == '\n' && !(s[1] == ' ' || s[1] == '\t'))) {
301 /* Strip leading whitespace */
302 if(value.nvec || !(c == ' ' || c == '\t' || c == '\n' || c == '\r'))
303 dynstr_append(&value, c);
305 /* Strip trailing whitespace */
306 while(value.nvec > 0 && (value.vec[value.nvec - 1] == ' '
307 || value.vec[value.nvec - 1] == '\t'
308 || value.vec[value.nvec - 1] == '\n'
309 || value.vec[value.nvec - 1] == '\r'))
313 dynstr_terminate(&name);
314 dynstr_terminate(&value);
315 if(!strcmp(name.vec, "content-transfer-encoding")) {
316 cte = xstrdup(value.vec);
317 for(p = cte; *p; p++)
318 *p = tolower((unsigned char)*p);
320 if(callback(name.vec, value.vec, u))
326 if(!strcmp(cte, "base64"))
327 return mime_base64(s, 0);
328 if(!strcmp(cte, "quoted-printable"))
330 if(!strcmp(cte, "7bit") || !strcmp(cte, "8bit"))
332 disorder_error(0, "unknown content-transfer-encoding '%s'", cte);
338 /** @brief Match the boundary string */
339 static int isboundary(const char *ptr, const char *boundary, size_t bl) {
340 return (ptr[0] == '-'
342 && !strncmp(ptr + 2, boundary, bl)
343 && (iscrlf(ptr + bl + 2)
344 || (ptr[bl + 2] == '-'
345 && ptr[bl + 3] == '-'
346 && (iscrlf(ptr + bl + 4) || *(ptr + bl + 4) == 0))));
349 /** @brief Match the final boundary string */
350 static int isfinal(const char *ptr, const char *boundary, size_t bl) {
351 return (ptr[0] == '-'
353 && !strncmp(ptr + 2, boundary, bl)
354 && ptr[bl + 2] == '-'
355 && ptr[bl + 3] == '-'
356 && (iscrlf(ptr + bl + 4) || *(ptr + bl + 4) == 0));
359 /** @brief Parse a multipart MIME body
360 * @param s Start of message
361 * @param callback Callback for each part
362 * @param boundary Boundary string
363 * @param u Passed to callback
364 * @return 0 on success, non-0 on error
366 * See <a href="http://tools.ietf.org/html/rfc2046#section-5.1">RFC 2046
367 * s5.1</a>. @p callback is called for each part (not yet decoded in any way)
368 * in succession; you should probably call mime_parse() for each part.
370 int mime_multipart(const char *s,
371 int (*callback)(const char *s, void *u),
372 const char *boundary,
374 size_t bl = strlen(boundary);
375 const char *start, *e;
378 /* We must start with a boundary string */
379 if(!isboundary(s, boundary, bl)) {
380 disorder_error(0, "mime_multipart: first line is not the boundary string");
383 /* Keep going until we hit a final boundary */
384 while(!isfinal(s, boundary, bl)) {
385 s = strstr(s, "\r\n") + 2;
387 while(!isboundary(s, boundary, bl)) {
388 if(!(e = strstr(s, "\r\n"))) {
389 disorder_error(0, "mime_multipart: line does not end CRLF");
394 if((ret = callback(xstrndup(start,
395 s == start ? 0 : s - start - 2),
402 /** @brief Parse an RFC2388-style content-disposition field
403 * @param s Start of field
404 * @param dispositionp Where to store disposition
405 * @param parameternamep Where to store parameter name
406 * @param parametervaluep Where to store parameter value
407 * @return 0 on success, non-0 on error
409 * See <a href="http://tools.ietf.org/html/rfc2388#section-3">RFC 2388 s3</a>
410 * and <a href="http://tools.ietf.org/html/rfc2183">RFC 2183</a>.
412 int mime_rfc2388_content_disposition(const char *s,
414 char **parameternamep,
415 char **parametervaluep) {
416 struct dynstr disposition, parametername;
418 dynstr_init(&disposition);
419 if(!(s = skipwhite(s, 1)))
423 while(*s && !mime_tspecial(*s) && !whitespace(*s))
424 dynstr_append(&disposition, tolower((unsigned char)*s++));
425 if(!(s = skipwhite(s, 1)))
429 dynstr_init(¶metername);
431 if(!(s = skipwhite(s, 1)))
435 while(*s && !mime_tspecial(*s) && !whitespace(*s))
436 dynstr_append(¶metername, tolower((unsigned char)*s++));
437 if(!(s = skipwhite(s, 1)))
441 if(!(s = skipwhite(s, 1)))
443 if(!(s = mime_parse_word(s, parametervaluep, mime_tspecial)))
445 if(!(s = skipwhite(s, 1)))
447 dynstr_terminate(¶metername);
448 *parameternamep = parametername.vec;
450 *parametervaluep = *parameternamep = 0;
451 dynstr_terminate(&disposition);
452 *dispositionp = disposition.vec;
456 /** @brief Convert MIME quoted-printable
457 * @param s Quoted-printable data
458 * @return Decoded data
460 * See <a href="http://tools.ietf.org/html/rfc2045#section-6.7">RFC 2045
463 char *mime_qp(const char *s) {
472 if((a = unhexdigitq(s[0])) != -1
473 && (b = unhexdigitq(s[1])) != -1) {
474 dynstr_append(&d, a * 16 + b);
478 while(*t == ' ' || *t == '\t') ++t;
480 /* soft line break */
489 while(*t == ' ' || *t == '\t') ++t;
491 /* trailing space is always eliminated */
494 dynstr_append(&d, c);
497 dynstr_append(&d, c);
501 dynstr_terminate(&d);
505 /** @brief Match cookie separator characters
507 * This is a subset of the RFC2616 specials, and technically is in breach of
508 * the specification. However rejecting (in particular) slashes is
509 * unreasonably strict and has broken at least one (admittedly somewhat
510 * obscure) browser, so we're more forgiving.
512 static int cookie_separator(int c) {
529 /** @brief Match cookie value separator characters
531 * Same as cookie_separator() but allows for @c = in cookie values.
533 static int cookie_value_separator(int c) {
549 /** @brief Parse a RFC2109 Cookie: header
550 * @param s Header field value
551 * @param cd Where to store result
552 * @return 0 on success, non-0 on error
554 * See <a href="http://tools.ietf.org/html/rfc2109">RFC 2109</a>.
556 int parse_cookie(const char *s,
557 struct cookiedata *cd) {
560 memset(cd, 0, sizeof *cd);
563 /* Skip separators */
564 if(*s == ';' || *s == ',') {
569 if(!(s = parsetoken(s, &n, cookie_separator))) {
570 disorder_error(0, "parse_cookie: cannot parse attribute name");
575 disorder_error(0, "parse_cookie: did not find expected '='");
579 if(!(s = mime_parse_word(s, &v, cookie_value_separator))) {
580 disorder_error(0, "parse_cookie: cannot parse value for '%s'", n);
584 /* Some bit of meta-information */
585 if(!strcmp(n, "$Version"))
587 else if(!strcmp(n, "$Path")) {
588 if(cd->ncookies > 0 && cd->cookies[cd->ncookies-1].path == 0)
589 cd->cookies[cd->ncookies-1].path = v;
591 disorder_error(0, "redundant $Path in Cookie: header");
594 } else if(!strcmp(n, "$Domain")) {
595 if(cd->ncookies > 0 && cd->cookies[cd->ncookies-1].domain == 0)
596 cd->cookies[cd->ncookies-1].domain = v;
598 disorder_error(0, "redundant $Domain in Cookie: header");
603 /* It's a new cookie */
604 cd->cookies = xrealloc(cd->cookies,
605 (cd->ncookies + 1) * sizeof (struct cookie));
606 cd->cookies[cd->ncookies].name = n;
607 cd->cookies[cd->ncookies].value = v;
608 cd->cookies[cd->ncookies].path = 0;
609 cd->cookies[cd->ncookies].domain = 0;
613 if(*s && (*s != ',' && *s != ';')) {
614 disorder_error(0, "missing separator in Cookie: header");
621 /** @brief Find a named cookie
622 * @param cd Parse cookie data
623 * @param name Name of cookie
624 * @return Cookie structure or NULL if not found
626 const struct cookie *find_cookie(const struct cookiedata *cd,
630 for(n = 0; n < cd->ncookies; ++n)
631 if(!strcmp(cd->cookies[n].name, name))
632 return &cd->cookies[n];
636 /** @brief RFC822 quoting
637 * @param s String to quote
638 * @param force If non-0, always quote
639 * @return Possibly quoted string
641 char *quote822(const char *s, int force) {
647 /* See if we need to quote */
648 for(t = s; (c = (unsigned char)*t); ++t) {
649 if(mime_tspecial(c) || mime_http_separator(c) || whitespace(c))
660 dynstr_append(d, '"');
661 for(t = s; (c = (unsigned char)*t); ++t) {
662 if(c == '"' || c == '\\')
663 dynstr_append(d, '\\');
666 dynstr_append(d, '"');
671 /** @brief Return true if @p ptr points at trailing space */
672 static int is_trailing_space(const char *ptr) {
673 if(*ptr == ' ' || *ptr == '\t') {
674 while(*ptr == ' ' || *ptr == '\t')
676 return *ptr == '\n' || *ptr == 0;
681 /** @brief Encoding text as quoted-printable
682 * @param text String to encode
683 * @return Encoded string
685 * See <a href="http://tools.ietf.org/html/rfc2045#section-6.7">RFC2045
688 char *mime_to_qp(const char *text) {
690 int linelength = 0; /* length of current line */
695 * 1. Anything except newline can be replaced with =%02X
696 * 2. Newline, 33-60 and 62-126 stand for themselves (i.e. not '=')
697 * 3. Non-trailing space/tab stand for themselves.
698 * 4. Output lines are limited to 76 chars, with =<newline> being used
699 * as a soft line break
700 * 5. Newlines aren't counted towards the 76 char limit.
703 const int c = (unsigned char)*text;
705 /* Newline stands as itself */
706 dynstr_append(d, '\n');
708 } else if((c >= 33 && c <= 126 && c != '=')
709 || ((c == ' ' || c == '\t')
710 && !is_trailing_space(text))) {
711 /* Things that can stand for themselves */
715 /* Anything else that needs encoding */
716 byte_snprintf(buffer, sizeof buffer, "=%02X", c);
717 dynstr_append_string(d, buffer);
721 if(linelength > 73 && *text && *text != '\n') {
722 /* Next character might overflow 76 character limit if encoded, so we
723 * insert a soft break */
724 dynstr_append_string(d, "=\n");
728 /* Ensure there is a final newline */
730 dynstr_append(d, '\n');
736 /** @brief Encode text
737 * @param text Underlying UTF-8 text
738 * @param charsetp Where to store charset string
739 * @param encodingp Where to store encoding string
740 * @return Encoded text (might be @p text)
742 const char *mime_encode_text(const char *text,
743 const char **charsetp,
744 const char **encodingp) {
747 /* See if there are in fact any non-ASCII characters */
748 for(ptr = text; *ptr; ++ptr)
749 if((unsigned char)*ptr >= 128)
752 /* Plain old ASCII, no encoding required */
753 *charsetp = "us-ascii";
758 *encodingp = "quoted-printable";
759 return mime_to_qp(text);