Added DomainKeys support. See doc/experimental-spec.txt for documentation.
[exim.git] / src / src / mime.c
1 /* $Cambridge: exim/src/src/mime.c,v 1.5 2005/03/08 15:32:02 tom Exp $ */
2
3 /*************************************************
4 *     Exim - an Internet mail transport agent    *
5 *************************************************/
6
7 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2004 */
8 /* License: GPL */
9
10 #include "exim.h"
11 #ifdef WITH_CONTENT_SCAN
12 #include "mime.h"
13 #include <sys/stat.h>
14
15 FILE *mime_stream = NULL;
16 uschar *mime_current_boundary = NULL;
17
18 /*************************************************
19 * set MIME anomaly level + text                  *
20 *************************************************/
21
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. */
25
26 void mime_set_anomaly(int level, char *text) {
27   mime_anomaly_level = level;
28   mime_anomaly_text = US text;
29 }
30
31
32 /*************************************************
33 * decode quoted-printable chars                  *
34 *************************************************/
35
36 /* gets called when we hit a =
37    returns: new pointer position
38    result code in c:
39           -2 - decode error
40           -1 - soft line break, no char
41            0-255 - char to write
42 */
43
44 unsigned int mime_qp_hstr_i(uschar *cptr) {
45   unsigned int i, j = 0;
46   while (cptr && *cptr && isxdigit(*cptr)) {
47     i = *cptr++ - '0';
48     if (9 < i) i -= 7;
49     j <<= 4;
50     j |= (i & 0x0f);
51   }
52   return(j);
53 }
54
55 uschar *mime_decode_qp_char(uschar *qp_p,int *c) {
56   uschar hex[] = {0,0,0};
57   int nan = 0;
58   uschar *initial_pos = qp_p;
59
60   /* advance one char */
61   qp_p++;
62
63   REPEAT_FIRST:
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
68        encoding any more */
69     nan = 1;
70     qp_p++;
71     goto REPEAT_FIRST;
72   }
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 */
75     if (nan) {
76       /* this is illegal */
77       *c = -2;
78       return initial_pos;
79     }
80     else {
81       hex[0] = *qp_p;
82       qp_p++;
83     };
84   }
85   else if (*qp_p == '\n') {
86     /* hit soft line break already, continue */
87     *c = -1;
88     return qp_p;
89   }
90   else {
91     /* illegal char here */
92     *c = -2;
93     return initial_pos;
94   };
95
96   if ( (('0' <= *qp_p) && (*qp_p <= '9')) || (('A' <= *qp_p) && (*qp_p <= 'F')) || (('a' <= *qp_p) && (*qp_p <= 'f')) ) {
97     if (hex[0] > 0) {
98       hex[1] = *qp_p;
99       /* do hex conversion */
100       *c = mime_qp_hstr_i(hex);
101       qp_p++;
102       return qp_p;
103     }
104     else {
105       /* huh ? */
106       *c = -2;
107       return initial_pos;
108     };
109   }
110   else {
111     /* illegal char */
112     *c = -2;
113     return initial_pos;
114   };
115 }
116
117
118 uschar *mime_parse_line(uschar *buffer, uschar *data, uschar *encoding, int *num_decoded) {
119  
120   if (encoding == NULL) {
121     /* no encoding type at all */
122     NO_DECODING:
123     memcpy(data, buffer, Ustrlen(buffer));
124     data[(Ustrlen(buffer))] = 0;
125     *num_decoded = Ustrlen(data);
126     return data;
127   }
128   else if (Ustrcmp(encoding,"base64") == 0) {
129     uschar *p = buffer;
130     int offset = 0;
131
132     /* ----- BASE64 ---------------------------------------------------- */
133     /* NULL out '\r' and '\n' chars */
134     while (Ustrrchr(p,'\r') != NULL) {
135       *(Ustrrchr(p,'\r')) = '\0';
136     };
137     while (Ustrrchr(p,'\n') != NULL) {
138       *(Ustrrchr(p,'\n')) = '\0';
139     };
140
141     while (*(p+offset) != '\0') {
142       /* hit illegal char ? */
143       if (mime_b64[*(p+offset)] == 128) {
144         mime_set_anomaly(MIME_ANOMALY_BROKEN_BASE64);
145         offset++;
146       }
147       else {
148         *p = mime_b64[*(p+offset)];
149         p++;
150       };
151     };
152     *p = 255;
153
154     /* line is translated, start bit shifting */
155     p = buffer;
156     *num_decoded = 0;
157     while(*p != 255) {
158       uschar tmp_c;
159
160       /* byte 0 ---------------------- */
161       if (*(p+1) == 255) {
162         mime_set_anomaly(MIME_ANOMALY_BROKEN_BASE64);
163         break;
164       }
165       data[(*num_decoded)] = *p;
166       data[(*num_decoded)] <<= 2;
167       tmp_c = *(p+1);
168       tmp_c >>= 4;
169       data[(*num_decoded)] |= tmp_c;
170       (*num_decoded)++;
171       p++;
172       /* byte 1 ---------------------- */
173       if (*(p+1) == 255) {
174         mime_set_anomaly(MIME_ANOMALY_BROKEN_BASE64);
175         break;
176       }
177       data[(*num_decoded)] = *p;
178       data[(*num_decoded)] <<= 4;
179       tmp_c = *(p+1);
180       tmp_c >>= 2;
181       data[(*num_decoded)] |= tmp_c;
182       (*num_decoded)++;
183       p++;
184       /* byte 2 ---------------------- */
185       if (*(p+1) == 255) {
186         mime_set_anomaly(MIME_ANOMALY_BROKEN_BASE64);
187         break;
188       }
189       data[(*num_decoded)] = *p;
190       data[(*num_decoded)] <<= 6;
191       data[(*num_decoded)] |= *(p+1);
192       (*num_decoded)++;
193       p+=2;
194
195     };
196     return data;
197     /* ----------------------------------------------------------------- */
198   }
199   else if (Ustrcmp(encoding,"quoted-printable") == 0) {
200     uschar *p = buffer;
201
202     /* ----- QP -------------------------------------------------------- */
203     *num_decoded = 0;
204     while (*p != 0) {
205       if (*p == '=') {
206         int decode_qp_result;
207
208         p = mime_decode_qp_char(p,&decode_qp_result);
209
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)] = '=';
214           (*num_decoded)++;
215           p++;
216         }
217         else if (decode_qp_result == -1) {
218           break;
219         }
220         else if (decode_qp_result >= 0) {
221           data[(*num_decoded)] = decode_qp_result;
222           (*num_decoded)++;
223         };
224       }
225       else {
226         data[(*num_decoded)] = *p;
227         (*num_decoded)++;
228         p++;
229       };
230     };
231     return data;
232     /* ----------------------------------------------------------------- */
233   }
234   /* unknown encoding type, just dump as-is */
235   else goto NO_DECODING;
236 }
237
238
239 FILE *mime_get_decode_file(uschar *pname, uschar *fname) {
240   FILE *f = NULL;
241   uschar *filename;
242
243   filename = (uschar *)malloc(2048);
244
245   if ((pname != NULL) && (fname != NULL)) {
246     snprintf(CS filename, 2048, "%s/%s", pname, fname);
247     f = fopen(CS filename,"w+");
248   }
249   else if (pname == NULL) {
250     f = fopen(CS fname,"w+");
251   }
252   else if (fname == NULL) {
253     int file_nr = 0;
254     int result = 0;
255
256     /* must find first free sequential filename */
257     do {
258       struct stat mystat;
259       snprintf(CS filename,2048,"%s/%s-%05u", pname, message_id, file_nr);
260       file_nr++;
261       /* security break */
262       if (file_nr >= 1024)
263         break;
264       result = stat(CS filename,&mystat);
265     }
266     while(result != -1);
267     f = fopen(CS filename,"w+");
268   };
269
270   /* set expansion variable */
271   mime_decoded_filename = filename;
272
273   return f;
274 }
275
276
277 int mime_decode(uschar **listptr) {
278   int sep = 0;
279   uschar *list = *listptr;
280   uschar *option;
281   uschar option_buffer[1024];
282   uschar decode_path[1024];
283   FILE *decode_file = NULL;
284   uschar *buffer = NULL;
285   uschar *decode_buffer = NULL;
286   long f_pos = 0;
287   unsigned int size_counter = 0;
288
289   if (mime_stream == NULL)
290     return FAIL;
291
292   f_pos = ftell(mime_stream);
293
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);
296
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);
302     return DEFER;
303   };
304
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);
309     return DEFER;
310   };
311
312   /* try to find 1st option */
313   if ((option = string_nextinlist(&list, &sep,
314                                   option_buffer,
315                                   sizeof(option_buffer))) != NULL) {
316
317     /* parse 1st option */
318     if ( (Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0) ) {
319       /* explicitly no decoding */
320       return FAIL;
321     };
322
323     if (Ustrcmp(option,"default") == 0) {
324       /* explicit default path + file names */
325       goto DEFAULT_PATH;
326     };
327
328     if (option[0] == '/') {
329       struct stat statbuf;
330
331       memset(&statbuf,0,sizeof(statbuf));
332
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);
337       else
338         /* does not exist or is a file, use as full file name */
339         decode_file = mime_get_decode_file(NULL, option);
340     }
341     else
342       /* assume file name only, use default path */
343       decode_file = mime_get_decode_file(decode_path, option);
344   }
345   else
346     /* no option? patch default path */
347     DEFAULT_PATH: decode_file = mime_get_decode_file(decode_path, NULL);
348
349   if (decode_file == NULL)
350     return DEFER;
351
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;
357
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)
362           break;
363       };
364     };
365
366     decoded_line = mime_parse_line(buffer, decode_buffer, mime_content_transfer_encoding, &decoded_line_length);
367
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);
373       return DEFER;
374     };
375     size_counter += decoded_line_length;
376
377     if (size_counter > 1023) {
378       if ((mime_content_size + (size_counter / 1024)) < 65535)
379         mime_content_size += (size_counter / 1024);
380       else
381         mime_content_size = 65535;
382       size_counter = (size_counter % 1024);
383     };
384
385   }
386
387   fclose(decode_file);
388
389   clearerr(mime_stream);
390   fseek(mime_stream,f_pos,SEEK_SET);
391
392   /* round up remaining size bytes to one k */
393   if (size_counter) {
394     mime_content_size++;
395   };
396
397   return OK;
398 }
399
400 int mime_get_header(FILE *f, uschar *header) {
401   int c = EOF;
402   int done = 0;
403   int header_value_mode = 0;
404   int header_open_brackets = 0;
405   int num_copied = 0;
406
407   while(!done) {
408
409     c = fgetc(f);
410     if (c == EOF) break;
411
412     /* always skip CRs */
413     if (c == '\r') continue;
414
415     if (c == '\n') {
416       if (num_copied > 0) {
417         /* look if next char is '\t' or ' ' */
418         c = fgetc(f);
419         if (c == EOF) break;
420         if ( (c == '\t') || (c == ' ') ) continue;
421         ungetc(c,f);
422       };
423       /* end of the header, terminate with ';' */
424       c = ';';
425       done = 1;
426     };
427
428     /* skip control characters */
429     if (c < 32) continue;
430
431     if (header_value_mode) {
432       /* --------- value mode ----------- */
433       /* skip leading whitespace */
434       if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
435         continue;
436
437       /* we have hit a non-whitespace char, start copying value data */
438       header_value_mode = 2;
439
440       /* skip quotes */
441       if (c == '"') continue;
442
443       /* leave value mode on ';' */
444       if (c == ';') {
445         header_value_mode = 0;
446       };
447       /* -------------------------------- */
448     }
449     else {
450       /* -------- non-value mode -------- */
451       /* skip whitespace + tabs */
452       if ( (c == ' ') || (c == '\t') )
453         continue;
454       if (c == '\\') {
455         /* quote next char. can be used
456         to escape brackets. */
457         c = fgetc(f);
458         if (c == EOF) break;
459       }
460       else if (c == '(') {
461         header_open_brackets++;
462         continue;
463       }
464       else if ((c == ')') && header_open_brackets) {
465         header_open_brackets--;
466         continue;
467       }
468       else if ( (c == '=') && !header_open_brackets ) {
469         /* enter value mode */
470         header_value_mode = 1;
471       };
472
473       /* skip chars while we are in a comment */
474       if (header_open_brackets > 0)
475         continue;
476       /* -------------------------------- */
477     };
478
479     /* copy the char to the buffer */
480     header[num_copied] = (uschar)c;
481     /* raise counter */
482     num_copied++;
483
484     /* break if header buffer is full */
485     if (num_copied > MIME_MAX_HEADER_SIZE-1) {
486       done = 1;
487     };
488   };
489
490   if (header[num_copied-1] != ';') {
491     header[num_copied-1] = ';';
492   };
493
494   /* 0-terminate */
495   header[num_copied] = '\0';
496
497   /* return 0 for EOF or empty line */
498   if ((c == EOF) || (num_copied == 1))
499     return 0;
500   else
501     return 1;
502 }
503
504
505 int mime_acl_check(FILE *f, struct mime_boundary_context *context, uschar
506                    **user_msgptr, uschar **log_msgptr) {
507   int rc = OK;
508   uschar *header = NULL;
509   struct mime_boundary_context nested_context;
510
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);
516     return DEFER;
517   };
518
519   /* Not actually used at the moment, but will be vital to fixing
520    * some RFC 2046 nonconformance later... */
521   nested_context.parent = context;
522
523   /* loop through parts */
524   while(1) {
525
526     /* reset all per-part mime variables */
527     mime_anomaly_level     = 0;
528     mime_anomaly_text      = NULL;
529     mime_boundary          = NULL;
530     mime_charset           = 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;
540
541     /*
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
545     block.
546     */
547
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.
551      *
552      * (I have moved partway towards adding support, however, by adding
553      * a "parent" field to my new boundary-context structure.)
554      */
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) {
560             /* found boundary */
561             if (Ustrncmp((header+2+Ustrlen(context->boundary)),"--",2) == 0) {
562               /* END boundary found */
563               debug_printf("End boundary found %s\n", context->boundary);
564               return rc;
565             }
566             else {
567               debug_printf("Next part with boundary %s\n", context->boundary);
568             };
569             /* can't use break here */
570             goto DECODE_HEADERS;
571           }
572         };
573       }
574       /* Hit EOF or read error. Ugh. */
575       debug_printf("Hit EOF ...\n");
576       return rc;
577     };
578
579     DECODE_HEADERS:
580     /* parse headers, set up expansion variables */
581     while(mime_get_header(f,header)) {
582       int i;
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;
587
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 */
593           while(*p != ';') {
594             *p = tolower(*p);
595             p++;
596           };
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;
604
605           /* make p point to the next character after the closing ';' */
606           p += (header_value_len+1);
607
608           /* grab all param=value tags on the remaining line, check if they are interesting */
609           NEXT_PARAM_SEARCH: while (*p != 0) {
610             int j;
611             for (j = 0; j < mime_parameter_list_size; j++) {
612               uschar *param_value = NULL;
613               int param_value_len = 0;
614
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, &param_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;
630               };
631             }
632             /* There is something, but not one of our interesting parameters.
633                Advance to the next semicolon */
634             while(*p != ';') p++;
635             p++;
636           };
637         };
638       };
639     };
640
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;
645
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;
650
651     /* raise global counter */
652     mime_part_count++;
653
654     /* copy current file handle to global variable */
655     mime_stream = f;
656     mime_current_boundary = context ? context->boundary : 0;
657
658     /* Note the context */
659     mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
660
661     /* call ACL handling function */
662     rc = acl_check(ACL_WHERE_MIME, NULL, acl_smtp_mime, user_msgptr, log_msgptr);
663
664     mime_stream = NULL;
665     mime_current_boundary = NULL;
666
667     if (rc != OK) break;
668
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);
674
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;
680       else
681         nested_context.context = MBC_COVERLETTER_ONESHOT;
682
683       rc = mime_acl_check(f, &nested_context, user_msgptr, log_msgptr);
684       if (rc != OK) break;
685     }
686     else if ( (mime_content_type != NULL) &&
687             (Ustrncmp(mime_content_type,"message/rfc822",14) == 0) ) {
688       uschar *rfc822name = NULL;
689       uschar filename[2048];
690       int file_nr = 0;
691       int result = 0;
692
693       /* must find first free sequential filename */
694       do {
695         struct stat mystat;
696         snprintf(CS filename,2048,"%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr);
697         file_nr++;
698         /* security break */
699         if (file_nr >= 128)
700           goto NO_RFC822;
701         result = stat(CS filename,&mystat);
702       }
703       while(result != -1);
704
705       rfc822name = filename;
706
707       /* decode RFC822 attachment */
708       mime_decoded_filename = NULL;
709       mime_stream = f;
710       mime_current_boundary = context ? context->boundary : NULL;
711       mime_decode(&rfc822name);
712       mime_stream = NULL;
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.");
718         return DEFER;
719       };
720       mime_decoded_filename = NULL;
721     };
722
723     NO_RFC822:
724     /* If the boundary of this instance is NULL, we are finished here */
725     if (context == NULL) break;
726
727     if (context->context == MBC_COVERLETTER_ONESHOT)
728       context->context = MBC_ATTACHMENT;
729
730   };
731
732   return rc;
733 }
734
735 #endif