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 fseek(mime_stream, f_pos, SEEK_SET);
309 if (fclose(decode_file) != 0 || size_counter < 0)
312 /* round up to the next KiB */
313 mime_content_size = (size_counter + 1023) / 1024;
320 mime_get_header(FILE *f, uschar *header)
324 int header_value_mode = 0;
325 int header_open_brackets = 0;
330 if ((c = fgetc(f)) == EOF) break;
332 /* always skip CRs */
333 if (c == '\r') continue;
339 /* look if next char is '\t' or ' ' */
340 if ((c = fgetc(f)) == EOF) break;
341 if ( (c == '\t') || (c == ' ') ) continue;
344 /* end of the header, terminate with ';' */
349 /* skip control characters */
350 if (c < 32) continue;
352 if (header_value_mode)
354 /* --------- value mode ----------- */
355 /* skip leading whitespace */
356 if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
359 /* we have hit a non-whitespace char, start copying value data */
360 header_value_mode = 2;
362 if (c == '"') /* flip "quoted" mode */
363 header_value_mode = header_value_mode==2 ? 3 : 2;
365 /* leave value mode on unquoted ';' */
366 if (header_value_mode == 2 && c == ';') {
367 header_value_mode = 0;
369 /* -------------------------------- */
373 /* -------- non-value mode -------- */
374 /* skip whitespace + tabs */
375 if ( (c == ' ') || (c == '\t') )
379 /* quote next char. can be used
380 to escape brackets. */
381 if ((c = fgetc(f)) == EOF) break;
385 header_open_brackets++;
388 else if ((c == ')') && header_open_brackets)
390 header_open_brackets--;
393 else if ( (c == '=') && !header_open_brackets ) /* enter value mode */
394 header_value_mode = 1;
396 /* skip chars while we are in a comment */
397 if (header_open_brackets > 0)
399 /* -------------------------------- */
402 /* copy the char to the buffer */
403 header[num_copied++] = (uschar)c;
405 /* break if header buffer is full */
406 if (num_copied > MIME_MAX_HEADER_SIZE-1)
410 if ((num_copied > 0) && (header[num_copied-1] != ';'))
411 header[num_copied-1] = ';';
414 header[num_copied] = '\0';
416 /* return 0 for EOF or empty line */
417 if ((c == EOF) || (num_copied == 1))
425 mime_vars_reset(void)
427 mime_anomaly_level = 0;
428 mime_anomaly_text = NULL;
429 mime_boundary = NULL;
431 mime_decoded_filename = NULL;
432 mime_filename = NULL;
433 mime_content_description = NULL;
434 mime_content_disposition = NULL;
435 mime_content_id = NULL;
436 mime_content_transfer_encoding = NULL;
437 mime_content_type = NULL;
438 mime_is_multipart = 0;
439 mime_content_size = 0;
443 /* Grab a parameter value, dealing with quoting.
446 str Input string. Updated on return to point to terminating ; or NUL
449 Allocated string with parameter value
452 mime_param_val(uschar ** sp)
456 int size = 0, ptr = 0;
458 /* debug_printf(" considering paramval '%s'\n", s); */
460 while (*s && *s != ';') /* ; terminates */
463 s++; /* skip opening " */
464 while (*s && *s != '"') /* " protects ; */
465 val = string_cat(val, &size, &ptr, s++, 1);
466 if (*s) s++; /* skip closing " */
469 val = string_cat(val, &size, &ptr, s++, 1);
470 if (val) val[ptr] = '\0';
476 mime_next_semicolon(uschar * s)
478 while (*s && *s != ';') /* ; terminates */
481 s++; /* skip opening " */
482 while (*s && *s != '"') /* " protects ; */
484 if (*s) s++; /* skip closing " */
493 rfc2231_to_2047(const uschar * fname, const uschar * charset, int * len)
495 int size = 0, ptr = 0;
496 uschar * val = string_cat(NULL, &size, &ptr, US"=?", 2);
500 val = string_cat(val, &size, &ptr, charset, Ustrlen(charset));
501 val = string_cat(val, &size, &ptr, US"?Q?", 3);
504 if (c == '%' && isxdigit(fname[1]) && isxdigit(fname[2]))
506 val = string_cat(val, &size, &ptr, US"=", 1);
507 val = string_cat(val, &size, &ptr, ++fname, 2);
511 val = string_cat(val, &size, &ptr, fname++, 1);
513 val = string_cat(val, &size, &ptr, US"?=", 2);
514 val[*len = ptr] = '\0';
520 mime_acl_check(uschar *acl, FILE *f, struct mime_boundary_context *context,
521 uschar **user_msgptr, uschar **log_msgptr)
524 uschar * header = NULL;
525 struct mime_boundary_context nested_context;
527 /* reserve a line buffer to work in */
528 header = store_get(MIME_MAX_HEADER_SIZE+1);
530 /* Not actually used at the moment, but will be vital to fixing
531 * some RFC 2046 nonconformance later... */
532 nested_context.parent = context;
534 /* loop through parts */
537 /* reset all per-part mime variables */
540 /* If boundary is null, we assume that *f is positioned on the start of
541 headers (for example, at the very beginning of a message. If a boundary is
542 given, we must first advance to it to reach the start of the next header
545 /* NOTE -- there's an error here -- RFC2046 specifically says to
546 * check for outer boundaries. This code doesn't do that, and
547 * I haven't fixed this.
549 * (I have moved partway towards adding support, however, by adding
550 * a "parent" field to my new boundary-context structure.)
552 if (context) for (;;)
554 if (!fgets(CS header, MIME_MAX_HEADER_SIZE, f))
556 /* Hit EOF or read error. Ugh. */
557 DEBUG(D_acl) debug_printf("MIME: Hit EOF ...\n");
561 /* boundary line must start with 2 dashes */
562 if ( Ustrncmp(header, "--", 2) == 0
563 && Ustrncmp(header+2, context->boundary, Ustrlen(context->boundary)) == 0
565 { /* found boundary */
566 if (Ustrncmp((header+2+Ustrlen(context->boundary)), "--", 2) == 0)
568 /* END boundary found */
569 DEBUG(D_acl) debug_printf("MIME: End boundary found %s\n",
574 DEBUG(D_acl) debug_printf("MIME: Next part with boundary %s\n",
580 /* parse headers, set up expansion variables */
581 while (mime_get_header(f, header))
583 struct mime_header * mh;
585 /* look for interesting headers */
586 for (mh = mime_header_list;
587 mh < mime_header_list + mime_header_list_size;
588 mh++) if (strncmpic(mh->name, header, mh->namelen) == 0)
590 uschar * p = header + mh->namelen;
593 /* grab the value (normalize to lower case)
594 and copy to its corresponding expansion variable */
596 for (q = p; *q != ';' && *q; q++) ;
597 *mh->value = string_copynlc(p, q-p);
598 DEBUG(D_acl) debug_printf("MIME: found %s header, value is '%s'\n",
599 mh->name, *mh->value);
601 if (*(p = q)) p++; /* jump past the ; */
604 uschar * mime_fname = NULL;
605 uschar * mime_fname_rfc2231 = NULL;
606 uschar * mime_filename_charset = NULL;
607 BOOL decoding_failed = FALSE;
609 /* grab all param=value tags on the remaining line,
610 check if they are interesting */
616 DEBUG(D_acl) debug_printf("MIME: considering paramlist '%s'\n", p);
619 && strncmpic(CUS"content-disposition:", header, 20) == 0
620 && strncmpic(CUS"filename*", p, 9) == 0
622 { /* RFC 2231 filename */
625 /* find value of the filename */
627 while(*p != '=' && *p) p++;
628 if (*p) p++; /* p is filename or NUL */
629 q = mime_param_val(&p); /* p now trailing ; or NUL */
633 uschar * temp_string, * err_msg;
636 /* build up an un-decoded filename over successive
637 filename*= parameters (for use when 2047 decode fails) */
639 mime_fname_rfc2231 = string_sprintf("%#s%s",
640 mime_fname_rfc2231, q);
642 if (!decoding_failed)
645 if (!mime_filename_charset)
649 /* look for a ' in the "filename" */
650 while(*s != '\'' && *s) s++; /* s is 1st ' or NUL */
652 if ((size = s-q) > 0)
653 mime_filename_charset = string_copyn(q, size);
656 while(*p == '\'') p++; /* p is after 2nd ' */
661 DEBUG(D_acl) debug_printf("MIME: charset %s fname '%s'\n",
662 mime_filename_charset ? mime_filename_charset : US"<NULL>", p);
664 temp_string = rfc2231_to_2047(p, mime_filename_charset, &slen);
665 DEBUG(D_acl) debug_printf("MIME: 2047-name %s\n", temp_string);
667 temp_string = rfc2047_decode(temp_string, FALSE, NULL, ' ',
669 DEBUG(D_acl) debug_printf("MIME: plain-name %s\n", temp_string);
671 size = Ustrlen(temp_string);
674 decoding_failed = TRUE;
676 /* build up a decoded filename over successive
677 filename*= parameters */
679 mime_filename = mime_fname = mime_fname
680 ? string_sprintf("%s%s", mime_fname, temp_string)
687 /* look for interesting parameters */
688 for (mp = mime_parameter_list;
689 mp < mime_parameter_list + nelem(mime_parameter_list);
691 ) if (strncmpic(mp->name, p, mp->namelen) == 0)
694 uschar * dummy_errstr;
696 /* grab the value and copy to its expansion variable */
698 q = mime_param_val(&p); /* p now trailing ; or NUL */
701 ? rfc2047_decode(q, check_rfc2047_length, NULL, 32, NULL,
704 DEBUG(D_acl) debug_printf(
705 "MIME: found %s parameter in %s header, value '%s'\n",
706 mp->name, mh->name, *mp->value);
708 break; /* done matching param names */
712 /* There is something, but not one of our interesting parameters.
713 Advance past the next semicolon */
714 p = mime_next_semicolon(p);
716 } /* param scan on line */
718 if (strncmpic(CUS"content-disposition:", header, 20) == 0)
720 if (decoding_failed) mime_filename = mime_fname_rfc2231;
722 DEBUG(D_acl) debug_printf(
723 "MIME: found %s parameter in %s header, value is '%s'\n",
724 "filename", mh->name, mime_filename);
730 /* set additional flag variables (easier access) */
731 if ( mime_content_type
732 && Ustrncmp(mime_content_type,"multipart",9) == 0
734 mime_is_multipart = 1;
736 /* Make a copy of the boundary pointer.
737 Required since mime_boundary is global
738 and can be overwritten further down in recursion */
739 nested_context.boundary = mime_boundary;
741 /* raise global counter */
744 /* copy current file handle to global variable */
746 mime_current_boundary = context ? context->boundary : 0;
748 /* Note the context */
749 mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
751 /* call ACL handling function */
752 rc = acl_check(ACL_WHERE_MIME, NULL, acl, user_msgptr, log_msgptr);
755 mime_current_boundary = NULL;
759 /* If we have a multipart entity and a boundary, go recursive */
760 if ( (mime_content_type != NULL) &&
761 (nested_context.boundary != NULL) &&
762 (Ustrncmp(mime_content_type,"multipart",9) == 0) )
765 debug_printf("MIME: Entering multipart recursion, boundary '%s'\n",
766 nested_context.boundary);
768 nested_context.context =
769 context && context->context == MBC_ATTACHMENT
771 : Ustrcmp(mime_content_type,"multipart/alternative") == 0
772 || Ustrcmp(mime_content_type,"multipart/related") == 0
773 ? MBC_COVERLETTER_ALL
774 : MBC_COVERLETTER_ONESHOT;
776 rc = mime_acl_check(acl, f, &nested_context, user_msgptr, log_msgptr);
779 else if ( (mime_content_type != NULL) &&
780 (Ustrncmp(mime_content_type,"message/rfc822",14) == 0) )
782 const uschar *rfc822name = NULL;
783 uschar filename[2048];
787 /* must find first free sequential filename */
791 (void)string_format(filename, 2048,
792 "%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr++);
796 result = stat(CS filename,&mystat);
797 } while (result != -1);
799 rfc822name = filename;
801 /* decode RFC822 attachment */
802 mime_decoded_filename = NULL;
804 mime_current_boundary = context ? context->boundary : NULL;
805 mime_decode(&rfc822name);
807 mime_current_boundary = NULL;
808 if (!mime_decoded_filename) /* decoding failed */
810 log_write(0, LOG_MAIN,
811 "mime_regex acl condition warning - could not decode RFC822 MIME part to file.");
815 mime_decoded_filename = NULL;
819 /* If the boundary of this instance is NULL, we are finished here */
822 if (context->context == MBC_COVERLETTER_ONESHOT)
823 context->context = MBC_ATTACHMENT;
831 #endif /*WITH_CONTENT_SCAN*/