1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2004, 2015 */
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(const uschar
**listptr
)
289 const 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;
374 mime_get_header(FILE *f
, uschar
*header
)
378 int header_value_mode
= 0;
379 int header_open_brackets
= 0;
384 if ((c
= fgetc(f
)) == EOF
) break;
386 /* always skip CRs */
387 if (c
== '\r') continue;
393 /* look if next char is '\t' or ' ' */
394 if ((c
= fgetc(f
)) == EOF
) break;
395 if ( (c
== '\t') || (c
== ' ') ) continue;
398 /* end of the header, terminate with ';' */
403 /* skip control characters */
404 if (c
< 32) continue;
406 if (header_value_mode
)
408 /* --------- value mode ----------- */
409 /* skip leading whitespace */
410 if ( ((c
== '\t') || (c
== ' ')) && (header_value_mode
== 1) )
413 /* we have hit a non-whitespace char, start copying value data */
414 header_value_mode
= 2;
416 if (c
== '"') /* flip "quoted" mode */
417 header_value_mode
= header_value_mode
==2 ? 3 : 2;
419 /* leave value mode on unquoted ';' */
420 if (header_value_mode
== 2 && c
== ';') {
421 header_value_mode
= 0;
423 /* -------------------------------- */
427 /* -------- non-value mode -------- */
428 /* skip whitespace + tabs */
429 if ( (c
== ' ') || (c
== '\t') )
433 /* quote next char. can be used
434 to escape brackets. */
435 if ((c
= fgetc(f
)) == EOF
) break;
439 header_open_brackets
++;
442 else if ((c
== ')') && header_open_brackets
)
444 header_open_brackets
--;
447 else if ( (c
== '=') && !header_open_brackets
) /* enter value mode */
448 header_value_mode
= 1;
450 /* skip chars while we are in a comment */
451 if (header_open_brackets
> 0)
453 /* -------------------------------- */
456 /* copy the char to the buffer */
457 header
[num_copied
++] = (uschar
)c
;
459 /* break if header buffer is full */
460 if (num_copied
> MIME_MAX_HEADER_SIZE
-1)
464 if ((num_copied
> 0) && (header
[num_copied
-1] != ';'))
465 header
[num_copied
-1] = ';';
468 header
[num_copied
] = '\0';
470 /* return 0 for EOF or empty line */
471 if ((c
== EOF
) || (num_copied
== 1))
479 mime_vars_reset(void)
481 mime_anomaly_level
= 0;
482 mime_anomaly_text
= NULL
;
483 mime_boundary
= NULL
;
485 mime_decoded_filename
= NULL
;
486 mime_filename
= NULL
;
487 mime_content_description
= NULL
;
488 mime_content_disposition
= NULL
;
489 mime_content_id
= NULL
;
490 mime_content_transfer_encoding
= NULL
;
491 mime_content_type
= NULL
;
492 mime_is_multipart
= 0;
493 mime_content_size
= 0;
497 /* Grab a parameter value, dealing with quoting.
500 str Input string. Updated on return to point to terminating ; or NUL
503 Allocated string with parameter value
506 mime_param_val(uschar
** sp
)
510 int size
= 0, ptr
= 0;
512 /* debug_printf(" considering paramval '%s'\n", s); */
514 while (*s
&& *s
!= ';') /* ; terminates */
517 s
++; /* skip opening " */
518 while (*s
&& *s
!= '"') /* " protects ; */
519 val
= string_cat(val
, &size
, &ptr
, s
++, 1);
520 if (*s
) s
++; /* skip closing " */
523 val
= string_cat(val
, &size
, &ptr
, s
++, 1);
524 if (val
) val
[ptr
] = '\0';
530 mime_next_semicolon(uschar
* s
)
532 while (*s
&& *s
!= ';') /* ; terminates */
535 s
++; /* skip opening " */
536 while (*s
&& *s
!= '"') /* " protects ; */
538 if (*s
) s
++; /* skip closing " */
547 rfc2231_to_2047(const uschar
* fname
, const uschar
* charset
, int * len
)
549 int size
= 0, ptr
= 0;
550 uschar
* val
= string_cat(NULL
, &size
, &ptr
, US
"=?", 2);
553 val
= string_cat(val
, &size
, &ptr
, charset
, Ustrlen(charset
));
554 val
= string_cat(val
, &size
, &ptr
, US
"?Q?", 3);
557 if (c
== '%' && isxdigit(fname
[1]) && isxdigit(fname
[2]))
559 val
= string_cat(val
, &size
, &ptr
, US
"=", 1);
560 val
= string_cat(val
, &size
, &ptr
, ++fname
, 2);
564 val
= string_cat(val
, &size
, &ptr
, fname
++, 1);
566 val
= string_cat(val
, &size
, &ptr
, US
"?=", 2);
567 val
[*len
= ptr
] = '\0';
573 mime_acl_check(uschar
*acl
, FILE *f
, struct mime_boundary_context
*context
,
574 uschar
**user_msgptr
, uschar
**log_msgptr
)
577 uschar
* header
= NULL
;
578 struct mime_boundary_context nested_context
;
580 /* reserve a line buffer to work in */
581 header
= store_get(MIME_MAX_HEADER_SIZE
+1);
583 /* Not actually used at the moment, but will be vital to fixing
584 * some RFC 2046 nonconformance later... */
585 nested_context
.parent
= context
;
587 /* loop through parts */
590 /* reset all per-part mime variables */
593 /* If boundary is null, we assume that *f is positioned on the start of
594 headers (for example, at the very beginning of a message. If a boundary is
595 given, we must first advance to it to reach the start of the next header
598 /* NOTE -- there's an error here -- RFC2046 specifically says to
599 * check for outer boundaries. This code doesn't do that, and
600 * I haven't fixed this.
602 * (I have moved partway towards adding support, however, by adding
603 * a "parent" field to my new boundary-context structure.)
605 if (context
) for (;;)
607 if (!fgets(CS header
, MIME_MAX_HEADER_SIZE
, f
))
609 /* Hit EOF or read error. Ugh. */
610 DEBUG(D_acl
) debug_printf("Hit EOF ...\n");
614 /* boundary line must start with 2 dashes */
615 if ( Ustrncmp(header
, "--", 2) == 0
616 && Ustrncmp(header
+2, context
->boundary
, Ustrlen(context
->boundary
)) == 0
618 { /* found boundary */
619 if (Ustrncmp((header
+2+Ustrlen(context
->boundary
)), "--", 2) == 0)
621 /* END boundary found */
622 DEBUG(D_acl
) debug_printf("End boundary found %s\n",
627 DEBUG(D_acl
) debug_printf("Next part with boundary %s\n",
633 /* parse headers, set up expansion variables */
634 while (mime_get_header(f
, header
))
636 struct mime_header
* mh
;
638 /* look for interesting headers */
639 for (mh
= mime_header_list
;
640 mh
< mime_header_list
+ mime_header_list_size
;
641 mh
++) if (strncmpic(mh
->name
, header
, mh
->namelen
) == 0)
643 uschar
* p
= header
+ mh
->namelen
;
646 /* grab the value (normalize to lower case)
647 and copy to its corresponding expansion variable */
649 for (q
= p
; *q
!= ';' && *q
; q
++) ;
650 *mh
->value
= string_copynlc(p
, q
-p
);
651 DEBUG(D_acl
) debug_printf("found %s MIME header, value is '%s'\n",
652 mh
->name
, *mh
->value
);
654 if (*(p
= q
)) p
++; /* jump past the ; */
657 uschar
* mime_fname
= NULL
;
658 uschar
* mime_fname_rfc2231
= NULL
;
659 uschar
* mime_filename_charset
= NULL
;
660 BOOL decoding_failed
= FALSE
;
662 /* grab all param=value tags on the remaining line,
663 check if they are interesting */
669 DEBUG(D_acl
) debug_printf(" considering paramlist '%s'\n", p
);
672 && strncmpic(CUS
"content-disposition:", header
, 20) == 0
673 && strncmpic(CUS
"filename*", p
, 9) == 0
675 { /* RFC 2231 filename */
678 /* find value of the filename */
680 while(*p
!= '=' && *p
) p
++;
681 if (*p
) p
++; /* p is filename or NUL */
682 q
= mime_param_val(&p
); /* p now trailing ; or NUL */
686 uschar
* temp_string
, * err_msg
;
689 /* build up an un-decoded filename over successive
690 filename*= parameters (for use when 2047 decode fails) */
692 mime_fname_rfc2231
= string_sprintf("%#s%s",
693 mime_fname_rfc2231
, q
);
695 if (!decoding_failed
)
698 if (!mime_filename_charset
)
702 /* look for a ' in the "filename" */
703 while(*s
!= '\'' && *s
) s
++; /* s is ' or NUL */
705 if ((size
= s
-q
) > 0)
707 mime_filename_charset
= string_copyn(q
, size
);
710 while(*p
== '\'' && *p
) p
++; /* p is after ' */
716 temp_string
= rfc2231_to_2047(p
, mime_filename_charset
, &slen
);
717 temp_string
= rfc2047_decode(temp_string
, FALSE
, NULL
, 32,
719 size
= Ustrlen(temp_string
);
722 decoding_failed
= TRUE
;
724 /* build up a decoded filename over successive
725 filename*= parameters */
727 mime_filename
= mime_fname
= mime_fname
728 ? string_sprintf("%s%s", mime_fname
, temp_string
)
735 /* look for interesting parameters */
736 for (mp
= mime_parameter_list
;
737 mp
< mime_parameter_list
+ nelem(mime_parameter_list
);
739 ) if (strncmpic(mp
->name
, p
, mp
->namelen
) == 0)
742 uschar
* dummy_errstr
;
744 /* grab the value and copy to its expansion variable */
746 q
= mime_param_val(&p
); /* p now trailing ; or NUL */
749 ? rfc2047_decode(q
, check_rfc2047_length
, NULL
, 32, NULL
,
752 DEBUG(D_acl
) debug_printf(
753 " found %s MIME parameter in %s header, value '%s'\n",
754 mp
->name
, mh
->name
, *mp
->value
);
756 break; /* done matching param names */
760 /* There is something, but not one of our interesting parameters.
761 Advance past the next semicolon */
762 p
= mime_next_semicolon(p
);
764 } /* param scan on line */
766 if (strncmpic(CUS
"content-disposition:", header
, 20) == 0)
768 if (decoding_failed
) mime_filename
= mime_fname_rfc2231
;
770 DEBUG(D_acl
) debug_printf(
771 " found %s MIME parameter in %s header, value is '%s'\n",
772 "filename", mh
->name
, mime_filename
);
778 /* set additional flag variables (easier access) */
779 if ( mime_content_type
780 && Ustrncmp(mime_content_type
,"multipart",9) == 0
782 mime_is_multipart
= 1;
784 /* Make a copy of the boundary pointer.
785 Required since mime_boundary is global
786 and can be overwritten further down in recursion */
787 nested_context
.boundary
= mime_boundary
;
789 /* raise global counter */
792 /* copy current file handle to global variable */
794 mime_current_boundary
= context
? context
->boundary
: 0;
796 /* Note the context */
797 mime_is_coverletter
= !(context
&& context
->context
== MBC_ATTACHMENT
);
799 /* call ACL handling function */
800 rc
= acl_check(ACL_WHERE_MIME
, NULL
, acl
, user_msgptr
, log_msgptr
);
803 mime_current_boundary
= NULL
;
807 /* If we have a multipart entity and a boundary, go recursive */
808 if ( (mime_content_type
!= NULL
) &&
809 (nested_context
.boundary
!= NULL
) &&
810 (Ustrncmp(mime_content_type
,"multipart",9) == 0) )
812 DEBUG(D_acl
) debug_printf("Entering multipart recursion, boundary '%s'\n",
813 nested_context
.boundary
);
815 nested_context
.context
=
816 context
&& context
->context
== MBC_ATTACHMENT
818 : Ustrcmp(mime_content_type
,"multipart/alternative") == 0
819 || Ustrcmp(mime_content_type
,"multipart/related") == 0
820 ? MBC_COVERLETTER_ALL
821 : MBC_COVERLETTER_ONESHOT
;
823 rc
= mime_acl_check(acl
, f
, &nested_context
, user_msgptr
, log_msgptr
);
826 else if ( (mime_content_type
!= NULL
) &&
827 (Ustrncmp(mime_content_type
,"message/rfc822",14) == 0) )
829 const uschar
*rfc822name
= NULL
;
830 uschar filename
[2048];
834 /* must find first free sequential filename */
838 (void)string_format(filename
, 2048,
839 "%s/scan/%s/__rfc822_%05u", spool_directory
, message_id
, file_nr
++);
843 result
= stat(CS filename
,&mystat
);
844 } while (result
!= -1);
846 rfc822name
= filename
;
848 /* decode RFC822 attachment */
849 mime_decoded_filename
= NULL
;
851 mime_current_boundary
= context
? context
->boundary
: NULL
;
852 mime_decode(&rfc822name
);
854 mime_current_boundary
= NULL
;
855 if (!mime_decoded_filename
) /* decoding failed */
857 log_write(0, LOG_MAIN
,
858 "mime_regex acl condition warning - could not decode RFC822 MIME part to file.");
862 mime_decoded_filename
= NULL
;
866 /* If the boundary of this instance is NULL, we are finished here */
869 if (context
->context
== MBC_COVERLETTER_ONESHOT
)
870 context
->context
= MBC_ATTACHMENT
;
878 #endif /*WITH_CONTENT_SCAN*/