2 * This file is part of DisOrder
3 * Copyright (C) 2005, 2007 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
21 * @brief Support for MIME and allied protocols
40 /** @brief Match whitespace characters */
41 static int whitespace(int c) {
53 /** @brief Match RFC2045 tspecial characters */
54 static int tspecial(int c) {
77 /** @brief Match RFC2616 separator characters */
78 static int http_separator(int c) {
105 /** @brief Match CRLF */
106 static int iscrlf(const char *ptr) {
107 return ptr[0] == '\r' && ptr[1] == '\n';
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
115 static const char *skipwhite(const char *s, int rfc822_comments) {
134 case '(': ++depth; break;
135 case ')': --depth; break;
152 /** @brief Test for a word character
153 * @param c Character to test
154 * @param special tspecial() (MIME/RFC2405) or http_separator() (HTTP/RFC2616)
155 * @return 1 if @p c is a word character, else 0
157 static int iswordchar(int c, int (*special)(int)) {
158 return !(c <= ' ' || c > '~' || special(c));
161 /** @brief Parse an RFC1521/RFC2616 word
162 * @param s Pointer to start of word
163 * @param valuep Where to store value
164 * @param special tspecial() (MIME/RFC2405) or http_separator() (HTTP/RFC2616)
165 * @return Pointer just after end of word or NULL if there's no word
167 * A word is a token or a quoted-string.
169 static const char *parseword(const char *s, char **valuep,
170 int (*special)(int)) {
171 struct dynstr value[1];
177 while((c = *s++) != '"') {
183 dynstr_append(value, c);
190 if(!iswordchar((unsigned char)*s, special))
193 while(iswordchar((unsigned char)*s, special))
194 dynstr_append(value, *s++);
196 dynstr_terminate(value);
197 *valuep = value->vec;
201 /** @brief Parse an RFC1521/RFC2616 token
202 * @param s Pointer to start of token
203 * @param valuep Where to store value
204 * @param special tspecial() (MIME/RFC2405) or http_separator() (HTTP/RFC2616)
205 * @return Pointer just after end of token or NULL if there's no token
207 static const char *parsetoken(const char *s, char **valuep,
208 int (*special)(int)) {
211 return parseword(s, valuep, special);
214 /** @brief Parse a MIME content-type field
215 * @param s Start of field
216 * @param typep Where to store type
217 * @param parametersp Where to store parameter list
218 * @return 0 on success, non-0 on error
220 * See <a href="http://tools.ietf.org/html/rfc2045#section-5">RFC 2045 s5</a>.
222 int mime_content_type(const char *s,
224 struct kvp **parametersp) {
225 struct dynstr type, parametername;
226 struct kvp *parameters = 0;
227 char *parametervalue;
230 if(!(s = skipwhite(s, 1)))
234 while(*s && !tspecial(*s) && !whitespace(*s))
235 dynstr_append(&type, tolower((unsigned char)*s++));
236 if(!(s = skipwhite(s, 1)))
240 dynstr_append(&type, '/');
241 if(!(s = skipwhite(s, 1)))
243 while(*s && !tspecial(*s) && !whitespace(*s))
244 dynstr_append(&type, tolower((unsigned char)*s++));
245 if(!(s = skipwhite(s, 1)))
249 dynstr_init(¶metername);
251 if(!(s = skipwhite(s, 1)))
255 while(*s && !tspecial(*s) && !whitespace(*s))
256 dynstr_append(¶metername, tolower((unsigned char)*s++));
257 if(!(s = skipwhite(s, 1)))
261 if(!(s = skipwhite(s, 1)))
263 if(!(s = parseword(s, ¶metervalue, tspecial)))
265 if(!(s = skipwhite(s, 1)))
267 dynstr_terminate(¶metername);
268 kvp_set(¶meters, parametername.vec, parametervalue);
270 dynstr_terminate(&type);
272 *parametersp = parameters;
276 /** @brief Parse a MIME message
277 * @param s Start of message
278 * @param callback Called for each header field
279 * @param u Passed to callback
280 * @return Pointer to decoded body (might be in original string), or NULL on error
282 * This does an RFC 822-style parse and honors Content-Transfer-Encoding as
283 * described in <a href="http://tools.ietf.org/html/rfc2045#section-6">RFC 2045
284 * s6</a>. @p callback is called for each header field encountered, in order,
285 * with ASCII characters in the header name forced to lower case.
287 const char *mime_parse(const char *s,
288 int (*callback)(const char *name, const char *value,
291 struct dynstr name, value;
294 while(*s && !iscrlf(s)) {
297 while(*s && !tspecial(*s) && !whitespace(*s))
298 dynstr_append(&name, tolower((unsigned char)*s++));
299 if(!(s = skipwhite(s, 1)))
304 while(*s && !(*s == '\n' && !(s[1] == ' ' || s[1] == '\t'))) {
306 /* Strip leading whitespace */
307 if(value.nvec || !(c == ' ' || c == '\t' || c == '\n' || c == '\r'))
308 dynstr_append(&value, c);
310 /* Strip trailing whitespace */
311 while(value.nvec > 0 && (value.vec[value.nvec - 1] == ' '
312 || value.vec[value.nvec - 1] == '\t'
313 || value.vec[value.nvec - 1] == '\n'
314 || value.vec[value.nvec - 1] == '\r'))
318 dynstr_terminate(&name);
319 dynstr_terminate(&value);
320 if(!strcmp(name.vec, "content-transfer-encoding")) {
321 cte = xstrdup(value.vec);
322 for(p = cte; *p; p++)
323 *p = tolower((unsigned char)*p);
325 if(callback(name.vec, value.vec, u))
331 if(!strcmp(cte, "base64"))
332 return mime_base64(s, 0);
333 if(!strcmp(cte, "quoted-printable"))
335 if(!strcmp(cte, "7bit") || !strcmp(cte, "8bit"))
337 error(0, "unknown content-transfer-encoding '%s'", cte);
343 /** @brief Match the boundary string */
344 static int isboundary(const char *ptr, const char *boundary, size_t bl) {
345 return (ptr[0] == '-'
347 && !strncmp(ptr + 2, boundary, bl)
348 && (iscrlf(ptr + bl + 2)
349 || (ptr[bl + 2] == '-'
350 && ptr[bl + 3] == '-'
351 && (iscrlf(ptr + bl + 4) || *(ptr + bl + 4) == 0))));
354 /** @brief Match the final boundary string */
355 static int isfinal(const char *ptr, const char *boundary, size_t bl) {
356 return (ptr[0] == '-'
358 && !strncmp(ptr + 2, boundary, bl)
359 && ptr[bl + 2] == '-'
360 && ptr[bl + 3] == '-'
361 && (iscrlf(ptr + bl + 4) || *(ptr + bl + 4) == 0));
364 /** @brief Parse a multipart MIME body
365 * @param s Start of message
366 * @param callback Callback for each part
367 * @param boundary Boundary string
368 * @param u Passed to callback
369 * @return 0 on success, non-0 on error
371 * See <a href="http://tools.ietf.org/html/rfc2046#section-5.1">RFC 2046
372 * s5.1</a>. @p callback is called for each part (not yet decoded in any way)
373 * in succession; you should probably call mime_parse() for each part.
375 int mime_multipart(const char *s,
376 int (*callback)(const char *s, void *u),
377 const char *boundary,
379 size_t bl = strlen(boundary);
380 const char *start, *e;
383 /* We must start with a boundary string */
384 if(!isboundary(s, boundary, bl))
386 /* Keep going until we hit a final boundary */
387 while(!isfinal(s, boundary, bl)) {
388 s = strstr(s, "\r\n") + 2;
390 while(!isboundary(s, boundary, bl)) {
391 if(!(e = strstr(s, "\r\n")))
395 if((ret = callback(xstrndup(start,
396 s == start ? 0 : s - start - 2),
403 /** @brief Parse an RFC2388-style content-disposition field
404 * @param s Start of field
405 * @param dispositionp Where to store disposition
406 * @param parameternamep Where to store parameter name
407 * @param parametervaluep Wher to store parameter value
408 * @return 0 on success, non-0 on error
410 * See <a href="http://tools.ietf.org/html/rfc2388#section-3">RFC 2388 s3</a>
411 * and <a href="http://tools.ietf.org/html/rfc2183">RFC 2183</a>.
413 int mime_rfc2388_content_disposition(const char *s,
415 char **parameternamep,
416 char **parametervaluep) {
417 struct dynstr disposition, parametername;
419 dynstr_init(&disposition);
420 if(!(s = skipwhite(s, 1)))
424 while(*s && !tspecial(*s) && !whitespace(*s))
425 dynstr_append(&disposition, tolower((unsigned char)*s++));
426 if(!(s = skipwhite(s, 1)))
430 dynstr_init(¶metername);
432 if(!(s = skipwhite(s, 1)))
436 while(*s && !tspecial(*s) && !whitespace(*s))
437 dynstr_append(¶metername, tolower((unsigned char)*s++));
438 if(!(s = skipwhite(s, 1)))
442 if(!(s = skipwhite(s, 1)))
444 if(!(s = parseword(s, parametervaluep, tspecial)))
446 if(!(s = skipwhite(s, 1)))
448 dynstr_terminate(¶metername);
449 *parameternamep = parametername.vec;
451 *parametervaluep = *parameternamep = 0;
452 dynstr_terminate(&disposition);
453 *dispositionp = disposition.vec;
457 /** @brief Convert MIME quoted-printable
458 * @param s Quoted-printable data
459 * @return Decoded data
461 * See <a href="http://tools.ietf.org/html/rfc2045#section-6.7">RFC 2045
464 char *mime_qp(const char *s) {
473 if((a = unhexdigitq(s[0])) != -1
474 && (b = unhexdigitq(s[1])) != -1) {
475 dynstr_append(&d, a * 16 + b);
479 while(*t == ' ' || *t == '\t') ++t;
481 /* soft line break */
490 while(*t == ' ' || *t == '\t') ++t;
492 /* trailing space is always eliminated */
495 dynstr_append(&d, c);
498 dynstr_append(&d, c);
502 dynstr_terminate(&d);
506 /** @brief Parse a RFC2109 Cookie: header
507 * @param s Header field value
508 * @param cd Where to store result
509 * @return 0 on success, non-0 on error
511 * See <a href="http://tools.ietf.org/html/rfc2109">RFC 2109</a>.
513 int parse_cookie(const char *s,
514 struct cookiedata *cd) {
517 memset(cd, 0, sizeof *cd);
520 /* Skip separators */
521 if(*s == ';' || *s == ',') {
526 if(!(s = parsetoken(s, &n, http_separator)))
532 if(!(s = parseword(s, &v, http_separator)))
535 /* Some bit of meta-information */
536 if(!strcmp(n, "$Version"))
538 else if(!strcmp(n, "$Path")) {
539 if(cd->ncookies > 0 && cd->cookies[cd->ncookies-1].path == 0)
540 cd->cookies[cd->ncookies-1].path = v;
542 error(0, "redundant $Path in Cookie: header");
545 } else if(!strcmp(n, "$Domain")) {
546 if(cd->ncookies > 0 && cd->cookies[cd->ncookies-1].domain == 0)
547 cd->cookies[cd->ncookies-1].domain = v;
549 error(0, "redundant $Domain in Cookie: header");
554 /* It's a new cookie */
555 cd->cookies = xrealloc(cd->cookies,
556 (cd->ncookies + 1) * sizeof (struct cookie));
557 cd->cookies[cd->ncookies].name = n;
558 cd->cookies[cd->ncookies].value = v;
559 cd->cookies[cd->ncookies].path = 0;
560 cd->cookies[cd->ncookies].domain = 0;
564 if(*s && (*s != ',' && *s != ';')) {
565 error(0, "missing separator in Cookie: header");
572 /** @brief Find a named cookie
573 * @param cd Parse cookie data
574 * @param name Name of cookie
575 * @return Cookie structure or NULL if not found
577 const struct cookie *find_cookie(const struct cookiedata *cd,
581 for(n = 0; n < cd->ncookies; ++n)
582 if(!strcmp(cd->cookies[n].name, name))
583 return &cd->cookies[n];
587 /** @brief RFC822 quoting
588 * @param s String to quote
589 * @param force If non-0, always quote
590 * @return Possibly quoted string
592 char *quote822(const char *s, int force) {
598 /* See if we need to quote */
599 for(t = s; (c = (unsigned char)*t); ++t) {
600 if(tspecial(c) || http_separator(c) || whitespace(c))
611 dynstr_append(d, '"');
612 for(t = s; (c = (unsigned char)*t); ++t) {
613 if(c == '"' || c == '\\')
614 dynstr_append(d, '\\');
617 dynstr_append(d, '"');
622 /** @brief Return true if @p ptr points at trailing space */
623 static int is_trailing_space(const char *ptr) {
624 if(*ptr == ' ' || *ptr == '\t') {
625 while(*ptr == ' ' || *ptr == '\t')
627 return *ptr == '\n' || *ptr == 0;
632 /** @brief Encoding text as quoted-printable
633 * @param text String to encode
634 * @return Encoded string
636 * See <a href="http://tools.ietf.org/html/rfc2045#section-6.7">RFC2045
639 char *mime_to_qp(const char *text) {
641 int linelength = 0; /* length of current line */
646 * 1. Anything except newline can be replaced with =%02X
647 * 2. Newline, 33-60 and 62-126 stand for themselves (i.e. not '=')
648 * 3. Non-trailing space/tab stand for themselves.
649 * 4. Output lines are limited to 76 chars, with =<newline> being used
650 * as a soft line break
651 * 5. Newlines aren't counted towards the 76 char limit.
654 const int c = (unsigned char)*text;
656 /* Newline stands as itself */
657 dynstr_append(d, '\n');
659 } else if((c >= 33 && c <= 126 && c != '=')
660 || ((c == ' ' || c == '\t')
661 && !is_trailing_space(text))) {
662 /* Things that can stand for themselves */
666 /* Anything else that needs encoding */
667 snprintf(buffer, sizeof buffer, "=%02X", c);
668 dynstr_append_string(d, buffer);
672 if(linelength > 73 && *text && *text != '\n') {
673 /* Next character might overflow 76 character limit if encoded, so we
674 * insert a soft break */
675 dynstr_append_string(d, "=\n");
679 /* Ensure there is a final newline */
681 dynstr_append(d, '\n');
687 /** @brief Encode text
688 * @param text Underlying UTF-8 text
689 * @param charsetp Where to store charset string
690 * @param encodingp Where to store encoding string
691 * @return Encoded text (might be @ref text)
693 const char *mime_encode_text(const char *text,
694 const char **charsetp,
695 const char **encodingp) {
698 /* See if there are in fact any non-ASCII characters */
699 for(ptr = text; *ptr; ++ptr)
700 if((unsigned char)*ptr >= 128)
703 /* Plain old ASCII, no encoding required */
704 *charsetp = "us-ascii";
709 *encodingp = "quoted-printable";
710 return mime_to_qp(text);