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