1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2004 */
9 #ifdef WITH_CONTENT_SCAN /* entire file */
13 FILE *mime_stream = NULL;
14 uschar *mime_current_boundary = NULL;
16 /*************************************************
17 * set MIME anomaly level + text *
18 *************************************************/
20 /* Small wrapper to set the two expandables which
21 give info on detected "problems" in MIME
22 encodings. Those are defined in mime.h. */
25 mime_set_anomaly(int level, const char *text)
27 mime_anomaly_level = level;
28 mime_anomaly_text = CUS text;
32 /*************************************************
33 * decode quoted-printable chars *
34 *************************************************/
36 /* gets called when we hit a =
37 returns: new pointer position
40 -1 - soft line break, no char
45 mime_decode_qp_char(uschar *qp_p, int *c)
47 uschar *initial_pos = qp_p;
49 /* advance one char */
52 /* Check for two hex digits and decode them */
53 if (isxdigit(*qp_p) && isxdigit(qp_p[1]))
55 /* Do hex conversion */
56 *c = (isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10) <<4;
58 *c |= isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10;
62 /* tab or whitespace may follow just ignore it if it precedes \n */
63 while (*qp_p == '\t' || *qp_p == ' ' || *qp_p == '\r')
66 if (*qp_p == '\n') /* hit soft line break */
72 /* illegal char here */
78 /* just dump MIME part without any decoding */
80 mime_decode_asis(FILE* in, FILE* out, uschar* boundary)
82 ssize_t len, size = 0;
83 uschar buffer[MIME_MAX_LINE_LENGTH];
85 while(fgets(CS buffer, MIME_MAX_LINE_LENGTH, mime_stream) != NULL)
88 && Ustrncmp(buffer, "--", 2) == 0
89 && Ustrncmp((buffer+2), boundary, Ustrlen(boundary)) == 0
93 len = Ustrlen(buffer);
94 if (fwrite(buffer, 1, (size_t)len, out) < len)
102 /* decode base64 MIME part */
104 mime_decode_base64(FILE* in, FILE* out, uschar* boundary)
106 uschar ibuf[MIME_MAX_LINE_LENGTH], obuf[MIME_MAX_LINE_LENGTH];
108 ssize_t len, size = 0;
113 while (Ufgets(ibuf, MIME_MAX_LINE_LENGTH, in) != NULL)
116 && Ustrncmp(ibuf, "--", 2) == 0
117 && Ustrncmp((ibuf+2), boundary, Ustrlen(boundary)) == 0
121 for (ipos = ibuf ; *ipos != '\r' && *ipos != '\n' && *ipos != 0; ++ipos)
123 if (*ipos == '=') /* skip padding */
128 if (mime_b64[*ipos] == 128) /* skip bad characters */
130 mime_set_anomaly(MIME_ANOMALY_BROKEN_BASE64);
134 /* simple state-machine */
135 switch((bytestate++) & 3)
138 *opos = mime_b64[*ipos] << 2;
141 *opos |= mime_b64[*ipos] >> 4;
143 *opos = mime_b64[*ipos] << 4;
146 *opos |= mime_b64[*ipos] >> 2;
148 *opos = mime_b64[*ipos] << 6;
151 *opos |= mime_b64[*ipos];
157 /* something to write? */
161 if (fwrite(obuf, 1, len, out) != len) return -1; /* error */
163 /* copy incomplete last byte to start of obuf, where we continue */
164 if ((bytestate & 3) != 0)
170 /* write out last byte if it was incomplete */
173 if (fwrite(obuf, 1, 1, out) != 1) return -1;
181 /* decode quoted-printable MIME part */
183 mime_decode_qp(FILE* in, FILE* out, uschar* boundary)
185 uschar ibuf[MIME_MAX_LINE_LENGTH], obuf[MIME_MAX_LINE_LENGTH];
187 ssize_t len, size = 0;
189 while (fgets(CS ibuf, MIME_MAX_LINE_LENGTH, in) != NULL)
192 && Ustrncmp(ibuf, "--", 2) == 0
193 && Ustrncmp((ibuf+2), boundary, Ustrlen(boundary)) == 0
195 break; /* todo: check for missing boundary */
204 int decode_qp_result;
206 ipos = mime_decode_qp_char(ipos, &decode_qp_result);
208 if (decode_qp_result == -2)
210 /* Error from decoder. ipos is unchanged. */
211 mime_set_anomaly(MIME_ANOMALY_BROKEN_QP);
216 else if (decode_qp_result == -1)
218 else if (decode_qp_result >= 0)
220 *opos = decode_qp_result;
231 /* something to write? */
235 if (fwrite(obuf, 1, len, out) != len) return -1; /* error */
244 mime_get_decode_file(uschar *pname, uschar *fname)
249 filename = (uschar *)malloc(2048);
253 (void)string_format(filename, 2048, "%s/%s", pname, fname);
254 f = modefopen(filename,"wb+",SPOOL_MODE);
257 f = modefopen(fname,"wb+",SPOOL_MODE);
263 /* must find first free sequential filename */
267 (void)string_format(filename, 2048,
268 "%s/%s-%05u", pname, message_id, file_nr++);
272 result = stat(CS filename, &mystat);
273 } while(result != -1);
275 f = modefopen(filename, "wb+", SPOOL_MODE);
278 /* set expansion variable */
279 mime_decoded_filename = filename;
286 mime_decode(uschar **listptr)
289 uschar *list = *listptr;
291 uschar option_buffer[1024];
292 uschar decode_path[1024];
293 FILE *decode_file = NULL;
295 ssize_t size_counter = 0;
296 ssize_t (*decode_function)(FILE*, FILE*, uschar*);
298 if (mime_stream == NULL)
301 f_pos = ftell(mime_stream);
303 /* build default decode path (will exist since MBOX must be spooled up) */
304 (void)string_format(decode_path,1024,"%s/scan/%s",spool_directory,message_id);
306 /* try to find 1st option */
307 if ((option = string_nextinlist(&list, &sep,
309 sizeof(option_buffer))) != NULL)
311 /* parse 1st option */
312 if ( (Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0) )
313 /* explicitly no decoding */
316 if (Ustrcmp(option,"default") == 0)
317 /* explicit default path + file names */
320 if (option[0] == '/')
324 memset(&statbuf,0,sizeof(statbuf));
326 /* assume either path or path+file name */
327 if ( (stat(CS option, &statbuf) == 0) && S_ISDIR(statbuf.st_mode) )
328 /* is directory, use it as decode_path */
329 decode_file = mime_get_decode_file(option, NULL);
331 /* does not exist or is a file, use as full file name */
332 decode_file = mime_get_decode_file(NULL, option);
335 /* assume file name only, use default path */
336 decode_file = mime_get_decode_file(decode_path, option);
340 /* no option? patch default path */
342 decode_file = mime_get_decode_file(decode_path, NULL);
348 /* decode according to mime type */
350 !mime_content_transfer_encoding
351 ? mime_decode_asis /* no encoding, dump as-is */
352 : Ustrcmp(mime_content_transfer_encoding, "base64") == 0
354 : Ustrcmp(mime_content_transfer_encoding, "quoted-printable") == 0
356 : mime_decode_asis; /* unknown encoding type, just dump as-is */
358 size_counter = decode_function(mime_stream, decode_file, mime_current_boundary);
360 clearerr(mime_stream);
361 fseek(mime_stream, f_pos, SEEK_SET);
363 if (fclose(decode_file) != 0 || size_counter < 0)
366 /* round up to the next KiB */
367 mime_content_size = (size_counter + 1023) / 1024;
373 mime_get_header(FILE *f, uschar *header)
377 int header_value_mode = 0;
378 int header_open_brackets = 0;
383 if ((c = fgetc(f)) == EOF) break;
385 /* always skip CRs */
386 if (c == '\r') continue;
392 /* look if next char is '\t' or ' ' */
393 if ((c = fgetc(f)) == EOF) break;
394 if ( (c == '\t') || (c == ' ') ) continue;
397 /* end of the header, terminate with ';' */
402 /* skip control characters */
403 if (c < 32) continue;
405 if (header_value_mode)
407 /* --------- value mode ----------- */
408 /* skip leading whitespace */
409 if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
412 /* we have hit a non-whitespace char, start copying value data */
413 header_value_mode = 2;
415 if (c == '"') /* flip "quoted" mode */
416 header_value_mode = header_value_mode==2 ? 3 : 2;
418 /* leave value mode on unquoted ';' */
419 if (header_value_mode == 2 && c == ';') {
420 header_value_mode = 0;
422 /* -------------------------------- */
426 /* -------- non-value mode -------- */
427 /* skip whitespace + tabs */
428 if ( (c == ' ') || (c == '\t') )
432 /* quote next char. can be used
433 to escape brackets. */
434 if ((c = fgetc(f)) == EOF) break;
438 header_open_brackets++;
441 else if ((c == ')') && header_open_brackets)
443 header_open_brackets--;
446 else if ( (c == '=') && !header_open_brackets ) /* enter value mode */
447 header_value_mode = 1;
449 /* skip chars while we are in a comment */
450 if (header_open_brackets > 0)
452 /* -------------------------------- */
455 /* copy the char to the buffer */
456 header[num_copied++] = (uschar)c;
458 /* break if header buffer is full */
459 if (num_copied > MIME_MAX_HEADER_SIZE-1)
463 if ((num_copied > 0) && (header[num_copied-1] != ';'))
464 header[num_copied-1] = ';';
467 header[num_copied] = '\0';
469 /* return 0 for EOF or empty line */
470 if ((c == EOF) || (num_copied == 1))
478 mime_acl_check(uschar *acl, FILE *f, struct mime_boundary_context *context,
479 uschar **user_msgptr, uschar **log_msgptr)
482 uschar *header = NULL;
483 struct mime_boundary_context nested_context;
485 /* reserve a line buffer to work in */
486 if (!(header = (uschar *)malloc(MIME_MAX_HEADER_SIZE+1)))
488 log_write(0, LOG_PANIC,
489 "MIME ACL: can't allocate %d bytes of memory.", MIME_MAX_HEADER_SIZE+1);
493 /* Not actually used at the moment, but will be vital to fixing
494 * some RFC 2046 nonconformance later... */
495 nested_context.parent = context;
497 /* loop through parts */
500 /* reset all per-part mime variables */
501 mime_anomaly_level = 0;
502 mime_anomaly_text = NULL;
503 mime_boundary = NULL;
505 mime_decoded_filename = NULL;
506 mime_filename = NULL;
507 mime_content_description = NULL;
508 mime_content_disposition = NULL;
509 mime_content_id = NULL;
510 mime_content_transfer_encoding = NULL;
511 mime_content_type = NULL;
512 mime_is_multipart = 0;
513 mime_content_size = 0;
516 If boundary is null, we assume that *f is positioned on the start of headers (for example,
517 at the very beginning of a message.
518 If a boundary is given, we must first advance to it to reach the start of the next header
522 /* NOTE -- there's an error here -- RFC2046 specifically says to
523 * check for outer boundaries. This code doesn't do that, and
524 * I haven't fixed this.
526 * (I have moved partway towards adding support, however, by adding
527 * a "parent" field to my new boundary-context structure.)
531 while(fgets(CS header, MIME_MAX_HEADER_SIZE, f) != NULL)
533 /* boundary line must start with 2 dashes */
534 if (Ustrncmp(header,"--",2) == 0)
536 if (Ustrncmp((header+2),context->boundary,Ustrlen(context->boundary)) == 0)
539 if (Ustrncmp((header+2+Ustrlen(context->boundary)),"--",2) == 0)
541 /* END boundary found */
542 debug_printf("End boundary found %s\n", context->boundary);
546 debug_printf("Next part with boundary %s\n", context->boundary);
548 /* can't use break here */
553 /* Hit EOF or read error. Ugh. */
554 debug_printf("Hit EOF ...\n");
559 /* parse headers, set up expansion variables */
560 while (mime_get_header(f,header))
563 /* loop through header list */
564 for (i = 0; i < mime_header_list_size; i++)
566 uschar *header_value = NULL;
567 int header_value_len = 0;
569 /* found an interesting header? */
570 if (strncmpic(mime_header_list[i].name,header,mime_header_list[i].namelen) == 0)
572 uschar *p = header + mime_header_list[i].namelen;
573 /* yes, grab the value (normalize to lower case)
574 and copy to its corresponding expansion variable */
580 header_value_len = (p - (header + mime_header_list[i].namelen));
581 header_value = (uschar *)malloc(header_value_len+1);
582 memset(header_value,0,header_value_len+1);
583 p = header + mime_header_list[i].namelen;
584 Ustrncpy(header_value, p, header_value_len);
585 debug_printf("Found %s MIME header, value is '%s'\n", mime_header_list[i].name, header_value);
586 *((uschar **)(mime_header_list[i].value)) = header_value;
588 /* make p point to the next character after the closing ';' */
589 p += (header_value_len+1);
591 /* grab all param=value tags on the remaining line, check if they are interesting */
596 for (mp = mime_parameter_list;
597 mp < &mime_parameter_list[mime_parameter_list_size];
600 uschar *param_value = NULL;
601 int param_value_len = 0;
603 /* found an interesting parameter? */
604 if (strncmpic(mp->name, p, mp->namelen) == 0)
606 uschar *q = p + mp->namelen;
610 /* yes, grab the value and copy to its corresponding expansion variable */
611 while(*q && *q != ';') /* ; terminates */
615 q++; /* skip leading " */
616 while(*q && *q != '"') /* which protects ; */
617 param_value = string_cat(param_value, &size, &ptr, q++, 1);
618 if (*q) q++; /* skip trailing " */
621 param_value = string_cat(param_value, &size, &ptr, q++, 1);
625 param_value[ptr++] = '\0';
626 param_value_len = ptr;
628 param_value = rfc2047_decode(param_value,
629 check_rfc2047_length, NULL, 32, ¶m_value_len, &q);
630 debug_printf("Found %s MIME parameter in %s header, "
631 "value is '%s'\n", mp->name, mime_header_list[i].name,
634 *mp->value = param_value;
635 p += (mp->namelen + param_value_len + 1);
636 goto NEXT_PARAM_SEARCH;
639 /* There is something, but not one of our interesting parameters.
640 Advance to the next semicolon */
641 while(*p != ';') p++;
648 /* set additional flag variables (easier access) */
649 if ( (mime_content_type != NULL) &&
650 (Ustrncmp(mime_content_type,"multipart",9) == 0) )
651 mime_is_multipart = 1;
653 /* Make a copy of the boundary pointer.
654 Required since mime_boundary is global
655 and can be overwritten further down in recursion */
656 nested_context.boundary = mime_boundary;
658 /* raise global counter */
661 /* copy current file handle to global variable */
663 mime_current_boundary = context ? context->boundary : 0;
665 /* Note the context */
666 mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
668 /* call ACL handling function */
669 rc = acl_check(ACL_WHERE_MIME, NULL, acl, user_msgptr, log_msgptr);
672 mime_current_boundary = NULL;
676 /* If we have a multipart entity and a boundary, go recursive */
677 if ( (mime_content_type != NULL) &&
678 (nested_context.boundary != NULL) &&
679 (Ustrncmp(mime_content_type,"multipart",9) == 0) )
681 debug_printf("Entering multipart recursion, boundary '%s'\n", nested_context.boundary);
683 nested_context.context =
684 context && context->context == MBC_ATTACHMENT
686 : Ustrcmp(mime_content_type,"multipart/alternative") == 0
687 || Ustrcmp(mime_content_type,"multipart/related") == 0
688 ? MBC_COVERLETTER_ALL
689 : MBC_COVERLETTER_ONESHOT;
691 rc = mime_acl_check(acl, f, &nested_context, user_msgptr, log_msgptr);
694 else if ( (mime_content_type != NULL) &&
695 (Ustrncmp(mime_content_type,"message/rfc822",14) == 0) )
697 uschar *rfc822name = NULL;
698 uschar filename[2048];
702 /* must find first free sequential filename */
706 (void)string_format(filename, 2048,
707 "%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr++);
711 result = stat(CS filename,&mystat);
712 } while (result != -1);
714 rfc822name = filename;
716 /* decode RFC822 attachment */
717 mime_decoded_filename = NULL;
719 mime_current_boundary = context ? context->boundary : NULL;
720 mime_decode(&rfc822name);
722 mime_current_boundary = NULL;
723 if (!mime_decoded_filename) /* decoding failed */
725 log_write(0, LOG_MAIN,
726 "mime_regex acl condition warning - could not decode RFC822 MIME part to file.");
729 mime_decoded_filename = NULL;
733 /* If the boundary of this instance is NULL, we are finished here */
734 if (context == NULL) break;
736 if (context->context == MBC_COVERLETTER_ONESHOT)
737 context->context = MBC_ATTACHMENT;
743 #endif /*WITH_CONTENT_SCAN*/