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>
19 #include "fetchmail.h"
21 static unsigned char unhex(unsigned char c)
23 if ((c >= '0') && (c <= '9'))
25 else if ((c >= 'A') && (c <= 'F'))
26 return (c - 'A' + 10);
27 else if ((c >= 'a') && (c <= 'f'))
28 return (c - 'a' + 10);
33 static int qp_char(unsigned char c1, unsigned char c2, unsigned char *c_out)
38 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;
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 + strlen(MIMEHDR_INIT);
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;
254 * Delimiter for multipart messages. RFC 2046 states that this must
255 * NEVER be longer than 70 characters. Add 3 for the two hyphens
256 * at the beginning, and a terminating null.
258 #define MAX_DELIM_LEN 70
259 static unsigned char MultipartDelimiter[MAX_DELIM_LEN+3];
262 /* This string replaces the "Content-Transfer-Encoding: quoted-printable"
263 * string in all headers, including those in body-parts. The replacement
264 * must be no longer than the original string.
266 static const char ENC8BIT[] = "Content-Transfer-Encoding: 8bit";
267 static void SetEncoding8bit(unsigned char *XferEncOfs)
271 if (XferEncOfs != NULL) {
272 memcpy(XferEncOfs, ENC8BIT, strlen(ENC8BIT));
274 /* If anything left, in this header, replace with whitespace */
275 for (p=XferEncOfs+strlen(ENC8BIT); (*p >= ' '); p++) *p=' ';
279 static char *GetBoundary(char *CntType)
284 /* Find the "boundary" delimiter. It must be preceded with a ';'
285 * and optionally some whitespace.
289 p2 = strchr(p1, ';');
291 for (p2++; isspace(*p2); p2++);
294 } while ((p1) && (strncasecmp(p1, "boundary", 8) != 0));
297 /* No boundary delimiter */
300 /* Skip "boundary", whitespace and '='; check that we do have a '=' */
301 for (p1+=8, flag=0; (isspace(*p1) || (*p1 == '=')); p1++)
302 flag |= (*p1 == '=');
306 /* Find end of boundary delimiter string */
308 /* The delimiter is inside quotes */
310 p2 = strchr(p1, '\"');
312 return NULL; /* No closing '"' !?! */
315 /* There might be more text after the "boundary" string. */
316 p2 = strchr(p1, ';'); /* Safe - delimiter with ';' must be in quotes */
319 /* Zero-terminate the boundary string */
323 return (p1 && strlen(p1)) ? p1 : NULL;
328 * This routine does three things:
329 * 1) It determines - based on the message headers - whether the
330 * message body is a MIME message that may hold 8 bit data.
331 * - A message that has a "quoted-printable" or "8bit" transfer
332 * encoding is assumed to contain 8-bit data (when decoded).
333 * - A multipart message is assumed to contain 8-bit data
334 * when decoded (there might be quoted-printable body-parts).
335 * - All other messages are assumed NOT to include 8-bit data.
336 * 2) It determines the delimiter-string used in multi-part message
338 * 3) It sets the initial values of the CurrEncodingIsQP and BodyState
339 * variables, from the header contents.
341 * The return value is a bitmask.
343 int MimeBodyType(unsigned char *hdrs, int WantDecode)
345 unsigned char *NxtHdr = hdrs;
346 unsigned char *XferEnc, *XferEncOfs, *CntType, *MimeVer, *p;
347 int HdrsFound = 0; /* We only look for three headers */
348 int BodyType; /* Return value */
350 /* Setup for a standard (no MIME, no QP, 7-bit US-ASCII) message */
351 MultipartDelimiter[0] = '\0';
352 CurrEncodingIsQP = 0;
353 BodyState = S_BODY_DATA;
356 /* Just in case ... */
360 XferEnc = XferEncOfs = CntType = MimeVer = NULL;
363 if (strncasecmp("Content-Transfer-Encoding:", NxtHdr, 26) == 0) {
367 xalloca(XferEnc, char *, strlen(p) + 1);
372 else if (strncasecmp("Content-Type:", NxtHdr, 13) == 0) {
374 * This one is difficult. We cannot use the standard
375 * nxtaddr() routine, since the boundary-delimiter is
376 * (probably) enclosed in quotes - and thus appears
377 * as an rfc822 comment, and nxtaddr() "eats" up any
378 * spaces in the delimiter. So, we have to do this
382 /* Skip the "Content-Type:" part and whitespace after it */
383 for (NxtHdr += 13; ((*NxtHdr == ' ') || (*NxtHdr == '\t')); NxtHdr++);
386 * Get the full value of the Content-Type header;
387 * it might span multiple lines. So search for
388 * a newline char, but ignore those that have a
389 * have a TAB or space just after the NL (continued
394 p=strchr((p+1),'\n');
395 } while ( (p != NULL) && ((*(p+1) == '\t') || (*(p+1) == ' ')) );
396 if (p == NULL) p = NxtHdr + strlen(NxtHdr);
398 xalloca(CntType, char *, p-NxtHdr+2);
399 strncpy(CntType, NxtHdr, (p-NxtHdr));
400 *(CntType+(p-NxtHdr)) = '\0';
403 else if (strncasecmp("MIME-Version:", NxtHdr, 13) == 0) {
406 xalloca(MimeVer, char *, strlen(p) + 1);
412 NxtHdr = (strchr(NxtHdr, '\n'));
413 if (NxtHdr != NULL) NxtHdr++;
414 } while ((NxtHdr != NULL) && (*NxtHdr) && (HdrsFound != 3));
417 /* Done looking through the headers, now check what they say */
418 if ((MimeVer != NULL) && (strcmp(MimeVer, "1.0") == 0)) {
420 /* Check Content-Type to see if this is a multipart message */
421 if ( (CntType != NULL) &&
422 ((strncasecmp(CntType, "multipart/", 10) == 0) ||
423 (strncasecmp(CntType, "message/", 8) == 0)) ) {
425 char *p1 = GetBoundary(CntType);
428 /* The actual delimiter is "--" followed by
429 the boundary string */
430 strcpy(MultipartDelimiter, "--");
431 strncat(MultipartDelimiter, p1, MAX_DELIM_LEN);
432 BodyType = (MSG_IS_8BIT | MSG_NEEDS_DECODE);
437 * Check Content-Transfer-Encoding, but
438 * ONLY for non-multipart messages (BodyType == 0).
440 if ((XferEnc != NULL) && (BodyType == 0)) {
441 if (strcasecmp(XferEnc, "quoted-printable") == 0) {
442 CurrEncodingIsQP = 1;
443 BodyType = (MSG_IS_8BIT | MSG_NEEDS_DECODE);
445 SetEncoding8bit(XferEncOfs);
448 else if (strcasecmp(XferEnc, "7bit") == 0) {
449 CurrEncodingIsQP = 0;
450 BodyType = (MSG_IS_7BIT);
452 else if (strcasecmp(XferEnc, "8bit") == 0) {
453 CurrEncodingIsQP = 0;
454 BodyType = (MSG_IS_8BIT);
465 * Decode one line of data containing QP data.
466 * Return flag set if this line ends with a soft line-break.
467 * 'bufp' is modified to point to the end of the output buffer.
469 static int DoOneQPLine(unsigned char **bufp, int collapsedoubledot)
471 unsigned char *buf = *bufp;
472 unsigned char *p_in, *p_out, *p;
477 if (collapsedoubledot && (strncmp(buf, "..", 2) == 0))
480 for (p_out = buf; (*p_in); ) {
481 p = strchr(p_in, '=');
483 /* No more QP data, just move remainder into place */
485 memmove(p_out, p_in, n);
486 p_in += n; p_out += n;
490 /* There are some uncoded chars at the beginning. */
492 memmove(p_out, p_in, n);
497 case '\0': case '\r': case '\n':
498 /* Soft line break, skip '=' */
500 if (*p_in == '\r') p_in++;
501 if (*p_in == '\n') p_in++;
506 /* There is a QP encoded byte */
507 if (qp_char(*(p+1), *(p+2), p_out) == 0) {
511 /* Invalid QP data - pass through unchanged. */
527 /* This is called once per line in the message body. We need to scan
528 * all lines in the message body for the multipart delimiter string,
529 * and handle any body-part headers in such messages (these can toggle
530 * qp-decoding on and off).
532 * Note: Messages that are NOT multipart-messages go through this
533 * routine quickly, since BodyState will always be S_BODY_DATA,
534 * and MultipartDelimiter is NULL.
536 * Return flag set if this line ends with a soft line-break.
537 * 'bufp' is modified to point to the end of the output buffer.
540 int UnMimeBodyline(unsigned char **bufp, int collapsedoubledot)
542 unsigned char *buf = *bufp;
547 UnMimeHeader(buf); /* Headers in body-parts can be encoded, too! */
548 if (strncasecmp("Content-Transfer-Encoding:", buf, 26) == 0) {
551 XferEnc = nxtaddr(buf);
552 if ((XferEnc != NULL) && (strcasecmp(XferEnc, "quoted-printable") == 0)) {
553 CurrEncodingIsQP = 1;
554 SetEncoding8bit(buf);
557 else if ((*buf == '\0') || (*buf == '\n') || (strcmp(buf, "\r\n") == 0))
558 BodyState = S_BODY_DATA;
560 *bufp = (buf + strlen(buf));
564 if ((*MultipartDelimiter) &&
565 (strncmp(buf, MultipartDelimiter, strlen(MultipartDelimiter)) == 0)) {
566 BodyState = S_BODY_HDR;
567 CurrEncodingIsQP = 0;
570 if (CurrEncodingIsQP)
571 ret = DoOneQPLine(bufp, collapsedoubledot);
573 *bufp = (buf + strlen(buf));
585 char *program_name = "unmime";
587 #define BUFSIZE_INCREMENT 4096
590 #define DBG_FWRITE(B,L,BS,FD) fwrite(B, L, BS, FD)
592 #define DBG_FWRITE(B,L,BS,FD)
595 int main(int argc, char *argv[])
597 unsigned int BufSize;
598 unsigned char *buffer, *buf_p;
599 int nl_count, i, bodytype;
603 FILE *fd_orig, *fd_conv;
607 sprintf(fnam, "/tmp/i_unmime.%x", pid);
608 fd_orig = fopen(fnam, "w");
609 sprintf(fnam, "/tmp/o_unmime.%x", pid);
610 fd_conv = fopen(fnam, "w");
613 BufSize = BUFSIZE_INCREMENT; /* Initial size of buffer */
614 buf_p = buffer = (unsigned char *) xmalloc(BufSize);
618 i = fread(buf_p, 1, 1, stdin);
633 if ((buf_p - buffer) == BufSize) {
634 /* Buffer is full! Get more room. */
635 buffer = xrealloc(buffer, BufSize+BUFSIZE_INCREMENT);
636 buf_p = buffer + BufSize;
637 BufSize += BUFSIZE_INCREMENT;
639 } while ((i > 0) && (nl_count < 2));
642 DBG_FWRITE(buffer, strlen(buffer), 1, fd_orig);
644 UnMimeHeader(buffer);
645 bodytype = MimeBodyType(buffer, 1);
648 fwrite(buffer, i, 1, stdout);
649 DBG_FWRITE(buffer, i, 1, fd_conv);
652 buf_p = (buffer - 1);
655 i = fread(buf_p, 1, 1, stdin);
656 } while ((i == 1) && (*buf_p != '\n'));
659 DBG_FWRITE(buf, (buf_p - buffer), 1, fd_orig);
661 if (buf_p > buffer) {
662 if (bodytype & MSG_NEEDS_DECODE) {
664 UnMimeBodyline(&buf_p, 0);
666 fwrite(buffer, (buf_p - buffer), 1, stdout);
667 DBG_FWRITE(buffer, (buf_p - buffer), 1, fd_conv);
669 } while (buf_p > buffer);