4 * This module contains decoding routines for converting
5 * quoted-printable data into pure 8-bit data, in MIME
8 * By Henrik Storner <storner@image.dk>
10 * Configuration file support for fetchmail 4.3.8 by
11 * Frank Damgaard <frda@post3.tele.dk>
20 #include "fetchmail.h"
22 static unsigned char unhex(unsigned char c)
24 if ((c >= '0') && (c <= '9'))
26 else if ((c >= 'A') && (c <= 'F'))
27 return (c - 'A' + 10);
28 else if ((c >= 'a') && (c <= 'f'))
29 return (c - 'a' + 10);
34 static int qp_char(unsigned char c1, unsigned char c2, unsigned char *c_out)
39 if ((c1 > 15) || (c2 > 15))
49 * Routines to decode MIME QP-encoded headers, as per RFC 2047.
52 /* States of the decoding state machine */
53 #define S_COPY_PLAIN 0 /* Just copy, but watch for the QP flag */
54 #define S_SKIP_MIMEINIT 1 /* Get the encoding, and skip header */
55 #define S_COPY_MIME 2 /* Decode a sequence of coded characters */
57 static const char MIMEHDR_INIT[] = "=?"; /* Start of coded sequence */
58 static const char MIMEHDR_END[] = "?="; /* End of coded sequence */
60 void UnMimeHeader(unsigned char *hdr)
62 /* Decode a buffer containing data encoded according to RFC
63 * 2047. This only handles content-transfer-encoding; conversion
64 * between character sets is not implemented. In other words: We
65 * assume the charsets used can be displayed by your mail program
69 /* Note: Decoding is done "in-situ", i.e. without using an
70 * additional buffer for temp. storage. This is possible, since the
71 * decoded string will always be shorter than the encoded string,
72 * due to the en- coding scheme.
75 int state = S_COPY_PLAIN;
76 unsigned char *p_in, *p_out, *p;
77 unsigned char enc = '\0'; /* initialization pacifies -Wall */
80 /* Speed up in case this is not a MIME-encoded header */
81 p = strstr(hdr, MIMEHDR_INIT);
83 return; /* No MIME header */
85 /* Loop through the buffer.
86 * p_in : Next char to be processed.
87 * p_out: Where to put the next processed char
88 * enc : Encoding used (usually, 'q' = quoted-printable)
90 for (p_out = p_in = hdr; (*p_in); ) {
93 p = strstr(p_in, MIMEHDR_INIT);
96 * No more coded data in buffer,
97 * just move remainder into place.
99 i = strlen(p_in); /* How much left */
100 memmove(p_out, p_in, i);
101 p_in += i; p_out += i;
104 /* MIME header init found at location p */
106 /* There are some uncoded chars at the beginning. */
108 memmove(p_out, p_in, i);
112 state = S_SKIP_MIMEINIT;
116 case S_SKIP_MIMEINIT:
117 /* Mime type definition: "charset?encoding?" */
118 p = strchr(p_in, '?');
120 /* p_in .. (p-1) holds the charset */
122 /* *(p+1) is the transfer encoding, *(p+2) must be a '?' */
124 enc = tolower(*(p+1));
129 state = S_COPY_PLAIN;
132 state = S_COPY_PLAIN; /* Invalid data */
136 p = strstr(p_in, MIMEHDR_END); /* Find end of coded data */
137 if (p == NULL) p = p_in + strlen(p_in);
138 for (; (p_in < p); ) {
139 /* Decode all encoded data */
142 /* Decode one char qp-coded at (p_in+1) and (p_in+2) */
143 if (qp_char(*(p_in+1), *(p_in+2), p_out) == 0)
146 /* Invalid QP data - pass through unchanged. */
151 else if (*p_in == '_') {
153 * RFC 2047: '_' inside encoded word represents 0x20.
154 * NOT a space - always the value 0x20.
166 else if (enc == 'b') {
167 /* Decode base64 encoded data */
171 delimsave = *p; *p = '\r';
172 decoded_count = from64tobits(p_out, p_in);
174 if (decoded_count > 0)
175 p_out += decoded_count;
186 p_in += 2; /* Skip the MIMEHDR_END delimiter */
189 * We've completed decoding one encoded sequence. But another
190 * may follow immediately, in which case whitespace before the
191 * new MIMEHDR_INIT delimiter must be discarded.
192 * See if that is the case
194 p = strstr(p_in, MIMEHDR_INIT);
195 state = S_COPY_PLAIN;
198 * There is more MIME data later on. Is there
199 * whitespace only before the delimiter?
204 for (q=p_in; (wsp_only && (q < p)); q++)
205 wsp_only = isspace(*q);
209 * Whitespace-only before the MIME delimiter. OK,
210 * just advance p_in to past the new MIMEHDR_INIT,
211 * and prepare to process the new MIME charset/encoding
214 p_in = p + sizeof(MIMEHDR_INIT) - 1;
215 state = S_SKIP_MIMEINIT;
228 * Routines for decoding body-parts of a message.
230 * Since the "fetch" part of fetchmail gets a message body
231 * one line at a time, we need to maintain some state variables
232 * across multiple invokations of the UnMimeBodyline() routine.
233 * The driver routine should call MimeBodyType() when all
234 * headers have been received, and then UnMimeBodyline() for
235 * every line in the message body.
238 #define S_BODY_DATA 0
242 * Flag indicating if we are currently processing
243 * the headers or the body of a (multipart) message.
245 static int BodyState = S_BODY_DATA;
248 * Flag indicating if we are in the process of decoding
249 * a quoted-printable body part.
251 static int CurrEncodingIsQP = 0;
252 static int CurrTypeNeedsDecode = 0;
255 * Delimiter for multipart messages. RFC 2046 states that this must
256 * NEVER be longer than 70 characters. Add 3 for the two hyphens
257 * at the beginning, and a terminating null.
259 #define MAX_DELIM_LEN 70
260 static unsigned char MultipartDelimiter[MAX_DELIM_LEN+3];
263 /* This string replaces the "Content-Transfer-Encoding: quoted-printable"
264 * string in all headers, including those in body-parts. The replacement
265 * must be no longer than the original string.
267 static const char ENC8BIT[] = "Content-Transfer-Encoding: 8bit";
268 static void SetEncoding8bit(unsigned char *XferEncOfs)
272 if (XferEncOfs != NULL) {
273 memcpy(XferEncOfs, ENC8BIT, sizeof(ENC8BIT) - 1);
275 /* If anything left, in this header, replace with whitespace */
276 for (p=XferEncOfs+sizeof(ENC8BIT)-1; (*p >= ' '); p++) *p=' ';
280 static char *GetBoundary(char *CntType)
285 /* Find the "boundary" delimiter. It must be preceded with a ';'
286 * and optionally some whitespace.
290 p2 = strchr(p1, ';');
292 for (p2++; isspace(*p2); p2++);
295 } while ((p1) && (strncasecmp(p1, "boundary", 8) != 0));
298 /* No boundary delimiter */
301 /* Skip "boundary", whitespace and '='; check that we do have a '=' */
302 for (p1+=8, flag=0; (isspace(*p1) || (*p1 == '=')); p1++)
303 flag |= (*p1 == '=');
307 /* Find end of boundary delimiter string */
309 /* The delimiter is inside quotes */
311 p2 = strchr(p1, '\"');
313 return NULL; /* No closing '"' !?! */
316 /* There might be more text after the "boundary" string. */
317 p2 = strchr(p1, ';'); /* Safe - delimiter with ';' must be in quotes */
320 /* Zero-terminate the boundary string */
324 return (p1 && strlen(p1)) ? p1 : NULL;
328 int CheckContentType(char *CntType)
331 * Static array of Content-Type's for which we will do
332 * quoted-printable decoding, if requested.
333 * It is probably wise to do this only on known text-only types;
334 * be really careful if you change this.
337 static char *DecodedTypes[] = {
338 "text/", /* Will match ALL content-type's starting with 'text/' */
346 /* If no Content-Type header, it isn't MIME - don't touch it */
347 if (CntType == NULL) return 0;
349 /* Skip whitespace, if any */
350 for (; isspace(*p); p++) ;
354 (strncasecmp(p, DecodedTypes[i], strlen(DecodedTypes[i]))));
357 return (DecodedTypes[i] != NULL);
362 * This routine does three things:
363 * 1) It determines - based on the message headers - whether the
364 * message body is a MIME message that may hold 8 bit data.
365 * - A message that has a "quoted-printable" or "8bit" transfer
366 * encoding is assumed to contain 8-bit data (when decoded).
367 * - A multipart message is assumed to contain 8-bit data
368 * when decoded (there might be quoted-printable body-parts).
369 * - All other messages are assumed NOT to include 8-bit data.
370 * 2) It determines the delimiter-string used in multi-part message
372 * 3) It sets the initial values of the CurrEncodingIsQP,
373 * CurrTypeNeedsDecode, and BodyState variables, from the header
376 * The return value is a bitmask.
378 int MimeBodyType(unsigned char *hdrs, int WantDecode)
380 unsigned char *NxtHdr = hdrs;
381 unsigned char *XferEnc, *XferEncOfs, *CntType, *MimeVer, *p;
382 int HdrsFound = 0; /* We only look for three headers */
383 int BodyType; /* Return value */
385 /* Setup for a standard (no MIME, no QP, 7-bit US-ASCII) message */
386 MultipartDelimiter[0] = '\0';
387 CurrEncodingIsQP = CurrTypeNeedsDecode = 0;
388 BodyState = S_BODY_DATA;
391 /* Just in case ... */
395 XferEnc = XferEncOfs = CntType = MimeVer = NULL;
398 if (strncasecmp("Content-Transfer-Encoding:", NxtHdr, 26) == 0) {
402 xalloca(XferEnc, char *, strlen(p) + 1);
407 else if (strncasecmp("Content-Type:", NxtHdr, 13) == 0) {
409 * This one is difficult. We cannot use the standard
410 * nxtaddr() routine, since the boundary-delimiter is
411 * (probably) enclosed in quotes - and thus appears
412 * as an rfc822 comment, and nxtaddr() "eats" up any
413 * spaces in the delimiter. So, we have to do this
417 /* Skip the "Content-Type:" part and whitespace after it */
418 for (NxtHdr += 13; ((*NxtHdr == ' ') || (*NxtHdr == '\t')); NxtHdr++);
421 * Get the full value of the Content-Type header;
422 * it might span multiple lines. So search for
423 * a newline char, but ignore those that have a
424 * have a TAB or space just after the NL (continued
429 p=strchr((p+1),'\n');
430 } while ( (p != NULL) && ((*(p+1) == '\t') || (*(p+1) == ' ')) );
431 if (p == NULL) p = NxtHdr + strlen(NxtHdr);
433 xalloca(CntType, char *, p-NxtHdr+2);
434 strncpy(CntType, NxtHdr, (p-NxtHdr));
435 *(CntType+(p-NxtHdr)) = '\0';
438 else if (strncasecmp("MIME-Version:", NxtHdr, 13) == 0) {
441 xalloca(MimeVer, char *, strlen(p) + 1);
447 NxtHdr = (strchr(NxtHdr, '\n'));
448 if (NxtHdr != NULL) NxtHdr++;
449 } while ((NxtHdr != NULL) && (*NxtHdr) && (HdrsFound != 3));
452 /* Done looking through the headers, now check what they say */
453 if ((MimeVer != NULL) && (strcmp(MimeVer, "1.0") == 0)) {
455 CurrTypeNeedsDecode = CheckContentType(CntType);
457 /* Check Content-Type to see if this is a multipart message */
458 if ( (CntType != NULL) &&
459 ((strncasecmp(CntType, "multipart/mixed", 16) == 0) ||
460 (strncasecmp(CntType, "message/", 8) == 0)) ) {
462 char *p1 = GetBoundary(CntType);
465 /* The actual delimiter is "--" followed by
466 the boundary string */
467 strcpy(MultipartDelimiter, "--");
468 strncat(MultipartDelimiter, p1, MAX_DELIM_LEN);
469 BodyType = (MSG_IS_8BIT | MSG_NEEDS_DECODE);
474 * Check Content-Transfer-Encoding, but
475 * ONLY for non-multipart messages (BodyType == 0).
477 if ((XferEnc != NULL) && (BodyType == 0)) {
478 if (strcasecmp(XferEnc, "quoted-printable") == 0) {
479 CurrEncodingIsQP = 1;
480 BodyType = (MSG_IS_8BIT | MSG_NEEDS_DECODE);
481 if (WantDecode && CurrTypeNeedsDecode) {
482 SetEncoding8bit(XferEncOfs);
485 else if (strcasecmp(XferEnc, "7bit") == 0) {
486 CurrEncodingIsQP = 0;
487 BodyType = (MSG_IS_7BIT);
489 else if (strcasecmp(XferEnc, "8bit") == 0) {
490 CurrEncodingIsQP = 0;
491 BodyType = (MSG_IS_8BIT);
502 * Decode one line of data containing QP data.
503 * Return flag set if this line ends with a soft line-break.
504 * 'bufp' is modified to point to the end of the output buffer.
506 static int DoOneQPLine(unsigned char **bufp, flag delimited, flag issoftline)
508 unsigned char *buf = *bufp;
509 unsigned char *p_in, *p_out, *p;
514 * Special case: line consists of a single =2E and messages are
515 * dot-terminated. Line has to be dot-stuffed after decoding.
517 if (delimited && !issoftline && buf[0]=='=' && !strncmp(*bufp, "=2E\r\n", 5))
519 strcpy(buf, "..\r\n");
525 if (delimited && issoftline && (strncmp(buf, "..", 2) == 0))
528 for (p_out = buf; (*p_in); ) {
529 p = strchr(p_in, '=');
531 /* No more QP data, just move remainder into place */
533 memmove(p_out, p_in, n);
534 p_in += n; p_out += n;
538 /* There are some uncoded chars at the beginning. */
540 memmove(p_out, p_in, n);
545 case '\0': case '\r': case '\n':
546 /* Soft line break, skip '=' */
548 if (*p_in == '\r') p_in++;
549 if (*p_in == '\n') p_in++;
554 /* There is a QP encoded byte */
555 if (qp_char(*(p+1), *(p+2), p_out) == 0) {
559 /* Invalid QP data - pass through unchanged. */
575 /* This is called once per line in the message body. We need to scan
576 * all lines in the message body for the multipart delimiter string,
577 * and handle any body-part headers in such messages (these can toggle
578 * qp-decoding on and off).
580 * Note: Messages that are NOT multipart-messages go through this
581 * routine quickly, since BodyState will always be S_BODY_DATA,
582 * and MultipartDelimiter is NULL.
584 * Return flag set if this line ends with a soft line-break.
585 * 'bufp' is modified to point to the end of the output buffer.
588 int UnMimeBodyline(unsigned char **bufp, flag delimited, flag softline)
590 unsigned char *buf = *bufp;
595 UnMimeHeader(buf); /* Headers in body-parts can be encoded, too! */
596 if ((*buf == '\0') || (*buf == '\n') || (strcmp(buf, "\r\n") == 0)) {
597 BodyState = S_BODY_DATA;
599 else if (strncasecmp("Content-Transfer-Encoding:", buf, 26) == 0) {
602 XferEnc = nxtaddr(buf);
603 if ((XferEnc != NULL) && (strcasecmp(XferEnc, "quoted-printable") == 0)) {
604 CurrEncodingIsQP = 1;
607 * Hmm ... we cannot be really sure that CurrTypeNeedsDecode
608 * has been set - we may not have seen the Content-Type header
609 * yet. But *usually* the Content-Type header comes first, so
610 * this will work. And there is really no way of doing it
611 * "right" as long as we stick with the line-by-line processing.
613 if (CurrTypeNeedsDecode)
614 SetEncoding8bit(buf);
617 else if (strncasecmp("Content-Type:", buf, 13) == 0) {
618 CurrTypeNeedsDecode = CheckContentType(nxtaddr(buf));
621 *bufp = (buf + strlen(buf));
625 if ((*MultipartDelimiter) &&
626 (strncmp(buf, MultipartDelimiter, strlen(MultipartDelimiter)) == 0)) {
627 BodyState = S_BODY_HDR;
628 CurrEncodingIsQP = CurrTypeNeedsDecode = 0;
631 if (CurrEncodingIsQP && CurrTypeNeedsDecode)
632 ret = DoOneQPLine(bufp, delimited, softline);
634 *bufp = (buf + strlen(buf));
646 char *program_name = "unmime";
649 #define BUFSIZE_INCREMENT 4096
652 #define DBG_FWRITE(B,L,BS,FD) fwrite(B, L, BS, FD)
654 #define DBG_FWRITE(B,L,BS,FD)
657 int main(int argc, char *argv[])
659 unsigned int BufSize;
660 unsigned char *buffer, *buf_p;
661 int nl_count, i, bodytype;
665 FILE *fd_orig, *fd_conv;
669 sprintf(fnam, "/tmp/i_unmime.%x", pid);
670 fd_orig = fopen(fnam, "w");
671 sprintf(fnam, "/tmp/o_unmime.%x", pid);
672 fd_conv = fopen(fnam, "w");
675 BufSize = BUFSIZE_INCREMENT; /* Initial size of buffer */
676 buf_p = buffer = (unsigned char *) xmalloc(BufSize);
680 i = fread(buf_p, 1, 1, stdin);
695 if ((buf_p - buffer) == BufSize) {
696 /* Buffer is full! Get more room. */
697 buffer = xrealloc(buffer, BufSize+BUFSIZE_INCREMENT);
698 buf_p = buffer + BufSize;
699 BufSize += BUFSIZE_INCREMENT;
701 } while ((i > 0) && (nl_count < 2));
704 DBG_FWRITE(buffer, strlen(buffer), 1, fd_orig);
706 UnMimeHeader(buffer);
707 bodytype = MimeBodyType(buffer, 1);
710 fwrite(buffer, i, 1, stdout);
711 DBG_FWRITE(buffer, i, 1, fd_conv);
714 buf_p = (buffer - 1);
717 i = fread(buf_p, 1, 1, stdin);
718 } while ((i == 1) && (*buf_p != '\n'));
721 DBG_FWRITE(buf, (buf_p - buffer), 1, fd_orig);
723 if (buf_p > buffer) {
724 if (bodytype & MSG_NEEDS_DECODE) {
726 UnMimeBodyline(&buf_p, 0);
728 fwrite(buffer, (buf_p - buffer), 1, stdout);
729 DBG_FWRITE(buffer, (buf_p - buffer), 1, fd_conv);
731 } while (buf_p > buffer);