1 /* $Cambridge: exim/src/src/mime.c,v 1.6 2005/03/08 16:57:28 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 ---------------------- */
162 mime_set_anomaly(MIME_ANOMALY_BROKEN_BASE64);
165 data[(*num_decoded)] = *p;
166 data[(*num_decoded)] <<= 2;
169 data[(*num_decoded)] |= tmp_c;
172 /* byte 1 ---------------------- */
174 mime_set_anomaly(MIME_ANOMALY_BROKEN_BASE64);
177 data[(*num_decoded)] = *p;
178 data[(*num_decoded)] <<= 4;
181 data[(*num_decoded)] |= tmp_c;
184 /* byte 2 ---------------------- */
186 mime_set_anomaly(MIME_ANOMALY_BROKEN_BASE64);
189 data[(*num_decoded)] = *p;
190 data[(*num_decoded)] <<= 6;
191 data[(*num_decoded)] |= *(p+1);
197 /* ----------------------------------------------------------------- */
199 else if (Ustrcmp(encoding,"quoted-printable") == 0) {
202 /* ----- QP -------------------------------------------------------- */
206 int decode_qp_result;
208 p = mime_decode_qp_char(p,&decode_qp_result);
210 if (decode_qp_result == -2) {
211 /* Error from decoder. p is unchanged. */
212 mime_set_anomaly(MIME_ANOMALY_BROKEN_QP);
213 data[(*num_decoded)] = '=';
217 else if (decode_qp_result == -1) {
220 else if (decode_qp_result >= 0) {
221 data[(*num_decoded)] = decode_qp_result;
226 data[(*num_decoded)] = *p;
232 /* ----------------------------------------------------------------- */
234 /* unknown encoding type, just dump as-is */
235 else goto NO_DECODING;
239 FILE *mime_get_decode_file(uschar *pname, uschar *fname) {
243 filename = (uschar *)malloc(2048);
245 if ((pname != NULL) && (fname != NULL)) {
246 snprintf(CS filename, 2048, "%s/%s", pname, fname);
247 f = fopen(CS filename,"w+");
249 else if (pname == NULL) {
250 f = fopen(CS fname,"w+");
252 else if (fname == NULL) {
256 /* must find first free sequential filename */
259 snprintf(CS filename,2048,"%s/%s-%05u", pname, message_id, file_nr);
264 result = stat(CS filename,&mystat);
267 f = fopen(CS filename,"w+");
270 /* set expansion variable */
271 mime_decoded_filename = filename;
277 int mime_decode(uschar **listptr) {
279 uschar *list = *listptr;
281 uschar option_buffer[1024];
282 uschar decode_path[1024];
283 FILE *decode_file = NULL;
284 uschar *buffer = NULL;
285 uschar *decode_buffer = NULL;
287 unsigned int size_counter = 0;
289 if (mime_stream == NULL)
292 f_pos = ftell(mime_stream);
294 /* build default decode path (will exist since MBOX must be spooled up) */
295 snprintf(CS decode_path,1024,"%s/scan/%s",spool_directory,message_id);
297 /* reserve a line and decoder buffer to work in */
298 buffer = (uschar *)malloc(MIME_MAX_LINE_LENGTH+1);
299 if (buffer == NULL) {
300 log_write(0, LOG_PANIC,
301 "decode ACL condition: can't allocate %d bytes of memory.", MIME_MAX_LINE_LENGTH+1);
305 decode_buffer = (uschar *)malloc(MIME_MAX_LINE_LENGTH+1);
306 if (decode_buffer == NULL) {
307 log_write(0, LOG_PANIC,
308 "decode ACL condition: can't allocate %d bytes of memory.", MIME_MAX_LINE_LENGTH+1);
312 /* try to find 1st option */
313 if ((option = string_nextinlist(&list, &sep,
315 sizeof(option_buffer))) != NULL) {
317 /* parse 1st option */
318 if ( (Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0) ) {
319 /* explicitly no decoding */
323 if (Ustrcmp(option,"default") == 0) {
324 /* explicit default path + file names */
328 if (option[0] == '/') {
331 memset(&statbuf,0,sizeof(statbuf));
333 /* assume either path or path+file name */
334 if ( (stat(CS option, &statbuf) == 0) && S_ISDIR(statbuf.st_mode) )
335 /* is directory, use it as decode_path */
336 decode_file = mime_get_decode_file(option, NULL);
338 /* does not exist or is a file, use as full file name */
339 decode_file = mime_get_decode_file(NULL, option);
342 /* assume file name only, use default path */
343 decode_file = mime_get_decode_file(decode_path, option);
346 /* no option? patch default path */
347 DEFAULT_PATH: decode_file = mime_get_decode_file(decode_path, NULL);
349 if (decode_file == NULL)
352 /* read data linewise and dump it to the file,
353 while looking for the current boundary */
354 while(fgets(CS buffer, MIME_MAX_LINE_LENGTH, mime_stream) != NULL) {
355 uschar *decoded_line = NULL;
356 int decoded_line_length = 0;
358 if (mime_current_boundary != NULL) {
359 /* boundary line must start with 2 dashes */
360 if (Ustrncmp(buffer,"--",2) == 0) {
361 if (Ustrncmp((buffer+2),mime_current_boundary,Ustrlen(mime_current_boundary)) == 0)
366 decoded_line = mime_parse_line(buffer, decode_buffer, mime_content_transfer_encoding, &decoded_line_length);
368 /* write line to decode file */
369 if (fwrite(decoded_line, 1, decoded_line_length, decode_file) < decoded_line_length) {
370 /* error/short write */
371 clearerr(mime_stream);
372 fseek(mime_stream,f_pos,SEEK_SET);
375 size_counter += decoded_line_length;
377 if (size_counter > 1023) {
378 if ((mime_content_size + (size_counter / 1024)) < 65535)
379 mime_content_size += (size_counter / 1024);
381 mime_content_size = 65535;
382 size_counter = (size_counter % 1024);
389 clearerr(mime_stream);
390 fseek(mime_stream,f_pos,SEEK_SET);
392 /* round up remaining size bytes to one k */
400 int mime_get_header(FILE *f, uschar *header) {
403 int header_value_mode = 0;
404 int header_open_brackets = 0;
412 /* always skip CRs */
413 if (c == '\r') continue;
416 if (num_copied > 0) {
417 /* look if next char is '\t' or ' ' */
420 if ( (c == '\t') || (c == ' ') ) continue;
423 /* end of the header, terminate with ';' */
428 /* skip control characters */
429 if (c < 32) continue;
431 if (header_value_mode) {
432 /* --------- value mode ----------- */
433 /* skip leading whitespace */
434 if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
437 /* we have hit a non-whitespace char, start copying value data */
438 header_value_mode = 2;
441 if (c == '"') continue;
443 /* leave value mode on ';' */
445 header_value_mode = 0;
447 /* -------------------------------- */
450 /* -------- non-value mode -------- */
451 /* skip whitespace + tabs */
452 if ( (c == ' ') || (c == '\t') )
455 /* quote next char. can be used
456 to escape brackets. */
461 header_open_brackets++;
464 else if ((c == ')') && header_open_brackets) {
465 header_open_brackets--;
468 else if ( (c == '=') && !header_open_brackets ) {
469 /* enter value mode */
470 header_value_mode = 1;
473 /* skip chars while we are in a comment */
474 if (header_open_brackets > 0)
476 /* -------------------------------- */
479 /* copy the char to the buffer */
480 header[num_copied] = (uschar)c;
484 /* break if header buffer is full */
485 if (num_copied > MIME_MAX_HEADER_SIZE-1) {
490 if (header[num_copied-1] != ';') {
491 header[num_copied-1] = ';';
495 header[num_copied] = '\0';
497 /* return 0 for EOF or empty line */
498 if ((c == EOF) || (num_copied == 1))
505 int mime_acl_check(FILE *f, struct mime_boundary_context *context, uschar
506 **user_msgptr, uschar **log_msgptr) {
508 uschar *header = NULL;
509 struct mime_boundary_context nested_context;
511 /* reserve a line buffer to work in */
512 header = (uschar *)malloc(MIME_MAX_HEADER_SIZE+1);
513 if (header == NULL) {
514 log_write(0, LOG_PANIC,
515 "acl_smtp_mime: can't allocate %d bytes of memory.", MIME_MAX_HEADER_SIZE+1);
519 /* Not actually used at the moment, but will be vital to fixing
520 * some RFC 2046 nonconformance later... */
521 nested_context.parent = context;
523 /* loop through parts */
526 /* reset all per-part mime variables */
527 mime_anomaly_level = 0;
528 mime_anomaly_text = NULL;
529 mime_boundary = NULL;
531 mime_decoded_filename = NULL;
532 mime_filename = NULL;
533 mime_content_description = NULL;
534 mime_content_disposition = NULL;
535 mime_content_id = NULL;
536 mime_content_transfer_encoding = NULL;
537 mime_content_type = NULL;
538 mime_is_multipart = 0;
539 mime_content_size = 0;
542 If boundary is null, we assume that *f is positioned on the start of headers (for example,
543 at the very beginning of a message.
544 If a boundary is given, we must first advance to it to reach the start of the next header
548 /* NOTE -- there's an error here -- RFC2046 specifically says to
549 * check for outer boundaries. This code doesn't do that, and
550 * I haven't fixed this.
552 * (I have moved partway towards adding support, however, by adding
553 * a "parent" field to my new boundary-context structure.)
555 if (context != NULL) {
556 while(fgets(CS header, MIME_MAX_HEADER_SIZE, f) != NULL) {
557 /* boundary line must start with 2 dashes */
558 if (Ustrncmp(header,"--",2) == 0) {
559 if (Ustrncmp((header+2),context->boundary,Ustrlen(context->boundary)) == 0) {
561 if (Ustrncmp((header+2+Ustrlen(context->boundary)),"--",2) == 0) {
562 /* END boundary found */
563 debug_printf("End boundary found %s\n", context->boundary);
567 debug_printf("Next part with boundary %s\n", context->boundary);
569 /* can't use break here */
574 /* Hit EOF or read error. Ugh. */
575 debug_printf("Hit EOF ...\n");
580 /* parse headers, set up expansion variables */
581 while(mime_get_header(f,header)) {
583 /* loop through header list */
584 for (i = 0; i < mime_header_list_size; i++) {
585 uschar *header_value = NULL;
586 int header_value_len = 0;
588 /* found an interesting header? */
589 if (strncmpic(mime_header_list[i].name,header,mime_header_list[i].namelen) == 0) {
590 uschar *p = header + mime_header_list[i].namelen;
591 /* yes, grab the value (normalize to lower case)
592 and copy to its corresponding expansion variable */
597 header_value_len = (p - (header + mime_header_list[i].namelen));
598 header_value = (uschar *)malloc(header_value_len+1);
599 memset(header_value,0,header_value_len+1);
600 p = header + mime_header_list[i].namelen;
601 Ustrncpy(header_value, p, header_value_len);
602 debug_printf("Found %s MIME header, value is '%s'\n", mime_header_list[i].name, header_value);
603 *((uschar **)(mime_header_list[i].value)) = header_value;
605 /* make p point to the next character after the closing ';' */
606 p += (header_value_len+1);
608 /* grab all param=value tags on the remaining line, check if they are interesting */
609 NEXT_PARAM_SEARCH: while (*p != 0) {
611 for (j = 0; j < mime_parameter_list_size; j++) {
612 uschar *param_value = NULL;
613 int param_value_len = 0;
615 /* found an interesting parameter? */
616 if (strncmpic(mime_parameter_list[j].name,p,mime_parameter_list[j].namelen) == 0) {
617 uschar *q = p + mime_parameter_list[j].namelen;
618 /* yes, grab the value and copy to its corresponding expansion variable */
619 while(*q != ';') q++;
620 param_value_len = (q - (p + mime_parameter_list[j].namelen));
621 param_value = (uschar *)malloc(param_value_len+1);
622 memset(param_value,0,param_value_len+1);
623 q = p + mime_parameter_list[j].namelen;
624 Ustrncpy(param_value, q, param_value_len);
625 param_value = rfc2047_decode(param_value, TRUE, NULL, 32, ¶m_value_len, &q);
626 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);
627 *((uschar **)(mime_parameter_list[j].value)) = param_value;
628 p += (mime_parameter_list[j].namelen + param_value_len + 1);
629 goto NEXT_PARAM_SEARCH;
632 /* There is something, but not one of our interesting parameters.
633 Advance to the next semicolon */
634 while(*p != ';') p++;
641 /* set additional flag variables (easier access) */
642 if ( (mime_content_type != NULL) &&
643 (Ustrncmp(mime_content_type,"multipart",9) == 0) )
644 mime_is_multipart = 1;
646 /* Make a copy of the boundary pointer.
647 Required since mime_boundary is global
648 and can be overwritten further down in recursion */
649 nested_context.boundary = mime_boundary;
651 /* raise global counter */
654 /* copy current file handle to global variable */
656 mime_current_boundary = context ? context->boundary : 0;
658 /* Note the context */
659 mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
661 /* call ACL handling function */
662 rc = acl_check(ACL_WHERE_MIME, NULL, acl_smtp_mime, user_msgptr, log_msgptr);
665 mime_current_boundary = NULL;
669 /* If we have a multipart entity and a boundary, go recursive */
670 if ( (mime_content_type != NULL) &&
671 (nested_context.boundary != NULL) &&
672 (Ustrncmp(mime_content_type,"multipart",9) == 0) ) {
673 debug_printf("Entering multipart recursion, boundary '%s'\n", nested_context.boundary);
675 if (context && context->context == MBC_ATTACHMENT)
676 nested_context.context = MBC_ATTACHMENT;
677 else if (!Ustrcmp(mime_content_type,"multipart/alternative")
678 || !Ustrcmp(mime_content_type,"multipart/related"))
679 nested_context.context = MBC_COVERLETTER_ALL;
681 nested_context.context = MBC_COVERLETTER_ONESHOT;
683 rc = mime_acl_check(f, &nested_context, user_msgptr, log_msgptr);
686 else if ( (mime_content_type != NULL) &&
687 (Ustrncmp(mime_content_type,"message/rfc822",14) == 0) ) {
688 uschar *rfc822name = NULL;
689 uschar filename[2048];
693 /* must find first free sequential filename */
696 snprintf(CS filename,2048,"%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr);
701 result = stat(CS filename,&mystat);
705 rfc822name = filename;
707 /* decode RFC822 attachment */
708 mime_decoded_filename = NULL;
710 mime_current_boundary = context ? context->boundary : NULL;
711 mime_decode(&rfc822name);
713 mime_current_boundary = NULL;
714 if (mime_decoded_filename == NULL) {
715 /* decoding failed */
716 log_write(0, LOG_MAIN,
717 "mime_regex acl condition warning - could not decode RFC822 MIME part to file.");
720 mime_decoded_filename = NULL;
724 /* If the boundary of this instance is NULL, we are finished here */
725 if (context == NULL) break;
727 if (context->context == MBC_COVERLETTER_ONESHOT)
728 context->context = MBC_ATTACHMENT;