]> code.citadel.org Git - citadel.git/blob - citadel/mime_parser.c
* Moved memreadline() to tools.c
[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  * For non-multipart messages, we need to generate a quickie partnum of "1"
53  * to return to callback functions.  Some callbacks demand it.
54  */
55 char *fixed_partnum(char *supplied_partnum) {
56         if (supplied_partnum == NULL) return "1";
57         if (strlen(supplied_partnum)==0) return "1";
58         return supplied_partnum;
59 }
60
61
62 /*
63  * Given a message or message-part body and a length, handle any necessary
64  * decoding and pass the request up the stack.
65  */
66 void mime_decode(char *partnum,
67                  char *part_start, size_t length,
68                  char *content_type, char *encoding,
69                  char *disposition,
70                  char *name, char *filename,
71                  void (*CallBack)
72                   (char *cbname,
73                    char *cbfilename,
74                    char *cbpartnum,
75                    char *cbdisp,
76                    void *cbcontent,
77                    char *cbtype,
78                    size_t cblength,
79                    char *cbencoding,
80                    void *cbuserdata),
81                  void (*PreMultiPartCallBack)
82                   (char *cbname,
83                    char *cbfilename,
84                    char *cbpartnum,
85                    char *cbdisp,
86                    void *cbcontent,
87                    char *cbtype,
88                    size_t cblength,
89                    char *cbencoding,
90                    void *cbuserdata),
91                  void (*PostMultiPartCallBack)
92                   (char *cbname,
93                    char *cbfilename,
94                    char *cbpartnum,
95                    char *cbdisp,
96                    void *cbcontent,
97                    char *cbtype,
98                    size_t cblength,
99                    char *cbencoding,
100                    void *cbuserdata),
101                   void *userdata,
102                   int dont_decode
103 )
104 {
105
106         char *decoded;
107         struct stat statbuf;
108         int sendpipe[2];
109         int recvpipe[2];
110         int childpid;
111         size_t bytes_sent = 0;
112         size_t bytes_recv = 0;
113         size_t blocksize;
114         int write_error = 0;
115
116         lprintf(9, "mime_decode() called\n");
117
118         /* Some encodings aren't really encodings */
119         if (!strcasecmp(encoding, "7bit"))
120                 strcpy(encoding, "");
121         if (!strcasecmp(encoding, "8bit"))
122                 strcpy(encoding, "");
123         if (!strcasecmp(encoding, "binary"))
124                 strcpy(encoding, "");
125
126         /* If this part is not encoded, send as-is */
127         if ( (strlen(encoding) == 0) || (dont_decode)) {
128                 if (CallBack != NULL) {
129                         CallBack(name, filename, fixed_partnum(partnum),
130                                 disposition, part_start,
131                                 content_type, length, encoding, userdata);
132                         }
133                 return;
134         }
135         if ((strcasecmp(encoding, "base64"))
136             && (strcasecmp(encoding, "quoted-printable"))) {
137                 lprintf(5, "ERROR: unknown MIME encoding '%s'\n", encoding);
138                 return;
139         }
140         /*
141          * Allocate a buffer for the decoded data.  The output buffer is the
142          * same size as the input buffer; this assumes that the decoded data
143          * will never be larger than the encoded data.  This is a safe
144          * assumption with base64, uuencode, and quoted-printable.  Just to
145          * be safe, we still pad the buffer a bit.
146          */
147         decoded = mallok(length + 1024);
148         if (decoded == NULL) {
149                 lprintf(5, "ERROR: cannot allocate memory.\n");
150                 return;
151         }
152         if (pipe(sendpipe) != 0)
153                 return;
154         if (pipe(recvpipe) != 0)
155                 return;
156
157         childpid = fork();
158         if (childpid < 0) {
159                 phree(decoded);
160                 return;
161         }
162         if (childpid == 0) {
163                 close(2);
164                 /* send stdio to the pipes */
165                 if (dup2(sendpipe[0], 0) < 0)
166                         lprintf(5, "ERROR dup2()\n");
167                 if (dup2(recvpipe[1], 1) < 0)
168                         lprintf(5, "ERROR dup2()\n");
169                 close(sendpipe[1]);     /* Close the ends we're not using */
170                 close(recvpipe[0]);
171                 if (!strcasecmp(encoding, "base64"))
172                         execlp("./base64", "base64", "-d", NULL);
173                 else if (!strcasecmp(encoding, "quoted-printable"))
174                         execlp("./qpdecode", "qpdecode", NULL);
175                 lprintf(5, "ERROR: cannot exec decoder for %s\n", encoding);
176                 exit(1);
177         }
178         close(sendpipe[0]);     /* Close the ends we're not using  */
179         close(recvpipe[1]);
180
181         while ((bytes_sent < length) && (write_error == 0)) {
182                 /* Empty the input pipe FIRST */
183                 while (fstat(recvpipe[0], &statbuf), (statbuf.st_size > 0)) {
184                         blocksize = read(recvpipe[0], &decoded[bytes_recv],
185                                          statbuf.st_size);
186                         if (blocksize < 0)
187                                 lprintf(5, "ERROR: cannot read from pipe\n");
188                         else
189                                 bytes_recv = bytes_recv + blocksize;
190                 }
191                 /* Then put some data into the output pipe */
192                 blocksize = length - bytes_sent;
193                 if (blocksize > 2048)
194                         blocksize = 2048;
195                 if (write(sendpipe[1], &part_start[bytes_sent], blocksize) < 0) {
196                         lprintf(5, "ERROR: cannot write to pipe: %s\n",
197                                 strerror(errno));
198                         write_error = 1;
199                 }
200                 bytes_sent = bytes_sent + blocksize;
201         }
202         close(sendpipe[1]);
203         /* Empty the input pipe */
204         while ((blocksize = read(recvpipe[0], &decoded[bytes_recv], 1)),
205                (blocksize > 0)) {
206                 bytes_recv = bytes_recv + blocksize;
207         }
208
209         if (bytes_recv > 0) if (CallBack != NULL) {
210                 CallBack(name, filename, fixed_partnum(partnum),
211                         disposition, decoded,
212                         content_type, bytes_recv, "binary", userdata);
213         }
214
215         phree(decoded);
216 }
217
218 /*
219  * Break out the components of a multipart message
220  * (This function expects to be fed HEADERS + CONTENT)
221  * Note: NULL can be supplied as content_end; in this case, the message is
222  * considered to have ended when the parser encounters a 0x00 byte.
223  */
224 void the_mime_parser(char *partnum,
225                      char *content_start, char *content_end,
226                      void (*CallBack)
227                       (char *cbname,
228                        char *cbfilename,
229                        char *cbpartnum,
230                        char *cbdisp,
231                        void *cbcontent,
232                        char *cbtype,
233                        size_t cblength,
234                        char *cbencoding,
235                        void *cbuserdata),
236                      void (*PreMultiPartCallBack)
237                       (char *cbname,
238                        char *cbfilename,
239                        char *cbpartnum,
240                        char *cbdisp,
241                        void *cbcontent,
242                        char *cbtype,
243                        size_t cblength,
244                        char *cbencoding,
245                        void *cbuserdata),
246                      void (*PostMultiPartCallBack)
247                       (char *cbname,
248                        char *cbfilename,
249                        char *cbpartnum,
250                        char *cbdisp,
251                        void *cbcontent,
252                        char *cbtype,
253                        size_t cblength,
254                        char *cbencoding,
255                        void *cbuserdata),
256                       void *userdata,
257                       int dont_decode
258 )
259 {
260
261         char *ptr;
262         char *part_start, *part_end;
263         char buf[SIZ];
264         char header[SIZ];
265         char boundary[SIZ];
266         char startary[SIZ];
267         char endary[SIZ];
268         char content_type[SIZ];
269         char encoding[SIZ];
270         char disposition[SIZ];
271         char name[SIZ];
272         char filename[SIZ];
273         int is_multipart;
274         int part_seq = 0;
275         int i;
276         size_t length;
277         char nested_partnum[SIZ];
278
279         lprintf(9, "the_mime_parser() called\n");
280         ptr = content_start;
281         memset(boundary, 0, sizeof boundary);
282         memset(content_type, 0, sizeof content_type);
283         memset(encoding, 0, sizeof encoding);
284         memset(name, 0, sizeof name);
285         memset(filename, 0, sizeof filename);
286         memset(disposition, 0, sizeof disposition);
287
288         /* Learn interesting things from the headers */
289         strcpy(header, "");
290         do {
291                 ptr = memreadline(ptr, buf, sizeof buf);
292                 if (*ptr == 0)
293                         return; /* premature end of message */
294                 if (content_end != NULL)
295                         if (ptr >= content_end)
296                                 return;
297
298                 for (i = 0; i < strlen(buf); ++i)
299                         if (isspace(buf[i]))
300                                 buf[i] = ' ';
301                 if (!isspace(buf[0])) {
302                         if (!strncasecmp(header, "Content-type: ", 14)) {
303                                 strcpy(content_type, &header[14]);
304                                 extract_key(name, content_type, "name");
305                         }
306                         if (!strncasecmp(header, "Content-Disposition: ", 21)) {
307                                 strcpy(disposition, &header[21]);
308                                 extract_key(filename, disposition, "filename");
309                         }
310                         if (!strncasecmp(header,
311                                       "Content-transfer-encoding: ", 27))
312                                 strcpy(encoding, &header[27]);
313                         if (strlen(boundary) == 0)
314                                 extract_key(boundary, header, "boundary");
315                         strcpy(header, "");
316                 }
317                 if ((strlen(header) + strlen(buf) + 2) < sizeof(header))
318                         strcat(header, buf);
319         } while ((strlen(buf) > 0) && (*ptr != 0));
320
321         for (i = 0; i < strlen(disposition); ++i)
322                 if (disposition[i] == ';')
323                         disposition[i] = 0;
324         while (isspace(disposition[0]))
325                 strcpy(disposition, &disposition[1]);
326         for (i = 0; i < strlen(content_type); ++i)
327                 if (content_type[i] == ';')
328                         content_type[i] = 0;
329         while (isspace(content_type[0]))
330                 strcpy(content_type, &content_type[1]);
331
332         if (strlen(boundary) > 0) {
333                 is_multipart = 1;
334         } else {
335                 is_multipart = 0;
336         }
337
338         /* If this is a multipart message, then recursively process it */
339         part_start = NULL;
340         if (is_multipart) {
341
342                 /* Tell the client about this message's multipartedness */
343                 if (PreMultiPartCallBack != NULL) {
344                         PreMultiPartCallBack("", "", partnum, "",
345                                 NULL, content_type,
346                                 0, encoding, userdata);
347                 }
348                 /*
349                 if (CallBack != NULL) {
350                         CallBack("", "", fixed_partnum(partnum),
351                                 "", NULL, content_type,
352                                 0, encoding, userdata);
353                 }
354                  */
355
356                 /* Figure out where the boundaries are */
357                 sprintf(startary, "--%s", boundary);
358                 sprintf(endary, "--%s--", boundary);
359                 do {
360                         part_end = ptr;
361                         ptr = memreadline(ptr, buf, sizeof buf);
362                         if (content_end != NULL)
363                                 if (ptr >= content_end) goto END_MULTI;
364
365                         if ( (!strcasecmp(buf, startary))
366                            || (!strcasecmp(buf, endary)) ) {
367                                 if (part_start != NULL) {
368                                         if (strlen(partnum) > 0) {
369                                                 sprintf(nested_partnum, "%s.%d",
370                                                         partnum, ++part_seq);
371                                         }
372                                         else {
373                                                 sprintf(nested_partnum, "%d",
374                                                         ++part_seq);
375                                         }
376                                         the_mime_parser(nested_partnum,
377                                                     part_start, part_end,
378                                                         CallBack,
379                                                         PreMultiPartCallBack,
380                                                         PostMultiPartCallBack,
381                                                         userdata,
382                                                         dont_decode);
383                                 }
384                                 part_start = ptr;
385                         }
386                 } while ( (strcasecmp(buf, endary)) && (ptr != 0) );
387 END_MULTI:      if (PostMultiPartCallBack != NULL) {
388                         PostMultiPartCallBack("", "", partnum, "", NULL,
389                                 content_type, 0, encoding, userdata);
390                 }
391                 return;
392         }
393
394         /* If it's not a multipart message, then do something with it */
395         if (!is_multipart) {
396                 part_start = ptr;
397                 length = 0;
398                 while ((*ptr != 0)
399                       && ((content_end == NULL) || (ptr < content_end))) {
400                         ++length;
401                         part_end = ptr++;
402                 }
403                 mime_decode(partnum,
404                             part_start, length,
405                             content_type, encoding, disposition,
406                             name, filename,
407                             CallBack, NULL, NULL,
408                             userdata, dont_decode);
409         }
410
411
412 }
413
414
415
416 /*
417  * Entry point for the MIME parser.
418  * (This function expects to be fed HEADERS + CONTENT)
419  * Note: NULL can be supplied as content_end; in this case, the message is
420  * considered to have ended when the parser encounters a 0x00 byte.
421  */
422 void mime_parser(char *content_start,
423                 char *content_end,
424
425                  void (*CallBack)
426                   (char *cbname,
427                    char *cbfilename,
428                    char *cbpartnum,
429                    char *cbdisp,
430                    void *cbcontent,
431                    char *cbtype,
432                    size_t cblength,
433                    char *cbencoding,
434                    void *cbuserdata),
435
436                  void (*PreMultiPartCallBack)
437                   (char *cbname,
438                    char *cbfilename,
439                    char *cbpartnum,
440                    char *cbdisp,
441                    void *cbcontent,
442                    char *cbtype,
443                    size_t cblength,
444                    char *cbencoding,
445                    void *cbuserdata),
446
447                  void (*PostMultiPartCallBack)
448                   (char *cbname,
449                    char *cbfilename,
450                    char *cbpartnum,
451                    char *cbdisp,
452                    void *cbcontent,
453                    char *cbtype,
454                    size_t cblength,
455                    char *cbencoding,
456                    void *cbuserdata),
457
458                   void *userdata,
459                   int dont_decode
460 )
461 {
462
463         lprintf(9, "mime_parser() called\n");
464         the_mime_parser("", content_start, content_end,
465                         CallBack,
466                         PreMultiPartCallBack,
467                         PostMultiPartCallBack,
468                         userdata, dont_decode);
469 }