11f2a27cfb9b3a1938ea7dd87a8742e5ef4fc99a
[citadel.git] / libcitadel / lib / mime_parser.c
1 /*
2  * This is the MIME parser for Citadel.
3  *
4  * Copyright (c) 1998-2010 by the citadel.org development team.
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  */
20
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <stdio.h>
24 #include <signal.h>
25 #include <sys/types.h>
26 #include <ctype.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <dirent.h>
31 #include <errno.h>
32
33 #include "xdgmime/xdgmime.h"
34 #include "libcitadel.h"
35 #include "libcitadellocal.h"
36
37 const unsigned char FromHexTable [256] = {
38         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //  0
39         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 10
40         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 20
41         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 30
42         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01, // 40
43         0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, // 50
44         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, // 60
45         0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 70
46         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 80
47         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, // 90
48         0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //100
49         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //110
50         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //120
51         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //130
52         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //140
53         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //150
54         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //160
55         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //170
56         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //180
57         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //190
58         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //200
59         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //210
60         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //220
61         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //230
62         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, //240
63         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF                          //250
64 };
65
66
67 long extract_key(char *target, char *source, long sourcelen, char *key, long keylen, char KeyEnd)
68 {
69         char *sptr, *ptr = NULL;
70         int double_quotes = 0;
71         long RealKeyLen = keylen;
72
73         sptr = source;
74
75         while (sptr != NULL)
76         {
77                 ptr = bmstrcasestr_len(sptr, sourcelen - (sptr - source), 
78                                        key, keylen);
79                 if(ptr != NULL)
80                 {
81                         while (isspace(*(ptr + RealKeyLen)))
82                                 RealKeyLen ++;
83                         if (*(ptr + RealKeyLen) == KeyEnd)
84                         {
85                                 sptr = NULL;
86                                 RealKeyLen ++;                          
87                         }
88                         else
89                         {
90                                 sptr = ptr + RealKeyLen + 1;
91                         }
92                 }
93                 else 
94                         sptr = ptr;
95         }
96         if (ptr == NULL) {
97                 *target = '\0';
98                 return 0;
99         }
100         strcpy(target, (ptr + RealKeyLen));
101
102         for (ptr=target; (*ptr != 0); ptr++) {
103
104                 /* A semicolon means we've hit the end of the key, unless we're inside double quotes */
105                 if ( (double_quotes != 1) && (*ptr == ';')) {
106                         *ptr = 0;
107                 }
108
109                 /* if we find double quotes, we've got a great set of string boundaries */
110                 if (*ptr == '\"') {
111                         ++double_quotes;
112                         if (double_quotes == 1) {
113                                 strcpy(ptr, ptr+1);
114                         }
115                         else {
116                                 *ptr = 0;
117                         }
118                 }
119         }
120         *ptr = '\0';
121         return ptr - target;
122 }
123
124
125 /*
126  * For non-multipart messages, we need to generate a quickie partnum of "1"
127  * to return to callback functions.  Some callbacks demand it.
128  */
129 char *fixed_partnum(char *supplied_partnum) {
130         if (supplied_partnum == NULL) return "1";
131         if (strlen(supplied_partnum)==0) return "1";
132         return supplied_partnum;
133 }
134
135
136 static inline unsigned int _decode_hex(const char *Source)
137 {
138         int ret = '?';
139         unsigned char LO_NIBBLE;
140         unsigned char HI_NIBBLE;
141
142         HI_NIBBLE = FromHexTable[(unsigned char) *Source];
143         LO_NIBBLE = FromHexTable[(unsigned char) *(Source+1)];
144         
145         if ((LO_NIBBLE == 0xFF) || (LO_NIBBLE == 0xFF))
146                 return ret;
147         ret = HI_NIBBLE;
148         ret = ret << 4;
149         ret = ret | LO_NIBBLE;
150         return ret;
151 }
152
153 unsigned int decode_hex(char *Source) {return _decode_hex(Source);}
154
155 /*
156  * Convert "quoted-printable" to binary.  Returns number of bytes decoded.
157  * according to RFC2045 section 6.7
158  */
159 int CtdlDecodeQuotedPrintable(char *decoded, char *encoded, int sourcelen) {
160         unsigned int ch;
161         int decoded_length = 0;
162         int pos = 0;
163
164         while (pos < sourcelen)
165         {
166                 if (*(encoded + pos) == '=')
167                 {
168                         pos ++;
169                         if (*(encoded + pos) == '\n')
170                         {
171                                 pos ++;
172                         }
173                         else if (*(encoded + pos) == '\r')
174                         {
175                                 pos ++;
176                                 if (*(encoded + pos) == '\n')
177                                         pos++;
178                         }
179                         else
180                         {
181                                 ch = 0;
182                                 ch = _decode_hex(&encoded[pos]);
183                                 pos += 2;
184                                 decoded[decoded_length++] = ch;
185                         }
186                 }
187                 else
188                 {
189                         decoded[decoded_length++] = encoded[pos];
190                         pos += 1;
191                 }
192         }
193         decoded[decoded_length] = 0;
194         return(decoded_length);
195 }
196
197
198 /*
199  * Given a message or message-part body and a length, handle any necessary
200  * decoding and pass the request up the stack.
201  */
202 void mime_decode(char *partnum,
203                  char *part_start, size_t length,
204                  char *content_type, char *charset, char *encoding,
205                  char *disposition,
206                  char *id,
207                  char *name, char *filename,
208                  MimeParserCallBackType CallBack,
209                  MimeParserCallBackType PreMultiPartCallBack,
210                  MimeParserCallBackType PostMultiPartCallBack,
211                  void *userdata,
212                  int dont_decode)
213 {
214
215         char *decoded;
216         size_t bytes_decoded = 0;
217
218         /* Some encodings aren't really encodings */
219         if (!strcasecmp(encoding, "7bit"))
220                 strcpy(encoding, "");
221         if (!strcasecmp(encoding, "8bit"))
222                 strcpy(encoding, "");
223         if (!strcasecmp(encoding, "binary"))
224                 strcpy(encoding, "");
225         if (!strcasecmp(encoding, "ISO-8859-1"))
226                 strcpy(encoding, "");
227
228         /* If this part is not encoded, send as-is */
229         if ( (strlen(encoding) == 0) || (dont_decode)) {
230                 if (CallBack != NULL) {
231                         CallBack(name, 
232                                  filename, 
233                                  fixed_partnum(partnum),
234                                  disposition, 
235                                  part_start,
236                                  content_type, 
237                                  charset, 
238                                  length, 
239                                  encoding, 
240                                  id,
241                                  userdata);
242                         }
243                 return;
244         }
245         
246         /* Fail silently if we hit an unknown encoding. */
247         if ((strcasecmp(encoding, "base64"))
248             && (strcasecmp(encoding, "quoted-printable"))) {
249                 return;
250         }
251
252         /*
253          * Allocate a buffer for the decoded data.  The output buffer is slightly
254          * larger than the input buffer; this assumes that the decoded data
255          * will never be significantly larger than the encoded data.  This is a
256          * safe assumption with base64, uuencode, and quoted-printable.
257          */
258         decoded = malloc(length + 32768);
259         if (decoded == NULL) {
260                 return;
261         }
262
263         if (!strcasecmp(encoding, "base64")) {
264                 bytes_decoded = CtdlDecodeBase64(decoded, part_start, length);
265         }
266         else if (!strcasecmp(encoding, "quoted-printable")) {
267                 bytes_decoded = CtdlDecodeQuotedPrintable(decoded, part_start, length);
268         }
269
270         if (bytes_decoded > 0) if (CallBack != NULL) {
271                         char encoding_buf[SIZ];
272
273                         strcpy(encoding_buf, "binary");
274                         CallBack(name, 
275                                  filename, 
276                                  fixed_partnum(partnum),
277                                  disposition, 
278                                  decoded,
279                                  content_type, 
280                                  charset, 
281                                  bytes_decoded, 
282                                  encoding_buf, 
283                                  id, 
284                                  userdata);
285         }
286
287         free(decoded);
288 }
289
290 /*
291  * this is the extract of mime_decode which can be called if 'dont_decode' was set; 
292  * to save the cpu intense process of decoding to the time when it realy wants the content. 
293  * returns: 
294  *   - > 0 we decoded something, its on *decoded, you need to free it.
295  *   - = 0 no need to decode stuff. *decoded will be NULL.
296  *   - < 0 an error occured, either an unknown encoding, or alloc failed. no need to free.
297  */
298 int mime_decode_now (char *part_start, 
299                      size_t length,
300                      char *encoding,
301                      char **decoded,
302                      size_t *bytes_decoded)
303 {
304         *bytes_decoded = 0;
305         *decoded = NULL;
306         /* Some encodings aren't really encodings */
307         if (!strcasecmp(encoding, "7bit"))
308                 strcpy(encoding, "");
309         if (!strcasecmp(encoding, "8bit"))
310                 strcpy(encoding, "");
311         if (!strcasecmp(encoding, "binary"))
312                 strcpy(encoding, "");
313
314         /* If this part is not encoded, send as-is */
315         if (strlen(encoding) == 0) {
316                 return 0;
317         }
318         
319
320         /* Fail if we hit an unknown encoding. */
321         if ((strcasecmp(encoding, "base64"))
322             && (strcasecmp(encoding, "quoted-printable"))) {
323                 return -1;
324         }
325
326         /*
327          * Allocate a buffer for the decoded data.  The output buffer is slightly
328          * larger than the input buffer; this assumes that the decoded data
329          * will never be significantly larger than the encoded data.  This is a
330          * safe assumption with base64, uuencode, and quoted-printable.
331          */
332         *decoded = malloc(length + 32768);
333         if (decoded == NULL) {
334                 return -1;
335         }
336
337         if (!strcasecmp(encoding, "base64")) {
338                 *bytes_decoded = CtdlDecodeBase64(*decoded, part_start, length);
339                 return 1;
340         }
341         else if (!strcasecmp(encoding, "quoted-printable")) {
342                 *bytes_decoded = CtdlDecodeQuotedPrintable(*decoded, part_start, length);
343                 return 1;
344         }
345         return -1;
346 }
347
348 typedef enum _eIntMimeHdrs {
349         boundary,
350         startary,
351         endary,
352         content_type,
353         charset,
354         encoding,
355         content_type_name,
356         content_disposition_name,
357         filename,
358         disposition,
359         id,
360         eMax /* don't move ! */
361 } eIntMimeHdrs;
362
363 typedef struct _CBufStr {
364         char Key[SIZ];
365         long len;
366 }CBufStr;
367
368 typedef struct _interesting_mime_headers {
369         CBufStr b[eMax];
370         long content_length;
371         long is_multipart;
372 } interesting_mime_headers;
373
374
375 static void FlushInterestingMimes(interesting_mime_headers *m)
376 {
377         int i;
378         
379         for (i = 0; i < eMax; i++) {
380              m->b[i].Key[0] = '\0';
381              m->b[i].len = 0;
382         }
383         m->content_length = -1;
384 }
385 static interesting_mime_headers *InitInterestingMimes(void)
386 {
387         interesting_mime_headers *m;
388         m = (interesting_mime_headers*) malloc( sizeof(interesting_mime_headers));
389
390         FlushInterestingMimes(m);
391
392         return m;
393 }
394
395
396 static long parse_MimeHeaders(interesting_mime_headers *m, 
397                               char** pcontent_start, 
398                               char *content_end)
399 {
400         char buf[SIZ];
401         char header[SIZ];
402         long headerlen;
403         char *ptr, *pch;
404         int buflen = 0;
405         int i;
406
407         /* Learn interesting things from the headers */
408         ptr = *pcontent_start;
409         *header = '\0';
410         headerlen = 0;
411         do {
412                 ptr = memreadlinelen(ptr, buf, SIZ, &buflen);
413
414                 for (i = 0; i < buflen; ++i) {
415                         if (isspace(buf[i])) {
416                                 buf[i] = ' ';
417                         }
418                 }
419
420                 if (!isspace(buf[0]) && (headerlen > 0)) {
421                         if (!strncasecmp(header, "Content-type:", 13)) {
422                                 memcpy (m->b[content_type].Key, &header[13], headerlen - 12);
423                                 m->b[content_type].Key[headerlen - 12] = '\0';
424                                 m->b[content_type].len = striplt (m->b[content_type].Key);
425
426                                 m->b[content_type_name].len = extract_key(m->b[content_type_name].Key, CKEY(m->b[content_type]), HKEY("name"), '=');
427                                 m->b[charset].len           = extract_key(m->b[charset].Key,           CKEY(m->b[content_type]), HKEY("charset"), '=');
428                                 m->b[boundary].len          = extract_key(m->b[boundary].Key,          header,       headerlen,  HKEY("boundary"), '=');
429
430                                 /* Deal with weird headers */
431                                 pch = strchr(m->b[content_type].Key, ' ');
432                                 if (pch != NULL) {
433                                         *pch = '\0';
434                                         m->b[content_type].len = m->b[content_type].Key - pch;
435                                 }
436                                 pch = strchr(m->b[content_type].Key, ';');
437                                 if (pch != NULL) {
438                                         *pch = '\0';
439                                         m->b[content_type].len = m->b[content_type].Key - pch;
440                                 }
441                         }
442                         else if (!strncasecmp(header, "Content-Disposition:", 20)) {
443                                 memcpy (m->b[disposition].Key, &header[20], headerlen - 19);
444                                 m->b[disposition].Key[headerlen - 19] = '\0';
445                                 m->b[disposition].len = striplt(m->b[disposition].Key);
446
447                                 m->b[content_disposition_name].len = extract_key(m->b[content_disposition_name].Key, CKEY(m->b[disposition]), HKEY("name"), '=');
448                                 m->b[filename].len                 = extract_key(m->b[filename].Key,                 CKEY(m->b[disposition]), HKEY("filename"), '=');
449                                 pch = strchr(m->b[disposition].Key, ';');
450                                 if (pch != NULL) *pch = '\0';
451                                 m->b[disposition].len = striplt(m->b[disposition].Key);
452                         }
453                         else if (!strncasecmp(header, "Content-ID:", 11)) {
454                                 memcpy(m->b[id].Key, &header[11], headerlen - 11);
455                                 m->b[id].Key[headerlen - 11] = '\0';
456                                 striplt(m->b[id].Key);
457                                 m->b[id].len = stripallbut(m->b[id].Key, '<', '>');
458                         }
459                         else if (!strncasecmp(header, "Content-length: ", 15)) {
460                                 char *clbuf;
461                                 clbuf = &header[15];
462                                 while (isspace(*clbuf))
463                                         clbuf ++;
464                                 m->content_length = (size_t) atol(clbuf);
465                         }
466                         else if (!strncasecmp(header, "Content-transfer-encoding: ", 26)) {
467                                 memcpy(m->b[encoding].Key, &header[26], headerlen - 26);
468                                 m->b[encoding].Key[headerlen - 26] = '\0';
469                                 m->b[encoding].len = striplt(m->b[encoding].Key);
470                         }
471                         *header = '\0';
472                         headerlen = 0;
473                 }
474                 if ((headerlen + buflen + 2) < SIZ) {
475                         memcpy(&header[headerlen], buf, buflen);
476                         headerlen += buflen;
477                         header[headerlen] = '\0';
478                 }
479                 if (ptr >= content_end) {
480                         return -1;
481                 }
482         } while ((!IsEmptyStr(buf)) && (*ptr != 0));
483
484         m->is_multipart = m->b[boundary].len != 0;
485         *pcontent_start = ptr;
486
487         return 0;
488 }
489
490
491 static int IsAsciiEncoding(interesting_mime_headers *m)
492 {
493
494         if ((m->b[encoding].len != 0) &&
495             (strcasecmp(m->b[encoding].Key, "base64") == 0))
496                 return 1;
497         if ((m->b[encoding].len != 0) &&
498             (strcmp(m->b[encoding].Key, "quoted-printable") == 0))
499                 return 1;
500
501         return 0;
502 }
503
504 static char *FindNextContent(char *ptr,
505                              char *content_end,
506                              interesting_mime_headers *SubMimeHeaders,
507                              interesting_mime_headers *m)
508 {
509         char *next_boundary;
510         char  tmp;
511
512         if (IsAsciiEncoding(SubMimeHeaders)) {
513                 tmp = *content_end;
514                 *content_end = '\0';
515
516                 /** 
517                  * ok, if we have a content length of the mime part, 
518                  * try skipping the content on the search for the next
519                  * boundary. since we don't trust the content_length
520                  * to be all accurate, and suspect it to lose one digit 
521                  * per line with a line length of 80 chars, we need 
522                  * to start searching a little before..
523                  */
524                                    
525                 if ((SubMimeHeaders->content_length != -1) &&
526                     (SubMimeHeaders->content_length > 10))
527                 {
528                         char *pptr;
529                         long lines;
530                                         
531                         lines = SubMimeHeaders->content_length / 80;
532                         pptr = ptr + SubMimeHeaders->content_length - lines - 10;
533                         if (pptr < content_end)
534                                 ptr = pptr;
535                 }
536                         
537                 next_boundary = strstr(ptr, m->b[startary].Key);
538                 *content_end = tmp;
539         }
540         else {
541                 char *srch;
542                 /** 
543                  * ok, if we have a content length of the mime part, 
544                  * try skipping the content on the search for the next
545                  * boundary. since we don't trust the content_length
546                  * to be all accurate, start searching a little before..
547                  */
548                                    
549                 if ((SubMimeHeaders->content_length != -1) &&
550                     (SubMimeHeaders->content_length > 10))
551                 {
552                         char *pptr;
553                         pptr = ptr + SubMimeHeaders->content_length - 10;
554                         if (pptr < content_end)
555                                 ptr = pptr;
556                 }
557                 
558
559                 srch = next_boundary = NULL;
560                 for (srch = memchr(ptr, '-',  content_end - ptr);
561                      (srch != NULL) && (srch < content_end); 
562                      srch = memchr(srch, '-',  content_end - srch)) 
563                 {
564                         if (!memcmp(srch, 
565                                     m->b[startary].Key, 
566                                     m->b[startary].len)) 
567                         {
568                                 next_boundary = srch;
569                                 srch = content_end;
570                         }
571                         else srch ++;
572
573                 }
574
575         }
576         return next_boundary;
577 }
578
579 /*
580  * Break out the components of a multipart message
581  * (This function expects to be fed HEADERS + CONTENT)
582  * Note: NULL can be supplied as content_end; in this case, the message is
583  * considered to have ended when the parser encounters a 0x00 byte.
584  */
585 static void recurseable_mime_parser(char *partnum,
586                                     char *content_start, char *content_end,
587                                     MimeParserCallBackType CallBack,
588                                     MimeParserCallBackType PreMultiPartCallBack,
589                                     MimeParserCallBackType PostMultiPartCallBack,
590                                     void *userdata,
591                                     int dont_decode, 
592                                     interesting_mime_headers *m)
593 {
594         interesting_mime_headers *SubMimeHeaders;
595         char     *ptr;
596         char     *part_start;
597         char     *part_end = NULL;
598         char     *evaluate_crlf_ptr = NULL;
599         char     *next_boundary;
600         char      nested_partnum[256];
601         int       crlf_in_use = 0;
602         int       part_seq = 0;
603         CBufStr  *chosen_name;
604
605
606         /* If this is a multipart message, then recursively process it */
607         ptr = content_start;
608         part_start = NULL;
609         if (m->is_multipart) {
610
611                 /* Tell the client about this message's multipartedness */
612                 if (PreMultiPartCallBack != NULL) {
613                         PreMultiPartCallBack("", 
614                                              "", 
615                                              partnum, 
616                                              "",
617                                              NULL, 
618                                              m->b[content_type].Key, 
619                                              m->b[charset].Key,
620                                              0, 
621                                              m->b[encoding].Key, 
622                                              m->b[id].Key, 
623                                              userdata);
624                 }
625
626                 /* Figure out where the boundaries are */
627                 m->b[startary].len = snprintf(m->b[startary].Key, SIZ, "--%s", m->b[boundary].Key);
628                 SubMimeHeaders = InitInterestingMimes ();
629
630                 while ((*ptr == '\r') || (*ptr == '\n')) ptr ++;
631
632                 if (strncmp(ptr, m->b[startary].Key, m->b[startary].len) == 0)
633                         ptr += m->b[startary].len;
634
635                 while ((*ptr == '\r') || (*ptr == '\n')) ptr ++;
636
637                 part_start = NULL;
638                 do {
639                         char *optr;
640
641                         optr = ptr;
642                         if (parse_MimeHeaders(SubMimeHeaders, &ptr, content_end) != 0)
643                                 break;
644                         if ((ptr - optr > 2) && 
645                             (*(ptr - 2) == '\r'))
646                                 crlf_in_use = 1;
647                         
648                         part_start = ptr;
649                         
650                         next_boundary = FindNextContent(ptr,
651                                                         content_end,
652                                                         SubMimeHeaders,
653                                                         m);
654                         if ((next_boundary != NULL) && 
655                             (next_boundary - part_start < 3)) {
656                                 FlushInterestingMimes(SubMimeHeaders);
657
658                                 continue;
659                         }
660
661                         if ( (part_start != NULL) && (next_boundary != NULL) ) {
662                                 part_end = next_boundary;
663                                 --part_end;             /* omit the trailing LF */
664                                 if (crlf_in_use) {
665                                         --part_end;     /* omit the trailing CR */
666                                 }
667
668                                 if (!IsEmptyStr(partnum)) {
669                                         snprintf(nested_partnum,
670                                                  sizeof nested_partnum,
671                                                  "%s.%d", partnum,
672                                                  ++part_seq);
673                                 }
674                                 else {
675                                         snprintf(nested_partnum,
676                                                  sizeof nested_partnum,
677                                                  "%d", ++part_seq);
678                                 }
679                                 recurseable_mime_parser(nested_partnum,
680                                                         part_start, 
681                                                         part_end,
682                                                         CallBack,
683                                                         PreMultiPartCallBack,
684                                                         PostMultiPartCallBack,
685                                                         userdata,
686                                                         dont_decode, 
687                                                         SubMimeHeaders);
688                         }
689
690                         if (next_boundary != NULL) {
691                                 /* If we pass out of scope, don't attempt to
692                                  * read past the end boundary. */
693                                 if ((*(next_boundary + m->b[startary].len) == '-') && 
694                                     (*(next_boundary + m->b[startary].len + 1) == '-') ){
695                                         ptr = content_end;
696                                 }
697                                 else {
698                                         /* Set up for the next part. */
699                                         part_start = strstr(next_boundary, "\n");
700                                         
701                                         /* Determine whether newlines are LF or CRLF */
702                                         evaluate_crlf_ptr = part_start;
703                                         --evaluate_crlf_ptr;
704                                         if ((*evaluate_crlf_ptr == '\r') && 
705                                             (*(evaluate_crlf_ptr + 1) == '\n'))
706                                         {
707                                                 crlf_in_use = 1;
708                                         }
709                                         else {
710                                                 crlf_in_use = 0;
711                                         }
712
713                                         /* Advance past the LF ... now we're in the next part */
714                                         ++part_start;
715                                         ptr = part_start;
716                                 }
717                         }
718                         else {
719                                 /* Invalid end of multipart.  Bail out! */
720                                 ptr = content_end;
721                         }
722                         FlushInterestingMimes(SubMimeHeaders);
723                 } while ( (ptr < content_end) && (next_boundary != NULL) );
724
725                 free(SubMimeHeaders);
726
727                 if (PostMultiPartCallBack != NULL) {
728                         PostMultiPartCallBack("", 
729                                               "", 
730                                               partnum, 
731                                               "", 
732                                               NULL,
733                                               m->b[content_type].Key, 
734                                               m->b[charset].Key,
735                                               0, 
736                                               m->b[encoding].Key, 
737                                               m->b[id].Key, 
738                                               userdata);
739                 }
740         } /* If it's not a multipart message, then do something with it */
741         else {
742                 size_t length;
743                 part_start = ptr;
744                 length = content_end - part_start;
745                 ptr = part_end = content_end;
746
747
748                 /* The following code will truncate the MIME part to the size
749                  * specified by the Content-length: header.   We have commented it
750                  * out because these headers have a tendency to be wrong.
751                  *
752                  *      if ( (content_length > 0) && (length > content_length) ) {
753                  *              length = content_length;
754                  *      }
755                  */
756
757                 /* Sometimes the "name" field is tacked on to Content-type,
758                  * and sometimes it's tacked on to Content-disposition.  Use
759                  * whichever one we have.
760                  */
761                 if (m->b[content_disposition_name].len > m->b[content_type_name].len) {
762                         chosen_name = &m->b[content_disposition_name];
763                 }
764                 else {
765                         chosen_name = &m->b[content_type_name];
766                 }
767         
768                 /* Ok, we've got a non-multipart part here, so do something with it.
769                  */
770                 mime_decode(partnum,
771                             part_start, 
772                             length,
773                             m->b[content_type].Key, 
774                             m->b[charset].Key,
775                             m->b[encoding].Key, 
776                             m->b[disposition].Key, 
777                             m->b[id].Key, 
778                             chosen_name->Key, 
779                             m->b[filename].Key,
780                             CallBack, 
781                             NULL, NULL,
782                             userdata, 
783                             dont_decode
784                         );
785
786                 /*
787                  * Now if it's an encapsulated message/rfc822 then we have to recurse into it
788                  */
789                 if (!strcasecmp(&m->b[content_type].Key[0], "message/rfc822")) {
790
791                         if (PreMultiPartCallBack != NULL) {
792                                 PreMultiPartCallBack("", 
793                                                      "", 
794                                                      partnum, 
795                                                      "",
796                                                      NULL, 
797                                                      m->b[content_type].Key, 
798                                                      m->b[charset].Key,
799                                                      0, 
800                                                      m->b[encoding].Key, 
801                                                      m->b[id].Key, 
802                                                      userdata);
803                         }
804                         if (CallBack != NULL) {
805                                 if (strlen(partnum) > 0) {
806                                         snprintf(nested_partnum,
807                                                  sizeof nested_partnum,
808                                                  "%s.%d", partnum,
809                                                  ++part_seq);
810                                 }
811                                 else {
812                                         snprintf(nested_partnum,
813                                                  sizeof nested_partnum,
814                                                  "%d", ++part_seq);
815                                 }
816                                 the_mime_parser(nested_partnum,
817                                                 part_start, 
818                                                 part_end,
819                                                 CallBack,
820                                                 PreMultiPartCallBack,
821                                                 PostMultiPartCallBack,
822                                                 userdata,
823                                                 dont_decode
824                                         );
825                         }
826                         if (PostMultiPartCallBack != NULL) {
827                                 PostMultiPartCallBack("", 
828                                                       "", 
829                                                       partnum, 
830                                                       "", 
831                                                       NULL,
832                                                       m->b[content_type].Key, 
833                                                       m->b[charset].Key,
834                                                       0, 
835                                                       m->b[encoding].Key, 
836                                                       m->b[id].Key, 
837                                                       userdata);
838                         }
839
840
841                 }
842
843         }
844
845 }
846
847 /*
848  * Break out the components of a multipart message
849  * (This function expects to be fed HEADERS + CONTENT)
850  * Note: NULL can be supplied as content_end; in this case, the message is
851  * considered to have ended when the parser encounters a 0x00 byte.
852  */
853 void the_mime_parser(char *partnum,
854                      char *content_start, char *content_end,
855                      MimeParserCallBackType CallBack,
856                      MimeParserCallBackType PreMultiPartCallBack,
857                      MimeParserCallBackType PostMultiPartCallBack,
858                      void *userdata,
859                      int dont_decode)
860 {
861         interesting_mime_headers *m;
862
863         /* If the caller didn't supply an endpointer, generate one by measure */
864         if (content_end == NULL) {
865                 content_end = &content_start[strlen(content_start)];
866         }
867
868         m = InitInterestingMimes();
869
870         if (!parse_MimeHeaders(m, &content_start, content_end))
871         {
872
873                 recurseable_mime_parser(partnum,
874                                         content_start, content_end,
875                                         CallBack,
876                                         PreMultiPartCallBack,
877                                         PostMultiPartCallBack,
878                                         userdata,
879                                         dont_decode,
880                                         m);
881         }
882         free(m);
883 }
884
885 /*
886  * Entry point for the MIME parser.
887  * (This function expects to be fed HEADERS + CONTENT)
888  * Note: NULL can be supplied as content_end; in this case, the message is
889  * considered to have ended when the parser encounters a 0x00 byte.
890  */
891 void mime_parser(char *content_start,
892                  char *content_end,
893                  MimeParserCallBackType CallBack,
894                  MimeParserCallBackType PreMultiPartCallBack,
895                  MimeParserCallBackType PostMultiPartCallBack,
896                  void *userdata,
897                  int dont_decode)
898 {
899
900         the_mime_parser("", content_start, content_end,
901                         CallBack,
902                         PreMultiPartCallBack,
903                         PostMultiPartCallBack,
904                         userdata, dont_decode);
905 }
906
907
908
909
910
911
912 typedef struct _MimeGuess {
913         const char *Pattern;
914         size_t PatternLen;
915         long PatternOffset;
916         const char *MimeString;
917 } MimeGuess;
918
919 MimeGuess MyMimes [] = {
920         {
921                 "GIF",
922                 3,
923                 0,
924                 "image/gif"
925         },
926         {
927                 "\xff\xd8",
928                 2,
929                 0,
930                 "image/jpeg"
931         },
932         {
933                 "\x89PNG",
934                 4,
935                 0,
936                 "image/png"
937         },
938         { // last...
939                 "",
940                 0,
941                 0,
942                 ""
943         }
944 };
945
946
947 const char *GuessMimeType(const char *data, size_t dlen)
948 {
949         int MimeIndex = 0;
950
951         while (MyMimes[MimeIndex].PatternLen != 0)
952         {
953                 if ((MyMimes[MimeIndex].PatternLen + 
954                      MyMimes[MimeIndex].PatternOffset < dlen) &&
955                     strncmp(MyMimes[MimeIndex].Pattern, 
956                             &data[MyMimes[MimeIndex].PatternOffset], 
957                             MyMimes[MimeIndex].PatternLen) == 0)
958                 {
959                         return MyMimes[MimeIndex].MimeString;
960                 }
961                 MimeIndex ++;
962         }
963         /* 
964          * ok, our simple minded algorythm didn't find anything, 
965          * let the big chegger try it, he wil default to application/octet-stream
966          */
967         return (xdg_mime_get_mime_type_for_data(data, dlen));
968 }
969
970
971 const char* GuessMimeByFilename(const char *what, size_t len)
972 {
973         /* we know some hardcoded on our own, try them... */
974         if ((len > 3) && !strncasecmp(&what[len - 4], ".gif", 4))
975                 return "image/gif";
976         else if ((len > 2) && !strncasecmp(&what[len - 3], ".js", 3))
977                 return  "text/javascript";
978         else if ((len > 3) && !strncasecmp(&what[len - 4], ".txt", 4))
979                 return "text/plain";
980         else if ((len > 3) && !strncasecmp(&what[len - 4], ".css", 4))
981                 return "text/css";
982         else if ((len > 3) && !strncasecmp(&what[len - 4], ".htc", 4))
983                 return "text/x-component";
984         else if ((len > 3) && !strncasecmp(&what[len - 4], ".jpg", 4))
985                 return "image/jpeg";
986         else if ((len > 3) && !strncasecmp(&what[len - 4], ".png", 4))
987                 return "image/png";
988         else if ((len > 3) && !strncasecmp(&what[len - 4], ".ico", 4))
989                 return "image/x-icon";
990         else if ((len > 3) && !strncasecmp(&what[len - 4], ".vcf", 4))
991                 return "text/x-vcard";
992         else if ((len > 4) && !strncasecmp(&what[len - 5], ".html", 5))
993                 return "text/html";
994         else if ((len > 3) && !strncasecmp(&what[len - 4], ".htm", 4))
995                 return "text/html";
996         else if ((len > 3) && !strncasecmp(&what[len - 4], ".wml", 4))
997                 return "text/vnd.wap.wml";
998         else if ((len > 4) && !strncasecmp(&what[len - 5], ".wmls", 5))
999                 return "text/vnd.wap.wmlscript";
1000         else if ((len > 4) && !strncasecmp(&what[len - 5], ".wmlc", 5))
1001                 return "application/vnd.wap.wmlc";
1002         else if ((len > 5) && !strncasecmp(&what[len - 6], ".wmlsc", 6))
1003                 return "application/vnd.wap.wmlscriptc";
1004         else if ((len > 4) && !strncasecmp(&what[len - 5], ".wbmp", 5))
1005                 return "image/vnd.wap.wbmp";
1006         else
1007                 /* and let xdgmime do the fallback. */
1008                 return xdg_mime_get_mime_type_from_file_name(what);
1009 }
1010
1011 static HashList *IconHash = NULL;
1012
1013 typedef struct IconName IconName;
1014
1015 struct IconName {
1016         char *FlatName;
1017         char *FileName;
1018 };
1019
1020 static void DeleteIcon(void *IconNamePtr)
1021 {
1022         IconName *Icon = (IconName*) IconNamePtr;
1023         free(Icon->FlatName);
1024         free(Icon->FileName);
1025         free(Icon);
1026 }
1027
1028 /*
1029 static const char *PrintFlat(void *IconNamePtr)
1030 {
1031         IconName *Icon = (IconName*) IconNamePtr;
1032         return Icon->FlatName;
1033 }
1034 static const char *PrintFile(void *IconNamePtr)
1035 {
1036         IconName *Icon = (IconName*) IconNamePtr;
1037         return Icon->FileName;
1038 }
1039 */
1040
1041 #define GENSTR "x-generic"
1042 #define IGNORE_PREFIX_1 "gnome-mime"
1043 int LoadIconDir(const char *DirName)
1044 {
1045         DIR *filedir = NULL;
1046         struct dirent *filedir_entry;
1047         int d_namelen;
1048         int d_without_ext;
1049         IconName *Icon;
1050
1051         filedir = opendir (DirName);
1052         IconHash = NewHash(1, NULL);
1053         if (filedir == NULL) {
1054                 return 0;
1055         }
1056
1057         while ((filedir_entry = readdir(filedir)))
1058         {
1059                 char *MinorPtr;
1060                 char *PStart;
1061 #ifdef _DIRENT_HAVE_D_NAMELEN
1062                 d_namelen = filedir_entry->d_namelen;
1063 #else
1064                 d_namelen = strlen(filedir_entry->d_name);
1065 #endif
1066                 d_without_ext = d_namelen;
1067                 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
1068                         d_without_ext --;
1069                 if ((d_without_ext == 0) || (d_namelen < 3))
1070                         continue;
1071
1072                 if ((sizeof(IGNORE_PREFIX_1) < d_namelen) &&
1073                     (strncmp(IGNORE_PREFIX_1, 
1074                              filedir_entry->d_name, 
1075                              sizeof(IGNORE_PREFIX_1) - 1) == 0)) {
1076                         PStart = filedir_entry->d_name + sizeof(IGNORE_PREFIX_1);
1077                         d_without_ext -= sizeof(IGNORE_PREFIX_1);
1078                 }
1079                 else {
1080                         PStart = filedir_entry->d_name;
1081                 }
1082                 Icon = malloc(sizeof(IconName));
1083
1084                 Icon->FileName = malloc(d_namelen + 1);
1085                 memcpy(Icon->FileName, filedir_entry->d_name, d_namelen + 1);
1086
1087                 Icon->FlatName = malloc(d_without_ext + 1);
1088                 memcpy(Icon->FlatName, PStart, d_without_ext);
1089                 Icon->FlatName[d_without_ext] = '\0';
1090                 /* Try to find Minor type in image-jpeg */
1091                 MinorPtr = strchr(Icon->FlatName, '-');
1092                 if (MinorPtr != NULL) {
1093                         size_t MinorLen;
1094                         MinorLen = 1 + d_without_ext - (MinorPtr - Icon->FlatName + 1);
1095                         if ((MinorLen == sizeof(GENSTR)) && 
1096                             (strncmp(MinorPtr + 1, GENSTR, sizeof(GENSTR)) == 0)) {
1097                                 /* ok, we found a generic filename. cut the generic. */
1098                                 *MinorPtr = '\0';
1099                                 d_without_ext = d_without_ext - (MinorPtr - Icon->FlatName);
1100                         }
1101                         else { /* Map the major / minor separator to / */
1102                                 *MinorPtr = '/';
1103                         }
1104                 }
1105
1106 //              PrintHash(IconHash, PrintFlat, PrintFile);
1107 //              printf("%s - %s\n", Icon->FlatName, Icon->FileName);
1108                 Put(IconHash, Icon->FlatName, d_without_ext, Icon, DeleteIcon);
1109 //              PrintHash(IconHash, PrintFlat, PrintFile);
1110         }
1111         closedir(filedir);
1112         return 1;
1113 }
1114
1115 const char *GetIconFilename(char *MimeType, size_t len)
1116 {
1117         void *vIcon;
1118         IconName *Icon;
1119         
1120         if(IconHash == NULL)
1121                 return NULL;
1122
1123         GetHash(IconHash, MimeType, len, &vIcon), Icon = (IconName*) vIcon;
1124         /* didn't find the exact mimetype? try major only. */
1125         if (Icon == NULL) {
1126                 char * pMinor;
1127                 pMinor = strchr(MimeType, '/');
1128                 if (pMinor != NULL) {
1129                         *pMinor = '\0';
1130                         GetHash(IconHash, MimeType, pMinor - MimeType, &vIcon),
1131                                 Icon = (IconName*) vIcon;
1132                 }
1133         }
1134         if (Icon == NULL) {
1135                 return NULL;
1136         }
1137
1138         /*printf("Getting: [%s] == [%s] -> [%s]\n", MimeType, Icon->FlatName, Icon->FileName);*/
1139         return Icon->FileName;
1140 }
1141
1142 void ShutDownLibCitadelMime(void)
1143 {
1144         DeleteHash(&IconHash);
1145 }