55f1f4d7ffc8c1d5a4c8d61405fa98952c79749d
[citadel.git] / citadel / mime_parser.c
1 /*
2  * mime_parser.c
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  * $Id$
11  *
12  */
13
14 #include "sysdep.h"
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 #ifdef HAVE_PTHREAD_H
25 #include <pthread.h>
26 #endif
27 #include "citadel.h"
28 #include "mime_parser.h"
29 #include "sysdep_decls.h"
30 #include "server.h"
31
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 /* 
57  * Utility function to "readline" from memory
58  * (returns new pointer)
59  */
60 char *memreadline(char *start, char *buf, int maxlen)
61 {
62         char ch;
63         char *ptr;
64
65         ptr = start;
66         memset(buf, 0, maxlen);
67
68         while (1) {
69                 ch = *ptr++;
70                 if ((ch == 10) || (ch == 0)) {
71                         if (strlen(buf) > 0)
72                                 if (buf[strlen(buf) - 1] == 13)
73                                         buf[strlen(buf) - 1] = 0;
74                         return ptr;
75                 }
76                 if (strlen(buf) < (maxlen - 1)) {
77                         buf[strlen(buf) + 1] = 0;
78                         buf[strlen(buf)] = ch;
79                 }
80         }
81 }
82
83 /*
84  * Given a message or message-part body and a length, handle any necessary
85  * decoding and pass the request up the stack.
86  */
87 void mime_decode(char *partnum,
88                  char *part_start, size_t length,
89                  char *content_type, char *encoding,
90                  char *disposition,
91                  char *name, char *filename,
92                  void (*CallBack)
93                   (char *cbname,
94                    char *cbfilename,
95                    char *cbpartnum,
96                    char *cbdisp,
97                    void *cbcontent,
98                    char *cbtype,
99                    size_t cblength)
100 )
101 {
102
103         char *decoded;
104         struct stat statbuf;
105         int sendpipe[2];
106         int recvpipe[2];
107         int childpid;
108         size_t bytes_sent = 0;
109         size_t bytes_recv = 0;
110         size_t blocksize;
111         int write_error = 0;
112
113         lprintf(9, "mime_decode() called\n");
114
115         /* Some encodings aren't really encodings */
116         if (!strcasecmp(encoding, "7bit"))
117                 strcpy(encoding, "");
118         if (!strcasecmp(encoding, "8bit"))
119                 strcpy(encoding, "");
120         if (!strcasecmp(encoding, "binary"))
121                 strcpy(encoding, "");
122
123         /* If this part is not encoded, send as-is */
124         if (strlen(encoding) == 0) {
125                 CallBack(name, filename, partnum, disposition, part_start,
126                          content_type, length);
127                 return;
128         }
129         if ((strcasecmp(encoding, "base64"))
130             && (strcasecmp(encoding, "quoted-printable"))) {
131                 lprintf(5, "ERROR: unknown MIME encoding '%s'\n", encoding);
132                 return;
133         }
134         /*
135          * Allocate a buffer for the decoded data.  The output buffer is the
136          * same size as the input buffer; this assumes that the decoded data
137          * will never be larger than the encoded data.  This is a safe
138          * assumption with base64, uuencode, and quoted-printable.  Just to
139          * be safe, we still pad the buffer a bit.
140          */
141         decoded = mallok(length + 1024);
142         if (decoded == NULL) {
143                 lprintf(5, "ERROR: cannot allocate memory.\n");
144                 return;
145         }
146         if (pipe(sendpipe) != 0)
147                 return;
148         if (pipe(recvpipe) != 0)
149                 return;
150
151         childpid = fork();
152         if (childpid < 0) {
153                 phree(decoded);
154                 return;
155         }
156         if (childpid == 0) {
157                 close(2);
158                 /* send stdio to the pipes */
159                 if (dup2(sendpipe[0], 0) < 0)
160                         lprintf(5, "ERROR dup2()\n");
161                 if (dup2(recvpipe[1], 1) < 0)
162                         lprintf(5, "ERROR dup2()\n");
163                 close(sendpipe[1]);     /* Close the ends we're not using */
164                 close(recvpipe[0]);
165                 if (!strcasecmp(encoding, "base64"))
166                         execlp("./base64", "base64", "-d", NULL);
167                 else if (!strcasecmp(encoding, "quoted-printable"))
168                         execlp("./qpdecode", "qpdecode", NULL);
169                 lprintf(5, "ERROR: cannot exec decoder for %s\n", encoding);
170                 exit(1);
171         }
172         close(sendpipe[0]);     /* Close the ends we're not using  */
173         close(recvpipe[1]);
174
175         while ((bytes_sent < length) && (write_error == 0)) {
176                 /* Empty the input pipe FIRST */
177                 while (fstat(recvpipe[0], &statbuf), (statbuf.st_size > 0)) {
178                         blocksize = read(recvpipe[0], &decoded[bytes_recv],
179                                          statbuf.st_size);
180                         if (blocksize < 0)
181                                 lprintf(5, "ERROR: cannot read from pipe\n");
182                         else
183                                 bytes_recv = bytes_recv + blocksize;
184                 }
185                 /* Then put some data into the output pipe */
186                 blocksize = length - bytes_sent;
187                 if (blocksize > 2048)
188                         blocksize = 2048;
189                 if (write(sendpipe[1], &part_start[bytes_sent], blocksize) < 0) {
190                         lprintf(5, "ERROR: cannot write to pipe: %s\n",
191                                 strerror(errno));
192                         write_error = 1;
193                 }
194                 bytes_sent = bytes_sent + blocksize;
195         }
196         close(sendpipe[1]);
197         /* Empty the input pipe */
198         while ((blocksize = read(recvpipe[0], &decoded[bytes_recv], 1)),
199                (blocksize > 0)) {
200                 bytes_recv = bytes_recv + blocksize;
201         }
202
203         if (bytes_recv > 0)
204                 CallBack(name, filename, partnum, disposition, decoded,
205                          content_type, bytes_recv);
206
207         phree(decoded);
208 }
209
210 /*
211  * Break out the components of a multipart message
212  * (This function expects to be fed HEADERS + CONTENT)
213  * Note: NULL can be supplied as content_end; in this case, the message is
214  * considered to have ended when the parser encounters a 0x00 byte.
215  */
216 void the_mime_parser(char *partnum,
217                      char *content_start, char *content_end,
218                      void (*CallBack)
219                       (char *cbname,
220                        char *cbfilename,
221                        char *cbpartnum,
222                        char *cbdisp,
223                        void *cbcontent,
224                        char *cbtype,
225                        size_t cblength)
226 )
227 {
228
229         char *ptr;
230         char *part_start, *part_end;
231         char buf[256];
232         char header[256];
233         char boundary[256];
234         char startary[256];
235         char endary[256];
236         char content_type[256];
237         char encoding[256];
238         char disposition[256];
239         char name[256];
240         char filename[256];
241         int is_multipart;
242         int part_seq = 0;
243         int i;
244         size_t length;
245         char nested_partnum[256];
246
247         lprintf(9, "the_mime_parser() called\n");
248         ptr = content_start;
249         memset(boundary, 0, sizeof boundary);
250         memset(content_type, 0, sizeof content_type);
251         memset(encoding, 0, sizeof encoding);
252         memset(name, 0, sizeof name);
253         memset(filename, 0, sizeof filename);
254         memset(disposition, 0, sizeof disposition);
255
256         /* Learn interesting things from the headers */
257         strcpy(header, "");
258         do {
259                 ptr = memreadline(ptr, buf, sizeof buf);
260                 if (*ptr == 0)
261                         return; /* premature end of message */
262                 if (content_end != NULL)
263                         if (ptr >= content_end)
264                                 return;
265
266                 for (i = 0; i < strlen(buf); ++i)
267                         if (isspace(buf[i]))
268                                 buf[i] = ' ';
269                 if (!isspace(buf[0])) {
270                         if (!strncasecmp(header, "Content-type: ", 14)) {
271                                 strcpy(content_type, &header[14]);
272                                 extract_key(name, content_type, "name");
273                         }
274                         if (!strncasecmp(header, "Content-Disposition: ", 21)) {
275                                 strcpy(disposition, &header[21]);
276                                 extract_key(filename, disposition, "filename");
277                         }
278                         if (!strncasecmp(header,
279                                       "Content-transfer-encoding: ", 27))
280                                 strcpy(encoding, &header[27]);
281                         if (strlen(boundary) == 0)
282                                 extract_key(boundary, header, "boundary");
283                         strcpy(header, "");
284                 }
285                 if ((strlen(header) + strlen(buf) + 2) < sizeof(header))
286                         strcat(header, buf);
287         } while ((strlen(buf) > 0) && (*ptr != 0));
288
289         for (i = 0; i < strlen(disposition); ++i)
290                 if (disposition[i] == ';')
291                         disposition[i] = 0;
292         while (isspace(disposition[0]))
293                 strcpy(disposition, &disposition[1]);
294         for (i = 0; i < strlen(content_type); ++i)
295                 if (content_type[i] == ';')
296                         content_type[i] = 0;
297         while (isspace(content_type[0]))
298                 strcpy(content_type, &content_type[1]);
299
300         if (strlen(boundary) > 0) {
301                 is_multipart = 1;
302         } else {
303                 is_multipart = 0;
304         }
305
306         /* If this is a multipart message, then recursively process it */
307         part_start = NULL;
308         if (is_multipart) {
309
310                 /* Tell the client about this message's multipartedness */
311                 CallBack("", "", partnum, "", NULL, content_type, 0);
312
313                 /* Figure out where the boundaries are */
314                 sprintf(startary, "--%s", boundary);
315                 sprintf(endary, "--%s--", boundary);
316                 do {
317                         part_end = ptr;
318                         ptr = memreadline(ptr, buf, sizeof buf);
319                         if (*ptr == 0)
320                                 return;         /* premature end of message */
321                         if (content_end != NULL)
322                                 if (ptr >= content_end)
323                                         return;
324                         if ((!strcasecmp(buf, startary))
325                             || (!strcasecmp(buf, endary))) {
326                                 if (part_start != NULL) {
327                                         sprintf(nested_partnum, "%s.%d",
328                                                 partnum, ++part_seq);
329                                         the_mime_parser(nested_partnum,
330                                                     part_start, part_end,
331                                                         CallBack);
332                                 }
333                                 part_start = ptr;
334                         }
335                 } while (strcasecmp(buf, endary));
336         }
337
338         /* If it's not a multipart message, then do something with it */
339         if (!is_multipart) {
340                 part_start = ptr;
341                 length = 0;
342                 while ((*ptr != 0)
343                       && ((content_end == NULL) || (ptr < content_end))) {
344                         ++length;
345                         part_end = ptr++;
346                 }
347                 mime_decode(partnum,
348                             part_start, length,
349                             content_type, encoding, disposition,
350                             name, filename, CallBack);
351         }
352
353
354 }
355
356
357
358 /*
359  * Entry point for the MIME parser.
360  * (This function expects to be fed HEADERS + CONTENT)
361  * Note: NULL can be supplied as content_end; in this case, the message is
362  * considered to have ended when the parser encounters a 0x00 byte.
363  */
364 void mime_parser(char *content_start, char *content_end,
365                  void (*CallBack)
366                   (char *cbname,
367                    char *cbfilename,
368                    char *cbpartnum,
369                    char *cbdisp,
370                    void *cbcontent,
371                    char *cbtype,
372                    size_t cblength)
373 )
374 {
375
376         lprintf(9, "mime_parser() called\n");
377         the_mime_parser("1", content_start, content_end, CallBack);
378 }