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