ac0126d1864b51624d543848c31920948b7af072
[users/jgh/exim.git] / src / src / mime.c
1 /* $Cambridge: exim/src/src/mime.c,v 1.1.2.3 2004/11/30 15:18:58 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 /*************************************************
20 * decode quoted-printable chars                  *
21 *************************************************/
22
23 /* gets called when we hit a =
24    returns: new pointer position
25    result code in c:
26           -2 - decode error
27           -1 - soft line break, no char
28            0-255 - char to write
29 */
30
31 unsigned int mime_qp_hstr_i(uschar *cptr) {
32   unsigned int i, j = 0;
33   while (cptr && *cptr && isxdigit(*cptr)) {
34     i = *cptr++ - '0';
35     if (9 < i) i -= 7;
36     j <<= 4;
37     j |= (i & 0x0f);
38   }
39   return(j);
40 }
41
42 uschar *mime_decode_qp_char(uschar *qp_p,int *c) {
43   uschar hex[] = {0,0,0};
44   int nan = 0;
45   uschar *initial_pos = qp_p;
46   
47   /* advance one char */
48   qp_p++;
49   
50   REPEAT_FIRST:
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
55        encoding any more */
56     nan = 1;
57     qp_p++;
58     goto REPEAT_FIRST;
59   }
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 */
62     if (nan) {
63       /* this is illegal */
64       *c = -2;
65       return initial_pos;
66     }
67     else {
68       hex[0] = *qp_p;
69       qp_p++;
70     };
71   }
72   else if (*qp_p == '\n') {    
73     /* hit soft line break already, continue */
74     *c = -1;
75     return qp_p;
76   }
77   else {
78     /* illegal char here */
79     *c = -2;
80     return initial_pos;
81   };
82   
83   if ( (('0' <= *qp_p) && (*qp_p <= '9')) || (('A' <= *qp_p) && (*qp_p <= 'F')) || (('a' <= *qp_p) && (*qp_p <= 'f')) ) {
84     if (hex[0] > 0) {
85       hex[1] = *qp_p;
86       /* do hex conversion */
87       *c = mime_qp_hstr_i(hex);
88       qp_p++;
89       return qp_p;
90     }
91     else {
92       /* huh ? */
93       *c = -2;
94       return initial_pos;  
95     };
96   }
97   else {
98     /* illegal char */
99     *c = -2;
100     return initial_pos;  
101   };
102 }
103
104
105 uschar *mime_parse_line(uschar *buffer, uschar *encoding, int *num_decoded) {
106   uschar *data = NULL;
107
108   data = (uschar *)malloc(Ustrlen(buffer)+2);
109
110   if (encoding == NULL) {
111     /* no encoding type at all */
112     NO_DECODING:
113     memcpy(data, buffer, Ustrlen(buffer));
114     data[(Ustrlen(buffer))] = 0;
115     *num_decoded = Ustrlen(data);
116     return data;
117   }
118   else if (Ustrcmp(encoding,"base64") == 0) {
119     uschar *p = buffer;
120     int offset = 0;
121     
122     /* ----- BASE64 ---------------------------------------------------- */
123     /* NULL out '\r' and '\n' chars */
124     while (Ustrrchr(p,'\r') != NULL) {
125       *(Ustrrchr(p,'\r')) = '\0';
126     };
127     while (Ustrrchr(p,'\n') != NULL) {
128       *(Ustrrchr(p,'\n')) = '\0';
129     };
130
131     while (*(p+offset) != '\0') {
132       /* hit illegal char ? */
133       if (mime_b64[*(p+offset)] == 128) {
134         offset++;
135       }
136       else {
137         *p = mime_b64[*(p+offset)];
138         p++;
139       };
140     };
141     *p = 255;
142    
143     /* line is translated, start bit shifting */
144     p = buffer;
145     *num_decoded = 0;  
146     while(*p != 255) {
147       uschar tmp_c;
148       
149       /* byte 0 ---------------------- */
150       if (*(p+1) == 255) {
151         break;
152       }
153       data[(*num_decoded)] = *p;
154       data[(*num_decoded)] <<= 2;
155       tmp_c = *(p+1);
156       tmp_c >>= 4;
157       data[(*num_decoded)] |= tmp_c;
158       (*num_decoded)++;
159       p++;
160       /* byte 1 ---------------------- */
161       if (*(p+1) == 255) {
162         break;
163       }
164       data[(*num_decoded)] = *p;
165       data[(*num_decoded)] <<= 4;
166       tmp_c = *(p+1);
167       tmp_c >>= 2;
168       data[(*num_decoded)] |= tmp_c;
169       (*num_decoded)++;
170       p++;
171       /* byte 2 ---------------------- */
172       if (*(p+1) == 255) {
173         break;
174       }
175       data[(*num_decoded)] = *p;
176       data[(*num_decoded)] <<= 6;
177       data[(*num_decoded)] |= *(p+1); 
178       (*num_decoded)++;
179       p+=2;
180       
181     };
182     return data;
183     /* ----------------------------------------------------------------- */
184   }
185   else if (Ustrcmp(encoding,"quoted-printable") == 0) {
186     uschar *p = buffer;
187
188     /* ----- QP -------------------------------------------------------- */
189     *num_decoded = 0;
190     while (*p != 0) {
191       if (*p == '=') {
192         int decode_qp_result;
193         
194         p = mime_decode_qp_char(p,&decode_qp_result);
195               
196         if (decode_qp_result == -2) {
197           /* Error from decoder. p is unchanged. */
198           data[(*num_decoded)] = '=';
199           (*num_decoded)++;
200           p++;
201         }
202         else if (decode_qp_result == -1) {
203           break;
204         }
205         else if (decode_qp_result >= 0) {
206           data[(*num_decoded)] = decode_qp_result;
207           (*num_decoded)++;
208         };
209       }
210       else {
211         data[(*num_decoded)] = *p;
212         (*num_decoded)++;
213         p++;
214       };
215     };
216     return data;
217     /* ----------------------------------------------------------------- */
218   }
219   /* unknown encoding type, just dump as-is */
220   else goto NO_DECODING;
221 }
222
223
224 FILE *mime_get_decode_file(uschar *pname, uschar *fname) {
225   FILE *f;
226   uschar *filename;
227   
228   filename = (uschar *)malloc(2048);
229   
230   if ((pname != NULL) && (fname != NULL)) {
231     snprintf(CS filename, 2048, "%s/%s", pname, fname);
232     f = fopen(CS filename,"w+");
233   }
234   else if (pname == NULL) {
235     f = fopen(CS fname,"w+");
236   }
237   else if (fname == NULL) {
238     int file_nr = 0;
239     int result = 0;
240
241     /* must find first free sequential filename */
242     do {
243       struct stat mystat;
244       snprintf(CS filename,2048,"%s/%s-%05u", pname, message_id, file_nr);
245       file_nr++;
246       /* security break */
247       if (file_nr >= 1024)
248         break;
249       result = stat(CS filename,&mystat);
250     }
251     while(result != -1);
252     f = fopen(CS filename,"w+");
253   };
254   
255   /* set expansion variable */
256   mime_decoded_filename = filename;
257   
258   return f;
259 }
260
261
262 int mime_decode(uschar **listptr) {
263   int sep = 0;
264   uschar *list = *listptr;
265   uschar *option;
266   uschar option_buffer[1024];
267   uschar decode_path[1024];
268   FILE *decode_file = NULL;
269   uschar *buffer = NULL;
270   long f_pos = 0;
271   unsigned int size_counter = 0;
272
273   if (mime_stream == NULL)
274     return FAIL;
275   
276   f_pos = ftell(mime_stream);
277   
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);
280   
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);
286     return DEFER;
287   };
288   
289   /* try to find 1st option */
290   if ((option = string_nextinlist(&list, &sep,
291                                   option_buffer,
292                                   sizeof(option_buffer))) != NULL) {
293     
294     /* parse 1st option */
295     if ( (Ustrcmp(option,"false") == 0) || (Ustrcmp(option,"0") == 0) ) {
296       /* explicitly no decoding */
297       return FAIL;
298     };
299     
300     if (Ustrcmp(option,"default") == 0) {
301       /* explicit default path + file names */
302       goto DEFAULT_PATH;
303     };
304     
305     if (option[0] == '/') {
306       struct stat statbuf;
307
308       memset(&statbuf,0,sizeof(statbuf));
309       
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);
314       else
315         /* does not exist or is a file, use as full file name */
316         decode_file = mime_get_decode_file(NULL, option);
317     }
318     else
319       /* assume file name only, use default path */
320       decode_file = mime_get_decode_file(decode_path, option);
321   }
322   else
323     /* no option? patch default path */
324     DEFAULT_PATH: decode_file = mime_get_decode_file(decode_path, NULL);
325   
326   if (decode_file == NULL)
327     return DEFER;
328   
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;
334     
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)
339           break;
340       };
341     };
342   
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);
349       return DEFER;
350     };
351     size_counter += decoded_line_length;
352     
353     if (size_counter > 1023) { 
354       if ((mime_content_size + (size_counter / 1024)) < 65535)
355         mime_content_size += (size_counter / 1024);
356       else 
357         mime_content_size = 65535;
358       size_counter = (size_counter % 1024);
359     };
360     
361     free(decoded_line);
362   }
363   
364   fclose(decode_file);
365   
366   clearerr(mime_stream);
367   fseek(mime_stream,f_pos,SEEK_SET);
368   
369   /* round up remaining size bytes to one k */
370   if (size_counter) {
371     mime_content_size++;
372   };
373   
374   return OK;
375 }
376
377 int mime_get_header(FILE *f, uschar *header) {
378   int c = EOF;
379   int done = 0;
380   int header_value_mode = 0;
381   int header_open_brackets = 0;
382   int num_copied = 0;
383   
384   while(!done) {
385     
386     c = fgetc(f);
387     if (c == EOF) break;
388    
389     /* always skip CRs */
390     if (c == '\r') continue;
391     
392     if (c == '\n') {
393       if (num_copied > 0) {
394         /* look if next char is '\t' or ' ' */
395         c = fgetc(f);
396         if (c == EOF) break;
397         if ( (c == '\t') || (c == ' ') ) continue;
398         ungetc(c,f);
399       };
400       /* end of the header, terminate with ';' */
401       c = ';';
402       done = 1;
403     };
404   
405     /* skip control characters */
406     if (c < 32) continue;
407
408     if (header_value_mode) {
409       /* --------- value mode ----------- */
410       /* skip leading whitespace */
411       if ( ((c == '\t') || (c == ' ')) && (header_value_mode == 1) )
412         continue;
413       
414       /* we have hit a non-whitespace char, start copying value data */
415       header_value_mode = 2;
416       
417       /* skip quotes */
418       if (c == '"') continue;
419       
420       /* leave value mode on ';' */
421       if (c == ';') {
422         header_value_mode = 0;
423       };
424       /* -------------------------------- */
425     }
426     else {
427       /* -------- non-value mode -------- */
428       /* skip whitespace + tabs */
429       if ( (c == ' ') || (c == '\t') )
430         continue;
431       if (c == '\\') {
432         /* quote next char. can be used
433         to escape brackets. */
434         c = fgetc(f);
435         if (c == EOF) break;
436       }
437       else if (c == '(') {
438         header_open_brackets++;
439         continue;
440       }
441       else if ((c == ')') && header_open_brackets) {
442         header_open_brackets--;
443         continue;
444       }
445       else if ( (c == '=') && !header_open_brackets ) {
446         /* enter value mode */
447         header_value_mode = 1;
448       };
449       
450       /* skip chars while we are in a comment */
451       if (header_open_brackets > 0)
452         continue;
453       /* -------------------------------- */
454     };
455     
456     /* copy the char to the buffer */
457     header[num_copied] = (uschar)c;
458     /* raise counter */
459     num_copied++;
460     
461     /* break if header buffer is full */
462     if (num_copied > MIME_MAX_HEADER_SIZE-1) {
463       done = 1;
464     };
465   };
466
467   if (header[num_copied-1] != ';') {
468     header[num_copied-1] = ';';
469   };
470
471   /* 0-terminate */
472   header[num_copied] = '\0';
473   
474   /* return 0 for EOF or empty line */
475   if ((c == EOF) || (num_copied == 1))
476     return 0;
477   else
478     return 1;
479 }
480
481
482 int mime_acl_check(FILE *f, struct mime_boundary_context *context, uschar 
483                    **user_msgptr, uschar **log_msgptr) {
484   int rc = OK;
485   uschar *header = NULL;
486   struct mime_boundary_context nested_context;
487
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);
493     return DEFER;
494   };
495
496   /* Not actually used at the moment, but will be vital to fixing
497    * some RFC 2046 nonconformance later... */
498   nested_context.parent = context;
499
500   /* loop through parts */
501   while(1) {
502   
503     /* reset all per-part mime variables */
504     mime_anomaly_level     = NULL;
505     mime_anomaly_text      = NULL;
506     mime_boundary          = NULL;
507     mime_charset           = 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;
517   
518     /*
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
522     block.
523     */
524     
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.
528      *
529      * (I have moved partway towards adding support, however, by adding 
530      * a "parent" field to my new boundary-context structure.)
531      */
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) {
537             /* found boundary */
538             if (Ustrncmp((header+2+Ustrlen(context->boundary)),"--",2) == 0) {
539               /* END boundary found */
540               debug_printf("End boundary found %s\n", context->boundary);
541               return rc;
542             }
543             else {
544               debug_printf("Next part with boundary %s\n", context->boundary);
545             };
546             /* can't use break here */
547             goto DECODE_HEADERS;
548           }
549         };
550       }
551       /* Hit EOF or read error. Ugh. */
552       debug_printf("Hit EOF ...\n");
553       return rc;
554     };
555   
556     DECODE_HEADERS:
557     /* parse headers, set up expansion variables */
558     while(mime_get_header(f,header)) {
559       int i;
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;
564         
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 */
570           while(*p != ';') {
571             *p = tolower(*p);
572             p++;
573           };
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;
581           
582           /* make p point to the next character after the closing ';' */
583           p += (header_value_len+1);
584           
585           /* grab all param=value tags on the remaining line, check if they are interesting */
586           NEXT_PARAM_SEARCH: while (*p != 0) {
587             int j;
588             for (j = 0; j < mime_parameter_list_size; j++) {
589               uschar *param_value = NULL;
590               int param_value_len = 0;
591               
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, &param_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;
607               };
608             }
609             /* There is something, but not one of our interesting parameters.
610                Advance to the next semicolon */
611             while(*p != ';') p++;
612             p++;
613           };
614         };
615       };
616     };
617     
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;
622     
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;
627     
628     /* raise global counter */
629     mime_part_count++;
630     
631     /* copy current file handle to global variable */
632     mime_stream = f;
633     mime_current_boundary = context ? context->boundary : 0;
634
635     /* Note the context */
636     mime_is_coverletter = !(context && context->context == MBC_ATTACHMENT);
637     
638     /* call ACL handling function */
639     rc = acl_check(ACL_WHERE_MIME, NULL, acl_smtp_mime, user_msgptr, log_msgptr);
640     
641     mime_stream = NULL;
642     mime_current_boundary = NULL;
643     
644     if (rc != OK) break;
645     
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);
651
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;
657       else
658         nested_context.context = MBC_COVERLETTER_ONESHOT;
659
660       rc = mime_acl_check(f, &nested_context, user_msgptr, log_msgptr);
661       if (rc != OK) break;
662     }
663     else if ( (mime_content_type != NULL) &&
664             (Ustrncmp(mime_content_type,"message/rfc822",14) == 0) ) {
665       uschar *rfc822name = NULL;
666       uschar filename[2048];
667       int file_nr = 0;
668       int result = 0;
669       
670       /* must find first free sequential filename */
671       do {
672         struct stat mystat;
673         snprintf(CS filename,2048,"%s/scan/%s/__rfc822_%05u", spool_directory, message_id, file_nr);
674         file_nr++;
675         /* security break */
676         if (file_nr >= 128)
677           goto NO_RFC822;
678         result = stat(CS filename,&mystat);
679       }
680       while(result != -1);
681       
682       rfc822name = filename;
683       
684       /* decode RFC822 attachment */
685       mime_decoded_filename = NULL;
686       mime_stream = f;
687       mime_current_boundary = context ? context->boundary : NULL;
688       mime_decode(&rfc822name);
689       mime_stream = NULL;
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.");
695         return DEFER;
696       };
697       mime_decoded_filename = NULL;
698     };
699     
700     NO_RFC822:
701     /* If the boundary of this instance is NULL, we are finished here */
702     if (context == NULL) break;
703
704     if (context->context == MBC_COVERLETTER_ONESHOT)
705       context->context = MBC_ATTACHMENT;
706   
707   };
708
709   return rc;
710 }
711
712 #endif