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 static mime_header mime_header_list[] = {
17 { US"content-type:", 13, &mime_content_type },
18 { US"content-disposition:", 20, &mime_content_disposition },
19 { US"content-transfer-encoding:", 26, &mime_content_transfer_encoding },
20 { US"content-id:", 11, &mime_content_id },
21 { US"content-description:", 20, &mime_content_description }
24 static int mime_header_list_size = nelem(mime_header_list);
26 static mime_parameter mime_parameter_list[] = {
27 { US"name=", 5, &mime_filename },
28 { US"filename=", 9, &mime_filename },
29 { US"charset=", 8, &mime_charset },
30 { US"boundary=", 9, &mime_boundary }
34 /*************************************************
35 * set MIME anomaly level + text *
36 *************************************************/
38 /* Small wrapper to set the two expandables which
39 give info on detected "problems" in MIME
40 encodings. Indexes are defined in mime.h. */
43 mime_set_anomaly(int idx)
48 } anom[] = { {1, CUS"Broken Quoted-Printable encoding detected"},
49 {2, CUS"Broken BASE64 encoding detected"} };
51 mime_anomaly_level = anom[idx].level;
52 mime_anomaly_text = anom[idx].text;
56 /*************************************************
57 * decode quoted-printable chars *
58 *************************************************/
60 /* gets called when we hit a =
61 returns: new pointer position
64 -1 - soft line break, no char
69 mime_decode_qp_char(uschar *qp_p, int *c)
71 uschar *initial_pos = qp_p;
73 /* advance one char */
76 /* Check for two hex digits and decode them */
77 if (isxdigit(*qp_p) && isxdigit(qp_p[1]))
79 /* Do hex conversion */
80 *c = (isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10) <<4;
82 *c |= isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10;
86 /* tab or whitespace may follow just ignore it if it precedes \n */
87 while (*qp_p == '\t' || *qp_p == ' ' || *qp_p == '\r')
90 if (*qp_p == '\n') /* hit soft line break */
96 /* illegal char here */
102 /* just dump MIME part without any decoding */
104 mime_decode_asis(FILE* in, FILE* out, uschar* boundary)
106 ssize_t len, size = 0;
107 uschar buffer[MIME_MAX_LINE_LENGTH];
109 while(fgets(CS buffer, MIME_MAX_LINE_LENGTH, mime_stream) != NULL)
112 && Ustrncmp(buffer, "--", 2) == 0
113 && Ustrncmp((buffer+2), boundary, Ustrlen(boundary)) == 0
117 len = Ustrlen(buffer);
118 if (fwrite(buffer, 1, (size_t)len, out) < len)
127 /* decode quoted-printable MIME part */
129 mime_decode_qp(FILE* in, FILE* out, uschar* boundary)
131 uschar ibuf[MIME_MAX_LINE_LENGTH], obuf[MIME_MAX_LINE_LENGTH];
133 ssize_t len, size = 0;
135 while (fgets(CS ibuf, MIME_MAX_LINE_LENGTH, in) != NULL)
138 && Ustrncmp(ibuf, "--", 2) == 0
139 && Ustrncmp((ibuf+2), boundary, Ustrlen(boundary)) == 0
141 break; /* todo: check for missing boundary */
150 int decode_qp_result;
152 ipos = mime_decode_qp_char(ipos, &decode_qp_result);
154 if (decode_qp_result == -2)
156 /* Error from decoder. ipos is unchanged. */
157 mime_set_anomaly(MIME_ANOMALY_BROKEN_QP);
162 else if (decode_qp_result == -1)
164 else if (decode_qp_result >= 0)
166 *opos = decode_qp_result;
177 /* something to write? */
181 if (fwrite(obuf, 1, len, out) != len) return -1; /* error */
190 mime_get_decode_file(uschar *pname, uschar *fname)
195 filename = (uschar *)malloc(2048);
199 (void)string_format(filename, 2048, "%s/%s", pname, fname);
200 f = modefopen(filename,"wb+",SPOOL_MODE);
203 f = modefopen(fname,"wb+",SPOOL_MODE);
209 /* must find first free sequential filename */
213 (void)string_format(filename, 2048,
214 "%s/%s-%05u", pname, message_id, file_nr++);
218 result = stat(CS filename, &mystat);
219 } while(result != -1);
221 f = modefopen(filename, "wb+", SPOOL_MODE);
224 /* set expansion variable */
225 mime_decoded_filename = filename;
232 mime_decode(const uschar **listptr)
235 const uschar *list = *listptr;
237 uschar option_buffer[1024];
238 uschar decode_path[1024];
239 FILE *decode_file = NULL;
241 ssize_t size_counter = 0;
242 ssize_t (*decode_function)(FILE*, FILE*, uschar*);
244 if (mime_stream == NULL)
247 f_pos = ftell(mime_stream);
249 /* build default decode path (will exist since MBOX must be spooled up) */
250 (void)string_format(decode_path,1024,"%s/scan/%s",spool_directory,message_id);
252 /* try to find 1st option */
253 if ((option = string_nextinlist(&list, &sep,
255 sizeof(option_buffer))) != NULL)
257 /* parse 1st option */
258 if ( (Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0) )
259 /* explicitly no decoding */
262 if (Ustrcmp(option,"default") == 0)
263 /* explicit default path + file names */
266 if (option[0] == '/')
270 memset(&statbuf,0,sizeof(statbuf));
272 /* assume either path or path+file name */
273 if ( (stat(CS option, &statbuf) == 0) && S_ISDIR(statbuf.st_mode) )
274 /* is directory, use it as decode_path */
275 decode_file = mime_get_decode_file(option, NULL);
277 /* does not exist or is a file, use as full file name */
278 decode_file = mime_get_decode_file(NULL, option);
281 /* assume file name only, use default path */
282 decode_file = mime_get_decode_file(decode_path, option);
286 /* no option? patch default path */
288 decode_file = mime_get_decode_file(decode_path, NULL);
294 /* decode according to mime type */
296 !mime_content_transfer_encoding
297 ? mime_decode_asis /* no encoding, dump as-is */
298 : Ustrcmp(mime_content_transfer_encoding, "base64") == 0
300 : Ustrcmp(mime_content_transfer_encoding, "quoted-printable") == 0
302 : mime_decode_asis; /* unknown encoding type, just dump as-is */
304 size_counter = decode_function(mime_stream, decode_file, mime_current_boundary);
306 clearerr(mime_stream);
307 if (fseek(mime_stream, f_pos, SEEK_SET))
310 if (fclose(decode_file) != 0 || size_counter < 0)
313 /* round up to the next KiB */
314 mime_content_size = (size_counter + 1023) / 1024;
321 mime_get_header(FILE *f, uschar *header)
325 int header_value_mode = 0;
326 int header_open_brackets = 0;
331 if ((c = fgetc(f)) == EOF) break;
333 /* always skip CRs */
334 if (c == '\r') continue;
340 /* look if next char is '\t' or ' ' */
341 if ((c = fgetc(f)) == EOF) break;
342 if ( (c == '\t') || (c == ' ') ) continue;
345 /* end of the header, terminate with ';' */
350 /* skip control characters */
351 if (c < 32) continue;
353 if (header_value_mode)
355 /* --------- value mode ----------- */
356 /* skip leading whitespace */
357 if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
360 /* we have hit a non-whitespace char, start copying value data */
361 header_value_mode = 2;
363 if (c == '"') /* flip "quoted" mode */
364 header_value_mode = header_value_mode==2 ? 3 : 2;
366 /* leave value mode on unquoted ';' */
367 if (header_value_mode == 2 && c == ';') {
368 header_value_mode = 0;
370 /* -------------------------------- */
374 /* -------- non-value mode -------- */
375 /* skip whitespace + tabs */
376 if ( (c == ' ') || (c == '\t') )
380 /* quote next char. can be used
381 to escape brackets. */
382 if ((c = fgetc(f)) == EOF) break;
386 header_open_brackets++;
389 else if ((c == ')') && header_open_brackets)
391 header_open_brackets--;
394 else if ( (c == '=') && !header_open_brackets ) /* enter value mode */
395 header_value_mode = 1;
397 /* skip chars while we are in a comment */
398 if (header_open_brackets > 0)
400 /* -------------------------------- */
403 /* copy the char to the buffer */
404 header[num_copied++] = (uschar)c;
406 /* break if header buffer is full */
407 if (num_copied > MIME_MAX_HEADER_SIZE-1)
411 if ((num_copied > 0) && (header[num_copied-1] != ';'))
412 header[num_copied-1] = ';';
415 header[num_copied] = '\0';
417 /* return 0 for EOF or empty line */
418 if ((c == EOF) || (num_copied == 1))
426 mime_vars_reset(void)
428 mime_anomaly_level = 0;
429 mime_anomaly_text = NULL;
430 mime_boundary = NULL;
432 mime_decoded_filename = NULL;
433 mime_filename = NULL;
434 mime_content_description = NULL;
435 mime_content_disposition = NULL;
436 mime_content_id = NULL;
437 mime_content_transfer_encoding = NULL;
438 mime_content_type = NULL;
439 mime_is_multipart = 0;
440 mime_content_size = 0;
444 /* Grab a parameter value, dealing with quoting.
447 str Input string. Updated on return to point to terminating ; or NUL
450 Allocated string with parameter value
453 mime_param_val(uschar ** sp)
457 int size = 0, ptr = 0;
459 /* debug_printf(" considering paramval '%s'\n", s); */
461 while (*s && *s != ';') /* ; terminates */
464 s++; /* skip opening " */
465 while (*s && *s != '"') /* " protects ; */
466 val = string_cat(val, &size, &ptr, s++, 1);
467 if (*s) s++; /* skip closing " */
470 val = string_cat(val, &size, &ptr, s++, 1);
471 if (val) val[ptr] = '\0';
477 mime_next_semicolon(uschar * s)
479 while (*s && *s != ';') /* ; terminates */
482 s++; /* skip opening " */
483 while (*s && *s != '"') /* " protects ; */
485 if (*s) s++; /* skip closing " */
494 rfc2231_to_2047(const uschar * fname, const uschar * charset, int * len)
496 int size = 0, ptr = 0;
497 uschar * val = string_cat(NULL, &size, &ptr, US"=?", 2);
501 val = string_cat(val, &size, &ptr, charset, Ustrlen(charset));
502 val = string_cat(val, &size, &ptr, US"?Q?", 3);
505 if (c == '%' && isxdigit(fname[1]) && isxdigit(fname[2]))
507 val = string_cat(val, &size, &ptr, US"=", 1);
508 val = string_cat(val, &size, &ptr, ++fname, 2);
512 val = string_cat(val, &size, &ptr, fname++, 1);
514 val = string_cat(val, &size, &ptr, US"?=", 2);
515 val[*len = ptr] = '\0';
521 mime_acl_check(uschar *acl, FILE *f, struct mime_boundary_context *context,
522 uschar **user_msgptr, uschar **log_msgptr)
525 uschar * header = NULL;
526 struct mime_boundary_context nested_context;
528 /* reserve a line buffer to work in */
529 header = store_get(MIME_MAX_HEADER_SIZE+1);
531 /* Not actually used at the moment, but will be vital to fixing
532 * some RFC 2046 nonconformance later... */
533 nested_context.parent = context;
535 /* loop through parts */
538 /* reset all per-part mime variables */
541 /* If boundary is null, we assume that *f is positioned on the start of
542 headers (for example, at the very beginning of a message. If a boundary is
543 given, we must first advance to it to reach the start of the next header
546 /* NOTE -- there's an error here -- RFC2046 specifically says to
547 * check for outer boundaries. This code doesn't do that, and
548 * I haven't fixed this.
550 * (I have moved partway towards adding support, however, by adding
551 * a "parent" field to my new boundary-context structure.)
553 if (context) for (;;)
555 if (!fgets(CS header, MIME_MAX_HEADER_SIZE, f))
557 /* Hit EOF or read error. Ugh. */
558 DEBUG(D_acl) debug_printf("MIME: Hit EOF ...\n");
562 /* boundary line must start with 2 dashes */
563 if ( Ustrncmp(header, "--", 2) == 0
564 && Ustrncmp(header+2, context->boundary, Ustrlen(context->boundary)) == 0
566 { /* found boundary */
567 if (Ustrncmp((header+2+Ustrlen(context->boundary)), "--", 2) == 0)
569 /* END boundary found */
570 DEBUG(D_acl) debug_printf("MIME: End boundary found %s\n",
575 DEBUG(D_acl) debug_printf("MIME: Next part with boundary %s\n",
581 /* parse headers, set up expansion variables */
582 while (mime_get_header(f, header))
584 struct mime_header * mh;
586 /* look for interesting headers */
587 for (mh = mime_header_list;
588 mh < mime_header_list + mime_header_list_size;
589 mh++) if (strncmpic(mh->name, header, mh->namelen) == 0)
591 uschar * p = header + mh->namelen;
594 /* grab the value (normalize to lower case)
595 and copy to its corresponding expansion variable */
597 for (q = p; *q != ';' && *q; q++) ;
598 *mh->value = string_copynlc(p, q-p);
599 DEBUG(D_acl) debug_printf("MIME: found %s header, value is '%s'\n",
600 mh->name, *mh->value);
602 if (*(p = q)) p++; /* jump past the ; */
605 uschar * mime_fname = NULL;
606 uschar * mime_fname_rfc2231 = NULL;
607 uschar * mime_filename_charset = NULL;
608 BOOL decoding_failed = FALSE;
610 /* grab all param=value tags on the remaining line,
611 check if they are interesting */
617 DEBUG(D_acl) debug_printf("MIME: considering paramlist '%s'\n", p);
620 && strncmpic(CUS"content-disposition:", header, 20) == 0
621 && strncmpic(CUS"filename*", p, 9) == 0
623 { /* RFC 2231 filename */
626 /* find value of the filename */
628 while(*p != '=' && *p) p++;
629 if (*p) p++; /* p is filename or NUL */
630 q = mime_param_val(&p); /* p now trailing ; or NUL */
634 uschar * temp_string, * err_msg;
637 /* build up an un-decoded filename over successive
638 filename*= parameters (for use when 2047 decode fails) */
640 mime_fname_rfc2231 = string_sprintf("%#s%s",
641 mime_fname_rfc2231, q);
643 if (!decoding_failed)
646 if (!mime_filename_charset)
650 /* look for a ' in the "filename" */
651 while(*s != '\'' && *s) s++; /* s is 1st ' or NUL */
653 if ((size = s-q) > 0)
654 mime_filename_charset = string_copyn(q, size);
657 while(*p == '\'') p++; /* p is after 2nd ' */
662 DEBUG(D_acl) debug_printf("MIME: charset %s fname '%s'\n",
663 mime_filename_charset ? mime_filename_charset : US"<NULL>", p);
665 temp_string = rfc2231_to_2047(p, mime_filename_charset, &slen);
666 DEBUG(D_acl) debug_printf("MIME: 2047-name %s\n", temp_string);
668 temp_string = rfc2047_decode(temp_string, FALSE, NULL, ' ',
670 DEBUG(D_acl) debug_printf("MIME: plain-name %s\n", temp_string);
672 size = Ustrlen(temp_string);
675 decoding_failed = TRUE;
677 /* build up a decoded filename over successive
678 filename*= parameters */
680 mime_filename = mime_fname = mime_fname
681 ? string_sprintf("%s%s", mime_fname, temp_string)
688 /* look for interesting parameters */
689 for (mp = mime_parameter_list;
690 mp < mime_parameter_list + nelem(mime_parameter_list);
692 ) if (strncmpic(mp->name, p, mp->namelen) == 0)
695 uschar * dummy_errstr;
697 /* grab the value and copy to its expansion variable */
699 q = mime_param_val(&p); /* p now trailing ; or NUL */
702 ? rfc2047_decode(q, check_rfc2047_length, NULL, 32, NULL,
705 DEBUG(D_acl) debug_printf(
706 "MIME: found %s parameter in %s header, value '%s'\n",
707 mp->name, mh->name, *mp->value);
709 break; /* done matching param names */
713 /* There is something, but not one of our interesting parameters.
714 Advance past the next semicolon */
715 p = mime_next_semicolon(p);
717 } /* param scan on line */
719 if (strncmpic(CUS"content-disposition:", header, 20) == 0)
721 if (decoding_failed) mime_filename = mime_fname_rfc2231;
723 DEBUG(D_acl) debug_printf(
724 "MIME: found %s parameter in %s header, value is '%s'\n",
725 "filename", mh->name, mime_filename);
731 /* set additional flag variables (easier access) */
732 if ( mime_content_type
733 && Ustrncmp(mime_content_type,"multipart",9) == 0
735 mime_is_multipart = 1;
737 /* Make a copy of the boundary pointer.
738 Required since mime_boundary is global
739 and can be overwritten further down in recursion */
740 nested_context.boundary = mime_boundary;
742 /* raise global counter */
745 /* copy current file handle to global variable */
747 mime_current_boundary = context ? context->boundary : 0;
749 /* Note the context */
750 mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
752 /* call ACL handling function */
753 rc = acl_check(ACL_WHERE_MIME, NULL, acl, user_msgptr, log_msgptr);
756 mime_current_boundary = NULL;
760 /* If we have a multipart entity and a boundary, go recursive */
761 if ( (mime_content_type != NULL) &&
762 (nested_context.boundary != NULL) &&
763 (Ustrncmp(mime_content_type,"multipart",9) == 0) )
766 debug_printf("MIME: Entering multipart recursion, boundary '%s'\n",
767 nested_context.boundary);
769 nested_context.context =
770 context && context->context == MBC_ATTACHMENT
772 : Ustrcmp(mime_content_type,"multipart/alternative") == 0
773 || Ustrcmp(mime_content_type,"multipart/related") == 0
774 ? MBC_COVERLETTER_ALL
775 : MBC_COVERLETTER_ONESHOT;
777 rc = mime_acl_check(acl, f, &nested_context, user_msgptr, log_msgptr);
780 else if ( (mime_content_type != NULL) &&
781 (Ustrncmp(mime_content_type,"message/rfc822",14) == 0) )
783 const uschar *rfc822name = NULL;
784 uschar filename[2048];
788 /* must find first free sequential filename */
792 (void)string_format(filename, 2048,
793 "%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr++);
797 result = stat(CS filename,&mystat);
798 } while (result != -1);
800 rfc822name = filename;
802 /* decode RFC822 attachment */
803 mime_decoded_filename = NULL;
805 mime_current_boundary = context ? context->boundary : NULL;
806 mime_decode(&rfc822name);
808 mime_current_boundary = NULL;
809 if (!mime_decoded_filename) /* decoding failed */
811 log_write(0, LOG_MAIN,
812 "mime_regex acl condition warning - could not decode RFC822 MIME part to file.");
816 mime_decoded_filename = NULL;
820 /* If the boundary of this instance is NULL, we are finished here */
823 if (context->context == MBC_COVERLETTER_ONESHOT)
824 context->context = MBC_ATTACHMENT;
832 #endif /*WITH_CONTENT_SCAN*/