1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2004 */
9 #ifdef WITH_CONTENT_SCAN
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. */
24 void mime_set_anomaly(int level, const char *text) {
25 mime_anomaly_level = level;
26 mime_anomaly_text = CUS text;
30 /*************************************************
31 * decode quoted-printable chars *
32 *************************************************/
34 /* gets called when we hit a =
35 returns: new pointer position
38 -1 - soft line break, no char
42 uschar *mime_decode_qp_char(uschar *qp_p, int *c) {
43 uschar *initial_pos = qp_p;
45 /* advance one char */
48 /* Check for two hex digits and decode them */
49 if (isxdigit(*qp_p) && isxdigit(qp_p[1])) {
50 /* Do hex conversion */
51 if (isdigit(*qp_p)) {*c = *qp_p - '0';}
52 else {*c = toupper(*qp_p) - 'A' + 10;};
54 if (isdigit(qp_p[1])) {*c |= qp_p[1] - '0';}
55 else {*c |= toupper(qp_p[1]) - 'A' + 10;};
59 /* tab or whitespace may follow just ignore it if it precedes \n */
60 while (*qp_p == '\t' || *qp_p == ' ' || *qp_p == '\r')
64 /* hit soft line break */
69 /* illegal char here */
75 /* just dump MIME part without any decoding */
76 static int mime_decode_asis(FILE* in, FILE* out, uschar* boundary)
79 uschar buffer[MIME_MAX_LINE_LENGTH];
81 while(fgets(CS buffer, MIME_MAX_LINE_LENGTH, mime_stream) != NULL) {
83 && Ustrncmp(buffer, "--", 2) == 0
84 && Ustrncmp((buffer+2), boundary, Ustrlen(boundary)) == 0
88 len = Ustrlen(buffer);
89 if (fwrite(buffer, 1, (size_t)len, out) < len)
97 /* decode base64 MIME part */
98 static int mime_decode_base64(FILE* in, FILE* out, uschar* boundary)
100 uschar ibuf[MIME_MAX_LINE_LENGTH], obuf[MIME_MAX_LINE_LENGTH];
102 size_t len, size = 0;
107 while (Ufgets(ibuf, MIME_MAX_LINE_LENGTH, in) != NULL)
110 && Ustrncmp(ibuf, "--", 2) == 0
111 && Ustrncmp((ibuf+2), boundary, Ustrlen(boundary)) == 0
115 for (ipos = ibuf ; *ipos != '\r' && *ipos != '\n' && *ipos != 0; ++ipos) {
121 /* skip bad characters */
122 if (mime_b64[*ipos] == 128) {
123 mime_set_anomaly(MIME_ANOMALY_BROKEN_BASE64);
126 /* simple state-machine */
127 switch((bytestate++) & 3) {
129 *opos = mime_b64[*ipos] << 2;
132 *opos |= mime_b64[*ipos] >> 4;
134 *opos = mime_b64[*ipos] << 4;
137 *opos |= mime_b64[*ipos] >> 2;
139 *opos = mime_b64[*ipos] << 6;
142 *opos |= mime_b64[*ipos];
147 /* something to write? */
150 if (fwrite(obuf, 1, len, out) != len)
151 return -1; /* error */
153 /* copy incomplete last byte to start of obuf, where we continue */
154 if ((bytestate & 3) != 0)
160 /* write out last byte if it was incomplete */
162 if (fwrite(obuf, 1, 1, out) != 1)
171 /* decode quoted-printable MIME part */
172 static int mime_decode_qp(FILE* in, FILE* out, uschar* boundary)
174 uschar ibuf[MIME_MAX_LINE_LENGTH], obuf[MIME_MAX_LINE_LENGTH];
176 size_t len, size = 0;
178 while (fgets(CS ibuf, MIME_MAX_LINE_LENGTH, in) != NULL)
181 && Ustrncmp(ibuf, "--", 2) == 0
182 && Ustrncmp((ibuf+2), boundary, Ustrlen(boundary)) == 0
184 break; /* todo: check for missing boundary */
191 int decode_qp_result;
193 ipos = mime_decode_qp_char(ipos, &decode_qp_result);
195 if (decode_qp_result == -2) {
196 /* Error from decoder. ipos is unchanged. */
197 mime_set_anomaly(MIME_ANOMALY_BROKEN_QP);
202 else if (decode_qp_result == -1) {
205 else if (decode_qp_result >= 0) {
206 *opos = decode_qp_result;
216 /* something to write? */
219 if (fwrite(obuf, 1, len, out) != len)
220 return -1; /* error */
228 FILE *mime_get_decode_file(uschar *pname, uschar *fname) {
232 filename = (uschar *)malloc(2048);
234 if ((pname != NULL) && (fname != NULL)) {
235 (void)string_format(filename, 2048, "%s/%s", pname, fname);
236 f = modefopen(filename,"wb+",SPOOL_MODE);
238 else if (pname == NULL) {
239 f = modefopen(fname,"wb+",SPOOL_MODE);
241 else if (fname == NULL) {
245 /* must find first free sequential filename */
248 (void)string_format(filename,2048,"%s/%s-%05u", pname, message_id, file_nr);
253 result = stat(CS filename,&mystat);
256 f = modefopen(filename,"wb+",SPOOL_MODE);
259 /* set expansion variable */
260 mime_decoded_filename = filename;
266 int mime_decode(uschar **listptr) {
268 uschar *list = *listptr;
270 uschar option_buffer[1024];
271 uschar decode_path[1024];
272 FILE *decode_file = NULL;
274 unsigned int size_counter = 0;
275 int (*decode_function)(FILE*, FILE*, uschar*);
277 if (mime_stream == NULL)
280 f_pos = ftell(mime_stream);
282 /* build default decode path (will exist since MBOX must be spooled up) */
283 (void)string_format(decode_path,1024,"%s/scan/%s",spool_directory,message_id);
285 /* try to find 1st option */
286 if ((option = string_nextinlist(&list, &sep,
288 sizeof(option_buffer))) != NULL) {
290 /* parse 1st option */
291 if ( (Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0) ) {
292 /* explicitly no decoding */
296 if (Ustrcmp(option,"default") == 0) {
297 /* explicit default path + file names */
301 if (option[0] == '/') {
304 memset(&statbuf,0,sizeof(statbuf));
306 /* assume either path or path+file name */
307 if ( (stat(CS option, &statbuf) == 0) && S_ISDIR(statbuf.st_mode) )
308 /* is directory, use it as decode_path */
309 decode_file = mime_get_decode_file(option, NULL);
311 /* does not exist or is a file, use as full file name */
312 decode_file = mime_get_decode_file(NULL, option);
315 /* assume file name only, use default path */
316 decode_file = mime_get_decode_file(decode_path, option);
319 /* no option? patch default path */
320 DEFAULT_PATH: decode_file = mime_get_decode_file(decode_path, NULL);
322 if (decode_file == NULL)
325 /* decode according to mime type */
326 if (mime_content_transfer_encoding == NULL)
327 /* no encoding, dump as-is */
328 decode_function = mime_decode_asis;
329 else if (Ustrcmp(mime_content_transfer_encoding, "base64") == 0)
330 decode_function = mime_decode_base64;
331 else if (Ustrcmp(mime_content_transfer_encoding, "quoted-printable") == 0)
332 decode_function = mime_decode_qp;
334 /* unknown encoding type, just dump as-is */
335 decode_function = mime_decode_asis;
337 size_counter = decode_function(mime_stream, decode_file, mime_current_boundary);
339 clearerr(mime_stream);
340 fseek(mime_stream, f_pos, SEEK_SET);
342 if (fclose(decode_file) != 0 || size_counter < 0)
345 /* round up to the next KiB */
346 mime_content_size = (size_counter + 1023) / 1024;
351 int mime_get_header(FILE *f, uschar *header) {
354 int header_value_mode = 0;
355 int header_open_brackets = 0;
363 /* always skip CRs */
364 if (c == '\r') continue;
367 if (num_copied > 0) {
368 /* look if next char is '\t' or ' ' */
371 if ( (c == '\t') || (c == ' ') ) continue;
374 /* end of the header, terminate with ';' */
379 /* skip control characters */
380 if (c < 32) continue;
382 if (header_value_mode) {
383 /* --------- value mode ----------- */
384 /* skip leading whitespace */
385 if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
388 /* we have hit a non-whitespace char, start copying value data */
389 header_value_mode = 2;
392 if (c == '"') continue;
394 /* leave value mode on ';' */
396 header_value_mode = 0;
398 /* -------------------------------- */
401 /* -------- non-value mode -------- */
402 /* skip whitespace + tabs */
403 if ( (c == ' ') || (c == '\t') )
406 /* quote next char. can be used
407 to escape brackets. */
412 header_open_brackets++;
415 else if ((c == ')') && header_open_brackets) {
416 header_open_brackets--;
419 else if ( (c == '=') && !header_open_brackets ) {
420 /* enter value mode */
421 header_value_mode = 1;
424 /* skip chars while we are in a comment */
425 if (header_open_brackets > 0)
427 /* -------------------------------- */
430 /* copy the char to the buffer */
431 header[num_copied] = (uschar)c;
435 /* break if header buffer is full */
436 if (num_copied > MIME_MAX_HEADER_SIZE-1) {
441 if ((num_copied > 0) && (header[num_copied-1] != ';')) {
442 header[num_copied-1] = ';';
446 header[num_copied] = '\0';
448 /* return 0 for EOF or empty line */
449 if ((c == EOF) || (num_copied == 1))
456 int mime_acl_check(uschar *acl, FILE *f, struct mime_boundary_context *context,
457 uschar **user_msgptr, uschar **log_msgptr) {
459 uschar *header = NULL;
460 struct mime_boundary_context nested_context;
462 /* reserve a line buffer to work in */
463 header = (uschar *)malloc(MIME_MAX_HEADER_SIZE+1);
464 if (header == NULL) {
465 log_write(0, LOG_PANIC,
466 "MIME ACL: can't allocate %d bytes of memory.", MIME_MAX_HEADER_SIZE+1);
470 /* Not actually used at the moment, but will be vital to fixing
471 * some RFC 2046 nonconformance later... */
472 nested_context.parent = context;
474 /* loop through parts */
477 /* reset all per-part mime variables */
478 mime_anomaly_level = 0;
479 mime_anomaly_text = NULL;
480 mime_boundary = NULL;
482 mime_decoded_filename = NULL;
483 mime_filename = NULL;
484 mime_content_description = NULL;
485 mime_content_disposition = NULL;
486 mime_content_id = NULL;
487 mime_content_transfer_encoding = NULL;
488 mime_content_type = NULL;
489 mime_is_multipart = 0;
490 mime_content_size = 0;
493 If boundary is null, we assume that *f is positioned on the start of headers (for example,
494 at the very beginning of a message.
495 If a boundary is given, we must first advance to it to reach the start of the next header
499 /* NOTE -- there's an error here -- RFC2046 specifically says to
500 * check for outer boundaries. This code doesn't do that, and
501 * I haven't fixed this.
503 * (I have moved partway towards adding support, however, by adding
504 * a "parent" field to my new boundary-context structure.)
506 if (context != NULL) {
507 while(fgets(CS header, MIME_MAX_HEADER_SIZE, f) != NULL) {
508 /* boundary line must start with 2 dashes */
509 if (Ustrncmp(header,"--",2) == 0) {
510 if (Ustrncmp((header+2),context->boundary,Ustrlen(context->boundary)) == 0) {
512 if (Ustrncmp((header+2+Ustrlen(context->boundary)),"--",2) == 0) {
513 /* END boundary found */
514 debug_printf("End boundary found %s\n", context->boundary);
518 debug_printf("Next part with boundary %s\n", context->boundary);
520 /* can't use break here */
525 /* Hit EOF or read error. Ugh. */
526 debug_printf("Hit EOF ...\n");
531 /* parse headers, set up expansion variables */
532 while(mime_get_header(f,header)) {
534 /* loop through header list */
535 for (i = 0; i < mime_header_list_size; i++) {
536 uschar *header_value = NULL;
537 int header_value_len = 0;
539 /* found an interesting header? */
540 if (strncmpic(mime_header_list[i].name,header,mime_header_list[i].namelen) == 0) {
541 uschar *p = header + mime_header_list[i].namelen;
542 /* yes, grab the value (normalize to lower case)
543 and copy to its corresponding expansion variable */
548 header_value_len = (p - (header + mime_header_list[i].namelen));
549 header_value = (uschar *)malloc(header_value_len+1);
550 memset(header_value,0,header_value_len+1);
551 p = header + mime_header_list[i].namelen;
552 Ustrncpy(header_value, p, header_value_len);
553 debug_printf("Found %s MIME header, value is '%s'\n", mime_header_list[i].name, header_value);
554 *((uschar **)(mime_header_list[i].value)) = header_value;
556 /* make p point to the next character after the closing ';' */
557 p += (header_value_len+1);
559 /* grab all param=value tags on the remaining line, check if they are interesting */
560 NEXT_PARAM_SEARCH: while (*p != 0) {
562 for (j = 0; j < mime_parameter_list_size; j++) {
563 uschar *param_value = NULL;
564 int param_value_len = 0;
566 /* found an interesting parameter? */
567 if (strncmpic(mime_parameter_list[j].name,p,mime_parameter_list[j].namelen) == 0) {
568 uschar *q = p + mime_parameter_list[j].namelen;
569 /* yes, grab the value and copy to its corresponding expansion variable */
570 while(*q != ';') q++;
571 param_value_len = (q - (p + mime_parameter_list[j].namelen));
572 param_value = (uschar *)malloc(param_value_len+1);
573 memset(param_value,0,param_value_len+1);
574 q = p + mime_parameter_list[j].namelen;
575 Ustrncpy(param_value, q, param_value_len);
576 param_value = rfc2047_decode(param_value, check_rfc2047_length, NULL, 32, ¶m_value_len, &q);
577 debug_printf("Found %s MIME parameter in %s header, value is '%s'\n", mime_parameter_list[j].name, mime_header_list[i].name, param_value);
578 *((uschar **)(mime_parameter_list[j].value)) = param_value;
579 p += (mime_parameter_list[j].namelen + param_value_len + 1);
580 goto NEXT_PARAM_SEARCH;
583 /* There is something, but not one of our interesting parameters.
584 Advance to the next semicolon */
585 while(*p != ';') p++;
592 /* set additional flag variables (easier access) */
593 if ( (mime_content_type != NULL) &&
594 (Ustrncmp(mime_content_type,"multipart",9) == 0) )
595 mime_is_multipart = 1;
597 /* Make a copy of the boundary pointer.
598 Required since mime_boundary is global
599 and can be overwritten further down in recursion */
600 nested_context.boundary = mime_boundary;
602 /* raise global counter */
605 /* copy current file handle to global variable */
607 mime_current_boundary = context ? context->boundary : 0;
609 /* Note the context */
610 mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
612 /* call ACL handling function */
613 rc = acl_check(ACL_WHERE_MIME, NULL, acl, user_msgptr, log_msgptr);
616 mime_current_boundary = NULL;
620 /* If we have a multipart entity and a boundary, go recursive */
621 if ( (mime_content_type != NULL) &&
622 (nested_context.boundary != NULL) &&
623 (Ustrncmp(mime_content_type,"multipart",9) == 0) ) {
624 debug_printf("Entering multipart recursion, boundary '%s'\n", nested_context.boundary);
626 if (context && context->context == MBC_ATTACHMENT)
627 nested_context.context = MBC_ATTACHMENT;
628 else if (!Ustrcmp(mime_content_type,"multipart/alternative")
629 || !Ustrcmp(mime_content_type,"multipart/related"))
630 nested_context.context = MBC_COVERLETTER_ALL;
632 nested_context.context = MBC_COVERLETTER_ONESHOT;
634 rc = mime_acl_check(acl, f, &nested_context, user_msgptr, log_msgptr);
637 else if ( (mime_content_type != NULL) &&
638 (Ustrncmp(mime_content_type,"message/rfc822",14) == 0) ) {
639 uschar *rfc822name = NULL;
640 uschar filename[2048];
644 /* must find first free sequential filename */
647 (void)string_format(filename,2048,"%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr);
652 result = stat(CS filename,&mystat);
656 rfc822name = filename;
658 /* decode RFC822 attachment */
659 mime_decoded_filename = NULL;
661 mime_current_boundary = context ? context->boundary : NULL;
662 mime_decode(&rfc822name);
664 mime_current_boundary = NULL;
665 if (mime_decoded_filename == NULL) {
666 /* decoding failed */
667 log_write(0, LOG_MAIN,
668 "mime_regex acl condition warning - could not decode RFC822 MIME part to file.");
671 mime_decoded_filename = NULL;
675 /* If the boundary of this instance is NULL, we are finished here */
676 if (context == NULL) break;
678 if (context->context == MBC_COVERLETTER_ONESHOT)
679 context->context = MBC_ATTACHMENT;