1 /* $Cambridge: exim/src/src/mime.c,v 1.13 2005/11/15 10:08:25 ph10 Exp $ */
3 /*************************************************
4 * Exim - an Internet mail transport agent *
5 *************************************************/
7 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2004 */
11 #ifdef WITH_CONTENT_SCAN
15 FILE *mime_stream = NULL;
16 uschar *mime_current_boundary = NULL;
18 /*************************************************
19 * set MIME anomaly level + text *
20 *************************************************/
22 /* Small wrapper to set the two expandables which
23 give info on detected "problems" in MIME
24 encodings. Those are defined in mime.h. */
26 void mime_set_anomaly(int level, char *text) {
27 mime_anomaly_level = level;
28 mime_anomaly_text = US 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
44 unsigned int mime_qp_hstr_i(uschar *cptr) {
45 unsigned int i, j = 0;
46 while (cptr && *cptr && isxdigit(*cptr)) {
55 uschar *mime_decode_qp_char(uschar *qp_p,int *c) {
56 uschar hex[] = {0,0,0};
58 uschar *initial_pos = qp_p;
60 /* advance one char */
64 if ( (*qp_p == '\t') || (*qp_p == ' ') || (*qp_p == '\r') ) {
65 /* tab or whitespace may follow
66 just ignore it, but remember
67 that this is not a valid hex
73 else if ( (('0' <= *qp_p) && (*qp_p <= '9')) || (('A' <= *qp_p) && (*qp_p <= 'F')) || (('a' <= *qp_p) && (*qp_p <= 'f')) ) {
74 /* this is a valid hex char, if nan is unset */
85 else if (*qp_p == '\n') {
86 /* hit soft line break already, continue */
91 /* illegal char here */
96 if ( (('0' <= *qp_p) && (*qp_p <= '9')) || (('A' <= *qp_p) && (*qp_p <= 'F')) || (('a' <= *qp_p) && (*qp_p <= 'f')) ) {
99 /* do hex conversion */
100 *c = mime_qp_hstr_i(hex);
118 uschar *mime_parse_line(uschar *buffer, uschar *data, uschar *encoding, int *num_decoded) {
120 if (encoding == NULL) {
121 /* no encoding type at all */
123 memcpy(data, buffer, Ustrlen(buffer));
124 data[(Ustrlen(buffer))] = 0;
125 *num_decoded = Ustrlen(data);
128 else if (Ustrcmp(encoding,"base64") == 0) {
132 /* ----- BASE64 ---------------------------------------------------- */
133 /* NULL out '\r' and '\n' chars */
134 while (Ustrrchr(p,'\r') != NULL) {
135 *(Ustrrchr(p,'\r')) = '\0';
137 while (Ustrrchr(p,'\n') != NULL) {
138 *(Ustrrchr(p,'\n')) = '\0';
141 while (*(p+offset) != '\0') {
142 /* hit illegal char ? */
143 if (mime_b64[*(p+offset)] == 128) {
144 mime_set_anomaly(MIME_ANOMALY_BROKEN_BASE64);
148 *p = mime_b64[*(p+offset)];
154 /* line is translated, start bit shifting */
160 /* byte 0 ---------------------- */
164 data[(*num_decoded)] = *p;
165 data[(*num_decoded)] <<= 2;
168 data[(*num_decoded)] |= tmp_c;
171 /* byte 1 ---------------------- */
175 data[(*num_decoded)] = *p;
176 data[(*num_decoded)] <<= 4;
179 data[(*num_decoded)] |= tmp_c;
182 /* byte 2 ---------------------- */
186 data[(*num_decoded)] = *p;
187 data[(*num_decoded)] <<= 6;
188 data[(*num_decoded)] |= *(p+1);
194 /* ----------------------------------------------------------------- */
196 else if (Ustrcmp(encoding,"quoted-printable") == 0) {
199 /* ----- QP -------------------------------------------------------- */
203 int decode_qp_result;
205 p = mime_decode_qp_char(p,&decode_qp_result);
207 if (decode_qp_result == -2) {
208 /* Error from decoder. p is unchanged. */
209 mime_set_anomaly(MIME_ANOMALY_BROKEN_QP);
210 data[(*num_decoded)] = '=';
214 else if (decode_qp_result == -1) {
217 else if (decode_qp_result >= 0) {
218 data[(*num_decoded)] = decode_qp_result;
223 data[(*num_decoded)] = *p;
229 /* ----------------------------------------------------------------- */
231 /* unknown encoding type, just dump as-is */
232 else goto NO_DECODING;
236 FILE *mime_get_decode_file(uschar *pname, uschar *fname) {
240 filename = (uschar *)malloc(2048);
242 if ((pname != NULL) && (fname != NULL)) {
243 (void)string_format(filename, 2048, "%s/%s", pname, fname);
244 f = fopen(CS filename,"wb+");
246 else if (pname == NULL) {
247 f = fopen(CS fname,"wb+");
249 else if (fname == NULL) {
253 /* must find first free sequential filename */
256 (void)string_format(filename,2048,"%s/%s-%05u", pname, message_id, file_nr);
261 result = stat(CS filename,&mystat);
264 f = fopen(CS filename,"wb+");
267 /* set expansion variable */
268 mime_decoded_filename = filename;
274 int mime_decode(uschar **listptr) {
276 uschar *list = *listptr;
278 uschar option_buffer[1024];
279 uschar decode_path[1024];
280 FILE *decode_file = NULL;
281 uschar *buffer = NULL;
282 uschar *decode_buffer = NULL;
284 unsigned int size_counter = 0;
286 if (mime_stream == NULL)
289 f_pos = ftell(mime_stream);
291 /* build default decode path (will exist since MBOX must be spooled up) */
292 (void)string_format(decode_path,1024,"%s/scan/%s",spool_directory,message_id);
294 /* reserve a line and decoder buffer to work in */
295 buffer = (uschar *)malloc(MIME_MAX_LINE_LENGTH+1);
296 if (buffer == NULL) {
297 log_write(0, LOG_PANIC,
298 "decode ACL condition: can't allocate %d bytes of memory.", MIME_MAX_LINE_LENGTH+1);
302 decode_buffer = (uschar *)malloc(MIME_MAX_LINE_LENGTH+1);
303 if (decode_buffer == NULL) {
304 log_write(0, LOG_PANIC,
305 "decode ACL condition: can't allocate %d bytes of memory.", MIME_MAX_LINE_LENGTH+1);
309 /* try to find 1st option */
310 if ((option = string_nextinlist(&list, &sep,
312 sizeof(option_buffer))) != NULL) {
314 /* parse 1st option */
315 if ( (Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0) ) {
316 /* explicitly no decoding */
320 if (Ustrcmp(option,"default") == 0) {
321 /* explicit default path + file names */
325 if (option[0] == '/') {
328 memset(&statbuf,0,sizeof(statbuf));
330 /* assume either path or path+file name */
331 if ( (stat(CS option, &statbuf) == 0) && S_ISDIR(statbuf.st_mode) )
332 /* is directory, use it as decode_path */
333 decode_file = mime_get_decode_file(option, NULL);
335 /* does not exist or is a file, use as full file name */
336 decode_file = mime_get_decode_file(NULL, option);
339 /* assume file name only, use default path */
340 decode_file = mime_get_decode_file(decode_path, option);
343 /* no option? patch default path */
344 DEFAULT_PATH: decode_file = mime_get_decode_file(decode_path, NULL);
346 if (decode_file == NULL)
349 /* read data linewise and dump it to the file,
350 while looking for the current boundary */
351 while(fgets(CS buffer, MIME_MAX_LINE_LENGTH, mime_stream) != NULL) {
352 uschar *decoded_line = NULL;
353 int decoded_line_length = 0;
355 if (mime_current_boundary != NULL) {
356 /* boundary line must start with 2 dashes */
357 if (Ustrncmp(buffer,"--",2) == 0) {
358 if (Ustrncmp((buffer+2),mime_current_boundary,Ustrlen(mime_current_boundary)) == 0)
363 decoded_line = mime_parse_line(buffer, decode_buffer, mime_content_transfer_encoding, &decoded_line_length);
365 /* write line to decode file */
366 if (fwrite(decoded_line, 1, decoded_line_length, decode_file) < decoded_line_length) {
367 /* error/short write */
368 clearerr(mime_stream);
369 fseek(mime_stream,f_pos,SEEK_SET);
372 size_counter += decoded_line_length;
374 if (size_counter > 1023) {
375 if ((mime_content_size + (size_counter / 1024)) < 65535)
376 mime_content_size += (size_counter / 1024);
378 mime_content_size = 65535;
379 size_counter = (size_counter % 1024);
384 (void)fclose(decode_file);
386 clearerr(mime_stream);
387 fseek(mime_stream,f_pos,SEEK_SET);
389 /* round up remaining size bytes to one k */
397 int mime_get_header(FILE *f, uschar *header) {
400 int header_value_mode = 0;
401 int header_open_brackets = 0;
409 /* always skip CRs */
410 if (c == '\r') continue;
413 if (num_copied > 0) {
414 /* look if next char is '\t' or ' ' */
417 if ( (c == '\t') || (c == ' ') ) continue;
420 /* end of the header, terminate with ';' */
425 /* skip control characters */
426 if (c < 32) continue;
428 if (header_value_mode) {
429 /* --------- value mode ----------- */
430 /* skip leading whitespace */
431 if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
434 /* we have hit a non-whitespace char, start copying value data */
435 header_value_mode = 2;
438 if (c == '"') continue;
440 /* leave value mode on ';' */
442 header_value_mode = 0;
444 /* -------------------------------- */
447 /* -------- non-value mode -------- */
448 /* skip whitespace + tabs */
449 if ( (c == ' ') || (c == '\t') )
452 /* quote next char. can be used
453 to escape brackets. */
458 header_open_brackets++;
461 else if ((c == ')') && header_open_brackets) {
462 header_open_brackets--;
465 else if ( (c == '=') && !header_open_brackets ) {
466 /* enter value mode */
467 header_value_mode = 1;
470 /* skip chars while we are in a comment */
471 if (header_open_brackets > 0)
473 /* -------------------------------- */
476 /* copy the char to the buffer */
477 header[num_copied] = (uschar)c;
481 /* break if header buffer is full */
482 if (num_copied > MIME_MAX_HEADER_SIZE-1) {
487 if ((num_copied > 0) && (header[num_copied-1] != ';')) {
488 header[num_copied-1] = ';';
492 header[num_copied] = '\0';
494 /* return 0 for EOF or empty line */
495 if ((c == EOF) || (num_copied == 1))
502 int mime_acl_check(uschar *acl, FILE *f, struct mime_boundary_context *context,
503 uschar **user_msgptr, uschar **log_msgptr) {
505 uschar *header = NULL;
506 struct mime_boundary_context nested_context;
508 /* reserve a line buffer to work in */
509 header = (uschar *)malloc(MIME_MAX_HEADER_SIZE+1);
510 if (header == NULL) {
511 log_write(0, LOG_PANIC,
512 "MIME ACL: can't allocate %d bytes of memory.", MIME_MAX_HEADER_SIZE+1);
516 /* Not actually used at the moment, but will be vital to fixing
517 * some RFC 2046 nonconformance later... */
518 nested_context.parent = context;
520 /* loop through parts */
523 /* reset all per-part mime variables */
524 mime_anomaly_level = 0;
525 mime_anomaly_text = NULL;
526 mime_boundary = NULL;
528 mime_decoded_filename = NULL;
529 mime_filename = NULL;
530 mime_content_description = NULL;
531 mime_content_disposition = NULL;
532 mime_content_id = NULL;
533 mime_content_transfer_encoding = NULL;
534 mime_content_type = NULL;
535 mime_is_multipart = 0;
536 mime_content_size = 0;
539 If boundary is null, we assume that *f is positioned on the start of headers (for example,
540 at the very beginning of a message.
541 If a boundary is 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 != NULL) {
553 while(fgets(CS header, MIME_MAX_HEADER_SIZE, f) != NULL) {
554 /* boundary line must start with 2 dashes */
555 if (Ustrncmp(header,"--",2) == 0) {
556 if (Ustrncmp((header+2),context->boundary,Ustrlen(context->boundary)) == 0) {
558 if (Ustrncmp((header+2+Ustrlen(context->boundary)),"--",2) == 0) {
559 /* END boundary found */
560 debug_printf("End boundary found %s\n", context->boundary);
564 debug_printf("Next part with boundary %s\n", context->boundary);
566 /* can't use break here */
571 /* Hit EOF or read error. Ugh. */
572 debug_printf("Hit EOF ...\n");
577 /* parse headers, set up expansion variables */
578 while(mime_get_header(f,header)) {
580 /* loop through header list */
581 for (i = 0; i < mime_header_list_size; i++) {
582 uschar *header_value = NULL;
583 int header_value_len = 0;
585 /* found an interesting header? */
586 if (strncmpic(mime_header_list[i].name,header,mime_header_list[i].namelen) == 0) {
587 uschar *p = header + mime_header_list[i].namelen;
588 /* yes, grab the value (normalize to lower case)
589 and copy to its corresponding expansion variable */
594 header_value_len = (p - (header + mime_header_list[i].namelen));
595 header_value = (uschar *)malloc(header_value_len+1);
596 memset(header_value,0,header_value_len+1);
597 p = header + mime_header_list[i].namelen;
598 Ustrncpy(header_value, p, header_value_len);
599 debug_printf("Found %s MIME header, value is '%s'\n", mime_header_list[i].name, header_value);
600 *((uschar **)(mime_header_list[i].value)) = header_value;
602 /* make p point to the next character after the closing ';' */
603 p += (header_value_len+1);
605 /* grab all param=value tags on the remaining line, check if they are interesting */
606 NEXT_PARAM_SEARCH: while (*p != 0) {
608 for (j = 0; j < mime_parameter_list_size; j++) {
609 uschar *param_value = NULL;
610 int param_value_len = 0;
612 /* found an interesting parameter? */
613 if (strncmpic(mime_parameter_list[j].name,p,mime_parameter_list[j].namelen) == 0) {
614 uschar *q = p + mime_parameter_list[j].namelen;
615 /* yes, grab the value and copy to its corresponding expansion variable */
616 while(*q != ';') q++;
617 param_value_len = (q - (p + mime_parameter_list[j].namelen));
618 param_value = (uschar *)malloc(param_value_len+1);
619 memset(param_value,0,param_value_len+1);
620 q = p + mime_parameter_list[j].namelen;
621 Ustrncpy(param_value, q, param_value_len);
622 param_value = rfc2047_decode(param_value, check_rfc2047_length, NULL, 32, ¶m_value_len, &q);
623 debug_printf("Found %s MIME parameter in %s header, value is '%s'\n", mime_parameter_list[j].name, mime_header_list[i].name, param_value);
624 *((uschar **)(mime_parameter_list[j].value)) = param_value;
625 p += (mime_parameter_list[j].namelen + param_value_len + 1);
626 goto NEXT_PARAM_SEARCH;
629 /* There is something, but not one of our interesting parameters.
630 Advance to the next semicolon */
631 while(*p != ';') p++;
638 /* set additional flag variables (easier access) */
639 if ( (mime_content_type != NULL) &&
640 (Ustrncmp(mime_content_type,"multipart",9) == 0) )
641 mime_is_multipart = 1;
643 /* Make a copy of the boundary pointer.
644 Required since mime_boundary is global
645 and can be overwritten further down in recursion */
646 nested_context.boundary = mime_boundary;
648 /* raise global counter */
651 /* copy current file handle to global variable */
653 mime_current_boundary = context ? context->boundary : 0;
655 /* Note the context */
656 mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
658 /* call ACL handling function */
659 rc = acl_check(ACL_WHERE_MIME, NULL, acl, user_msgptr, log_msgptr);
662 mime_current_boundary = NULL;
666 /* If we have a multipart entity and a boundary, go recursive */
667 if ( (mime_content_type != NULL) &&
668 (nested_context.boundary != NULL) &&
669 (Ustrncmp(mime_content_type,"multipart",9) == 0) ) {
670 debug_printf("Entering multipart recursion, boundary '%s'\n", nested_context.boundary);
672 if (context && context->context == MBC_ATTACHMENT)
673 nested_context.context = MBC_ATTACHMENT;
674 else if (!Ustrcmp(mime_content_type,"multipart/alternative")
675 || !Ustrcmp(mime_content_type,"multipart/related"))
676 nested_context.context = MBC_COVERLETTER_ALL;
678 nested_context.context = MBC_COVERLETTER_ONESHOT;
680 rc = mime_acl_check(acl, f, &nested_context, user_msgptr, log_msgptr);
683 else if ( (mime_content_type != NULL) &&
684 (Ustrncmp(mime_content_type,"message/rfc822",14) == 0) ) {
685 uschar *rfc822name = NULL;
686 uschar filename[2048];
690 /* must find first free sequential filename */
693 (void)string_format(filename,2048,"%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr);
698 result = stat(CS filename,&mystat);
702 rfc822name = filename;
704 /* decode RFC822 attachment */
705 mime_decoded_filename = NULL;
707 mime_current_boundary = context ? context->boundary : NULL;
708 mime_decode(&rfc822name);
710 mime_current_boundary = NULL;
711 if (mime_decoded_filename == NULL) {
712 /* decoding failed */
713 log_write(0, LOG_MAIN,
714 "mime_regex acl condition warning - could not decode RFC822 MIME part to file.");
717 mime_decoded_filename = NULL;
721 /* If the boundary of this instance is NULL, we are finished here */
722 if (context == NULL) break;
724 if (context->context == MBC_COVERLETTER_ONESHOT)
725 context->context = MBC_ATTACHMENT;