1 /* $Cambridge: exim/src/src/mime.c,v 1.1.2.1 2004/11/26 09:13:34 tom Exp $ */
3 /*************************************************
4 * Exim - an Internet mail transport agent *
5 *************************************************/
7 /* This file is part of the exiscan-acl content scanner
8 patch. It is NOT part of the standard exim distribution. */
10 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2004 */
17 FILE *mime_stream = NULL;
18 uschar *mime_current_boundary = NULL;
21 /*************************************************
22 * decode quoted-printable chars *
23 *************************************************/
25 /* gets called when we hit a =
26 returns: new pointer position
29 -1 - soft line break, no char
33 unsigned int mime_qp_hstr_i(uschar *cptr) {
34 unsigned int i, j = 0;
35 while (cptr && *cptr && isxdigit(*cptr)) {
44 uschar *mime_decode_qp_char(uschar *qp_p,int *c) {
45 uschar hex[] = {0,0,0};
47 uschar *initial_pos = qp_p;
49 /* advance one char */
53 if ( (*qp_p == '\t') || (*qp_p == ' ') || (*qp_p == '\r') ) {
54 /* tab or whitespace may follow
55 just ignore it, but remember
56 that this is not a valid hex
62 else if ( (('0' <= *qp_p) && (*qp_p <= '9')) || (('A' <= *qp_p) && (*qp_p <= 'F')) || (('a' <= *qp_p) && (*qp_p <= 'f')) ) {
63 /* this is a valid hex char, if nan is unset */
74 else if (*qp_p == '\n') {
75 /* hit soft line break already, continue */
80 /* illegal char here */
85 if ( (('0' <= *qp_p) && (*qp_p <= '9')) || (('A' <= *qp_p) && (*qp_p <= 'F')) || (('a' <= *qp_p) && (*qp_p <= 'f')) ) {
88 /* do hex conversion */
89 *c = mime_qp_hstr_i(hex);
107 uschar *mime_parse_line(uschar *buffer, uschar *encoding, int *num_decoded) {
110 data = (uschar *)malloc(Ustrlen(buffer)+2);
112 if (encoding == NULL) {
113 /* no encoding type at all */
115 memcpy(data, buffer, Ustrlen(buffer));
116 data[(Ustrlen(buffer))] = 0;
117 *num_decoded = Ustrlen(data);
120 else if (Ustrcmp(encoding,"base64") == 0) {
124 /* ----- BASE64 ---------------------------------------------------- */
125 /* NULL out '\r' and '\n' chars */
126 while (Ustrrchr(p,'\r') != NULL) {
127 *(Ustrrchr(p,'\r')) = '\0';
129 while (Ustrrchr(p,'\n') != NULL) {
130 *(Ustrrchr(p,'\n')) = '\0';
133 while (*(p+offset) != '\0') {
134 /* hit illegal char ? */
135 if (mime_b64[*(p+offset)] == 128) {
139 *p = mime_b64[*(p+offset)];
145 /* line is translated, start bit shifting */
151 /* byte 0 ---------------------- */
155 data[(*num_decoded)] = *p;
156 data[(*num_decoded)] <<= 2;
159 data[(*num_decoded)] |= tmp_c;
162 /* byte 1 ---------------------- */
166 data[(*num_decoded)] = *p;
167 data[(*num_decoded)] <<= 4;
170 data[(*num_decoded)] |= tmp_c;
173 /* byte 2 ---------------------- */
177 data[(*num_decoded)] = *p;
178 data[(*num_decoded)] <<= 6;
179 data[(*num_decoded)] |= *(p+1);
185 /* ----------------------------------------------------------------- */
187 else if (Ustrcmp(encoding,"quoted-printable") == 0) {
190 /* ----- QP -------------------------------------------------------- */
194 int decode_qp_result;
196 p = mime_decode_qp_char(p,&decode_qp_result);
198 if (decode_qp_result == -2) {
199 /* Error from decoder. p is unchanged. */
200 data[(*num_decoded)] = '=';
204 else if (decode_qp_result == -1) {
207 else if (decode_qp_result >= 0) {
208 data[(*num_decoded)] = decode_qp_result;
213 data[(*num_decoded)] = *p;
219 /* ----------------------------------------------------------------- */
221 /* unknown encoding type, just dump as-is */
222 else goto NO_DECODING;
226 FILE *mime_get_decode_file(uschar *pname, uschar *fname) {
230 filename = (uschar *)malloc(2048);
232 if ((pname != NULL) && (fname != NULL)) {
233 snprintf(CS filename, 2048, "%s/%s", pname, fname);
234 f = fopen(CS filename,"w+");
236 else if (pname == NULL) {
237 f = fopen(CS fname,"w+");
239 else if (fname == NULL) {
243 /* must find first free sequential filename */
246 snprintf(CS filename,2048,"%s/%s-%05u", pname, message_id, file_nr);
251 result = stat(CS filename,&mystat);
254 f = fopen(CS filename,"w+");
257 /* set expansion variable */
258 mime_decoded_filename = filename;
264 int mime_decode(uschar **listptr) {
266 uschar *list = *listptr;
268 uschar option_buffer[1024];
269 uschar decode_path[1024];
270 FILE *decode_file = NULL;
271 uschar *buffer = NULL;
273 unsigned int size_counter = 0;
275 if (mime_stream == NULL)
278 f_pos = ftell(mime_stream);
280 /* build default decode path (will exist since MBOX must be spooled up) */
281 snprintf(CS decode_path,1024,"%s/scan/%s",spool_directory,message_id);
283 /* reserve a line buffer to work in */
284 buffer = (uschar *)malloc(MIME_MAX_LINE_LENGTH+1);
285 if (buffer == NULL) {
286 log_write(0, LOG_PANIC,
287 "decode ACL condition: can't allocate %d bytes of memory.", MIME_MAX_LINE_LENGTH+1);
291 /* try to find 1st option */
292 if ((option = string_nextinlist(&list, &sep,
294 sizeof(option_buffer))) != NULL) {
296 /* parse 1st option */
297 if ( (Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0) ) {
298 /* explicitly no decoding */
302 if (Ustrcmp(option,"default") == 0) {
303 /* explicit default path + file names */
307 if (option[0] == '/') {
310 memset(&statbuf,0,sizeof(statbuf));
312 /* assume either path or path+file name */
313 if ( (stat(CS option, &statbuf) == 0) && S_ISDIR(statbuf.st_mode) )
314 /* is directory, use it as decode_path */
315 decode_file = mime_get_decode_file(option, NULL);
317 /* does not exist or is a file, use as full file name */
318 decode_file = mime_get_decode_file(NULL, option);
321 /* assume file name only, use default path */
322 decode_file = mime_get_decode_file(decode_path, option);
325 /* no option? patch default path */
326 DEFAULT_PATH: decode_file = mime_get_decode_file(decode_path, NULL);
328 if (decode_file == NULL)
331 /* read data linewise and dump it to the file,
332 while looking for the current boundary */
333 while(fgets(CS buffer, MIME_MAX_LINE_LENGTH, mime_stream) != NULL) {
334 uschar *decoded_line = NULL;
335 int decoded_line_length = 0;
337 if (mime_current_boundary != NULL) {
338 /* boundary line must start with 2 dashes */
339 if (Ustrncmp(buffer,"--",2) == 0) {
340 if (Ustrncmp((buffer+2),mime_current_boundary,Ustrlen(mime_current_boundary)) == 0)
345 decoded_line = mime_parse_line(buffer, mime_content_transfer_encoding, &decoded_line_length);
346 /* write line to decode file */
347 if (fwrite(decoded_line, 1, decoded_line_length, decode_file) < decoded_line_length) {
348 /* error/short write */
349 clearerr(mime_stream);
350 fseek(mime_stream,f_pos,SEEK_SET);
353 size_counter += decoded_line_length;
355 if (size_counter > 1023) {
356 if ((mime_content_size + (size_counter / 1024)) < 65535)
357 mime_content_size += (size_counter / 1024);
359 mime_content_size = 65535;
360 size_counter = (size_counter % 1024);
368 clearerr(mime_stream);
369 fseek(mime_stream,f_pos,SEEK_SET);
371 /* round up remaining size bytes to one k */
379 int mime_get_header(FILE *f, uschar *header) {
382 int header_value_mode = 0;
383 int header_open_brackets = 0;
391 /* always skip CRs */
392 if (c == '\r') continue;
395 if (num_copied > 0) {
396 /* look if next char is '\t' or ' ' */
399 if ( (c == '\t') || (c == ' ') ) continue;
402 /* end of the header, terminate with ';' */
407 /* skip control characters */
408 if (c < 32) continue;
410 if (header_value_mode) {
411 /* --------- value mode ----------- */
412 /* skip leading whitespace */
413 if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
416 /* we have hit a non-whitespace char, start copying value data */
417 header_value_mode = 2;
420 if (c == '"') continue;
422 /* leave value mode on ';' */
424 header_value_mode = 0;
426 /* -------------------------------- */
429 /* -------- non-value mode -------- */
430 /* skip whitespace + tabs */
431 if ( (c == ' ') || (c == '\t') )
434 /* quote next char. can be used
435 to escape brackets. */
440 header_open_brackets++;
443 else if ((c == ')') && header_open_brackets) {
444 header_open_brackets--;
447 else if ( (c == '=') && !header_open_brackets ) {
448 /* enter value mode */
449 header_value_mode = 1;
452 /* skip chars while we are in a comment */
453 if (header_open_brackets > 0)
455 /* -------------------------------- */
458 /* copy the char to the buffer */
459 header[num_copied] = (uschar)c;
463 /* break if header buffer is full */
464 if (num_copied > MIME_MAX_HEADER_SIZE-1) {
469 if (header[num_copied-1] != ';') {
470 header[num_copied-1] = ';';
474 header[num_copied] = '\0';
476 /* return 0 for EOF or empty line */
477 if ((c == EOF) || (num_copied == 1))
484 int mime_acl_check(FILE *f, struct mime_boundary_context *context, uschar
485 **user_msgptr, uschar **log_msgptr) {
487 uschar *header = NULL;
488 struct mime_boundary_context nested_context;
490 /* reserve a line buffer to work in */
491 header = (uschar *)malloc(MIME_MAX_HEADER_SIZE+1);
492 if (header == NULL) {
493 log_write(0, LOG_PANIC,
494 "acl_smtp_mime: can't allocate %d bytes of memory.", MIME_MAX_HEADER_SIZE+1);
498 /* Not actually used at the moment, but will be vital to fixing
499 * some RFC 2046 nonconformance later... */
500 nested_context.parent = context;
502 /* loop through parts */
505 /* reset all per-part mime variables */
506 mime_anomaly_level = NULL;
507 mime_anomaly_text = NULL;
508 mime_boundary = NULL;
510 mime_decoded_filename = NULL;
511 mime_filename = NULL;
512 mime_content_description = NULL;
513 mime_content_disposition = NULL;
514 mime_content_id = NULL;
515 mime_content_transfer_encoding = NULL;
516 mime_content_type = NULL;
517 mime_is_multipart = 0;
518 mime_content_size = 0;
521 If boundary is null, we assume that *f is positioned on the start of headers (for example,
522 at the very beginning of a message.
523 If a boundary is given, we must first advance to it to reach the start of the next header
527 /* NOTE -- there's an error here -- RFC2046 specifically says to
528 * check for outer boundaries. This code doesn't do that, and
529 * I haven't fixed this.
531 * (I have moved partway towards adding support, however, by adding
532 * a "parent" field to my new boundary-context structure.)
534 if (context != NULL) {
535 while(fgets(CS header, MIME_MAX_HEADER_SIZE, f) != NULL) {
536 /* boundary line must start with 2 dashes */
537 if (Ustrncmp(header,"--",2) == 0) {
538 if (Ustrncmp((header+2),context->boundary,Ustrlen(context->boundary)) == 0) {
540 if (Ustrncmp((header+2+Ustrlen(context->boundary)),"--",2) == 0) {
541 /* END boundary found */
542 debug_printf("End boundary found %s\n", context->boundary);
546 debug_printf("Next part with boundary %s\n", context->boundary);
548 /* can't use break here */
553 /* Hit EOF or read error. Ugh. */
554 debug_printf("Hit EOF ...\n");
559 /* parse headers, set up expansion variables */
560 while(mime_get_header(f,header)) {
562 /* loop through header list */
563 for (i = 0; i < mime_header_list_size; i++) {
564 uschar *header_value = NULL;
565 int header_value_len = 0;
567 /* found an interesting header? */
568 if (strncmpic(mime_header_list[i].name,header,mime_header_list[i].namelen) == 0) {
569 uschar *p = header + mime_header_list[i].namelen;
570 /* yes, grab the value (normalize to lower case)
571 and copy to its corresponding expansion variable */
576 header_value_len = (p - (header + mime_header_list[i].namelen));
577 header_value = (uschar *)malloc(header_value_len+1);
578 memset(header_value,0,header_value_len+1);
579 p = header + mime_header_list[i].namelen;
580 Ustrncpy(header_value, p, header_value_len);
581 debug_printf("Found %s MIME header, value is '%s'\n", mime_header_list[i].name, header_value);
582 *((uschar **)(mime_header_list[i].value)) = header_value;
584 /* make p point to the next character after the closing ';' */
585 p += (header_value_len+1);
587 /* grab all param=value tags on the remaining line, check if they are interesting */
588 NEXT_PARAM_SEARCH: while (*p != 0) {
590 for (j = 0; j < mime_parameter_list_size; j++) {
591 uschar *param_value = NULL;
592 int param_value_len = 0;
594 /* found an interesting parameter? */
595 if (strncmpic(mime_parameter_list[j].name,p,mime_parameter_list[j].namelen) == 0) {
596 uschar *q = p + mime_parameter_list[j].namelen;
597 /* yes, grab the value and copy to its corresponding expansion variable */
598 while(*q != ';') q++;
599 param_value_len = (q - (p + mime_parameter_list[j].namelen));
600 param_value = (uschar *)malloc(param_value_len+1);
601 memset(param_value,0,param_value_len+1);
602 q = p + mime_parameter_list[j].namelen;
603 Ustrncpy(param_value, q, param_value_len);
604 param_value = rfc2047_decode(param_value, TRUE, NULL, 32, ¶m_value_len, &q);
605 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);
606 *((uschar **)(mime_parameter_list[j].value)) = param_value;
607 p += (mime_parameter_list[j].namelen + param_value_len + 1);
608 goto NEXT_PARAM_SEARCH;
611 /* There is something, but not one of our interesting parameters.
612 Advance to the next semicolon */
613 while(*p != ';') p++;
620 /* set additional flag variables (easier access) */
621 if ( (mime_content_type != NULL) &&
622 (Ustrncmp(mime_content_type,"multipart",9) == 0) )
623 mime_is_multipart = 1;
625 /* Make a copy of the boundary pointer.
626 Required since mime_boundary is global
627 and can be overwritten further down in recursion */
628 nested_context.boundary = mime_boundary;
630 /* raise global counter */
633 /* copy current file handle to global variable */
635 mime_current_boundary = context ? context->boundary : 0;
637 /* Note the context */
638 mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
640 /* call ACL handling function */
641 rc = acl_check(ACL_WHERE_MIME, NULL, acl_smtp_mime, user_msgptr, log_msgptr);
644 mime_current_boundary = NULL;
648 /* If we have a multipart entity and a boundary, go recursive */
649 if ( (mime_content_type != NULL) &&
650 (nested_context.boundary != NULL) &&
651 (Ustrncmp(mime_content_type,"multipart",9) == 0) ) {
652 debug_printf("Entering multipart recursion, boundary '%s'\n", nested_context.boundary);
654 if (context && context->context == MBC_ATTACHMENT)
655 nested_context.context = MBC_ATTACHMENT;
656 else if (!Ustrcmp(mime_content_type,"multipart/alternative")
657 || !Ustrcmp(mime_content_type,"multipart/related"))
658 nested_context.context = MBC_COVERLETTER_ALL;
660 nested_context.context = MBC_COVERLETTER_ONESHOT;
662 rc = mime_acl_check(f, &nested_context, user_msgptr, log_msgptr);
665 else if ( (mime_content_type != NULL) &&
666 (Ustrncmp(mime_content_type,"message/rfc822",14) == 0) ) {
667 uschar *rfc822name = NULL;
668 uschar filename[2048];
672 /* must find first free sequential filename */
675 snprintf(CS filename,2048,"%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr);
680 result = stat(CS filename,&mystat);
684 rfc822name = filename;
686 /* decode RFC822 attachment */
687 mime_decoded_filename = NULL;
689 mime_current_boundary = context ? context->boundary : NULL;
690 mime_decode(&rfc822name);
692 mime_current_boundary = NULL;
693 if (mime_decoded_filename == NULL) {
694 /* decoding failed */
695 log_write(0, LOG_MAIN,
696 "mime_regex acl condition warning - could not decode RFC822 MIME part to file.");
699 mime_decoded_filename = NULL;
703 /* If the boundary of this instance is NULL, we are finished here */
704 if (context == NULL) break;
706 if (context->context == MBC_COVERLETTER_ONESHOT)
707 context->context = MBC_ATTACHMENT;