]> code.citadel.org Git - citadel.git/blob - citadel/mime_parser.c
* imap bodystructure
[citadel.git] / citadel / mime_parser.c
1 /*
2  * $Id$
3  *
4  * This is a really bad attempt at writing a parser to handle MIME-encoded
5  * messages.
6  *
7  * Copyright (c) 1998-1999 by Art Cancro
8  * This code is distributed under the terms of the GNU General Public License.
9  *
10  */
11
12 #include "sysdep.h"
13 #include <stdlib.h>
14 #include <unistd.h>
15 #include <stdio.h>
16 #include <signal.h>
17 #include <sys/types.h>
18 #include <ctype.h>
19 #include <string.h>
20 #include <sys/stat.h>
21 #include <errno.h>
22 #include "citadel.h"
23 #include "mime_parser.h"
24 #include "sysdep_decls.h"
25 #include "server.h"
26
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 /* 
52  * Utility function to "readline" from memory
53  * (returns new pointer)
54  */
55 char *memreadline(char *start, char *buf, int maxlen)
56 {
57         char ch;
58         char *ptr;
59
60         ptr = start;
61         memset(buf, 0, maxlen);
62
63         while (1) {
64                 ch = *ptr++;
65                 if ((ch == 10) || (ch == 0)) {
66                         if (strlen(buf) > 0)
67                                 if (buf[strlen(buf) - 1] == 13)
68                                         buf[strlen(buf) - 1] = 0;
69                         return ptr;
70                 }
71                 if (strlen(buf) < (maxlen - 1)) {
72                         buf[strlen(buf) + 1] = 0;
73                         buf[strlen(buf)] = ch;
74                 }
75         }
76 }
77
78 /*
79  * Given a message or message-part body and a length, handle any necessary
80  * decoding and pass the request up the stack.
81  */
82 void mime_decode(char *partnum,
83                  char *part_start, size_t length,
84                  char *content_type, char *encoding,
85                  char *disposition,
86                  char *name, char *filename,
87                  void (*CallBack)
88                   (char *cbname,
89                    char *cbfilename,
90                    char *cbpartnum,
91                    char *cbdisp,
92                    void *cbcontent,
93                    char *cbtype,
94                    size_t cblength,
95                    char *cbencoding,
96                    void *cbuserdata),
97                  void (*PreMultiPartCallBack)
98                   (char *cbname,
99                    char *cbfilename,
100                    char *cbpartnum,
101                    char *cbdisp,
102                    void *cbcontent,
103                    char *cbtype,
104                    size_t cblength,
105                    char *cbencoding,
106                    void *cbuserdata),
107                  void (*PostMultiPartCallBack)
108                   (char *cbname,
109                    char *cbfilename,
110                    char *cbpartnum,
111                    char *cbdisp,
112                    void *cbcontent,
113                    char *cbtype,
114                    size_t cblength,
115                    char *cbencoding,
116                    void *cbuserdata),
117                   void *userdata,
118                   int dont_decode
119 )
120 {
121
122         char *decoded;
123         struct stat statbuf;
124         int sendpipe[2];
125         int recvpipe[2];
126         int childpid;
127         size_t bytes_sent = 0;
128         size_t bytes_recv = 0;
129         size_t blocksize;
130         int write_error = 0;
131
132         lprintf(9, "mime_decode() called\n");
133
134         /* Some encodings aren't really encodings */
135         if (!strcasecmp(encoding, "7bit"))
136                 strcpy(encoding, "");
137         if (!strcasecmp(encoding, "8bit"))
138                 strcpy(encoding, "");
139         if (!strcasecmp(encoding, "binary"))
140                 strcpy(encoding, "");
141
142         /* If this part is not encoded, send as-is */
143         if ( (strlen(encoding) == 0) || (dont_decode)) {
144                 CallBack(name, filename, partnum, disposition, part_start,
145                          content_type, length, encoding, userdata);
146                 return;
147         }
148         if ((strcasecmp(encoding, "base64"))
149             && (strcasecmp(encoding, "quoted-printable"))) {
150                 lprintf(5, "ERROR: unknown MIME encoding '%s'\n", encoding);
151                 return;
152         }
153         /*
154          * Allocate a buffer for the decoded data.  The output buffer is the
155          * same size as the input buffer; this assumes that the decoded data
156          * will never be larger than the encoded data.  This is a safe
157          * assumption with base64, uuencode, and quoted-printable.  Just to
158          * be safe, we still pad the buffer a bit.
159          */
160         decoded = mallok(length + 1024);
161         if (decoded == NULL) {
162                 lprintf(5, "ERROR: cannot allocate memory.\n");
163                 return;
164         }
165         if (pipe(sendpipe) != 0)
166                 return;
167         if (pipe(recvpipe) != 0)
168                 return;
169
170         childpid = fork();
171         if (childpid < 0) {
172                 phree(decoded);
173                 return;
174         }
175         if (childpid == 0) {
176                 close(2);
177                 /* send stdio to the pipes */
178                 if (dup2(sendpipe[0], 0) < 0)
179                         lprintf(5, "ERROR dup2()\n");
180                 if (dup2(recvpipe[1], 1) < 0)
181                         lprintf(5, "ERROR dup2()\n");
182                 close(sendpipe[1]);     /* Close the ends we're not using */
183                 close(recvpipe[0]);
184                 if (!strcasecmp(encoding, "base64"))
185                         execlp("./base64", "base64", "-d", NULL);
186                 else if (!strcasecmp(encoding, "quoted-printable"))
187                         execlp("./qpdecode", "qpdecode", NULL);
188                 lprintf(5, "ERROR: cannot exec decoder for %s\n", encoding);
189                 exit(1);
190         }
191         close(sendpipe[0]);     /* Close the ends we're not using  */
192         close(recvpipe[1]);
193
194         while ((bytes_sent < length) && (write_error == 0)) {
195                 /* Empty the input pipe FIRST */
196                 while (fstat(recvpipe[0], &statbuf), (statbuf.st_size > 0)) {
197                         blocksize = read(recvpipe[0], &decoded[bytes_recv],
198                                          statbuf.st_size);
199                         if (blocksize < 0)
200                                 lprintf(5, "ERROR: cannot read from pipe\n");
201                         else
202                                 bytes_recv = bytes_recv + blocksize;
203                 }
204                 /* Then put some data into the output pipe */
205                 blocksize = length - bytes_sent;
206                 if (blocksize > 2048)
207                         blocksize = 2048;
208                 if (write(sendpipe[1], &part_start[bytes_sent], blocksize) < 0) {
209                         lprintf(5, "ERROR: cannot write to pipe: %s\n",
210                                 strerror(errno));
211                         write_error = 1;
212                 }
213                 bytes_sent = bytes_sent + blocksize;
214         }
215         close(sendpipe[1]);
216         /* Empty the input pipe */
217         while ((blocksize = read(recvpipe[0], &decoded[bytes_recv], 1)),
218                (blocksize > 0)) {
219                 bytes_recv = bytes_recv + blocksize;
220         }
221
222         if (bytes_recv > 0)
223                 CallBack(name, filename, partnum, disposition, decoded,
224                          content_type, bytes_recv, "binary", userdata);
225
226         phree(decoded);
227 }
228
229 /*
230  * Break out the components of a multipart message
231  * (This function expects to be fed HEADERS + CONTENT)
232  * Note: NULL can be supplied as content_end; in this case, the message is
233  * considered to have ended when the parser encounters a 0x00 byte.
234  */
235 void the_mime_parser(char *partnum,
236                      char *content_start, char *content_end,
237                      void (*CallBack)
238                       (char *cbname,
239                        char *cbfilename,
240                        char *cbpartnum,
241                        char *cbdisp,
242                        void *cbcontent,
243                        char *cbtype,
244                        size_t cblength,
245                        char *cbencoding,
246                        void *cbuserdata),
247                      void (*PreMultiPartCallBack)
248                       (char *cbname,
249                        char *cbfilename,
250                        char *cbpartnum,
251                        char *cbdisp,
252                        void *cbcontent,
253                        char *cbtype,
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                        size_t cblength,
265                        char *cbencoding,
266                        void *cbuserdata),
267                       void *userdata,
268                       int dont_decode
269 )
270 {
271
272         char *ptr;
273         char *part_start, *part_end;
274         char buf[SIZ];
275         char header[SIZ];
276         char boundary[SIZ];
277         char startary[SIZ];
278         char endary[SIZ];
279         char content_type[SIZ];
280         char encoding[SIZ];
281         char disposition[SIZ];
282         char name[SIZ];
283         char filename[SIZ];
284         int is_multipart;
285         int part_seq = 0;
286         int i;
287         size_t length;
288         char nested_partnum[SIZ];
289
290         lprintf(9, "the_mime_parser() called\n");
291         ptr = content_start;
292         memset(boundary, 0, sizeof boundary);
293         memset(content_type, 0, sizeof content_type);
294         memset(encoding, 0, sizeof encoding);
295         memset(name, 0, sizeof name);
296         memset(filename, 0, sizeof filename);
297         memset(disposition, 0, sizeof disposition);
298
299         /* Learn interesting things from the headers */
300         strcpy(header, "");
301         do {
302                 ptr = memreadline(ptr, buf, sizeof buf);
303                 if (*ptr == 0)
304                         return; /* premature end of message */
305                 if (content_end != NULL)
306                         if (ptr >= content_end)
307                                 return;
308
309                 for (i = 0; i < strlen(buf); ++i)
310                         if (isspace(buf[i]))
311                                 buf[i] = ' ';
312                 if (!isspace(buf[0])) {
313                         if (!strncasecmp(header, "Content-type: ", 14)) {
314                                 strcpy(content_type, &header[14]);
315                                 extract_key(name, content_type, "name");
316                         }
317                         if (!strncasecmp(header, "Content-Disposition: ", 21)) {
318                                 strcpy(disposition, &header[21]);
319                                 extract_key(filename, disposition, "filename");
320                         }
321                         if (!strncasecmp(header,
322                                       "Content-transfer-encoding: ", 27))
323                                 strcpy(encoding, &header[27]);
324                         if (strlen(boundary) == 0)
325                                 extract_key(boundary, header, "boundary");
326                         strcpy(header, "");
327                 }
328                 if ((strlen(header) + strlen(buf) + 2) < sizeof(header))
329                         strcat(header, buf);
330         } while ((strlen(buf) > 0) && (*ptr != 0));
331
332         for (i = 0; i < strlen(disposition); ++i)
333                 if (disposition[i] == ';')
334                         disposition[i] = 0;
335         while (isspace(disposition[0]))
336                 strcpy(disposition, &disposition[1]);
337         for (i = 0; i < strlen(content_type); ++i)
338                 if (content_type[i] == ';')
339                         content_type[i] = 0;
340         while (isspace(content_type[0]))
341                 strcpy(content_type, &content_type[1]);
342
343         if (strlen(boundary) > 0) {
344                 is_multipart = 1;
345         } else {
346                 is_multipart = 0;
347         }
348
349         /* If this is a multipart message, then recursively process it */
350         part_start = NULL;
351         if (is_multipart) {
352
353                 /* Tell the client about this message's multipartedness */
354                 PreMultiPartCallBack("", "", partnum, "", NULL, content_type,
355                                 0, encoding, userdata);
356                 /*
357                 CallBack("", "", partnum, "", NULL, content_type,
358                                 0, encoding, userdata);
359                  */
360
361                 /* Figure out where the boundaries are */
362                 sprintf(startary, "--%s", boundary);
363                 sprintf(endary, "--%s--", boundary);
364                 do {
365                         part_end = ptr;
366                         ptr = memreadline(ptr, buf, sizeof buf);
367                         if (*ptr == 0) goto END_MULTI;  /* premature end */
368                         if (content_end != NULL)
369                                 if (ptr >= content_end) goto END_MULTI;
370                         if ((!strcasecmp(buf, startary))
371                             || (!strcasecmp(buf, endary))) {
372                                 if (part_start != NULL) {
373                                         if (strlen(partnum) > 0) {
374                                                 sprintf(nested_partnum, "%s.%d",
375                                                         partnum, ++part_seq);
376                                         }
377                                         else {
378                                                 sprintf(nested_partnum, "%d",
379                                                         ++part_seq);
380                                         }
381                                         the_mime_parser(nested_partnum,
382                                                     part_start, part_end,
383                                                         CallBack,
384                                                         PreMultiPartCallBack,
385                                                         PostMultiPartCallBack,
386                                                         userdata,
387                                                         dont_decode);
388                                 }
389                                 part_start = ptr;
390                         }
391                 } while (strcasecmp(buf, endary));
392 END_MULTI:      PostMultiPartCallBack("", "", partnum, "", NULL, content_type,
393                                 0, encoding, userdata);
394                 return;
395         }
396
397         /* If it's not a multipart message, then do something with it */
398         if (!is_multipart) {
399                 part_start = ptr;
400                 length = 0;
401                 while ((*ptr != 0)
402                       && ((content_end == NULL) || (ptr < content_end))) {
403                         ++length;
404                         part_end = ptr++;
405                 }
406                 mime_decode(partnum,
407                             part_start, length,
408                             content_type, encoding, disposition,
409                             name, filename,
410                             CallBack, NULL, NULL,
411                             userdata, dont_decode);
412         }
413
414
415 }
416
417
418
419 /*
420  * Entry point for the MIME parser.
421  * (This function expects to be fed HEADERS + CONTENT)
422  * Note: NULL can be supplied as content_end; in this case, the message is
423  * considered to have ended when the parser encounters a 0x00 byte.
424  */
425 void mime_parser(char *content_start,
426                 char *content_end,
427
428                  void (*CallBack)
429                   (char *cbname,
430                    char *cbfilename,
431                    char *cbpartnum,
432                    char *cbdisp,
433                    void *cbcontent,
434                    char *cbtype,
435                    size_t cblength,
436                    char *cbencoding,
437                    void *cbuserdata),
438
439                  void (*PreMultiPartCallBack)
440                   (char *cbname,
441                    char *cbfilename,
442                    char *cbpartnum,
443                    char *cbdisp,
444                    void *cbcontent,
445                    char *cbtype,
446                    size_t cblength,
447                    char *cbencoding,
448                    void *cbuserdata),
449
450                  void (*PostMultiPartCallBack)
451                   (char *cbname,
452                    char *cbfilename,
453                    char *cbpartnum,
454                    char *cbdisp,
455                    void *cbcontent,
456                    char *cbtype,
457                    size_t cblength,
458                    char *cbencoding,
459                    void *cbuserdata),
460
461                   void *userdata,
462                   int dont_decode
463 )
464 {
465
466         lprintf(9, "mime_parser() called\n");
467         the_mime_parser("", content_start, content_end,
468                         CallBack,
469                         PreMultiPartCallBack,
470                         PostMultiPartCallBack,
471                         userdata, dont_decode);
472 }