1 /* $Cambridge: exim/src/src/mime.c,v 1.1.2.2 2004/11/26 16:04:26 tom Exp $ */
3 /*************************************************
4 * Exim - an Internet mail transport agent *
5 *************************************************/
7 #ifdef WITH_CONTENT_SCAN
9 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2004 */
16 FILE *mime_stream = NULL;
17 uschar *mime_current_boundary = NULL;
20 /*************************************************
21 * decode quoted-printable chars *
22 *************************************************/
24 /* gets called when we hit a =
25 returns: new pointer position
28 -1 - soft line break, no char
32 unsigned int mime_qp_hstr_i(uschar *cptr) {
33 unsigned int i, j = 0;
34 while (cptr && *cptr && isxdigit(*cptr)) {
43 uschar *mime_decode_qp_char(uschar *qp_p,int *c) {
44 uschar hex[] = {0,0,0};
46 uschar *initial_pos = qp_p;
48 /* advance one char */
52 if ( (*qp_p == '\t') || (*qp_p == ' ') || (*qp_p == '\r') ) {
53 /* tab or whitespace may follow
54 just ignore it, but remember
55 that this is not a valid hex
61 else if ( (('0' <= *qp_p) && (*qp_p <= '9')) || (('A' <= *qp_p) && (*qp_p <= 'F')) || (('a' <= *qp_p) && (*qp_p <= 'f')) ) {
62 /* this is a valid hex char, if nan is unset */
73 else if (*qp_p == '\n') {
74 /* hit soft line break already, continue */
79 /* illegal char here */
84 if ( (('0' <= *qp_p) && (*qp_p <= '9')) || (('A' <= *qp_p) && (*qp_p <= 'F')) || (('a' <= *qp_p) && (*qp_p <= 'f')) ) {
87 /* do hex conversion */
88 *c = mime_qp_hstr_i(hex);
106 uschar *mime_parse_line(uschar *buffer, uschar *encoding, int *num_decoded) {
109 data = (uschar *)malloc(Ustrlen(buffer)+2);
111 if (encoding == NULL) {
112 /* no encoding type at all */
114 memcpy(data, buffer, Ustrlen(buffer));
115 data[(Ustrlen(buffer))] = 0;
116 *num_decoded = Ustrlen(data);
119 else if (Ustrcmp(encoding,"base64") == 0) {
123 /* ----- BASE64 ---------------------------------------------------- */
124 /* NULL out '\r' and '\n' chars */
125 while (Ustrrchr(p,'\r') != NULL) {
126 *(Ustrrchr(p,'\r')) = '\0';
128 while (Ustrrchr(p,'\n') != NULL) {
129 *(Ustrrchr(p,'\n')) = '\0';
132 while (*(p+offset) != '\0') {
133 /* hit illegal char ? */
134 if (mime_b64[*(p+offset)] == 128) {
138 *p = mime_b64[*(p+offset)];
144 /* line is translated, start bit shifting */
150 /* byte 0 ---------------------- */
154 data[(*num_decoded)] = *p;
155 data[(*num_decoded)] <<= 2;
158 data[(*num_decoded)] |= tmp_c;
161 /* byte 1 ---------------------- */
165 data[(*num_decoded)] = *p;
166 data[(*num_decoded)] <<= 4;
169 data[(*num_decoded)] |= tmp_c;
172 /* byte 2 ---------------------- */
176 data[(*num_decoded)] = *p;
177 data[(*num_decoded)] <<= 6;
178 data[(*num_decoded)] |= *(p+1);
184 /* ----------------------------------------------------------------- */
186 else if (Ustrcmp(encoding,"quoted-printable") == 0) {
189 /* ----- QP -------------------------------------------------------- */
193 int decode_qp_result;
195 p = mime_decode_qp_char(p,&decode_qp_result);
197 if (decode_qp_result == -2) {
198 /* Error from decoder. p is unchanged. */
199 data[(*num_decoded)] = '=';
203 else if (decode_qp_result == -1) {
206 else if (decode_qp_result >= 0) {
207 data[(*num_decoded)] = decode_qp_result;
212 data[(*num_decoded)] = *p;
218 /* ----------------------------------------------------------------- */
220 /* unknown encoding type, just dump as-is */
221 else goto NO_DECODING;
225 FILE *mime_get_decode_file(uschar *pname, uschar *fname) {
229 filename = (uschar *)malloc(2048);
231 if ((pname != NULL) && (fname != NULL)) {
232 snprintf(CS filename, 2048, "%s/%s", pname, fname);
233 f = fopen(CS filename,"w+");
235 else if (pname == NULL) {
236 f = fopen(CS fname,"w+");
238 else if (fname == NULL) {
242 /* must find first free sequential filename */
245 snprintf(CS filename,2048,"%s/%s-%05u", pname, message_id, file_nr);
250 result = stat(CS filename,&mystat);
253 f = fopen(CS filename,"w+");
256 /* set expansion variable */
257 mime_decoded_filename = filename;
263 int mime_decode(uschar **listptr) {
265 uschar *list = *listptr;
267 uschar option_buffer[1024];
268 uschar decode_path[1024];
269 FILE *decode_file = NULL;
270 uschar *buffer = NULL;
272 unsigned int size_counter = 0;
274 if (mime_stream == NULL)
277 f_pos = ftell(mime_stream);
279 /* build default decode path (will exist since MBOX must be spooled up) */
280 snprintf(CS decode_path,1024,"%s/scan/%s",spool_directory,message_id);
282 /* reserve a line buffer to work in */
283 buffer = (uschar *)malloc(MIME_MAX_LINE_LENGTH+1);
284 if (buffer == NULL) {
285 log_write(0, LOG_PANIC,
286 "decode ACL condition: can't allocate %d bytes of memory.", MIME_MAX_LINE_LENGTH+1);
290 /* try to find 1st option */
291 if ((option = string_nextinlist(&list, &sep,
293 sizeof(option_buffer))) != NULL) {
295 /* parse 1st option */
296 if ( (Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0) ) {
297 /* explicitly no decoding */
301 if (Ustrcmp(option,"default") == 0) {
302 /* explicit default path + file names */
306 if (option[0] == '/') {
309 memset(&statbuf,0,sizeof(statbuf));
311 /* assume either path or path+file name */
312 if ( (stat(CS option, &statbuf) == 0) && S_ISDIR(statbuf.st_mode) )
313 /* is directory, use it as decode_path */
314 decode_file = mime_get_decode_file(option, NULL);
316 /* does not exist or is a file, use as full file name */
317 decode_file = mime_get_decode_file(NULL, option);
320 /* assume file name only, use default path */
321 decode_file = mime_get_decode_file(decode_path, option);
324 /* no option? patch default path */
325 DEFAULT_PATH: decode_file = mime_get_decode_file(decode_path, NULL);
327 if (decode_file == NULL)
330 /* read data linewise and dump it to the file,
331 while looking for the current boundary */
332 while(fgets(CS buffer, MIME_MAX_LINE_LENGTH, mime_stream) != NULL) {
333 uschar *decoded_line = NULL;
334 int decoded_line_length = 0;
336 if (mime_current_boundary != NULL) {
337 /* boundary line must start with 2 dashes */
338 if (Ustrncmp(buffer,"--",2) == 0) {
339 if (Ustrncmp((buffer+2),mime_current_boundary,Ustrlen(mime_current_boundary)) == 0)
344 decoded_line = mime_parse_line(buffer, mime_content_transfer_encoding, &decoded_line_length);
345 /* write line to decode file */
346 if (fwrite(decoded_line, 1, decoded_line_length, decode_file) < decoded_line_length) {
347 /* error/short write */
348 clearerr(mime_stream);
349 fseek(mime_stream,f_pos,SEEK_SET);
352 size_counter += decoded_line_length;
354 if (size_counter > 1023) {
355 if ((mime_content_size + (size_counter / 1024)) < 65535)
356 mime_content_size += (size_counter / 1024);
358 mime_content_size = 65535;
359 size_counter = (size_counter % 1024);
367 clearerr(mime_stream);
368 fseek(mime_stream,f_pos,SEEK_SET);
370 /* round up remaining size bytes to one k */
378 int mime_get_header(FILE *f, uschar *header) {
381 int header_value_mode = 0;
382 int header_open_brackets = 0;
390 /* always skip CRs */
391 if (c == '\r') continue;
394 if (num_copied > 0) {
395 /* look if next char is '\t' or ' ' */
398 if ( (c == '\t') || (c == ' ') ) continue;
401 /* end of the header, terminate with ';' */
406 /* skip control characters */
407 if (c < 32) continue;
409 if (header_value_mode) {
410 /* --------- value mode ----------- */
411 /* skip leading whitespace */
412 if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
415 /* we have hit a non-whitespace char, start copying value data */
416 header_value_mode = 2;
419 if (c == '"') continue;
421 /* leave value mode on ';' */
423 header_value_mode = 0;
425 /* -------------------------------- */
428 /* -------- non-value mode -------- */
429 /* skip whitespace + tabs */
430 if ( (c == ' ') || (c == '\t') )
433 /* quote next char. can be used
434 to escape brackets. */
439 header_open_brackets++;
442 else if ((c == ')') && header_open_brackets) {
443 header_open_brackets--;
446 else if ( (c == '=') && !header_open_brackets ) {
447 /* enter value mode */
448 header_value_mode = 1;
451 /* skip chars while we are in a comment */
452 if (header_open_brackets > 0)
454 /* -------------------------------- */
457 /* copy the char to the buffer */
458 header[num_copied] = (uschar)c;
462 /* break if header buffer is full */
463 if (num_copied > MIME_MAX_HEADER_SIZE-1) {
468 if (header[num_copied-1] != ';') {
469 header[num_copied-1] = ';';
473 header[num_copied] = '\0';
475 /* return 0 for EOF or empty line */
476 if ((c == EOF) || (num_copied == 1))
483 int mime_acl_check(FILE *f, struct mime_boundary_context *context, uschar
484 **user_msgptr, uschar **log_msgptr) {
486 uschar *header = NULL;
487 struct mime_boundary_context nested_context;
489 /* reserve a line buffer to work in */
490 header = (uschar *)malloc(MIME_MAX_HEADER_SIZE+1);
491 if (header == NULL) {
492 log_write(0, LOG_PANIC,
493 "acl_smtp_mime: can't allocate %d bytes of memory.", MIME_MAX_HEADER_SIZE+1);
497 /* Not actually used at the moment, but will be vital to fixing
498 * some RFC 2046 nonconformance later... */
499 nested_context.parent = context;
501 /* loop through parts */
504 /* reset all per-part mime variables */
505 mime_anomaly_level = NULL;
506 mime_anomaly_text = NULL;
507 mime_boundary = NULL;
509 mime_decoded_filename = NULL;
510 mime_filename = NULL;
511 mime_content_description = NULL;
512 mime_content_disposition = NULL;
513 mime_content_id = NULL;
514 mime_content_transfer_encoding = NULL;
515 mime_content_type = NULL;
516 mime_is_multipart = 0;
517 mime_content_size = 0;
520 If boundary is null, we assume that *f is positioned on the start of headers (for example,
521 at the very beginning of a message.
522 If a boundary is given, we must first advance to it to reach the start of the next header
526 /* NOTE -- there's an error here -- RFC2046 specifically says to
527 * check for outer boundaries. This code doesn't do that, and
528 * I haven't fixed this.
530 * (I have moved partway towards adding support, however, by adding
531 * a "parent" field to my new boundary-context structure.)
533 if (context != NULL) {
534 while(fgets(CS header, MIME_MAX_HEADER_SIZE, f) != NULL) {
535 /* boundary line must start with 2 dashes */
536 if (Ustrncmp(header,"--",2) == 0) {
537 if (Ustrncmp((header+2),context->boundary,Ustrlen(context->boundary)) == 0) {
539 if (Ustrncmp((header+2+Ustrlen(context->boundary)),"--",2) == 0) {
540 /* END boundary found */
541 debug_printf("End boundary found %s\n", context->boundary);
545 debug_printf("Next part with boundary %s\n", context->boundary);
547 /* can't use break here */
552 /* Hit EOF or read error. Ugh. */
553 debug_printf("Hit EOF ...\n");
558 /* parse headers, set up expansion variables */
559 while(mime_get_header(f,header)) {
561 /* loop through header list */
562 for (i = 0; i < mime_header_list_size; i++) {
563 uschar *header_value = NULL;
564 int header_value_len = 0;
566 /* found an interesting header? */
567 if (strncmpic(mime_header_list[i].name,header,mime_header_list[i].namelen) == 0) {
568 uschar *p = header + mime_header_list[i].namelen;
569 /* yes, grab the value (normalize to lower case)
570 and copy to its corresponding expansion variable */
575 header_value_len = (p - (header + mime_header_list[i].namelen));
576 header_value = (uschar *)malloc(header_value_len+1);
577 memset(header_value,0,header_value_len+1);
578 p = header + mime_header_list[i].namelen;
579 Ustrncpy(header_value, p, header_value_len);
580 debug_printf("Found %s MIME header, value is '%s'\n", mime_header_list[i].name, header_value);
581 *((uschar **)(mime_header_list[i].value)) = header_value;
583 /* make p point to the next character after the closing ';' */
584 p += (header_value_len+1);
586 /* grab all param=value tags on the remaining line, check if they are interesting */
587 NEXT_PARAM_SEARCH: while (*p != 0) {
589 for (j = 0; j < mime_parameter_list_size; j++) {
590 uschar *param_value = NULL;
591 int param_value_len = 0;
593 /* found an interesting parameter? */
594 if (strncmpic(mime_parameter_list[j].name,p,mime_parameter_list[j].namelen) == 0) {
595 uschar *q = p + mime_parameter_list[j].namelen;
596 /* yes, grab the value and copy to its corresponding expansion variable */
597 while(*q != ';') q++;
598 param_value_len = (q - (p + mime_parameter_list[j].namelen));
599 param_value = (uschar *)malloc(param_value_len+1);
600 memset(param_value,0,param_value_len+1);
601 q = p + mime_parameter_list[j].namelen;
602 Ustrncpy(param_value, q, param_value_len);
603 param_value = rfc2047_decode(param_value, TRUE, NULL, 32, ¶m_value_len, &q);
604 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);
605 *((uschar **)(mime_parameter_list[j].value)) = param_value;
606 p += (mime_parameter_list[j].namelen + param_value_len + 1);
607 goto NEXT_PARAM_SEARCH;
610 /* There is something, but not one of our interesting parameters.
611 Advance to the next semicolon */
612 while(*p != ';') p++;
619 /* set additional flag variables (easier access) */
620 if ( (mime_content_type != NULL) &&
621 (Ustrncmp(mime_content_type,"multipart",9) == 0) )
622 mime_is_multipart = 1;
624 /* Make a copy of the boundary pointer.
625 Required since mime_boundary is global
626 and can be overwritten further down in recursion */
627 nested_context.boundary = mime_boundary;
629 /* raise global counter */
632 /* copy current file handle to global variable */
634 mime_current_boundary = context ? context->boundary : 0;
636 /* Note the context */
637 mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
639 /* call ACL handling function */
640 rc = acl_check(ACL_WHERE_MIME, NULL, acl_smtp_mime, user_msgptr, log_msgptr);
643 mime_current_boundary = NULL;
647 /* If we have a multipart entity and a boundary, go recursive */
648 if ( (mime_content_type != NULL) &&
649 (nested_context.boundary != NULL) &&
650 (Ustrncmp(mime_content_type,"multipart",9) == 0) ) {
651 debug_printf("Entering multipart recursion, boundary '%s'\n", nested_context.boundary);
653 if (context && context->context == MBC_ATTACHMENT)
654 nested_context.context = MBC_ATTACHMENT;
655 else if (!Ustrcmp(mime_content_type,"multipart/alternative")
656 || !Ustrcmp(mime_content_type,"multipart/related"))
657 nested_context.context = MBC_COVERLETTER_ALL;
659 nested_context.context = MBC_COVERLETTER_ONESHOT;
661 rc = mime_acl_check(f, &nested_context, user_msgptr, log_msgptr);
664 else if ( (mime_content_type != NULL) &&
665 (Ustrncmp(mime_content_type,"message/rfc822",14) == 0) ) {
666 uschar *rfc822name = NULL;
667 uschar filename[2048];
671 /* must find first free sequential filename */
674 snprintf(CS filename,2048,"%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr);
679 result = stat(CS filename,&mystat);
683 rfc822name = filename;
685 /* decode RFC822 attachment */
686 mime_decoded_filename = NULL;
688 mime_current_boundary = context ? context->boundary : NULL;
689 mime_decode(&rfc822name);
691 mime_current_boundary = NULL;
692 if (mime_decoded_filename == NULL) {
693 /* decoding failed */
694 log_write(0, LOG_MAIN,
695 "mime_regex acl condition warning - could not decode RFC822 MIME part to file.");
698 mime_decoded_filename = NULL;
702 /* If the boundary of this instance is NULL, we are finished here */
703 if (context == NULL) break;
705 if (context->context == MBC_COVERLETTER_ONESHOT)
706 context->context = MBC_ATTACHMENT;