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;
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
155 static int iswordchar(int c
, int (*special
)(int)) {
156 return !(c
<= ' ' || c
> '~' || special(c
));
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
165 * A word is a token or a quoted-string.
167 static const char *parseword(const char *s
, char **valuep
,
168 int (*special
)(int)) {
169 struct dynstr value
[1];
175 while((c
= *s
++) != '"') {
178 if(!(c
= *s
++)) return 0;
180 dynstr_append(value
, c
);
186 if(!iswordchar((unsigned char)*s
, special
))
189 while(iswordchar((unsigned char)*s
, special
))
190 dynstr_append(value
, *s
++);
192 dynstr_terminate(value
);
193 *valuep
= value
->vec
;
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
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
);
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))) 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;
238 dynstr_init(¶metername
);
240 if(!(s
= skipwhite(s
, 1))) return -1;
242 while(*s
&& !tspecial(*s
) && !whitespace(*s
))
243 dynstr_append(¶metername
, 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
, ¶metervalue
, tspecial
))) return -1;
248 if(!(s
= skipwhite(s
, 1))) return -1;
249 dynstr_terminate(¶metername
);
250 kvp_set(¶meters
, parametername
.vec
, parametervalue
);
252 dynstr_terminate(&type
);
254 *parametersp
= parameters
;
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
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.
269 const char *mime_parse(const char *s
,
270 int (*callback
)(const char *name
, const char *value
,
273 struct dynstr name
, value
;
276 while(*s
&& !iscrlf(s
)) {
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;
284 while(*s
&& !(*s
== '\n' && !(s
[1] == ' ' || s
[1] == '\t')))
285 dynstr_append(&value
, *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
);
294 if(callback(name
.vec
, value
.vec
, u
)) return 0;
298 if(!strcmp(cte
, "base64")) return mime_base64(s
, 0);
299 if(!strcmp(cte
, "quoted-printable")) return mime_qp(s
);
304 /** @brief Match the boundary string */
305 static int isboundary(const char *ptr
, const char *boundary
, size_t bl
) {
306 return (ptr
[0] == '-'
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))));
315 /** @brief Match the final boundary string */
316 static int isfinal(const char *ptr
, const char *boundary
, size_t bl
) {
317 return (ptr
[0] == '-'
319 && !strncmp(ptr
+ 2, boundary
, bl
)
320 && ptr
[bl
+ 2] == '-'
321 && ptr
[bl
+ 3] == '-'
322 && (iscrlf(ptr
+ bl
+ 4) || *(ptr
+ bl
+ 4) == 0));
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
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.
336 int mime_multipart(const char *s
,
337 int (*callback
)(const char *s
, void *u
),
338 const char *boundary
,
340 size_t bl
= strlen(boundary
);
341 const char *start
, *e
;
344 /* We must start with a boundary string */
345 if(!isboundary(s
, boundary
, bl
))
347 /* Keep going until we hit a final boundary */
348 while(!isfinal(s
, boundary
, bl
)) {
349 s
= strstr(s
, "\r\n") + 2;
351 while(!isboundary(s
, boundary
, bl
)) {
352 if(!(e
= strstr(s
, "\r\n")))
356 if((ret
= callback(xstrndup(start
,
357 s
== start ?
0 : s
- start
- 2),
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
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>.
374 int mime_rfc2388_content_disposition(const char *s
,
376 char **parameternamep
,
377 char **parametervaluep
) {
378 struct dynstr disposition
, parametername
;
380 dynstr_init(&disposition
);
381 if(!(s
= skipwhite(s
, 1))) 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;
388 dynstr_init(¶metername
);
390 if(!(s
= skipwhite(s
, 1))) return -1;
392 while(*s
&& !tspecial(*s
) && !whitespace(*s
))
393 dynstr_append(¶metername
, 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(¶metername
);
400 *parameternamep
= parametername
.vec
;
402 *parametervaluep
= *parameternamep
= 0;
403 dynstr_terminate(&disposition
);
404 *dispositionp
= disposition
.vec
;
408 /** @brief Convert MIME quoted-printable
409 * @param s Quoted-printable data
410 * @return Decoded data
412 * See <a href="http://tools.ietf.org/html/rfc2045#section-6.7">RFC 2045
415 char *mime_qp(const char *s
) {
424 if((a
= unhexdigitq(s
[0])) != -1
425 && (b
= unhexdigitq(s
[1])) != -1) {
426 dynstr_append(&d
, a
* 16 + b
);
430 while(*t
== ' ' || *t
== '\t') ++t
;
432 /* soft line break */
441 while(*t
== ' ' || *t
== '\t') ++t
;
443 /* trailing space is always eliminated */
446 dynstr_append(&d
, c
);
449 dynstr_append(&d
, c
);
453 dynstr_terminate(&d
);
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
462 * See <a href="http://tools.ietf.org/html/rfc2109">RFC 2109</a>.
464 int parse_cookie(const char *s
,
465 struct cookiedata
*cd
) {
468 memset(cd
, 0, sizeof *cd
);
471 /* Skip separators */
472 if(*s
== ';' || *s
== ',') {
477 if(!(s
= parsetoken(s
, &n
, http_separator
))) return -1;
479 if(*s
++ != '=') return -1;
481 if(!(s
= parseword(s
, &v
, http_separator
))) return -1;
483 /* Some bit of meta-information */
484 if(!strcmp(n
, "$Version"))
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
;
490 error(0, "redundant $Path in Cookie: header");
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
;
497 error(0, "redundant $Domain in Cookie: header");
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;
512 if(*s
&& (*s
!= ',' && *s
!= ';')) {
513 error(0, "missing separator in Cookie: header");
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
525 const struct cookie
*find_cookie(const struct cookiedata
*cd
,
529 for(n
= 0; n
< cd
->ncookies
; ++n
)
530 if(!strcmp(cd
->cookies
[n
].name
, name
))
531 return &cd
->cookies
[n
];
535 /** @brief RFC822 quoting
536 * @param s String to quote
537 * @param force If non-0, always quote
538 * @return Possibly quoted string
540 char *quote822(const char *s
, int 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
))
559 dynstr_append(d
, '"');
560 for(t
= s
; (c
= (unsigned char)*t
); ++t
) {
561 if(c
== '"' || c
== '\\')
562 dynstr_append(d
, '\\');
565 dynstr_append(d
, '"');
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')
575 return *ptr
== '\n' || *ptr
== 0;
580 /** @brief Encoding text as quoted-printable
581 * @param text String to encode
582 * @return Encoded string
584 * See <a href="http://tools.ietf.org/html/rfc2045#section-6.7">RFC2045
587 char *mime_to_qp(const char *text
) {
589 int linelength
= 0; /* length of current line */
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.
602 const int c
= (unsigned char)*text
;
604 /* Newline stands as itself */
605 dynstr_append(d
, '\n');
607 } else if((c
>= 33 && c
<= 126 && c
!= '=')
608 || ((c
== ' ' || c
== '\t')
609 && !is_trailing_space(text
))) {
610 /* Things that can stand for themselves */
614 /* Anything else that needs encoding */
615 snprintf(buffer
, sizeof buffer
, "=%02X", c
);
616 dynstr_append_string(d
, buffer
);
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");
627 /* Ensure there is a final newline */
629 dynstr_append(d
, '\n');
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)
641 const char *mime_encode_text(const char *text
,
642 const char **charsetp
,
643 const char **encodingp
) {
646 /* See if there are in fact any non-ASCII characters */
647 for(ptr
= text
; *ptr
; ++ptr
)
648 if((unsigned char)*ptr
>= 128)
651 /* Plain old ASCII, no encoding required */
652 *charsetp
= "us-ascii";
657 *encodingp
= "quoted-printable";
658 return mime_to_qp(text
);