1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2004, 2015
7 * Copyright (c) The Exim Maintainers 2016
11 #ifdef WITH_CONTENT_SCAN /* entire file */
15 FILE *mime_stream
= NULL
;
16 uschar
*mime_current_boundary
= NULL
;
18 static mime_header mime_header_list
[] = {
19 { US
"content-type:", 13, &mime_content_type
},
20 { US
"content-disposition:", 20, &mime_content_disposition
},
21 { US
"content-transfer-encoding:", 26, &mime_content_transfer_encoding
},
22 { US
"content-id:", 11, &mime_content_id
},
23 { US
"content-description:", 20, &mime_content_description
}
26 static int mime_header_list_size
= nelem(mime_header_list
);
28 static mime_parameter mime_parameter_list
[] = {
29 { US
"name=", 5, &mime_filename
},
30 { US
"filename=", 9, &mime_filename
},
31 { US
"charset=", 8, &mime_charset
},
32 { US
"boundary=", 9, &mime_boundary
}
36 /*************************************************
37 * set MIME anomaly level + text *
38 *************************************************/
40 /* Small wrapper to set the two expandables which
41 give info on detected "problems" in MIME
42 encodings. Indexes are defined in mime.h. */
45 mime_set_anomaly(int idx
)
50 } anom
[] = { {1, CUS
"Broken Quoted-Printable encoding detected"},
51 {2, CUS
"Broken BASE64 encoding detected"} };
53 mime_anomaly_level
= anom
[idx
].level
;
54 mime_anomaly_text
= anom
[idx
].text
;
58 /*************************************************
59 * decode quoted-printable chars *
60 *************************************************/
62 /* gets called when we hit a =
63 returns: new pointer position
66 -1 - soft line break, no char
71 mime_decode_qp_char(uschar
*qp_p
, int *c
)
73 uschar
*initial_pos
= qp_p
;
75 /* advance one char */
78 /* Check for two hex digits and decode them */
79 if (isxdigit(*qp_p
) && isxdigit(qp_p
[1]))
81 /* Do hex conversion */
82 *c
= (isdigit(*qp_p
) ? *qp_p
- '0' : toupper(*qp_p
) - 'A' + 10) <<4;
84 *c
|= isdigit(*qp_p
) ? *qp_p
- '0' : toupper(*qp_p
) - 'A' + 10;
88 /* tab or whitespace may follow just ignore it if it precedes \n */
89 while (*qp_p
== '\t' || *qp_p
== ' ' || *qp_p
== '\r')
92 if (*qp_p
== '\n') /* hit soft line break */
98 /* illegal char here */
104 /* just dump MIME part without any decoding */
106 mime_decode_asis(FILE* in
, FILE* out
, uschar
* boundary
)
108 ssize_t len
, size
= 0;
109 uschar buffer
[MIME_MAX_LINE_LENGTH
];
111 while(fgets(CS buffer
, MIME_MAX_LINE_LENGTH
, mime_stream
) != NULL
)
114 && Ustrncmp(buffer
, "--", 2) == 0
115 && Ustrncmp((buffer
+2), boundary
, Ustrlen(boundary
)) == 0
119 len
= Ustrlen(buffer
);
120 if (fwrite(buffer
, 1, (size_t)len
, out
) < len
)
129 /* decode quoted-printable MIME part */
131 mime_decode_qp(FILE* in
, FILE* out
, uschar
* boundary
)
133 uschar ibuf
[MIME_MAX_LINE_LENGTH
], obuf
[MIME_MAX_LINE_LENGTH
];
135 ssize_t len
, size
= 0;
137 while (fgets(CS ibuf
, MIME_MAX_LINE_LENGTH
, in
) != NULL
)
140 && Ustrncmp(ibuf
, "--", 2) == 0
141 && Ustrncmp((ibuf
+2), boundary
, Ustrlen(boundary
)) == 0
143 break; /* todo: check for missing boundary */
152 int decode_qp_result
;
154 ipos
= mime_decode_qp_char(ipos
, &decode_qp_result
);
156 if (decode_qp_result
== -2)
158 /* Error from decoder. ipos is unchanged. */
159 mime_set_anomaly(MIME_ANOMALY_BROKEN_QP
);
164 else if (decode_qp_result
== -1)
166 else if (decode_qp_result
>= 0)
168 *opos
= decode_qp_result
;
179 /* something to write? */
183 if (fwrite(obuf
, 1, len
, out
) != len
) return -1; /* error */
192 mime_get_decode_file(uschar
*pname
, uschar
*fname
)
197 filename
= (uschar
*)malloc(2048);
201 (void)string_format(filename
, 2048, "%s/%s", pname
, fname
);
202 f
= modefopen(filename
,"wb+",SPOOL_MODE
);
205 f
= modefopen(fname
,"wb+",SPOOL_MODE
);
211 /* must find first free sequential filename */
215 (void)string_format(filename
, 2048,
216 "%s/%s-%05u", pname
, message_id
, file_nr
++);
220 result
= stat(CS filename
, &mystat
);
221 } while(result
!= -1);
223 f
= modefopen(filename
, "wb+", SPOOL_MODE
);
226 /* set expansion variable */
227 mime_decoded_filename
= filename
;
234 mime_decode(const uschar
**listptr
)
237 const uschar
*list
= *listptr
;
239 uschar option_buffer
[1024];
240 uschar decode_path
[1024];
241 FILE *decode_file
= NULL
;
243 ssize_t size_counter
= 0;
244 ssize_t (*decode_function
)(FILE*, FILE*, uschar
*);
246 if (mime_stream
== NULL
)
249 f_pos
= ftell(mime_stream
);
251 /* build default decode path (will exist since MBOX must be spooled up) */
252 (void)string_format(decode_path
,1024,"%s/scan/%s",spool_directory
,message_id
);
254 /* try to find 1st option */
255 if ((option
= string_nextinlist(&list
, &sep
,
257 sizeof(option_buffer
))) != NULL
)
259 /* parse 1st option */
260 if ( (Ustrcmp(option
,"false") == 0) || (Ustrcmp(option
,"0") == 0) )
261 /* explicitly no decoding */
264 if (Ustrcmp(option
,"default") == 0)
265 /* explicit default path + file names */
268 if (option
[0] == '/')
272 memset(&statbuf
,0,sizeof(statbuf
));
274 /* assume either path or path+file name */
275 if ( (stat(CS option
, &statbuf
) == 0) && S_ISDIR(statbuf
.st_mode
) )
276 /* is directory, use it as decode_path */
277 decode_file
= mime_get_decode_file(option
, NULL
);
279 /* does not exist or is a file, use as full file name */
280 decode_file
= mime_get_decode_file(NULL
, option
);
283 /* assume file name only, use default path */
284 decode_file
= mime_get_decode_file(decode_path
, option
);
288 /* no option? patch default path */
290 decode_file
= mime_get_decode_file(decode_path
, NULL
);
296 /* decode according to mime type */
298 !mime_content_transfer_encoding
299 ? mime_decode_asis
/* no encoding, dump as-is */
300 : Ustrcmp(mime_content_transfer_encoding
, "base64") == 0
302 : Ustrcmp(mime_content_transfer_encoding
, "quoted-printable") == 0
304 : mime_decode_asis
; /* unknown encoding type, just dump as-is */
306 size_counter
= decode_function(mime_stream
, decode_file
, mime_current_boundary
);
308 clearerr(mime_stream
);
309 if (fseek(mime_stream
, f_pos
, SEEK_SET
))
312 if (fclose(decode_file
) != 0 || size_counter
< 0)
315 /* round up to the next KiB */
316 mime_content_size
= (size_counter
+ 1023) / 1024;
323 mime_get_header(FILE *f
, uschar
*header
)
327 int header_value_mode
= 0;
328 int header_open_brackets
= 0;
333 if ((c
= fgetc(f
)) == EOF
) break;
335 /* always skip CRs */
336 if (c
== '\r') continue;
342 /* look if next char is '\t' or ' ' */
343 if ((c
= fgetc(f
)) == EOF
) break;
344 if ( (c
== '\t') || (c
== ' ') ) continue;
347 /* end of the header, terminate with ';' */
352 /* skip control characters */
353 if (c
< 32) continue;
355 if (header_value_mode
)
357 /* --------- value mode ----------- */
358 /* skip leading whitespace */
359 if ( ((c
== '\t') || (c
== ' ')) && (header_value_mode
== 1) )
362 /* we have hit a non-whitespace char, start copying value data */
363 header_value_mode
= 2;
365 if (c
== '"') /* flip "quoted" mode */
366 header_value_mode
= header_value_mode
==2 ? 3 : 2;
368 /* leave value mode on unquoted ';' */
369 if (header_value_mode
== 2 && c
== ';') {
370 header_value_mode
= 0;
372 /* -------------------------------- */
376 /* -------- non-value mode -------- */
377 /* skip whitespace + tabs */
378 if ( (c
== ' ') || (c
== '\t') )
382 /* quote next char. can be used
383 to escape brackets. */
384 if ((c
= fgetc(f
)) == EOF
) break;
388 header_open_brackets
++;
391 else if ((c
== ')') && header_open_brackets
)
393 header_open_brackets
--;
396 else if ( (c
== '=') && !header_open_brackets
) /* enter value mode */
397 header_value_mode
= 1;
399 /* skip chars while we are in a comment */
400 if (header_open_brackets
> 0)
402 /* -------------------------------- */
405 /* copy the char to the buffer */
406 header
[num_copied
++] = (uschar
)c
;
408 /* break if header buffer is full */
409 if (num_copied
> MIME_MAX_HEADER_SIZE
-1)
413 if ((num_copied
> 0) && (header
[num_copied
-1] != ';'))
414 header
[num_copied
-1] = ';';
417 header
[num_copied
] = '\0';
419 /* return 0 for EOF or empty line */
420 if ((c
== EOF
) || (num_copied
== 1))
428 mime_vars_reset(void)
430 mime_anomaly_level
= 0;
431 mime_anomaly_text
= NULL
;
432 mime_boundary
= NULL
;
434 mime_decoded_filename
= NULL
;
435 mime_filename
= NULL
;
436 mime_content_description
= NULL
;
437 mime_content_disposition
= NULL
;
438 mime_content_id
= NULL
;
439 mime_content_transfer_encoding
= NULL
;
440 mime_content_type
= NULL
;
441 mime_is_multipart
= 0;
442 mime_content_size
= 0;
446 /* Grab a parameter value, dealing with quoting.
449 str Input string. Updated on return to point to terminating ; or NUL
452 Allocated string with parameter value
455 mime_param_val(uschar
** sp
)
459 int size
= 0, ptr
= 0;
461 /* debug_printf(" considering paramval '%s'\n", s); */
463 while (*s
&& *s
!= ';') /* ; terminates */
466 s
++; /* skip opening " */
467 while (*s
&& *s
!= '"') /* " protects ; */
468 val
= string_catn(val
, &size
, &ptr
, s
++, 1);
469 if (*s
) s
++; /* skip closing " */
472 val
= string_catn(val
, &size
, &ptr
, s
++, 1);
473 if (val
) val
[ptr
] = '\0';
479 mime_next_semicolon(uschar
* s
)
481 while (*s
&& *s
!= ';') /* ; terminates */
484 s
++; /* skip opening " */
485 while (*s
&& *s
!= '"') /* " protects ; */
487 if (*s
) s
++; /* skip closing " */
496 rfc2231_to_2047(const uschar
* fname
, const uschar
* charset
, int * len
)
498 int size
= 0, ptr
= 0;
499 uschar
* val
= string_catn(NULL
, &size
, &ptr
, US
"=?", 2);
503 val
= string_cat(val
, &size
, &ptr
, charset
);
504 val
= string_catn(val
, &size
, &ptr
, US
"?Q?", 3);
507 if (c
== '%' && isxdigit(fname
[1]) && isxdigit(fname
[2]))
509 val
= string_catn(val
, &size
, &ptr
, US
"=", 1);
510 val
= string_catn(val
, &size
, &ptr
, ++fname
, 2);
514 val
= string_catn(val
, &size
, &ptr
, fname
++, 1);
516 val
= string_catn(val
, &size
, &ptr
, US
"?=", 2);
517 val
[*len
= ptr
] = '\0';
523 mime_acl_check(uschar
*acl
, FILE *f
, struct mime_boundary_context
*context
,
524 uschar
**user_msgptr
, uschar
**log_msgptr
)
527 uschar
* header
= NULL
;
528 struct mime_boundary_context nested_context
;
530 /* reserve a line buffer to work in */
531 header
= store_get(MIME_MAX_HEADER_SIZE
+1);
533 /* Not actually used at the moment, but will be vital to fixing
534 * some RFC 2046 nonconformance later... */
535 nested_context
.parent
= context
;
537 /* loop through parts */
540 /* reset all per-part mime variables */
543 /* If boundary is null, we assume that *f is positioned on the start of
544 headers (for example, at the very beginning of a message. If a boundary is
545 given, we must first advance to it to reach the start of the next header
548 /* NOTE -- there's an error here -- RFC2046 specifically says to
549 * check for outer boundaries. This code doesn't do that, and
550 * I haven't fixed this.
552 * (I have moved partway towards adding support, however, by adding
553 * a "parent" field to my new boundary-context structure.)
555 if (context
) for (;;)
557 if (!fgets(CS header
, MIME_MAX_HEADER_SIZE
, f
))
559 /* Hit EOF or read error. Ugh. */
560 DEBUG(D_acl
) debug_printf("MIME: Hit EOF ...\n");
564 /* boundary line must start with 2 dashes */
565 if ( Ustrncmp(header
, "--", 2) == 0
566 && Ustrncmp(header
+2, context
->boundary
, Ustrlen(context
->boundary
)) == 0
568 { /* found boundary */
569 if (Ustrncmp((header
+2+Ustrlen(context
->boundary
)), "--", 2) == 0)
571 /* END boundary found */
572 DEBUG(D_acl
) debug_printf("MIME: End boundary found %s\n",
577 DEBUG(D_acl
) debug_printf("MIME: Next part with boundary %s\n",
583 /* parse headers, set up expansion variables */
584 while (mime_get_header(f
, header
))
586 struct mime_header
* mh
;
588 /* look for interesting headers */
589 for (mh
= mime_header_list
;
590 mh
< mime_header_list
+ mime_header_list_size
;
591 mh
++) if (strncmpic(mh
->name
, header
, mh
->namelen
) == 0)
593 uschar
* p
= header
+ mh
->namelen
;
596 /* grab the value (normalize to lower case)
597 and copy to its corresponding expansion variable */
599 for (q
= p
; *q
!= ';' && *q
; q
++) ;
600 *mh
->value
= string_copynlc(p
, q
-p
);
601 DEBUG(D_acl
) debug_printf("MIME: found %s header, value is '%s'\n",
602 mh
->name
, *mh
->value
);
604 if (*(p
= q
)) p
++; /* jump past the ; */
607 uschar
* mime_fname
= NULL
;
608 uschar
* mime_fname_rfc2231
= NULL
;
609 uschar
* mime_filename_charset
= NULL
;
610 BOOL decoding_failed
= FALSE
;
612 /* grab all param=value tags on the remaining line,
613 check if they are interesting */
619 DEBUG(D_acl
) debug_printf("MIME: considering paramlist '%s'\n", p
);
622 && strncmpic(CUS
"content-disposition:", header
, 20) == 0
623 && strncmpic(CUS
"filename*", p
, 9) == 0
625 { /* RFC 2231 filename */
628 /* find value of the filename */
630 while(*p
!= '=' && *p
) p
++;
631 if (*p
) p
++; /* p is filename or NUL */
632 q
= mime_param_val(&p
); /* p now trailing ; or NUL */
636 uschar
* temp_string
, * err_msg
;
639 /* build up an un-decoded filename over successive
640 filename*= parameters (for use when 2047 decode fails) */
642 mime_fname_rfc2231
= string_sprintf("%#s%s",
643 mime_fname_rfc2231
, q
);
645 if (!decoding_failed
)
648 if (!mime_filename_charset
)
652 /* look for a ' in the "filename" */
653 while(*s
!= '\'' && *s
) s
++; /* s is 1st ' or NUL */
655 if ((size
= s
-q
) > 0)
656 mime_filename_charset
= string_copyn(q
, size
);
659 while(*p
== '\'') p
++; /* p is after 2nd ' */
664 DEBUG(D_acl
) debug_printf("MIME: charset %s fname '%s'\n",
665 mime_filename_charset
? mime_filename_charset
: US
"<NULL>", p
);
667 temp_string
= rfc2231_to_2047(p
, mime_filename_charset
, &slen
);
668 DEBUG(D_acl
) debug_printf("MIME: 2047-name %s\n", temp_string
);
670 temp_string
= rfc2047_decode(temp_string
, FALSE
, NULL
, ' ',
672 DEBUG(D_acl
) debug_printf("MIME: plain-name %s\n", temp_string
);
674 size
= Ustrlen(temp_string
);
677 decoding_failed
= TRUE
;
679 /* build up a decoded filename over successive
680 filename*= parameters */
682 mime_filename
= mime_fname
= mime_fname
683 ? string_sprintf("%s%s", mime_fname
, temp_string
)
690 /* look for interesting parameters */
691 for (mp
= mime_parameter_list
;
692 mp
< mime_parameter_list
+ nelem(mime_parameter_list
);
694 ) if (strncmpic(mp
->name
, p
, mp
->namelen
) == 0)
697 uschar
* dummy_errstr
;
699 /* grab the value and copy to its expansion variable */
701 q
= mime_param_val(&p
); /* p now trailing ; or NUL */
704 ? rfc2047_decode(q
, check_rfc2047_length
, NULL
, 32, NULL
,
707 DEBUG(D_acl
) debug_printf(
708 "MIME: found %s parameter in %s header, value '%s'\n",
709 mp
->name
, mh
->name
, *mp
->value
);
711 break; /* done matching param names */
715 /* There is something, but not one of our interesting parameters.
716 Advance past the next semicolon */
717 p
= mime_next_semicolon(p
);
719 } /* param scan on line */
721 if (strncmpic(CUS
"content-disposition:", header
, 20) == 0)
723 if (decoding_failed
) mime_filename
= mime_fname_rfc2231
;
725 DEBUG(D_acl
) debug_printf(
726 "MIME: found %s parameter in %s header, value is '%s'\n",
727 "filename", mh
->name
, mime_filename
);
733 /* set additional flag variables (easier access) */
734 if ( mime_content_type
735 && Ustrncmp(mime_content_type
,"multipart",9) == 0
737 mime_is_multipart
= 1;
739 /* Make a copy of the boundary pointer.
740 Required since mime_boundary is global
741 and can be overwritten further down in recursion */
742 nested_context
.boundary
= mime_boundary
;
744 /* raise global counter */
747 /* copy current file handle to global variable */
749 mime_current_boundary
= context
? context
->boundary
: 0;
751 /* Note the context */
752 mime_is_coverletter
= !(context
&& context
->context
== MBC_ATTACHMENT
);
754 /* call ACL handling function */
755 rc
= acl_check(ACL_WHERE_MIME
, NULL
, acl
, user_msgptr
, log_msgptr
);
758 mime_current_boundary
= NULL
;
762 /* If we have a multipart entity and a boundary, go recursive */
763 if ( (mime_content_type
!= NULL
) &&
764 (nested_context
.boundary
!= NULL
) &&
765 (Ustrncmp(mime_content_type
,"multipart",9) == 0) )
768 debug_printf("MIME: Entering multipart recursion, boundary '%s'\n",
769 nested_context
.boundary
);
771 nested_context
.context
=
772 context
&& context
->context
== MBC_ATTACHMENT
774 : Ustrcmp(mime_content_type
,"multipart/alternative") == 0
775 || Ustrcmp(mime_content_type
,"multipart/related") == 0
776 ? MBC_COVERLETTER_ALL
777 : MBC_COVERLETTER_ONESHOT
;
779 rc
= mime_acl_check(acl
, f
, &nested_context
, user_msgptr
, log_msgptr
);
782 else if ( (mime_content_type
!= NULL
) &&
783 (Ustrncmp(mime_content_type
,"message/rfc822",14) == 0) )
785 const uschar
*rfc822name
= NULL
;
786 uschar filename
[2048];
790 /* must find first free sequential filename */
794 (void)string_format(filename
, 2048,
795 "%s/scan/%s/__rfc822_%05u", spool_directory
, message_id
, file_nr
++);
799 result
= stat(CS filename
,&mystat
);
800 } while (result
!= -1);
802 rfc822name
= filename
;
804 /* decode RFC822 attachment */
805 mime_decoded_filename
= NULL
;
807 mime_current_boundary
= context
? context
->boundary
: NULL
;
808 mime_decode(&rfc822name
);
810 mime_current_boundary
= NULL
;
811 if (!mime_decoded_filename
) /* decoding failed */
813 log_write(0, LOG_MAIN
,
814 "mime_regex acl condition warning - could not decode RFC822 MIME part to file.");
818 mime_decoded_filename
= NULL
;
822 /* If the boundary of this instance is NULL, we are finished here */
825 if (context
->context
== MBC_COVERLETTER_ONESHOT
)
826 context
->context
= MBC_ATTACHMENT
;
834 #endif /*WITH_CONTENT_SCAN*/