]> code.citadel.org Git - citadel.git/blob - citadel/mime_parser.c
* yeesh ... more on the 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                 if (CallBack != NULL) {
145                         CallBack(name, filename, partnum,
146                                 disposition, part_start,
147                                 content_type, length, encoding, userdata);
148                         }
149                 return;
150         }
151         if ((strcasecmp(encoding, "base64"))
152             && (strcasecmp(encoding, "quoted-printable"))) {
153                 lprintf(5, "ERROR: unknown MIME encoding '%s'\n", encoding);
154                 return;
155         }
156         /*
157          * Allocate a buffer for the decoded data.  The output buffer is the
158          * same size as the input buffer; this assumes that the decoded data
159          * will never be larger than the encoded data.  This is a safe
160          * assumption with base64, uuencode, and quoted-printable.  Just to
161          * be safe, we still pad the buffer a bit.
162          */
163         decoded = mallok(length + 1024);
164         if (decoded == NULL) {
165                 lprintf(5, "ERROR: cannot allocate memory.\n");
166                 return;
167         }
168         if (pipe(sendpipe) != 0)
169                 return;
170         if (pipe(recvpipe) != 0)
171                 return;
172
173         childpid = fork();
174         if (childpid < 0) {
175                 phree(decoded);
176                 return;
177         }
178         if (childpid == 0) {
179                 close(2);
180                 /* send stdio to the pipes */
181                 if (dup2(sendpipe[0], 0) < 0)
182                         lprintf(5, "ERROR dup2()\n");
183                 if (dup2(recvpipe[1], 1) < 0)
184                         lprintf(5, "ERROR dup2()\n");
185                 close(sendpipe[1]);     /* Close the ends we're not using */
186                 close(recvpipe[0]);
187                 if (!strcasecmp(encoding, "base64"))
188                         execlp("./base64", "base64", "-d", NULL);
189                 else if (!strcasecmp(encoding, "quoted-printable"))
190                         execlp("./qpdecode", "qpdecode", NULL);
191                 lprintf(5, "ERROR: cannot exec decoder for %s\n", encoding);
192                 exit(1);
193         }
194         close(sendpipe[0]);     /* Close the ends we're not using  */
195         close(recvpipe[1]);
196
197         while ((bytes_sent < length) && (write_error == 0)) {
198                 /* Empty the input pipe FIRST */
199                 while (fstat(recvpipe[0], &statbuf), (statbuf.st_size > 0)) {
200                         blocksize = read(recvpipe[0], &decoded[bytes_recv],
201                                          statbuf.st_size);
202                         if (blocksize < 0)
203                                 lprintf(5, "ERROR: cannot read from pipe\n");
204                         else
205                                 bytes_recv = bytes_recv + blocksize;
206                 }
207                 /* Then put some data into the output pipe */
208                 blocksize = length - bytes_sent;
209                 if (blocksize > 2048)
210                         blocksize = 2048;
211                 if (write(sendpipe[1], &part_start[bytes_sent], blocksize) < 0) {
212                         lprintf(5, "ERROR: cannot write to pipe: %s\n",
213                                 strerror(errno));
214                         write_error = 1;
215                 }
216                 bytes_sent = bytes_sent + blocksize;
217         }
218         close(sendpipe[1]);
219         /* Empty the input pipe */
220         while ((blocksize = read(recvpipe[0], &decoded[bytes_recv], 1)),
221                (blocksize > 0)) {
222                 bytes_recv = bytes_recv + blocksize;
223         }
224
225         if (bytes_recv > 0) if (CallBack != NULL) {
226                 CallBack(name, filename, partnum, disposition, decoded,
227                          content_type, bytes_recv, "binary", userdata);
228         }
229
230         phree(decoded);
231 }
232
233 /*
234  * Break out the components of a multipart message
235  * (This function expects to be fed HEADERS + CONTENT)
236  * Note: NULL can be supplied as content_end; in this case, the message is
237  * considered to have ended when the parser encounters a 0x00 byte.
238  */
239 void the_mime_parser(char *partnum,
240                      char *content_start, char *content_end,
241                      void (*CallBack)
242                       (char *cbname,
243                        char *cbfilename,
244                        char *cbpartnum,
245                        char *cbdisp,
246                        void *cbcontent,
247                        char *cbtype,
248                        size_t cblength,
249                        char *cbencoding,
250                        void *cbuserdata),
251                      void (*PreMultiPartCallBack)
252                       (char *cbname,
253                        char *cbfilename,
254                        char *cbpartnum,
255                        char *cbdisp,
256                        void *cbcontent,
257                        char *cbtype,
258                        size_t cblength,
259                        char *cbencoding,
260                        void *cbuserdata),
261                      void (*PostMultiPartCallBack)
262                       (char *cbname,
263                        char *cbfilename,
264                        char *cbpartnum,
265                        char *cbdisp,
266                        void *cbcontent,
267                        char *cbtype,
268                        size_t cblength,
269                        char *cbencoding,
270                        void *cbuserdata),
271                       void *userdata,
272                       int dont_decode
273 )
274 {
275
276         char *ptr;
277         char *part_start, *part_end;
278         char buf[SIZ];
279         char header[SIZ];
280         char boundary[SIZ];
281         char startary[SIZ];
282         char endary[SIZ];
283         char content_type[SIZ];
284         char encoding[SIZ];
285         char disposition[SIZ];
286         char name[SIZ];
287         char filename[SIZ];
288         int is_multipart;
289         int part_seq = 0;
290         int i;
291         size_t length;
292         char nested_partnum[SIZ];
293
294         lprintf(9, "the_mime_parser() called\n");
295         ptr = content_start;
296         memset(boundary, 0, sizeof boundary);
297         memset(content_type, 0, sizeof content_type);
298         memset(encoding, 0, sizeof encoding);
299         memset(name, 0, sizeof name);
300         memset(filename, 0, sizeof filename);
301         memset(disposition, 0, sizeof disposition);
302
303         /* Learn interesting things from the headers */
304         strcpy(header, "");
305         do {
306                 ptr = memreadline(ptr, buf, sizeof buf);
307                 if (*ptr == 0)
308                         return; /* premature end of message */
309                 if (content_end != NULL)
310                         if (ptr >= content_end)
311                                 return;
312
313                 for (i = 0; i < strlen(buf); ++i)
314                         if (isspace(buf[i]))
315                                 buf[i] = ' ';
316                 if (!isspace(buf[0])) {
317                         if (!strncasecmp(header, "Content-type: ", 14)) {
318                                 strcpy(content_type, &header[14]);
319                                 extract_key(name, content_type, "name");
320                         }
321                         if (!strncasecmp(header, "Content-Disposition: ", 21)) {
322                                 strcpy(disposition, &header[21]);
323                                 extract_key(filename, disposition, "filename");
324                         }
325                         if (!strncasecmp(header,
326                                       "Content-transfer-encoding: ", 27))
327                                 strcpy(encoding, &header[27]);
328                         if (strlen(boundary) == 0)
329                                 extract_key(boundary, header, "boundary");
330                         strcpy(header, "");
331                 }
332                 if ((strlen(header) + strlen(buf) + 2) < sizeof(header))
333                         strcat(header, buf);
334         } while ((strlen(buf) > 0) && (*ptr != 0));
335
336         for (i = 0; i < strlen(disposition); ++i)
337                 if (disposition[i] == ';')
338                         disposition[i] = 0;
339         while (isspace(disposition[0]))
340                 strcpy(disposition, &disposition[1]);
341         for (i = 0; i < strlen(content_type); ++i)
342                 if (content_type[i] == ';')
343                         content_type[i] = 0;
344         while (isspace(content_type[0]))
345                 strcpy(content_type, &content_type[1]);
346
347         if (strlen(boundary) > 0) {
348                 is_multipart = 1;
349         } else {
350                 is_multipart = 0;
351         }
352
353         /* If this is a multipart message, then recursively process it */
354         part_start = NULL;
355         if (is_multipart) {
356
357                 /* Tell the client about this message's multipartedness */
358                 if (PreMultiPartCallBack != NULL) {
359                         PreMultiPartCallBack("", "", partnum, "",
360                                 NULL, content_type,
361                                 0, encoding, userdata);
362                 }
363                 /*
364                 if (CallBack != NULL) {
365                         CallBack("", "", partnum, "", NULL, content_type,
366                                 0, encoding, userdata);
367                 }
368                  */
369
370                 /* Figure out where the boundaries are */
371                 sprintf(startary, "--%s", boundary);
372                 sprintf(endary, "--%s--", boundary);
373                 do {
374                         part_end = ptr;
375                         ptr = memreadline(ptr, buf, sizeof buf);
376                         if (*ptr == 0) goto END_MULTI;  /* premature end */
377                         if (content_end != NULL)
378                                 if (ptr >= content_end) goto END_MULTI;
379                         if ((!strcasecmp(buf, startary))
380                             || (!strcasecmp(buf, endary))) {
381                                 if (part_start != NULL) {
382                                         if (strlen(partnum) > 0) {
383                                                 sprintf(nested_partnum, "%s.%d",
384                                                         partnum, ++part_seq);
385                                         }
386                                         else {
387                                                 sprintf(nested_partnum, "%d",
388                                                         ++part_seq);
389                                         }
390                                         the_mime_parser(nested_partnum,
391                                                     part_start, part_end,
392                                                         CallBack,
393                                                         PreMultiPartCallBack,
394                                                         PostMultiPartCallBack,
395                                                         userdata,
396                                                         dont_decode);
397                                 }
398                                 part_start = ptr;
399                         }
400                 } while (strcasecmp(buf, endary));
401 END_MULTI:      if (PostMultiPartCallBack != NULL) {
402                         PostMultiPartCallBack("", "", partnum, "", NULL,
403                                 content_type, 0, encoding, userdata);
404                 }
405                 return;
406         }
407
408         /* If it's not a multipart message, then do something with it */
409         if (!is_multipart) {
410                 part_start = ptr;
411                 length = 0;
412                 while ((*ptr != 0)
413                       && ((content_end == NULL) || (ptr < content_end))) {
414                         ++length;
415                         part_end = ptr++;
416                 }
417                 mime_decode(partnum,
418                             part_start, length,
419                             content_type, encoding, disposition,
420                             name, filename,
421                             CallBack, NULL, NULL,
422                             userdata, dont_decode);
423         }
424
425
426 }
427
428
429
430 /*
431  * Entry point for the MIME parser.
432  * (This function expects to be fed HEADERS + CONTENT)
433  * Note: NULL can be supplied as content_end; in this case, the message is
434  * considered to have ended when the parser encounters a 0x00 byte.
435  */
436 void mime_parser(char *content_start,
437                 char *content_end,
438
439                  void (*CallBack)
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 (*PreMultiPartCallBack)
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 (*PostMultiPartCallBack)
462                   (char *cbname,
463                    char *cbfilename,
464                    char *cbpartnum,
465                    char *cbdisp,
466                    void *cbcontent,
467                    char *cbtype,
468                    size_t cblength,
469                    char *cbencoding,
470                    void *cbuserdata),
471
472                   void *userdata,
473                   int dont_decode
474 )
475 {
476
477         lprintf(9, "mime_parser() called\n");
478         the_mime_parser("", content_start, content_end,
479                         CallBack,
480                         PreMultiPartCallBack,
481                         PostMultiPartCallBack,
482                         userdata, dont_decode);
483 }