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