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;
15 static int mime_header_list_size = sizeof(mime_header_list)/sizeof(mime_header);
17 static mime_parameter mime_parameter_list[] = {
18 { US"name=", 5, &mime_filename },
19 { US"filename=", 9, &mime_filename },
20 { US"charset=", 8, &mime_charset },
21 { US"boundary=", 9, &mime_boundary }
25 /*************************************************
26 * set MIME anomaly level + text *
27 *************************************************/
29 /* Small wrapper to set the two expandables which
30 give info on detected "problems" in MIME
31 encodings. Indexes are defined in mime.h. */
34 mime_set_anomaly(int idx)
39 } anom[] = { {1, CUS"Broken Quoted-Printable encoding detected"},
40 {2, CUS"Broken BASE64 encoding detected"} };
42 mime_anomaly_level = anom[idx].level;
43 mime_anomaly_text = anom[idx].text;
47 /*************************************************
48 * decode quoted-printable chars *
49 *************************************************/
51 /* gets called when we hit a =
52 returns: new pointer position
55 -1 - soft line break, no char
60 mime_decode_qp_char(uschar *qp_p, int *c)
62 uschar *initial_pos = qp_p;
64 /* advance one char */
67 /* Check for two hex digits and decode them */
68 if (isxdigit(*qp_p) && isxdigit(qp_p[1]))
70 /* Do hex conversion */
71 *c = (isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10) <<4;
73 *c |= isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10;
77 /* tab or whitespace may follow just ignore it if it precedes \n */
78 while (*qp_p == '\t' || *qp_p == ' ' || *qp_p == '\r')
81 if (*qp_p == '\n') /* hit soft line break */
87 /* illegal char here */
93 /* just dump MIME part without any decoding */
95 mime_decode_asis(FILE* in, FILE* out, uschar* boundary)
97 ssize_t len, size = 0;
98 uschar buffer[MIME_MAX_LINE_LENGTH];
100 while(fgets(CS buffer, MIME_MAX_LINE_LENGTH, mime_stream) != NULL)
103 && Ustrncmp(buffer, "--", 2) == 0
104 && Ustrncmp((buffer+2), boundary, Ustrlen(boundary)) == 0
108 len = Ustrlen(buffer);
109 if (fwrite(buffer, 1, (size_t)len, out) < len)
118 /* decode quoted-printable MIME part */
120 mime_decode_qp(FILE* in, FILE* out, uschar* boundary)
122 uschar ibuf[MIME_MAX_LINE_LENGTH], obuf[MIME_MAX_LINE_LENGTH];
124 ssize_t len, size = 0;
126 while (fgets(CS ibuf, MIME_MAX_LINE_LENGTH, in) != NULL)
129 && Ustrncmp(ibuf, "--", 2) == 0
130 && Ustrncmp((ibuf+2), boundary, Ustrlen(boundary)) == 0
132 break; /* todo: check for missing boundary */
141 int decode_qp_result;
143 ipos = mime_decode_qp_char(ipos, &decode_qp_result);
145 if (decode_qp_result == -2)
147 /* Error from decoder. ipos is unchanged. */
148 mime_set_anomaly(MIME_ANOMALY_BROKEN_QP);
153 else if (decode_qp_result == -1)
155 else if (decode_qp_result >= 0)
157 *opos = decode_qp_result;
168 /* something to write? */
172 if (fwrite(obuf, 1, len, out) != len) return -1; /* error */
181 mime_get_decode_file(uschar *pname, uschar *fname)
186 filename = (uschar *)malloc(2048);
190 (void)string_format(filename, 2048, "%s/%s", pname, fname);
191 f = modefopen(filename,"wb+",SPOOL_MODE);
194 f = modefopen(fname,"wb+",SPOOL_MODE);
200 /* must find first free sequential filename */
204 (void)string_format(filename, 2048,
205 "%s/%s-%05u", pname, message_id, file_nr++);
209 result = stat(CS filename, &mystat);
210 } while(result != -1);
212 f = modefopen(filename, "wb+", SPOOL_MODE);
215 /* set expansion variable */
216 mime_decoded_filename = filename;
223 mime_decode(const uschar **listptr)
226 const uschar *list = *listptr;
228 uschar option_buffer[1024];
229 uschar decode_path[1024];
230 FILE *decode_file = NULL;
232 ssize_t size_counter = 0;
233 ssize_t (*decode_function)(FILE*, FILE*, uschar*);
235 if (mime_stream == NULL)
238 f_pos = ftell(mime_stream);
240 /* build default decode path (will exist since MBOX must be spooled up) */
241 (void)string_format(decode_path,1024,"%s/scan/%s",spool_directory,message_id);
243 /* try to find 1st option */
244 if ((option = string_nextinlist(&list, &sep,
246 sizeof(option_buffer))) != NULL)
248 /* parse 1st option */
249 if ( (Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0) )
250 /* explicitly no decoding */
253 if (Ustrcmp(option,"default") == 0)
254 /* explicit default path + file names */
257 if (option[0] == '/')
261 memset(&statbuf,0,sizeof(statbuf));
263 /* assume either path or path+file name */
264 if ( (stat(CS option, &statbuf) == 0) && S_ISDIR(statbuf.st_mode) )
265 /* is directory, use it as decode_path */
266 decode_file = mime_get_decode_file(option, NULL);
268 /* does not exist or is a file, use as full file name */
269 decode_file = mime_get_decode_file(NULL, option);
272 /* assume file name only, use default path */
273 decode_file = mime_get_decode_file(decode_path, option);
277 /* no option? patch default path */
279 decode_file = mime_get_decode_file(decode_path, NULL);
285 /* decode according to mime type */
287 !mime_content_transfer_encoding
288 ? mime_decode_asis /* no encoding, dump as-is */
289 : Ustrcmp(mime_content_transfer_encoding, "base64") == 0
291 : Ustrcmp(mime_content_transfer_encoding, "quoted-printable") == 0
293 : mime_decode_asis; /* unknown encoding type, just dump as-is */
295 size_counter = decode_function(mime_stream, decode_file, mime_current_boundary);
297 clearerr(mime_stream);
298 fseek(mime_stream, f_pos, SEEK_SET);
300 if (fclose(decode_file) != 0 || size_counter < 0)
303 /* round up to the next KiB */
304 mime_content_size = (size_counter + 1023) / 1024;
311 mime_get_header(FILE *f, uschar *header)
315 int header_value_mode = 0;
316 int header_open_brackets = 0;
321 if ((c = fgetc(f)) == EOF) break;
323 /* always skip CRs */
324 if (c == '\r') continue;
330 /* look if next char is '\t' or ' ' */
331 if ((c = fgetc(f)) == EOF) break;
332 if ( (c == '\t') || (c == ' ') ) continue;
335 /* end of the header, terminate with ';' */
340 /* skip control characters */
341 if (c < 32) continue;
343 if (header_value_mode)
345 /* --------- value mode ----------- */
346 /* skip leading whitespace */
347 if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
350 /* we have hit a non-whitespace char, start copying value data */
351 header_value_mode = 2;
353 if (c == '"') /* flip "quoted" mode */
354 header_value_mode = header_value_mode==2 ? 3 : 2;
356 /* leave value mode on unquoted ';' */
357 if (header_value_mode == 2 && c == ';') {
358 header_value_mode = 0;
360 /* -------------------------------- */
364 /* -------- non-value mode -------- */
365 /* skip whitespace + tabs */
366 if ( (c == ' ') || (c == '\t') )
370 /* quote next char. can be used
371 to escape brackets. */
372 if ((c = fgetc(f)) == EOF) break;
376 header_open_brackets++;
379 else if ((c == ')') && header_open_brackets)
381 header_open_brackets--;
384 else if ( (c == '=') && !header_open_brackets ) /* enter value mode */
385 header_value_mode = 1;
387 /* skip chars while we are in a comment */
388 if (header_open_brackets > 0)
390 /* -------------------------------- */
393 /* copy the char to the buffer */
394 header[num_copied++] = (uschar)c;
396 /* break if header buffer is full */
397 if (num_copied > MIME_MAX_HEADER_SIZE-1)
401 if ((num_copied > 0) && (header[num_copied-1] != ';'))
402 header[num_copied-1] = ';';
405 header[num_copied] = '\0';
407 /* return 0 for EOF or empty line */
408 if ((c == EOF) || (num_copied == 1))
416 mime_vars_reset(void)
418 mime_anomaly_level = 0;
419 mime_anomaly_text = NULL;
420 mime_boundary = NULL;
422 mime_decoded_filename = NULL;
423 mime_filename = NULL;
424 mime_content_description = NULL;
425 mime_content_disposition = NULL;
426 mime_content_id = NULL;
427 mime_content_transfer_encoding = NULL;
428 mime_content_type = NULL;
429 mime_is_multipart = 0;
430 mime_content_size = 0;
434 /* Grab a parameter value, dealing with quoting.
437 str Input string. Updated on return to point to terminating ; or NUL
440 Allocated string with parameter value
443 mime_param_val(uschar ** sp)
447 int size = 0, ptr = 0;
449 /* debug_printf(" considering paramval '%s'\n", s); */
451 while (*s && *s != ';') /* ; terminates */
454 s++; /* skip opening " */
455 while (*s && *s != '"') /* " protects ; */
456 val = string_cat(val, &size, &ptr, s++, 1);
457 if (*s) s++; /* skip closing " */
460 val = string_cat(val, &size, &ptr, s++, 1);
461 if (val) val[ptr] = '\0';
467 mime_next_semicolon(uschar * s)
469 while (*s && *s != ';') /* ; terminates */
472 s++; /* skip opening " */
473 while (*s && *s != '"') /* " protects ; */
475 if (*s) s++; /* skip closing " */
484 rfc2231_to_2047(const uschar * fname, const uschar * charset, int * len)
486 int size = 0, ptr = 0;
487 uschar * val = string_cat(NULL, &size, &ptr, US"=?", 2);
491 val = string_cat(val, &size, &ptr, charset, Ustrlen(charset));
492 val = string_cat(val, &size, &ptr, US"?Q?", 3);
495 if (c == '%' && isxdigit(fname[1]) && isxdigit(fname[2]))
497 val = string_cat(val, &size, &ptr, US"=", 1);
498 val = string_cat(val, &size, &ptr, ++fname, 2);
502 val = string_cat(val, &size, &ptr, fname++, 1);
504 val = string_cat(val, &size, &ptr, US"?=", 2);
505 val[*len = ptr] = '\0';
511 mime_acl_check(uschar *acl, FILE *f, struct mime_boundary_context *context,
512 uschar **user_msgptr, uschar **log_msgptr)
515 uschar * header = NULL;
516 struct mime_boundary_context nested_context;
518 /* reserve a line buffer to work in */
519 header = store_get(MIME_MAX_HEADER_SIZE+1);
521 /* Not actually used at the moment, but will be vital to fixing
522 * some RFC 2046 nonconformance later... */
523 nested_context.parent = context;
525 /* loop through parts */
528 /* reset all per-part mime variables */
531 /* If boundary is null, we assume that *f is positioned on the start of
532 headers (for example, at the very beginning of a message. If a boundary is
533 given, we must first advance to it to reach the start of the next header
536 /* NOTE -- there's an error here -- RFC2046 specifically says to
537 * check for outer boundaries. This code doesn't do that, and
538 * I haven't fixed this.
540 * (I have moved partway towards adding support, however, by adding
541 * a "parent" field to my new boundary-context structure.)
543 if (context) for (;;)
545 if (!fgets(CS header, MIME_MAX_HEADER_SIZE, f))
547 /* Hit EOF or read error. Ugh. */
548 DEBUG(D_acl) debug_printf("MIME: Hit EOF ...\n");
552 /* boundary line must start with 2 dashes */
553 if ( Ustrncmp(header, "--", 2) == 0
554 && Ustrncmp(header+2, context->boundary, Ustrlen(context->boundary)) == 0
556 { /* found boundary */
557 if (Ustrncmp((header+2+Ustrlen(context->boundary)), "--", 2) == 0)
559 /* END boundary found */
560 DEBUG(D_acl) debug_printf("MIME: End boundary found %s\n",
565 DEBUG(D_acl) debug_printf("MIME: Next part with boundary %s\n",
571 /* parse headers, set up expansion variables */
572 while (mime_get_header(f, header))
574 struct mime_header * mh;
576 /* look for interesting headers */
577 for (mh = mime_header_list;
578 mh < mime_header_list + mime_header_list_size;
579 mh++) if (strncmpic(mh->name, header, mh->namelen) == 0)
581 uschar * p = header + mh->namelen;
584 /* grab the value (normalize to lower case)
585 and copy to its corresponding expansion variable */
587 for (q = p; *q != ';' && *q; q++) ;
588 *mh->value = string_copynlc(p, q-p);
589 DEBUG(D_acl) debug_printf("MIME: found %s header, value is '%s'\n",
590 mh->name, *mh->value);
592 if (*(p = q)) p++; /* jump past the ; */
595 uschar * mime_fname = NULL;
596 uschar * mime_fname_rfc2231 = NULL;
597 uschar * mime_filename_charset = NULL;
598 BOOL decoding_failed = FALSE;
600 /* grab all param=value tags on the remaining line,
601 check if they are interesting */
607 DEBUG(D_acl) debug_printf("MIME: considering paramlist '%s'\n", p);
610 && strncmpic(CUS"content-disposition:", header, 20) == 0
611 && strncmpic(CUS"filename*", p, 9) == 0
613 { /* RFC 2231 filename */
616 /* find value of the filename */
618 while(*p != '=' && *p) p++;
619 if (*p) p++; /* p is filename or NUL */
620 q = mime_param_val(&p); /* p now trailing ; or NUL */
624 uschar * temp_string, * err_msg;
627 /* build up an un-decoded filename over successive
628 filename*= parameters (for use when 2047 decode fails) */
630 mime_fname_rfc2231 = string_sprintf("%#s%s",
631 mime_fname_rfc2231, q);
633 if (!decoding_failed)
636 if (!mime_filename_charset)
640 /* look for a ' in the "filename" */
641 while(*s != '\'' && *s) s++; /* s is 1st ' or NUL */
643 if ((size = s-q) > 0)
644 mime_filename_charset = string_copyn(q, size);
647 while(*p == '\'') p++; /* p is after 2nd ' */
652 DEBUG(D_acl) debug_printf("MIME: charset %s fname '%s'\n",
653 mime_filename_charset ? mime_filename_charset : US"<NULL>", p);
655 temp_string = rfc2231_to_2047(p, mime_filename_charset, &slen);
656 DEBUG(D_acl) debug_printf("MIME: 2047-name %s\n", temp_string);
658 temp_string = rfc2047_decode(temp_string, FALSE, NULL, ' ',
660 DEBUG(D_acl) debug_printf("MIME: plain-name %s\n", temp_string);
662 size = Ustrlen(temp_string);
665 decoding_failed = TRUE;
667 /* build up a decoded filename over successive
668 filename*= parameters */
670 mime_filename = mime_fname = mime_fname
671 ? string_sprintf("%s%s", mime_fname, temp_string)
678 /* look for interesting parameters */
679 for (mp = mime_parameter_list;
680 mp < mime_parameter_list + nelem(mime_parameter_list);
682 ) if (strncmpic(mp->name, p, mp->namelen) == 0)
685 uschar * dummy_errstr;
687 /* grab the value and copy to its expansion variable */
689 q = mime_param_val(&p); /* p now trailing ; or NUL */
692 ? rfc2047_decode(q, check_rfc2047_length, NULL, 32, NULL,
695 DEBUG(D_acl) debug_printf(
696 "MIME: found %s parameter in %s header, value '%s'\n",
697 mp->name, mh->name, *mp->value);
699 break; /* done matching param names */
703 /* There is something, but not one of our interesting parameters.
704 Advance past the next semicolon */
705 p = mime_next_semicolon(p);
707 } /* param scan on line */
709 if (strncmpic(CUS"content-disposition:", header, 20) == 0)
711 if (decoding_failed) mime_filename = mime_fname_rfc2231;
713 DEBUG(D_acl) debug_printf(
714 "MIME: found %s parameter in %s header, value is '%s'\n",
715 "filename", mh->name, mime_filename);
721 /* set additional flag variables (easier access) */
722 if ( mime_content_type
723 && Ustrncmp(mime_content_type,"multipart",9) == 0
725 mime_is_multipart = 1;
727 /* Make a copy of the boundary pointer.
728 Required since mime_boundary is global
729 and can be overwritten further down in recursion */
730 nested_context.boundary = mime_boundary;
732 /* raise global counter */
735 /* copy current file handle to global variable */
737 mime_current_boundary = context ? context->boundary : 0;
739 /* Note the context */
740 mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
742 /* call ACL handling function */
743 rc = acl_check(ACL_WHERE_MIME, NULL, acl, user_msgptr, log_msgptr);
746 mime_current_boundary = NULL;
750 /* If we have a multipart entity and a boundary, go recursive */
751 if ( (mime_content_type != NULL) &&
752 (nested_context.boundary != NULL) &&
753 (Ustrncmp(mime_content_type,"multipart",9) == 0) )
756 debug_printf("MIME: Entering multipart recursion, boundary '%s'\n",
757 nested_context.boundary);
759 nested_context.context =
760 context && context->context == MBC_ATTACHMENT
762 : Ustrcmp(mime_content_type,"multipart/alternative") == 0
763 || Ustrcmp(mime_content_type,"multipart/related") == 0
764 ? MBC_COVERLETTER_ALL
765 : MBC_COVERLETTER_ONESHOT;
767 rc = mime_acl_check(acl, f, &nested_context, user_msgptr, log_msgptr);
770 else if ( (mime_content_type != NULL) &&
771 (Ustrncmp(mime_content_type,"message/rfc822",14) == 0) )
773 const uschar *rfc822name = NULL;
774 uschar filename[2048];
778 /* must find first free sequential filename */
782 (void)string_format(filename, 2048,
783 "%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr++);
787 result = stat(CS filename,&mystat);
788 } while (result != -1);
790 rfc822name = filename;
792 /* decode RFC822 attachment */
793 mime_decoded_filename = NULL;
795 mime_current_boundary = context ? context->boundary : NULL;
796 mime_decode(&rfc822name);
798 mime_current_boundary = NULL;
799 if (!mime_decoded_filename) /* decoding failed */
801 log_write(0, LOG_MAIN,
802 "mime_regex acl condition warning - could not decode RFC822 MIME part to file.");
806 mime_decoded_filename = NULL;
810 /* If the boundary of this instance is NULL, we are finished here */
813 if (context->context == MBC_COVERLETTER_ONESHOT)
814 context->context = MBC_ATTACHMENT;
822 #endif /*WITH_CONTENT_SCAN*/