* Removed all of the thread cancellation cruft that is no longer necessary
[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 #include "citadel.h"
25 #include "mime_parser.h"
26 #include "sysdep_decls.h"
27 #include "server.h"
28
29
30
31 void extract_key(char *target, char *source, char *key)
32 {
33         int a, b;
34
35         strcpy(target, source);
36         for (a = 0; a < strlen(target); ++a) {
37                 if ((!strncasecmp(&target[a], key, strlen(key)))
38                     && (target[a + strlen(key)] == '=')) {
39                         strcpy(target, &target[a + strlen(key) + 1]);
40                         if (target[0] == 34)
41                                 strcpy(target, &target[1]);
42                         for (b = 0; b < strlen(target); ++b)
43                                 if (target[b] == 34)
44                                         target[b] = 0;
45                         return;
46                 }
47         }
48         strcpy(target, "");
49 }
50
51
52
53 /* 
54  * Utility function to "readline" from memory
55  * (returns new pointer)
56  */
57 char *memreadline(char *start, char *buf, int maxlen)
58 {
59         char ch;
60         char *ptr;
61
62         ptr = start;
63         memset(buf, 0, maxlen);
64
65         while (1) {
66                 ch = *ptr++;
67                 if ((ch == 10) || (ch == 0)) {
68                         if (strlen(buf) > 0)
69                                 if (buf[strlen(buf) - 1] == 13)
70                                         buf[strlen(buf) - 1] = 0;
71                         return ptr;
72                 }
73                 if (strlen(buf) < (maxlen - 1)) {
74                         buf[strlen(buf) + 1] = 0;
75                         buf[strlen(buf)] = ch;
76                 }
77         }
78 }
79
80 /*
81  * Given a message or message-part body and a length, handle any necessary
82  * decoding and pass the request up the stack.
83  */
84 void mime_decode(char *partnum,
85                  char *part_start, size_t length,
86                  char *content_type, char *encoding,
87                  char *disposition,
88                  char *name, char *filename,
89                  void (*CallBack)
90                   (char *cbname,
91                    char *cbfilename,
92                    char *cbpartnum,
93                    char *cbdisp,
94                    void *cbcontent,
95                    char *cbtype,
96                    size_t cblength)
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);
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);
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 )
224 {
225
226         char *ptr;
227         char *part_start, *part_end;
228         char buf[256];
229         char header[256];
230         char boundary[256];
231         char startary[256];
232         char endary[256];
233         char content_type[256];
234         char encoding[256];
235         char disposition[256];
236         char name[256];
237         char filename[256];
238         int is_multipart;
239         int part_seq = 0;
240         int i;
241         size_t length;
242         char nested_partnum[256];
243
244         lprintf(9, "the_mime_parser() called\n");
245         ptr = content_start;
246         memset(boundary, 0, sizeof boundary);
247         memset(content_type, 0, sizeof content_type);
248         memset(encoding, 0, sizeof encoding);
249         memset(name, 0, sizeof name);
250         memset(filename, 0, sizeof filename);
251         memset(disposition, 0, sizeof disposition);
252
253         /* Learn interesting things from the headers */
254         strcpy(header, "");
255         do {
256                 ptr = memreadline(ptr, buf, sizeof buf);
257                 if (*ptr == 0)
258                         return; /* premature end of message */
259                 if (content_end != NULL)
260                         if (ptr >= content_end)
261                                 return;
262
263                 for (i = 0; i < strlen(buf); ++i)
264                         if (isspace(buf[i]))
265                                 buf[i] = ' ';
266                 if (!isspace(buf[0])) {
267                         if (!strncasecmp(header, "Content-type: ", 14)) {
268                                 strcpy(content_type, &header[14]);
269                                 extract_key(name, content_type, "name");
270                         }
271                         if (!strncasecmp(header, "Content-Disposition: ", 21)) {
272                                 strcpy(disposition, &header[21]);
273                                 extract_key(filename, disposition, "filename");
274                         }
275                         if (!strncasecmp(header,
276                                       "Content-transfer-encoding: ", 27))
277                                 strcpy(encoding, &header[27]);
278                         if (strlen(boundary) == 0)
279                                 extract_key(boundary, header, "boundary");
280                         strcpy(header, "");
281                 }
282                 if ((strlen(header) + strlen(buf) + 2) < sizeof(header))
283                         strcat(header, buf);
284         } while ((strlen(buf) > 0) && (*ptr != 0));
285
286         for (i = 0; i < strlen(disposition); ++i)
287                 if (disposition[i] == ';')
288                         disposition[i] = 0;
289         while (isspace(disposition[0]))
290                 strcpy(disposition, &disposition[1]);
291         for (i = 0; i < strlen(content_type); ++i)
292                 if (content_type[i] == ';')
293                         content_type[i] = 0;
294         while (isspace(content_type[0]))
295                 strcpy(content_type, &content_type[1]);
296
297         if (strlen(boundary) > 0) {
298                 is_multipart = 1;
299         } else {
300                 is_multipart = 0;
301         }
302
303         /* If this is a multipart message, then recursively process it */
304         part_start = NULL;
305         if (is_multipart) {
306
307                 /* Tell the client about this message's multipartedness */
308                 CallBack("", "", partnum, "", NULL, content_type, 0);
309
310                 /* Figure out where the boundaries are */
311                 sprintf(startary, "--%s", boundary);
312                 sprintf(endary, "--%s--", boundary);
313                 do {
314                         part_end = ptr;
315                         ptr = memreadline(ptr, buf, sizeof buf);
316                         if (*ptr == 0)
317                                 return;         /* premature end of message */
318                         if (content_end != NULL)
319                                 if (ptr >= content_end)
320                                         return;
321                         if ((!strcasecmp(buf, startary))
322                             || (!strcasecmp(buf, endary))) {
323                                 if (part_start != NULL) {
324                                         sprintf(nested_partnum, "%s.%d",
325                                                 partnum, ++part_seq);
326                                         the_mime_parser(nested_partnum,
327                                                     part_start, part_end,
328                                                         CallBack);
329                                 }
330                                 part_start = ptr;
331                         }
332                 } while (strcasecmp(buf, endary));
333         }
334
335         /* If it's not a multipart message, then do something with it */
336         if (!is_multipart) {
337                 part_start = ptr;
338                 length = 0;
339                 while ((*ptr != 0)
340                       && ((content_end == NULL) || (ptr < content_end))) {
341                         ++length;
342                         part_end = ptr++;
343                 }
344                 mime_decode(partnum,
345                             part_start, length,
346                             content_type, encoding, disposition,
347                             name, filename, CallBack);
348         }
349
350
351 }
352
353
354
355 /*
356  * Entry point for the MIME parser.
357  * (This function expects to be fed HEADERS + CONTENT)
358  * Note: NULL can be supplied as content_end; in this case, the message is
359  * considered to have ended when the parser encounters a 0x00 byte.
360  */
361 void mime_parser(char *content_start, char *content_end,
362                  void (*CallBack)
363                   (char *cbname,
364                    char *cbfilename,
365                    char *cbpartnum,
366                    char *cbdisp,
367                    void *cbcontent,
368                    char *cbtype,
369                    size_t cblength)
370 )
371 {
372
373         lprintf(9, "mime_parser() called\n");
374         the_mime_parser("1", content_start, content_end, CallBack);
375 }