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 2015 - 2018
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 /* name namelen value */
20 { US"content-type:", 13, &mime_content_type },
21 { US"content-disposition:", 20, &mime_content_disposition },
22 { US"content-transfer-encoding:", 26, &mime_content_transfer_encoding },
23 { US"content-id:", 11, &mime_content_id },
24 { US"content-description:", 20, &mime_content_description }
27 static int mime_header_list_size = nelem(mime_header_list);
29 static mime_parameter mime_parameter_list[] = {
30 /* name namelen value */
31 { US"name=", 5, &mime_filename },
32 { US"filename=", 9, &mime_filename },
33 { US"charset=", 8, &mime_charset },
34 { US"boundary=", 9, &mime_boundary }
38 /*************************************************
39 * set MIME anomaly level + text *
40 *************************************************/
42 /* Small wrapper to set the two expandables which
43 give info on detected "problems" in MIME
44 encodings. Indexes are defined in mime.h. */
47 mime_set_anomaly(int idx)
52 } anom[] = { {1, CUS"Broken Quoted-Printable encoding detected"},
53 {2, CUS"Broken BASE64 encoding detected"} };
55 mime_anomaly_level = anom[idx].level;
56 mime_anomaly_text = anom[idx].text;
60 /*************************************************
61 * decode quoted-printable chars *
62 *************************************************/
64 /* gets called when we hit a =
65 returns: new pointer position
68 -1 - soft line break, no char
73 mime_decode_qp_char(uschar *qp_p, int *c)
75 uschar *initial_pos = qp_p;
77 /* advance one char */
80 /* Check for two hex digits and decode them */
81 if (isxdigit(*qp_p) && isxdigit(qp_p[1]))
83 /* Do hex conversion */
84 *c = (isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10) <<4;
86 *c |= isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10;
90 /* tab or whitespace may follow just ignore it if it precedes \n */
91 while (*qp_p == '\t' || *qp_p == ' ' || *qp_p == '\r')
94 if (*qp_p == '\n') /* hit soft line break */
100 /* illegal char here */
106 /* just dump MIME part without any decoding */
108 mime_decode_asis(FILE* in, FILE* out, uschar* boundary)
110 ssize_t len, size = 0;
111 uschar buffer[MIME_MAX_LINE_LENGTH];
113 while(fgets(CS buffer, MIME_MAX_LINE_LENGTH, mime_stream) != NULL)
116 && Ustrncmp(buffer, "--", 2) == 0
117 && Ustrncmp((buffer+2), boundary, Ustrlen(boundary)) == 0
121 len = Ustrlen(buffer);
122 if (fwrite(buffer, 1, (size_t)len, out) < len)
131 /* decode quoted-printable MIME part */
133 mime_decode_qp(FILE* in, FILE* out, uschar* boundary)
135 uschar ibuf[MIME_MAX_LINE_LENGTH], obuf[MIME_MAX_LINE_LENGTH];
137 ssize_t len, size = 0;
139 while (fgets(CS ibuf, MIME_MAX_LINE_LENGTH, in) != NULL)
142 && Ustrncmp(ibuf, "--", 2) == 0
143 && Ustrncmp((ibuf+2), boundary, Ustrlen(boundary)) == 0
145 break; /* todo: check for missing boundary */
154 int decode_qp_result;
156 ipos = mime_decode_qp_char(ipos, &decode_qp_result);
158 if (decode_qp_result == -2)
160 /* Error from decoder. ipos is unchanged. */
161 mime_set_anomaly(MIME_ANOMALY_BROKEN_QP);
165 else if (decode_qp_result == -1)
167 else if (decode_qp_result >= 0)
168 *opos++ = decode_qp_result;
173 /* something to write? */
177 if (fwrite(obuf, 1, len, out) != len) return -1; /* error */
186 * Return open filehandle for combo of path and file.
187 * Side-effect: set mime_decoded_filename, to copy in allocated mem
190 mime_get_decode_file(uschar *pname, uschar *fname)
193 mime_decoded_filename = string_sprintf("%s/%s", pname, fname);
195 mime_decoded_filename = string_copy(fname);
201 /* must find first free sequential filename */
205 mime_decoded_filename = string_sprintf("%s/%s-%05u", pname, message_id, file_nr++);
209 result = stat(CS mime_decoded_filename, &mystat);
210 } while(result != -1);
213 return modefopen(mime_decoded_filename, "wb+", SPOOL_MODE);
218 mime_decode(const uschar **listptr)
221 const uschar *list = *listptr;
223 uschar * decode_path;
224 FILE *decode_file = NULL;
226 ssize_t size_counter = 0;
227 ssize_t (*decode_function)(FILE*, FILE*, uschar*);
229 if (!mime_stream || (f_pos = ftell(mime_stream)) < 0)
232 /* build default decode path (will exist since MBOX must be spooled up) */
233 decode_path = string_sprintf("%s/scan/%s", spool_directory, message_id);
235 /* try to find 1st option */
236 if ((option = string_nextinlist(&list, &sep, NULL, 0)))
238 /* parse 1st option */
239 if ((Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0))
240 /* explicitly no decoding */
243 if (Ustrcmp(option,"default") == 0)
244 /* explicit default path + file names */
247 if (option[0] == '/')
251 memset(&statbuf,0,sizeof(statbuf));
253 /* assume either path or path+file name */
254 if ( (stat(CS option, &statbuf) == 0) && S_ISDIR(statbuf.st_mode) )
255 /* is directory, use it as decode_path */
256 decode_file = mime_get_decode_file(option, NULL);
258 /* does not exist or is a file, use as full file name */
259 decode_file = mime_get_decode_file(NULL, option);
262 /* assume file name only, use default path */
263 decode_file = mime_get_decode_file(decode_path, option);
267 /* no option? patch default path */
269 decode_file = mime_get_decode_file(decode_path, NULL);
275 /* decode according to mime type */
277 !mime_content_transfer_encoding
278 ? mime_decode_asis /* no encoding, dump as-is */
279 : Ustrcmp(mime_content_transfer_encoding, "base64") == 0
281 : Ustrcmp(mime_content_transfer_encoding, "quoted-printable") == 0
283 : mime_decode_asis; /* unknown encoding type, just dump as-is */
285 size_counter = decode_function(mime_stream, decode_file, mime_current_boundary);
287 clearerr(mime_stream);
288 if (fseek(mime_stream, f_pos, SEEK_SET))
291 if (fclose(decode_file) != 0 || size_counter < 0)
294 /* round up to the next KiB */
295 mime_content_size = (size_counter + 1023) / 1024;
302 mime_get_header(FILE *f, uschar *header)
306 int header_value_mode = 0;
307 int header_open_brackets = 0;
312 if ((c = fgetc(f)) == EOF) break;
314 /* always skip CRs */
315 if (c == '\r') continue;
321 /* look if next char is '\t' or ' ' */
322 if ((c = fgetc(f)) == EOF) break;
323 if ( (c == '\t') || (c == ' ') ) continue;
326 /* end of the header, terminate with ';' */
331 /* skip control characters */
332 if (c < 32) continue;
334 if (header_value_mode)
336 /* --------- value mode ----------- */
337 /* skip leading whitespace */
338 if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
341 /* we have hit a non-whitespace char, start copying value data */
342 header_value_mode = 2;
344 if (c == '"') /* flip "quoted" mode */
345 header_value_mode = header_value_mode==2 ? 3 : 2;
347 /* leave value mode on unquoted ';' */
348 if (header_value_mode == 2 && c == ';')
349 header_value_mode = 0;
350 /* -------------------------------- */
354 /* -------- non-value mode -------- */
355 /* skip whitespace + tabs */
356 if ( (c == ' ') || (c == '\t') )
360 /* quote next char. can be used
361 to escape brackets. */
362 if ((c = fgetc(f)) == EOF) break;
366 header_open_brackets++;
369 else if ((c == ')') && header_open_brackets)
371 header_open_brackets--;
374 else if ( (c == '=') && !header_open_brackets ) /* enter value mode */
375 header_value_mode = 1;
377 /* skip chars while we are in a comment */
378 if (header_open_brackets > 0)
380 /* -------------------------------- */
383 /* copy the char to the buffer */
384 header[num_copied++] = (uschar)c;
386 /* break if header buffer is full */
387 if (num_copied > MIME_MAX_HEADER_SIZE-1)
391 if ((num_copied > 0) && (header[num_copied-1] != ';'))
392 header[num_copied-1] = ';';
395 header[num_copied] = '\0';
397 /* return 0 for EOF or empty line */
398 if ((c == EOF) || (num_copied == 1))
406 mime_vars_reset(void)
408 mime_anomaly_level = 0;
409 mime_anomaly_text = NULL;
410 mime_boundary = NULL;
412 mime_decoded_filename = NULL;
413 mime_filename = NULL;
414 mime_content_description = NULL;
415 mime_content_disposition = NULL;
416 mime_content_id = NULL;
417 mime_content_transfer_encoding = NULL;
418 mime_content_type = NULL;
419 mime_is_multipart = 0;
420 mime_content_size = 0;
424 /* Grab a parameter value, dealing with quoting.
427 str Input string. Updated on return to point to terminating ; or NUL
430 Allocated string with parameter value
433 mime_param_val(uschar ** sp)
436 gstring * val = NULL;
438 /* debug_printf_indent(" considering paramval '%s'\n", s); */
440 while (*s && *s != ';') /* ; terminates */
443 s++; /* skip opening " */
444 while (*s && *s != '"') /* " protects ; */
445 val = string_catn(val, s++, 1);
446 if (*s) s++; /* skip closing " */
449 val = string_catn(val, s++, 1);
451 return string_from_gstring(val);
455 mime_next_semicolon(uschar * s)
457 while (*s && *s != ';') /* ; terminates */
460 s++; /* skip opening " */
461 while (*s && *s != '"') /* " protects ; */
463 if (*s) s++; /* skip closing " */
472 rfc2231_to_2047(const uschar * fname, const uschar * charset, int * len)
474 gstring * val = string_catn(NULL, US"=?", 2);
478 val = string_cat(val, charset);
479 val = string_catn(val, US"?Q?", 3);
482 if (c == '%' && isxdigit(fname[1]) && isxdigit(fname[2]))
484 val = string_catn(val, US"=", 1);
485 val = string_catn(val, ++fname, 2);
489 val = string_catn(val, fname++, 1);
491 val = string_catn(val, US"?=", 2);
493 return string_from_gstring(val);
498 mime_acl_check(uschar *acl, FILE *f, struct mime_boundary_context *context,
499 uschar **user_msgptr, uschar **log_msgptr)
502 uschar * header = NULL;
503 struct mime_boundary_context nested_context;
505 /* reserve a line buffer to work in */
506 header = store_get(MIME_MAX_HEADER_SIZE+1);
508 /* Not actually used at the moment, but will be vital to fixing
509 * some RFC 2046 nonconformance later... */
510 nested_context.parent = context;
512 /* loop through parts */
515 /* reset all per-part mime variables */
518 /* If boundary is null, we assume that *f is positioned on the start of
519 headers (for example, at the very beginning of a message. If a boundary is
520 given, we must first advance to it to reach the start of the next header
523 /* NOTE -- there's an error here -- RFC2046 specifically says to
524 * check for outer boundaries. This code doesn't do that, and
525 * I haven't fixed this.
527 * (I have moved partway towards adding support, however, by adding
528 * a "parent" field to my new boundary-context structure.)
530 if (context) for (;;)
532 if (!fgets(CS header, MIME_MAX_HEADER_SIZE, f))
534 /* Hit EOF or read error. Ugh. */
535 DEBUG(D_acl) debug_printf_indent("MIME: Hit EOF ...\n");
539 /* boundary line must start with 2 dashes */
540 if ( Ustrncmp(header, "--", 2) == 0
541 && Ustrncmp(header+2, context->boundary, Ustrlen(context->boundary)) == 0
543 { /* found boundary */
544 if (Ustrncmp((header+2+Ustrlen(context->boundary)), "--", 2) == 0)
546 /* END boundary found */
547 DEBUG(D_acl) debug_printf_indent("MIME: End boundary found %s\n",
552 DEBUG(D_acl) debug_printf_indent("MIME: Next part with boundary %s\n",
558 /* parse headers, set up expansion variables */
559 while (mime_get_header(f, header))
561 struct mime_header * mh;
563 /* look for interesting headers */
564 for (mh = mime_header_list;
565 mh < mime_header_list + mime_header_list_size;
566 mh++) if (strncmpic(mh->name, header, mh->namelen) == 0)
568 uschar * p = header + mh->namelen;
571 /* grab the value (normalize to lower case)
572 and copy to its corresponding expansion variable */
574 for (q = p; *q != ';' && *q; q++) ;
575 *mh->value = string_copynlc(p, q-p);
576 DEBUG(D_acl) debug_printf_indent("MIME: found %s header, value is '%s'\n",
577 mh->name, *mh->value);
579 if (*(p = q)) p++; /* jump past the ; */
582 uschar * mime_fname = NULL;
583 uschar * mime_fname_rfc2231 = NULL;
584 uschar * mime_filename_charset = NULL;
585 BOOL decoding_failed = FALSE;
587 /* grab all param=value tags on the remaining line,
588 check if they are interesting */
594 DEBUG(D_acl) debug_printf_indent("MIME: considering paramlist '%s'\n", p);
597 && strncmpic(CUS"content-disposition:", header, 20) == 0
598 && strncmpic(CUS"filename*", p, 9) == 0
600 { /* RFC 2231 filename */
603 /* find value of the filename */
605 while(*p != '=' && *p) p++;
606 if (*p) p++; /* p is filename or NUL */
607 q = mime_param_val(&p); /* p now trailing ; or NUL */
611 uschar * temp_string, * err_msg;
614 /* build up an un-decoded filename over successive
615 filename*= parameters (for use when 2047 decode fails) */
617 mime_fname_rfc2231 = string_sprintf("%#s%s",
618 mime_fname_rfc2231, q);
620 if (!decoding_failed)
623 if (!mime_filename_charset)
627 /* look for a ' in the "filename" */
628 while(*s != '\'' && *s) s++; /* s is 1st ' or NUL */
630 if ((size = s-q) > 0)
631 mime_filename_charset = string_copyn(q, size);
634 while(*p == '\'') p++; /* p is after 2nd ' */
639 DEBUG(D_acl) debug_printf_indent("MIME: charset %s fname '%s'\n",
640 mime_filename_charset ? mime_filename_charset : US"<NULL>", p);
642 temp_string = rfc2231_to_2047(p, mime_filename_charset, &slen);
643 DEBUG(D_acl) debug_printf_indent("MIME: 2047-name %s\n", temp_string);
645 temp_string = rfc2047_decode(temp_string, FALSE, NULL, ' ',
647 DEBUG(D_acl) debug_printf_indent("MIME: plain-name %s\n", temp_string);
649 if (!temp_string || (size = Ustrlen(temp_string)) == slen)
650 decoding_failed = TRUE;
652 /* build up a decoded filename over successive
653 filename*= parameters */
655 mime_filename = mime_fname = mime_fname
656 ? string_sprintf("%s%s", mime_fname, temp_string)
663 /* look for interesting parameters */
664 for (mp = mime_parameter_list;
665 mp < mime_parameter_list + nelem(mime_parameter_list);
667 ) if (strncmpic(mp->name, p, mp->namelen) == 0)
670 uschar * dummy_errstr;
672 /* grab the value and copy to its expansion variable */
674 q = mime_param_val(&p); /* p now trailing ; or NUL */
677 ? rfc2047_decode(q, check_rfc2047_length, NULL, 32, NULL,
680 DEBUG(D_acl) debug_printf_indent(
681 "MIME: found %s parameter in %s header, value '%s'\n",
682 mp->name, mh->name, *mp->value);
684 break; /* done matching param names */
688 /* There is something, but not one of our interesting parameters.
689 Advance past the next semicolon */
690 p = mime_next_semicolon(p);
692 } /* param scan on line */
694 if (strncmpic(CUS"content-disposition:", header, 20) == 0)
696 if (decoding_failed) mime_filename = mime_fname_rfc2231;
698 DEBUG(D_acl) debug_printf_indent(
699 "MIME: found %s parameter in %s header, value is '%s'\n",
700 "filename", mh->name, mime_filename);
706 /* set additional flag variables (easier access) */
707 if ( mime_content_type
708 && Ustrncmp(mime_content_type,"multipart",9) == 0
710 mime_is_multipart = 1;
712 /* Make a copy of the boundary pointer.
713 Required since mime_boundary is global
714 and can be overwritten further down in recursion */
715 nested_context.boundary = mime_boundary;
717 /* raise global counter */
720 /* copy current file handle to global variable */
722 mime_current_boundary = context ? context->boundary : 0;
724 /* Note the context */
725 mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
727 /* call ACL handling function */
728 rc = acl_check(ACL_WHERE_MIME, NULL, acl, user_msgptr, log_msgptr);
731 mime_current_boundary = NULL;
735 /* If we have a multipart entity and a boundary, go recursive */
736 if ( (mime_content_type != NULL) &&
737 (nested_context.boundary != NULL) &&
738 (Ustrncmp(mime_content_type,"multipart",9) == 0) )
741 debug_printf_indent("MIME: Entering multipart recursion, boundary '%s'\n",
742 nested_context.boundary);
744 nested_context.context =
745 context && context->context == MBC_ATTACHMENT
747 : Ustrcmp(mime_content_type,"multipart/alternative") == 0
748 || Ustrcmp(mime_content_type,"multipart/related") == 0
749 ? MBC_COVERLETTER_ALL
750 : MBC_COVERLETTER_ONESHOT;
752 rc = mime_acl_check(acl, f, &nested_context, user_msgptr, log_msgptr);
755 else if ( (mime_content_type != NULL) &&
756 (Ustrncmp(mime_content_type,"message/rfc822",14) == 0) )
758 const uschar *rfc822name = NULL;
759 uschar filename[2048];
763 /* must find first free sequential filename */
767 (void)string_format(filename, 2048,
768 "%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr++);
772 result = stat(CS filename,&mystat);
773 } while (result != -1);
775 rfc822name = filename;
777 /* decode RFC822 attachment */
778 mime_decoded_filename = NULL;
780 mime_current_boundary = context ? context->boundary : NULL;
781 mime_decode(&rfc822name);
783 mime_current_boundary = NULL;
784 if (!mime_decoded_filename) /* decoding failed */
786 log_write(0, LOG_MAIN,
787 "MIME acl condition warning - could not decode RFC822 MIME part to file.");
791 mime_decoded_filename = NULL;
795 /* If the boundary of this instance is NULL, we are finished here */
798 if (context->context == MBC_COVERLETTER_ONESHOT)
799 context->context = MBC_ATTACHMENT;
807 #endif /*WITH_CONTENT_SCAN*/