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