Moved to new module init structure.
[citadel.git] / citadel / mime_parser.c
1 /*
2  * $Id$
3  *
4  * This is the MIME parser for Citadel.
5  *
6  * Copyright (c) 1998-2006 by Art Cancro
7  * This code is distributed under the GNU General Public License v2.
8  *
9  */
10
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <stdio.h>
14 #include <signal.h>
15 #include <sys/types.h>
16 #include <ctype.h>
17 #include <string.h>
18 #include <sys/stat.h>
19 #include <errno.h>
20
21 #include "citadel.h"
22 #include "server.h"
23 #include "sysdep_decls.h"
24 #include "tools.h"
25
26 #include "mime_parser.h"
27
28
29 void extract_key(char *target, char *source, char *key)
30 {
31         int a, b;
32
33         strcpy(target, source);
34         for (a = 0; a < strlen(target); ++a) {
35                 if ((!strncasecmp(&target[a], key, strlen(key)))
36                     && (target[a + strlen(key)] == '=')) {
37                         strcpy(target, &target[a + strlen(key) + 1]);
38                         if (target[0] == 34)
39                                 strcpy(target, &target[1]);
40                         for (b = 0; b < strlen(target); ++b)
41                                 if (target[b] == 34)
42                                         target[b] = 0;
43                         return;
44                 }
45         }
46         strcpy(target, "");
47 }
48
49
50 /*
51  * For non-multipart messages, we need to generate a quickie partnum of "1"
52  * to return to callback functions.  Some callbacks demand it.
53  */
54 char *fixed_partnum(char *supplied_partnum) {
55         if (supplied_partnum == NULL) return "1";
56         if (strlen(supplied_partnum)==0) return "1";
57         return supplied_partnum;
58 }
59
60
61
62 /*
63  * Convert "quoted-printable" to binary.  Returns number of bytes decoded.
64  * according to RFC2045 section 6.7
65  */
66 int CtdlDecodeQuotedPrintable(char *decoded, char *encoded, int sourcelen) {
67         unsigned int ch;
68         int decoded_length = 0;
69         int pos = 0;
70
71         while (pos < sourcelen)
72         {
73                 if (!strncmp(&encoded[pos], "=\r\n", 3))
74                 {
75                         pos += 3;
76                 }
77                 else if (!strncmp(&encoded[pos], "=\n", 2))
78                 {
79                         pos += 2;
80                 }
81                 else if (encoded[pos] == '=')
82                 {
83                         ch = 0;
84                         sscanf(&encoded[pos+1], "%02x", &ch);
85                         pos += 3;
86                         decoded[decoded_length++] = ch;
87                 }
88                 else
89                 {
90                         decoded[decoded_length++] = encoded[pos];
91                         pos += 1;
92                 }
93         }
94         decoded[decoded_length] = 0;
95         return(decoded_length);
96 }
97
98
99 /*
100  * Given a message or message-part body and a length, handle any necessary
101  * decoding and pass the request up the stack.
102  */
103 void mime_decode(char *partnum,
104                  char *part_start, size_t length,
105                  char *content_type, char *charset, char *encoding,
106                  char *disposition,
107                  char *name, char *filename,
108                  void (*CallBack)
109                   (char *cbname,
110                    char *cbfilename,
111                    char *cbpartnum,
112                    char *cbdisp,
113                    void *cbcontent,
114                    char *cbtype,
115                    char *cbcharset,
116                    size_t cblength,
117                    char *cbencoding,
118                    void *cbuserdata),
119                  void (*PreMultiPartCallBack)
120                   (char *cbname,
121                    char *cbfilename,
122                    char *cbpartnum,
123                    char *cbdisp,
124                    void *cbcontent,
125                    char *cbtype,
126                    char *cbcharset,
127                    size_t cblength,
128                    char *cbencoding,
129                    void *cbuserdata),
130                  void (*PostMultiPartCallBack)
131                   (char *cbname,
132                    char *cbfilename,
133                    char *cbpartnum,
134                    char *cbdisp,
135                    void *cbcontent,
136                    char *cbtype,
137                    char *cbcharset,
138                    size_t cblength,
139                    char *cbencoding,
140                    void *cbuserdata),
141                   void *userdata,
142                   int dont_decode
143 )
144 {
145
146         char *decoded;
147         size_t bytes_decoded = 0;
148
149         /* Some encodings aren't really encodings */
150         if (!strcasecmp(encoding, "7bit"))
151                 strcpy(encoding, "");
152         if (!strcasecmp(encoding, "8bit"))
153                 strcpy(encoding, "");
154         if (!strcasecmp(encoding, "binary"))
155                 strcpy(encoding, "");
156
157         /* If this part is not encoded, send as-is */
158         if ( (strlen(encoding) == 0) || (dont_decode)) {
159                 if (CallBack != NULL) {
160                         CallBack(name, filename, fixed_partnum(partnum),
161                                 disposition, part_start,
162                                 content_type, charset, length, encoding, userdata);
163                         }
164                 return;
165         }
166         
167         /* Fail silently if we hit an unknown encoding. */
168         if ((strcasecmp(encoding, "base64"))
169             && (strcasecmp(encoding, "quoted-printable"))) {
170                 return;
171         }
172
173         /*
174          * Allocate a buffer for the decoded data.  The output buffer is slightly
175          * larger than the input buffer; this assumes that the decoded data
176          * will never be significantly larger than the encoded data.  This is a
177          * safe assumption with base64, uuencode, and quoted-printable.
178          */
179         decoded = malloc(length + 32768);
180         if (decoded == NULL) {
181                 return;
182         }
183
184         if (!strcasecmp(encoding, "base64")) {
185                 bytes_decoded = CtdlDecodeBase64(decoded, part_start, length);
186         }
187         else if (!strcasecmp(encoding, "quoted-printable")) {
188                 bytes_decoded = CtdlDecodeQuotedPrintable(decoded, part_start, length);
189         }
190
191         if (bytes_decoded > 0) if (CallBack != NULL) {
192                 CallBack(name, filename, fixed_partnum(partnum),
193                         disposition, decoded,
194                         content_type, charset, bytes_decoded, "binary", userdata);
195         }
196
197         free(decoded);
198 }
199
200 /*
201  * Break out the components of a multipart message
202  * (This function expects to be fed HEADERS + CONTENT)
203  * Note: NULL can be supplied as content_end; in this case, the message is
204  * considered to have ended when the parser encounters a 0x00 byte.
205  */
206 void the_mime_parser(char *partnum,
207                      char *content_start, char *content_end,
208                      void (*CallBack)
209                       (char *cbname,
210                        char *cbfilename,
211                        char *cbpartnum,
212                        char *cbdisp,
213                        void *cbcontent,
214                        char *cbtype,
215                        char *cbcharset,
216                        size_t cblength,
217                        char *cbencoding,
218                        void *cbuserdata),
219                      void (*PreMultiPartCallBack)
220                       (char *cbname,
221                        char *cbfilename,
222                        char *cbpartnum,
223                        char *cbdisp,
224                        void *cbcontent,
225                        char *cbtype,
226                        char *cbcharset,
227                        size_t cblength,
228                        char *cbencoding,
229                        void *cbuserdata),
230                      void (*PostMultiPartCallBack)
231                       (char *cbname,
232                        char *cbfilename,
233                        char *cbpartnum,
234                        char *cbdisp,
235                        void *cbcontent,
236                        char *cbtype,
237                        char *cbcharset,
238                        size_t cblength,
239                        char *cbencoding,
240                        void *cbuserdata),
241                       void *userdata,
242                       int dont_decode
243 )
244 {
245
246         char *ptr;
247         char *srch = NULL;
248         char *part_start, *part_end = NULL;
249         char buf[SIZ];
250         char *header;
251         char *boundary;
252         char *startary;
253         size_t startary_len = 0;
254         char *endary;
255         char *next_boundary;
256         char *content_type;
257         char *charset;
258         size_t content_length;
259         char *encoding;
260         char *disposition;
261         char *name = NULL;
262         char *content_type_name;
263         char *content_disposition_name;
264         char *filename;
265         int is_multipart;
266         int part_seq = 0;
267         int i;
268         size_t length;
269         char nested_partnum[256];
270         int crlf_in_use = 0;
271         char *evaluate_crlf_ptr = NULL;
272
273         ptr = content_start;
274         content_length = 0;
275
276         boundary = malloc(SIZ);
277         memset(boundary, 0, SIZ);
278
279         startary = malloc(SIZ);
280         memset(startary, 0, SIZ);
281
282         endary = malloc(SIZ);
283         memset(endary, 0, SIZ);
284
285         header = malloc(SIZ);
286         memset(header, 0, SIZ);
287
288         content_type = malloc(SIZ);
289         memset(content_type, 0, SIZ);
290
291         charset = malloc(SIZ);
292         memset(charset, 0, SIZ);
293
294         encoding = malloc(SIZ);
295         memset(encoding, 0, SIZ);
296
297         content_type_name = malloc(SIZ);
298         memset(content_type_name, 0, SIZ);
299
300         content_disposition_name = malloc(SIZ);
301         memset(content_disposition_name, 0, SIZ);
302
303         filename = malloc(SIZ);
304         memset(filename, 0, SIZ);
305
306         disposition = malloc(SIZ);
307         memset(disposition, 0, SIZ);
308
309         /* If the caller didn't supply an endpointer, generate one by measure */
310         if (content_end == NULL) {
311                 content_end = &content_start[strlen(content_start)];
312         }
313
314         /* Learn interesting things from the headers */
315         strcpy(header, "");
316         do {
317                 ptr = memreadline(ptr, buf, SIZ);
318                 if (ptr >= content_end) {
319                         goto end_parser;
320                 }
321
322                 for (i = 0; i < strlen(buf); ++i) {
323                         if (isspace(buf[i])) {
324                                 buf[i] = ' ';
325                         }
326                 }
327
328                 if (!isspace(buf[0])) {
329                         if (!strncasecmp(header, "Content-type:", 13)) {
330                                 strcpy(content_type, &header[13]);
331                                 striplt(content_type);
332                                 extract_key(content_type_name, content_type, "name");
333                                 extract_key(charset, content_type, "charset");
334                                 /* Deal with weird headers */
335                                 if (strchr(content_type, ' '))
336                                         *(strchr(content_type, ' ')) = '\0';
337                                 if (strchr(content_type, ';'))
338                                         *(strchr(content_type, ';')) = '\0';
339                         }
340                         if (!strncasecmp(header, "Content-Disposition:", 20)) {
341                                 strcpy(disposition, &header[20]);
342                                 striplt(disposition);
343                                 extract_key(content_disposition_name, disposition, "name");
344                                 extract_key(filename, disposition, "filename");
345                         }
346                         if (!strncasecmp(header, "Content-length: ", 15)) {
347                                 char clbuf[10];
348                                 safestrncpy(clbuf, &header[15], sizeof clbuf);
349                                 striplt(clbuf);
350                                 content_length = (size_t) atol(clbuf);
351                         }
352                         if (!strncasecmp(header, "Content-transfer-encoding: ", 26)) {
353                                 strcpy(encoding, &header[26]);
354                                 striplt(encoding);
355                         }
356                         if (strlen(boundary) == 0)
357                                 extract_key(boundary, header, "boundary");
358                         strcpy(header, "");
359                 }
360                 if ((strlen(header) + strlen(buf) + 2) < SIZ) {
361                         strcat(header, buf);
362                 }
363         } while ((strlen(buf) > 0) && (*ptr != 0));
364
365         if (strchr(disposition, ';'))
366                 *(strchr(disposition, ';')) = '\0';
367         striplt(disposition);
368         if (strchr(content_type, ';'))
369                 *(strchr(content_type, ';')) = '\0';
370         striplt(content_type);
371
372         if (strlen(boundary) > 0) {
373                 is_multipart = 1;
374         } else {
375                 is_multipart = 0;
376         }
377
378         /* If this is a multipart message, then recursively process it */
379         part_start = NULL;
380         if (is_multipart) {
381
382                 /* Tell the client about this message's multipartedness */
383                 if (PreMultiPartCallBack != NULL) {
384                         PreMultiPartCallBack("", "", partnum, "",
385                                 NULL, content_type, charset,
386                                 0, encoding, userdata);
387                 }
388
389                 /* Figure out where the boundaries are */
390                 snprintf(startary, SIZ, "--%s", boundary);
391                 snprintf(endary, SIZ, "--%s--", boundary);
392                 startary_len = strlen(startary);
393
394                 part_start = NULL;
395                 do {
396                         next_boundary = NULL;
397                         for (srch=ptr; srch<content_end; ++srch) {
398                                 if (!memcmp(srch, startary, startary_len)) {
399                                         next_boundary = srch;
400                                         srch = content_end;
401                                 }
402                         }
403
404                         if ( (part_start != NULL) && (next_boundary != NULL) ) {
405                                 part_end = next_boundary;
406                                 --part_end;             /* omit the trailing LF */
407                                 if (crlf_in_use) {
408                                         --part_end;     /* omit the trailing CR */
409                                 }
410
411                                 if (strlen(partnum) > 0) {
412                                         snprintf(nested_partnum,
413                                                  sizeof nested_partnum,
414                                                  "%s.%d", partnum,
415                                                  ++part_seq);
416                                 }
417                                 else {
418                                         snprintf(nested_partnum,
419                                                  sizeof nested_partnum,
420                                                  "%d", ++part_seq);
421                                 }
422                                 the_mime_parser(nested_partnum,
423                                             part_start, part_end,
424                                                 CallBack,
425                                                 PreMultiPartCallBack,
426                                                 PostMultiPartCallBack,
427                                                 userdata,
428                                                 dont_decode);
429                         }
430
431                         if (next_boundary != NULL) {
432                                 /* If we pass out of scope, don't attempt to
433                                  * read past the end boundary. */
434                                 if (!strcmp(next_boundary, endary)) {
435                                         ptr = content_end;
436                                 }
437                                 else {
438                                         /* Set up for the next part. */
439                                         part_start = strstr(next_boundary, "\n");
440                                         
441                                         /* Determine whether newlines are LF or CRLF */
442                                         evaluate_crlf_ptr = part_start;
443                                         --evaluate_crlf_ptr;
444                                         if (!memcmp(evaluate_crlf_ptr, "\r\n", 2)) {
445                                                 crlf_in_use = 1;
446                                         }
447                                         else {
448                                                 crlf_in_use = 0;
449                                         }
450
451                                         /* Advance past the LF ... now we're in the next part */
452                                         ++part_start;
453                                         ptr = part_start;
454                                 }
455                         }
456                         else {
457                                 /* Invalid end of multipart.  Bail out! */
458                                 ptr = content_end;
459                         }
460                 } while ( (ptr < content_end) && (next_boundary != NULL) );
461
462                 if (PostMultiPartCallBack != NULL) {
463                         PostMultiPartCallBack("", "", partnum, "", NULL,
464                                 content_type, charset, 0, encoding, userdata);
465                 }
466                 goto end_parser;
467         }
468
469         /* If it's not a multipart message, then do something with it */
470         if (!is_multipart) {
471                 part_start = ptr;
472                 length = 0;
473                 while (ptr < content_end) {
474                         ++ptr;
475                         ++length;
476                 }
477                 part_end = content_end;
478
479                 /******
480                  * I thought there was an off-by-one error here, but there isn't.
481                  * This probably means that there's an off-by-one error somewhere
482                  * else ... or maybe only in certain messages?
483                 --part_end;
484                 --length;
485                 ******/
486                 
487                 /* Truncate if the header told us to */
488                 if ( (content_length > 0) && (length > content_length) ) {
489                         length = content_length;
490                 }
491
492                 /* Sometimes the "name" field is tacked on to Content-type,
493                  * and sometimes it's tacked on to Content-disposition.  Use
494                  * whichever one we have.
495                  */
496                 if (strlen(content_disposition_name) > strlen(content_type_name)) {
497                         name = content_disposition_name;
498                 }
499                 else {
500                         name = content_type_name;
501                 }
502         
503                 /* lprintf(CTDL_DEBUG, "mime_decode part=%s, len=%d, type=%s, charset=%s, encoding=%s\n",
504                         partnum, length, content_type, charset, encoding); */
505
506                 /* Ok, we've got a non-multipart part here, so do something with it.
507                  */
508                 mime_decode(partnum,
509                         part_start, length,
510                         content_type, charset, encoding, disposition,
511                         name, filename,
512                         CallBack, NULL, NULL,
513                         userdata, dont_decode
514                 );
515
516                 /*
517                  * Now if it's an encapsulated message/rfc822 then we have to recurse into it
518                  */
519                 if (!strcasecmp(content_type, "message/rfc822")) {
520
521                         if (PreMultiPartCallBack != NULL) {
522                                 PreMultiPartCallBack("", "", partnum, "",
523                                         NULL, content_type, charset,
524                                         0, encoding, userdata);
525                         }
526                         if (CallBack != NULL) {
527                                 if (strlen(partnum) > 0) {
528                                         snprintf(nested_partnum,
529                                                  sizeof nested_partnum,
530                                                  "%s.%d", partnum,
531                                                  ++part_seq);
532                                 }
533                                 else {
534                                         snprintf(nested_partnum,
535                                                  sizeof nested_partnum,
536                                                  "%d", ++part_seq);
537                                 }
538                                 the_mime_parser(nested_partnum,
539                                         part_start, part_end,
540                                         CallBack,
541                                         PreMultiPartCallBack,
542                                         PostMultiPartCallBack,
543                                         userdata,
544                                         dont_decode
545                                 );
546                         }
547                         if (PostMultiPartCallBack != NULL) {
548                                 PostMultiPartCallBack("", "", partnum, "", NULL,
549                                         content_type, charset, 0, encoding, userdata);
550                         }
551
552
553                 }
554
555         }
556
557 end_parser:     /* free the buffers!  end the oppression!! */
558         free(boundary);
559         free(startary);
560         free(endary);   
561         free(header);
562         free(content_type);
563         free(charset);
564         free(encoding);
565         free(content_type_name);
566         free(content_disposition_name);
567         free(filename);
568         free(disposition);
569 }
570
571
572
573 /*
574  * Entry point for the MIME parser.
575  * (This function expects to be fed HEADERS + CONTENT)
576  * Note: NULL can be supplied as content_end; in this case, the message is
577  * considered to have ended when the parser encounters a 0x00 byte.
578  */
579 void mime_parser(char *content_start,
580                 char *content_end,
581
582                  void (*CallBack)
583                   (char *cbname,
584                    char *cbfilename,
585                    char *cbpartnum,
586                    char *cbdisp,
587                    void *cbcontent,
588                    char *cbtype,
589                    char *cbcharset,
590                    size_t cblength,
591                    char *cbencoding,
592                    void *cbuserdata),
593
594                  void (*PreMultiPartCallBack)
595                   (char *cbname,
596                    char *cbfilename,
597                    char *cbpartnum,
598                    char *cbdisp,
599                    void *cbcontent,
600                    char *cbtype,
601                    char *cbcharset,
602                    size_t cblength,
603                    char *cbencoding,
604                    void *cbuserdata),
605
606                  void (*PostMultiPartCallBack)
607                   (char *cbname,
608                    char *cbfilename,
609                    char *cbpartnum,
610                    char *cbdisp,
611                    void *cbcontent,
612                    char *cbtype,
613                    char *cbcharset,
614                    size_t cblength,
615                    char *cbencoding,
616                    void *cbuserdata),
617
618                   void *userdata,
619                   int dont_decode
620 )
621 {
622
623         the_mime_parser("", content_start, content_end,
624                         CallBack,
625                         PreMultiPartCallBack,
626                         PostMultiPartCallBack,
627                         userdata, dont_decode);
628 }