2 * This file is part of DisOrder
3 * Copyright (C) 2005, 2007, 2008 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 int mime_tspecial(int c
) {
77 /** @brief Match RFC2616 separator characters */
78 int mime_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 mime_tspecial() (MIME/RFC2405) or mime_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 mime_tspecial() (MIME/RFC2405) or mime_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 const char *mime_parse_word(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 mime_tspecial() (MIME/RFC2405) or mime_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 mime_parse_word(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
&& !mime_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
&& !mime_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
&& !mime_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
= mime_parse_word(s
, ¶metervalue
, mime_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
&& !mime_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
)) {
385 error(0, "mime_multipart: first line is not the boundary string");
388 /* Keep going until we hit a final boundary */
389 while(!isfinal(s
, boundary
, bl
)) {
390 s
= strstr(s
, "\r\n") + 2;
392 while(!isboundary(s
, boundary
, bl
)) {
393 if(!(e
= strstr(s
, "\r\n"))) {
394 error(0, "mime_multipart: line does not end CRLF");
399 if((ret
= callback(xstrndup(start
,
400 s
== start ?
0 : s
- start
- 2),
407 /** @brief Parse an RFC2388-style content-disposition field
408 * @param s Start of field
409 * @param dispositionp Where to store disposition
410 * @param parameternamep Where to store parameter name
411 * @param parametervaluep Wher to store parameter value
412 * @return 0 on success, non-0 on error
414 * See <a href="http://tools.ietf.org/html/rfc2388#section-3">RFC 2388 s3</a>
415 * and <a href="http://tools.ietf.org/html/rfc2183">RFC 2183</a>.
417 int mime_rfc2388_content_disposition(const char *s
,
419 char **parameternamep
,
420 char **parametervaluep
) {
421 struct dynstr disposition
, parametername
;
423 dynstr_init(&disposition
);
424 if(!(s
= skipwhite(s
, 1)))
428 while(*s
&& !mime_tspecial(*s
) && !whitespace(*s
))
429 dynstr_append(&disposition
, tolower((unsigned char)*s
++));
430 if(!(s
= skipwhite(s
, 1)))
434 dynstr_init(¶metername
);
436 if(!(s
= skipwhite(s
, 1)))
440 while(*s
&& !mime_tspecial(*s
) && !whitespace(*s
))
441 dynstr_append(¶metername
, tolower((unsigned char)*s
++));
442 if(!(s
= skipwhite(s
, 1)))
446 if(!(s
= skipwhite(s
, 1)))
448 if(!(s
= mime_parse_word(s
, parametervaluep
, mime_tspecial
)))
450 if(!(s
= skipwhite(s
, 1)))
452 dynstr_terminate(¶metername
);
453 *parameternamep
= parametername
.vec
;
455 *parametervaluep
= *parameternamep
= 0;
456 dynstr_terminate(&disposition
);
457 *dispositionp
= disposition
.vec
;
461 /** @brief Convert MIME quoted-printable
462 * @param s Quoted-printable data
463 * @return Decoded data
465 * See <a href="http://tools.ietf.org/html/rfc2045#section-6.7">RFC 2045
468 char *mime_qp(const char *s
) {
477 if((a
= unhexdigitq(s
[0])) != -1
478 && (b
= unhexdigitq(s
[1])) != -1) {
479 dynstr_append(&d
, a
* 16 + b
);
483 while(*t
== ' ' || *t
== '\t') ++t
;
485 /* soft line break */
494 while(*t
== ' ' || *t
== '\t') ++t
;
496 /* trailing space is always eliminated */
499 dynstr_append(&d
, c
);
502 dynstr_append(&d
, c
);
506 dynstr_terminate(&d
);
510 /** @brief Match cookie separator characters
512 * This is a subset of the RFC2616 specials, and technically is in breach of
513 * the specification. However rejecting (in particular) slashes is
514 * unreasonably strict and has broken at least one (admittedly somewhat
515 * obscure) browser, so we're more forgiving.
517 static int cookie_separator(int c
) {
534 /** @brief Match cookie value separator characters
536 * Same as cookie_separator() but allows for @c = in cookie values.
538 static int cookie_value_separator(int c
) {
554 /** @brief Parse a RFC2109 Cookie: header
555 * @param s Header field value
556 * @param cd Where to store result
557 * @return 0 on success, non-0 on error
559 * See <a href="http://tools.ietf.org/html/rfc2109">RFC 2109</a>.
561 int parse_cookie(const char *s
,
562 struct cookiedata
*cd
) {
565 memset(cd
, 0, sizeof *cd
);
568 /* Skip separators */
569 if(*s
== ';' || *s
== ',') {
574 if(!(s
= parsetoken(s
, &n
, cookie_separator
))) {
575 error(0, "parse_cookie: cannot parse attribute name");
580 error(0, "parse_cookie: did not find expected '='");
584 if(!(s
= mime_parse_word(s
, &v
, cookie_value_separator
))) {
585 error(0, "parse_cookie: cannot parse value for '%s'", n
);
589 /* Some bit of meta-information */
590 if(!strcmp(n
, "$Version"))
592 else if(!strcmp(n
, "$Path")) {
593 if(cd
->ncookies
> 0 && cd
->cookies
[cd
->ncookies
-1].path
== 0)
594 cd
->cookies
[cd
->ncookies
-1].path
= v
;
596 error(0, "redundant $Path in Cookie: header");
599 } else if(!strcmp(n
, "$Domain")) {
600 if(cd
->ncookies
> 0 && cd
->cookies
[cd
->ncookies
-1].domain
== 0)
601 cd
->cookies
[cd
->ncookies
-1].domain
= v
;
603 error(0, "redundant $Domain in Cookie: header");
608 /* It's a new cookie */
609 cd
->cookies
= xrealloc(cd
->cookies
,
610 (cd
->ncookies
+ 1) * sizeof (struct cookie
));
611 cd
->cookies
[cd
->ncookies
].name
= n
;
612 cd
->cookies
[cd
->ncookies
].value
= v
;
613 cd
->cookies
[cd
->ncookies
].path
= 0;
614 cd
->cookies
[cd
->ncookies
].domain
= 0;
618 if(*s
&& (*s
!= ',' && *s
!= ';')) {
619 error(0, "missing separator in Cookie: header");
626 /** @brief Find a named cookie
627 * @param cd Parse cookie data
628 * @param name Name of cookie
629 * @return Cookie structure or NULL if not found
631 const struct cookie
*find_cookie(const struct cookiedata
*cd
,
635 for(n
= 0; n
< cd
->ncookies
; ++n
)
636 if(!strcmp(cd
->cookies
[n
].name
, name
))
637 return &cd
->cookies
[n
];
641 /** @brief RFC822 quoting
642 * @param s String to quote
643 * @param force If non-0, always quote
644 * @return Possibly quoted string
646 char *quote822(const char *s
, int force
) {
652 /* See if we need to quote */
653 for(t
= s
; (c
= (unsigned char)*t
); ++t
) {
654 if(mime_tspecial(c
) || mime_http_separator(c
) || whitespace(c
))
665 dynstr_append(d
, '"');
666 for(t
= s
; (c
= (unsigned char)*t
); ++t
) {
667 if(c
== '"' || c
== '\\')
668 dynstr_append(d
, '\\');
671 dynstr_append(d
, '"');
676 /** @brief Return true if @p ptr points at trailing space */
677 static int is_trailing_space(const char *ptr
) {
678 if(*ptr
== ' ' || *ptr
== '\t') {
679 while(*ptr
== ' ' || *ptr
== '\t')
681 return *ptr
== '\n' || *ptr
== 0;
686 /** @brief Encoding text as quoted-printable
687 * @param text String to encode
688 * @return Encoded string
690 * See <a href="http://tools.ietf.org/html/rfc2045#section-6.7">RFC2045
693 char *mime_to_qp(const char *text
) {
695 int linelength
= 0; /* length of current line */
700 * 1. Anything except newline can be replaced with =%02X
701 * 2. Newline, 33-60 and 62-126 stand for themselves (i.e. not '=')
702 * 3. Non-trailing space/tab stand for themselves.
703 * 4. Output lines are limited to 76 chars, with =<newline> being used
704 * as a soft line break
705 * 5. Newlines aren't counted towards the 76 char limit.
708 const int c
= (unsigned char)*text
;
710 /* Newline stands as itself */
711 dynstr_append(d
, '\n');
713 } else if((c
>= 33 && c
<= 126 && c
!= '=')
714 || ((c
== ' ' || c
== '\t')
715 && !is_trailing_space(text
))) {
716 /* Things that can stand for themselves */
720 /* Anything else that needs encoding */
721 snprintf(buffer
, sizeof buffer
, "=%02X", c
);
722 dynstr_append_string(d
, buffer
);
726 if(linelength
> 73 && *text
&& *text
!= '\n') {
727 /* Next character might overflow 76 character limit if encoded, so we
728 * insert a soft break */
729 dynstr_append_string(d
, "=\n");
733 /* Ensure there is a final newline */
735 dynstr_append(d
, '\n');
741 /** @brief Encode text
742 * @param text Underlying UTF-8 text
743 * @param charsetp Where to store charset string
744 * @param encodingp Where to store encoding string
745 * @return Encoded text (might be @p text)
747 const char *mime_encode_text(const char *text
,
748 const char **charsetp
,
749 const char **encodingp
) {
752 /* See if there are in fact any non-ASCII characters */
753 for(ptr
= text
; *ptr
; ++ptr
)
754 if((unsigned char)*ptr
>= 128)
757 /* Plain old ASCII, no encoding required */
758 *charsetp
= "us-ascii";
763 *encodingp
= "quoted-printable";
764 return mime_to_qp(text
);