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