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