1 /* $Cambridge: exim/src/src/mime.c,v 1.1.2.3 2004/11/30 15:18:58 tom 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;
19 /*************************************************
20 * decode quoted-printable chars *
21 *************************************************/
23 /* gets called when we hit a =
24 returns: new pointer position
27 -1 - soft line break, no char
31 unsigned int mime_qp_hstr_i(uschar *cptr) {
32 unsigned int i, j = 0;
33 while (cptr && *cptr && isxdigit(*cptr)) {
42 uschar *mime_decode_qp_char(uschar *qp_p,int *c) {
43 uschar hex[] = {0,0,0};
45 uschar *initial_pos = qp_p;
47 /* advance one char */
51 if ( (*qp_p == '\t') || (*qp_p == ' ') || (*qp_p == '\r') ) {
52 /* tab or whitespace may follow
53 just ignore it, but remember
54 that this is not a valid hex
60 else if ( (('0' <= *qp_p) && (*qp_p <= '9')) || (('A' <= *qp_p) && (*qp_p <= 'F')) || (('a' <= *qp_p) && (*qp_p <= 'f')) ) {
61 /* this is a valid hex char, if nan is unset */
72 else if (*qp_p == '\n') {
73 /* hit soft line break already, continue */
78 /* illegal char here */
83 if ( (('0' <= *qp_p) && (*qp_p <= '9')) || (('A' <= *qp_p) && (*qp_p <= 'F')) || (('a' <= *qp_p) && (*qp_p <= 'f')) ) {
86 /* do hex conversion */
87 *c = mime_qp_hstr_i(hex);
105 uschar *mime_parse_line(uschar *buffer, uschar *encoding, int *num_decoded) {
108 data = (uschar *)malloc(Ustrlen(buffer)+2);
110 if (encoding == NULL) {
111 /* no encoding type at all */
113 memcpy(data, buffer, Ustrlen(buffer));
114 data[(Ustrlen(buffer))] = 0;
115 *num_decoded = Ustrlen(data);
118 else if (Ustrcmp(encoding,"base64") == 0) {
122 /* ----- BASE64 ---------------------------------------------------- */
123 /* NULL out '\r' and '\n' chars */
124 while (Ustrrchr(p,'\r') != NULL) {
125 *(Ustrrchr(p,'\r')) = '\0';
127 while (Ustrrchr(p,'\n') != NULL) {
128 *(Ustrrchr(p,'\n')) = '\0';
131 while (*(p+offset) != '\0') {
132 /* hit illegal char ? */
133 if (mime_b64[*(p+offset)] == 128) {
137 *p = mime_b64[*(p+offset)];
143 /* line is translated, start bit shifting */
149 /* byte 0 ---------------------- */
153 data[(*num_decoded)] = *p;
154 data[(*num_decoded)] <<= 2;
157 data[(*num_decoded)] |= tmp_c;
160 /* byte 1 ---------------------- */
164 data[(*num_decoded)] = *p;
165 data[(*num_decoded)] <<= 4;
168 data[(*num_decoded)] |= tmp_c;
171 /* byte 2 ---------------------- */
175 data[(*num_decoded)] = *p;
176 data[(*num_decoded)] <<= 6;
177 data[(*num_decoded)] |= *(p+1);
183 /* ----------------------------------------------------------------- */
185 else if (Ustrcmp(encoding,"quoted-printable") == 0) {
188 /* ----- QP -------------------------------------------------------- */
192 int decode_qp_result;
194 p = mime_decode_qp_char(p,&decode_qp_result);
196 if (decode_qp_result == -2) {
197 /* Error from decoder. p is unchanged. */
198 data[(*num_decoded)] = '=';
202 else if (decode_qp_result == -1) {
205 else if (decode_qp_result >= 0) {
206 data[(*num_decoded)] = decode_qp_result;
211 data[(*num_decoded)] = *p;
217 /* ----------------------------------------------------------------- */
219 /* unknown encoding type, just dump as-is */
220 else goto NO_DECODING;
224 FILE *mime_get_decode_file(uschar *pname, uschar *fname) {
228 filename = (uschar *)malloc(2048);
230 if ((pname != NULL) && (fname != NULL)) {
231 snprintf(CS filename, 2048, "%s/%s", pname, fname);
232 f = fopen(CS filename,"w+");
234 else if (pname == NULL) {
235 f = fopen(CS fname,"w+");
237 else if (fname == NULL) {
241 /* must find first free sequential filename */
244 snprintf(CS filename,2048,"%s/%s-%05u", pname, message_id, file_nr);
249 result = stat(CS filename,&mystat);
252 f = fopen(CS filename,"w+");
255 /* set expansion variable */
256 mime_decoded_filename = filename;
262 int mime_decode(uschar **listptr) {
264 uschar *list = *listptr;
266 uschar option_buffer[1024];
267 uschar decode_path[1024];
268 FILE *decode_file = NULL;
269 uschar *buffer = NULL;
271 unsigned int size_counter = 0;
273 if (mime_stream == NULL)
276 f_pos = ftell(mime_stream);
278 /* build default decode path (will exist since MBOX must be spooled up) */
279 snprintf(CS decode_path,1024,"%s/scan/%s",spool_directory,message_id);
281 /* reserve a line buffer to work in */
282 buffer = (uschar *)malloc(MIME_MAX_LINE_LENGTH+1);
283 if (buffer == NULL) {
284 log_write(0, LOG_PANIC,
285 "decode ACL condition: can't allocate %d bytes of memory.", MIME_MAX_LINE_LENGTH+1);
289 /* try to find 1st option */
290 if ((option = string_nextinlist(&list, &sep,
292 sizeof(option_buffer))) != NULL) {
294 /* parse 1st option */
295 if ( (Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0) ) {
296 /* explicitly no decoding */
300 if (Ustrcmp(option,"default") == 0) {
301 /* explicit default path + file names */
305 if (option[0] == '/') {
308 memset(&statbuf,0,sizeof(statbuf));
310 /* assume either path or path+file name */
311 if ( (stat(CS option, &statbuf) == 0) && S_ISDIR(statbuf.st_mode) )
312 /* is directory, use it as decode_path */
313 decode_file = mime_get_decode_file(option, NULL);
315 /* does not exist or is a file, use as full file name */
316 decode_file = mime_get_decode_file(NULL, option);
319 /* assume file name only, use default path */
320 decode_file = mime_get_decode_file(decode_path, option);
323 /* no option? patch default path */
324 DEFAULT_PATH: decode_file = mime_get_decode_file(decode_path, NULL);
326 if (decode_file == NULL)
329 /* read data linewise and dump it to the file,
330 while looking for the current boundary */
331 while(fgets(CS buffer, MIME_MAX_LINE_LENGTH, mime_stream) != NULL) {
332 uschar *decoded_line = NULL;
333 int decoded_line_length = 0;
335 if (mime_current_boundary != NULL) {
336 /* boundary line must start with 2 dashes */
337 if (Ustrncmp(buffer,"--",2) == 0) {
338 if (Ustrncmp((buffer+2),mime_current_boundary,Ustrlen(mime_current_boundary)) == 0)
343 decoded_line = mime_parse_line(buffer, mime_content_transfer_encoding, &decoded_line_length);
344 /* write line to decode file */
345 if (fwrite(decoded_line, 1, decoded_line_length, decode_file) < decoded_line_length) {
346 /* error/short write */
347 clearerr(mime_stream);
348 fseek(mime_stream,f_pos,SEEK_SET);
351 size_counter += decoded_line_length;
353 if (size_counter > 1023) {
354 if ((mime_content_size + (size_counter / 1024)) < 65535)
355 mime_content_size += (size_counter / 1024);
357 mime_content_size = 65535;
358 size_counter = (size_counter % 1024);
366 clearerr(mime_stream);
367 fseek(mime_stream,f_pos,SEEK_SET);
369 /* round up remaining size bytes to one k */
377 int mime_get_header(FILE *f, uschar *header) {
380 int header_value_mode = 0;
381 int header_open_brackets = 0;
389 /* always skip CRs */
390 if (c == '\r') continue;
393 if (num_copied > 0) {
394 /* look if next char is '\t' or ' ' */
397 if ( (c == '\t') || (c == ' ') ) continue;
400 /* end of the header, terminate with ';' */
405 /* skip control characters */
406 if (c < 32) continue;
408 if (header_value_mode) {
409 /* --------- value mode ----------- */
410 /* skip leading whitespace */
411 if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
414 /* we have hit a non-whitespace char, start copying value data */
415 header_value_mode = 2;
418 if (c == '"') continue;
420 /* leave value mode on ';' */
422 header_value_mode = 0;
424 /* -------------------------------- */
427 /* -------- non-value mode -------- */
428 /* skip whitespace + tabs */
429 if ( (c == ' ') || (c == '\t') )
432 /* quote next char. can be used
433 to escape brackets. */
438 header_open_brackets++;
441 else if ((c == ')') && header_open_brackets) {
442 header_open_brackets--;
445 else if ( (c == '=') && !header_open_brackets ) {
446 /* enter value mode */
447 header_value_mode = 1;
450 /* skip chars while we are in a comment */
451 if (header_open_brackets > 0)
453 /* -------------------------------- */
456 /* copy the char to the buffer */
457 header[num_copied] = (uschar)c;
461 /* break if header buffer is full */
462 if (num_copied > MIME_MAX_HEADER_SIZE-1) {
467 if (header[num_copied-1] != ';') {
468 header[num_copied-1] = ';';
472 header[num_copied] = '\0';
474 /* return 0 for EOF or empty line */
475 if ((c == EOF) || (num_copied == 1))
482 int mime_acl_check(FILE *f, struct mime_boundary_context *context, uschar
483 **user_msgptr, uschar **log_msgptr) {
485 uschar *header = NULL;
486 struct mime_boundary_context nested_context;
488 /* reserve a line buffer to work in */
489 header = (uschar *)malloc(MIME_MAX_HEADER_SIZE+1);
490 if (header == NULL) {
491 log_write(0, LOG_PANIC,
492 "acl_smtp_mime: can't allocate %d bytes of memory.", MIME_MAX_HEADER_SIZE+1);
496 /* Not actually used at the moment, but will be vital to fixing
497 * some RFC 2046 nonconformance later... */
498 nested_context.parent = context;
500 /* loop through parts */
503 /* reset all per-part mime variables */
504 mime_anomaly_level = NULL;
505 mime_anomaly_text = NULL;
506 mime_boundary = NULL;
508 mime_decoded_filename = NULL;
509 mime_filename = NULL;
510 mime_content_description = NULL;
511 mime_content_disposition = NULL;
512 mime_content_id = NULL;
513 mime_content_transfer_encoding = NULL;
514 mime_content_type = NULL;
515 mime_is_multipart = 0;
516 mime_content_size = 0;
519 If boundary is null, we assume that *f is positioned on the start of headers (for example,
520 at the very beginning of a message.
521 If a boundary is given, we must first advance to it to reach the start of the next header
525 /* NOTE -- there's an error here -- RFC2046 specifically says to
526 * check for outer boundaries. This code doesn't do that, and
527 * I haven't fixed this.
529 * (I have moved partway towards adding support, however, by adding
530 * a "parent" field to my new boundary-context structure.)
532 if (context != NULL) {
533 while(fgets(CS header, MIME_MAX_HEADER_SIZE, f) != NULL) {
534 /* boundary line must start with 2 dashes */
535 if (Ustrncmp(header,"--",2) == 0) {
536 if (Ustrncmp((header+2),context->boundary,Ustrlen(context->boundary)) == 0) {
538 if (Ustrncmp((header+2+Ustrlen(context->boundary)),"--",2) == 0) {
539 /* END boundary found */
540 debug_printf("End boundary found %s\n", context->boundary);
544 debug_printf("Next part with boundary %s\n", context->boundary);
546 /* can't use break here */
551 /* Hit EOF or read error. Ugh. */
552 debug_printf("Hit EOF ...\n");
557 /* parse headers, set up expansion variables */
558 while(mime_get_header(f,header)) {
560 /* loop through header list */
561 for (i = 0; i < mime_header_list_size; i++) {
562 uschar *header_value = NULL;
563 int header_value_len = 0;
565 /* found an interesting header? */
566 if (strncmpic(mime_header_list[i].name,header,mime_header_list[i].namelen) == 0) {
567 uschar *p = header + mime_header_list[i].namelen;
568 /* yes, grab the value (normalize to lower case)
569 and copy to its corresponding expansion variable */
574 header_value_len = (p - (header + mime_header_list[i].namelen));
575 header_value = (uschar *)malloc(header_value_len+1);
576 memset(header_value,0,header_value_len+1);
577 p = header + mime_header_list[i].namelen;
578 Ustrncpy(header_value, p, header_value_len);
579 debug_printf("Found %s MIME header, value is '%s'\n", mime_header_list[i].name, header_value);
580 *((uschar **)(mime_header_list[i].value)) = header_value;
582 /* make p point to the next character after the closing ';' */
583 p += (header_value_len+1);
585 /* grab all param=value tags on the remaining line, check if they are interesting */
586 NEXT_PARAM_SEARCH: while (*p != 0) {
588 for (j = 0; j < mime_parameter_list_size; j++) {
589 uschar *param_value = NULL;
590 int param_value_len = 0;
592 /* found an interesting parameter? */
593 if (strncmpic(mime_parameter_list[j].name,p,mime_parameter_list[j].namelen) == 0) {
594 uschar *q = p + mime_parameter_list[j].namelen;
595 /* yes, grab the value and copy to its corresponding expansion variable */
596 while(*q != ';') q++;
597 param_value_len = (q - (p + mime_parameter_list[j].namelen));
598 param_value = (uschar *)malloc(param_value_len+1);
599 memset(param_value,0,param_value_len+1);
600 q = p + mime_parameter_list[j].namelen;
601 Ustrncpy(param_value, q, param_value_len);
602 param_value = rfc2047_decode(param_value, TRUE, NULL, 32, ¶m_value_len, &q);
603 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);
604 *((uschar **)(mime_parameter_list[j].value)) = param_value;
605 p += (mime_parameter_list[j].namelen + param_value_len + 1);
606 goto NEXT_PARAM_SEARCH;
609 /* There is something, but not one of our interesting parameters.
610 Advance to the next semicolon */
611 while(*p != ';') p++;
618 /* set additional flag variables (easier access) */
619 if ( (mime_content_type != NULL) &&
620 (Ustrncmp(mime_content_type,"multipart",9) == 0) )
621 mime_is_multipart = 1;
623 /* Make a copy of the boundary pointer.
624 Required since mime_boundary is global
625 and can be overwritten further down in recursion */
626 nested_context.boundary = mime_boundary;
628 /* raise global counter */
631 /* copy current file handle to global variable */
633 mime_current_boundary = context ? context->boundary : 0;
635 /* Note the context */
636 mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
638 /* call ACL handling function */
639 rc = acl_check(ACL_WHERE_MIME, NULL, acl_smtp_mime, user_msgptr, log_msgptr);
642 mime_current_boundary = NULL;
646 /* If we have a multipart entity and a boundary, go recursive */
647 if ( (mime_content_type != NULL) &&
648 (nested_context.boundary != NULL) &&
649 (Ustrncmp(mime_content_type,"multipart",9) == 0) ) {
650 debug_printf("Entering multipart recursion, boundary '%s'\n", nested_context.boundary);
652 if (context && context->context == MBC_ATTACHMENT)
653 nested_context.context = MBC_ATTACHMENT;
654 else if (!Ustrcmp(mime_content_type,"multipart/alternative")
655 || !Ustrcmp(mime_content_type,"multipart/related"))
656 nested_context.context = MBC_COVERLETTER_ALL;
658 nested_context.context = MBC_COVERLETTER_ONESHOT;
660 rc = mime_acl_check(f, &nested_context, user_msgptr, log_msgptr);
663 else if ( (mime_content_type != NULL) &&
664 (Ustrncmp(mime_content_type,"message/rfc822",14) == 0) ) {
665 uschar *rfc822name = NULL;
666 uschar filename[2048];
670 /* must find first free sequential filename */
673 snprintf(CS filename,2048,"%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr);
678 result = stat(CS filename,&mystat);
682 rfc822name = filename;
684 /* decode RFC822 attachment */
685 mime_decoded_filename = NULL;
687 mime_current_boundary = context ? context->boundary : NULL;
688 mime_decode(&rfc822name);
690 mime_current_boundary = NULL;
691 if (mime_decoded_filename == NULL) {
692 /* decoding failed */
693 log_write(0, LOG_MAIN,
694 "mime_regex acl condition warning - could not decode RFC822 MIME part to file.");
697 mime_decoded_filename = NULL;
701 /* If the boundary of this instance is NULL, we are finished here */
702 if (context == NULL) break;
704 if (context->context == MBC_COVERLETTER_ONESHOT)
705 context->context = MBC_ATTACHMENT;