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