4 * This is the MIME parser for Citadel.
6 * Copyright (c) 1998-2007 by the citadel.org development team.
7 * This code is distributed under the GNU General Public License v3.
15 #include <sys/types.h>
19 #include <sys/types.h>
23 #include "xdgmime/xdgmime.h"
24 #include "libcitadel.h"
25 #include "libcitadellocal.h"
27 void extract_key(char *target, char *source, long sourcelen, char *key, long keylen)
31 //char looking_for[256];
32 int double_quotes = 0;
35 //snprintf(looking_for, sizeof looking_for, "%s=", key);
37 while ((lookat != NULL)) {
38 ptr = bmstrcasestr_len(lookat, sourcelen, key, keylen);
41 (*(ptr + keylen) == '='))
46 //ptr = bmstrcasestr(source, looking_for);
51 strcpy(target, (ptr + keylen + 1));
53 for (ptr=target; (*ptr != 0); ++ptr) {
55 /* A semicolon means we've hit the end of the key, unless we're inside double quotes */
56 if ( (double_quotes != 1) && (*ptr == ';')) {
60 /* if we find double quotes, we've got a great set of string boundaries */
63 if (double_quotes == 1) {
76 * For non-multipart messages, we need to generate a quickie partnum of "1"
77 * to return to callback functions. Some callbacks demand it.
79 char *fixed_partnum(char *supplied_partnum) {
80 if (supplied_partnum == NULL) return "1";
81 if (strlen(supplied_partnum)==0) return "1";
82 return supplied_partnum;
86 static inline unsigned int _decode_hex(char *Source)
89 if ((*Source >= '0') && (*Source <= '9')) {
90 ret += (*Source - '0');
92 else if ((*Source >= 'A') && (*Source <= 'F')) {
93 ret += (*Source - 'A' + 10);
95 else if ((*Source >= 'a') && (*Source <= 'f')) {
96 ret += (*Source - 'a' + 10);
104 if ((*(Source + 1) >= '0') && (*(Source + 1) <= '9')) {
105 ret |= (*(Source + 1) - '0');
107 else if ((*(Source + 1) >= 'A') && (*(Source + 1) <= 'F')) {
108 ret |= (*(Source + 1) - 'A' + 10);
110 else if ((*(Source + 1) >= 'a') && (*(Source + 1) <= 'f')) {
111 ret |= (*(Source + 1) - 'a' + 10);
119 unsigned int decode_hex(char *Source) {return _decode_hex(Source);}
122 * Convert "quoted-printable" to binary. Returns number of bytes decoded.
123 * according to RFC2045 section 6.7
125 int CtdlDecodeQuotedPrintable(char *decoded, char *encoded, int sourcelen) {
127 int decoded_length = 0;
130 while (pos < sourcelen)
132 if (!strncmp(&encoded[pos], "=\r\n", 3))
136 else if (!strncmp(&encoded[pos], "=\n", 2))
140 else if (encoded[pos] == '=')
143 ch = _decode_hex(&encoded[pos+1]);
145 decoded[decoded_length++] = ch;
149 decoded[decoded_length++] = encoded[pos];
153 decoded[decoded_length] = 0;
154 return(decoded_length);
159 * Given a message or message-part body and a length, handle any necessary
160 * decoding and pass the request up the stack.
162 void mime_decode(char *partnum,
163 char *part_start, size_t length,
164 char *content_type, char *charset, char *encoding,
167 char *name, char *filename,
180 void (*PreMultiPartCallBack)
192 void (*PostMultiPartCallBack)
210 size_t bytes_decoded = 0;
212 /* Some encodings aren't really encodings */
213 if (!strcasecmp(encoding, "7bit"))
214 strcpy(encoding, "");
215 if (!strcasecmp(encoding, "8bit"))
216 strcpy(encoding, "");
217 if (!strcasecmp(encoding, "binary"))
218 strcpy(encoding, "");
220 /* If this part is not encoded, send as-is */
221 if ( (strlen(encoding) == 0) || (dont_decode)) {
222 if (CallBack != NULL) {
223 CallBack(name, filename, fixed_partnum(partnum),
224 disposition, part_start,
225 content_type, charset, length, encoding, id, userdata);
230 /* Fail silently if we hit an unknown encoding. */
231 if ((strcasecmp(encoding, "base64"))
232 && (strcasecmp(encoding, "quoted-printable"))) {
237 * Allocate a buffer for the decoded data. The output buffer is slightly
238 * larger than the input buffer; this assumes that the decoded data
239 * will never be significantly larger than the encoded data. This is a
240 * safe assumption with base64, uuencode, and quoted-printable.
242 decoded = malloc(length + 32768);
243 if (decoded == NULL) {
247 if (!strcasecmp(encoding, "base64")) {
248 bytes_decoded = CtdlDecodeBase64(decoded, part_start, length);
250 else if (!strcasecmp(encoding, "quoted-printable")) {
251 bytes_decoded = CtdlDecodeQuotedPrintable(decoded, part_start, length);
254 if (bytes_decoded > 0) if (CallBack != NULL) {
255 CallBack(name, filename, fixed_partnum(partnum),
256 disposition, decoded,
257 content_type, charset, bytes_decoded, "binary", id, userdata);
264 * Break out the components of a multipart message
265 * (This function expects to be fed HEADERS + CONTENT)
266 * Note: NULL can be supplied as content_end; in this case, the message is
267 * considered to have ended when the parser encounters a 0x00 byte.
269 void the_mime_parser(char *partnum,
270 char *content_start, char *content_end,
283 void (*PreMultiPartCallBack)
295 void (*PostMultiPartCallBack)
314 char *part_start, *part_end = NULL;
319 size_t startary_len = 0;
324 size_t content_type_len;
325 size_t content_length;
328 size_t disposition_len;
331 char *content_type_name;
332 char *content_disposition_name;
338 char nested_partnum[256];
340 char *evaluate_crlf_ptr = NULL;
347 boundary = malloc(SIZ * 12);
350 startary = boundary + SIZ * 1;
353 endary = boundary + SIZ * 2;
356 header = boundary + SIZ * 3;
359 content_type = boundary + SIZ * 4;
360 *content_type = '\0';
362 charset = boundary + SIZ * 5;
365 encoding = boundary + SIZ * 6;
368 content_type_name = boundary + SIZ * 7;
369 *content_type_name = '\0';
371 content_disposition_name = boundary + SIZ * 8;
372 *content_disposition_name = '\0';
374 filename = boundary + SIZ * 9;
377 disposition = boundary + SIZ * 10;
380 id = boundary + SIZ * 11;
383 /* If the caller didn't supply an endpointer, generate one by measure */
384 if (content_end == NULL) {
385 content_end = &content_start[strlen(content_start)];
388 /* Learn interesting things from the headers */
392 ptr = memreadlinelen(ptr, buf, SIZ, &buflen);
393 if (ptr >= content_end) {
397 for (i = 0; i < buflen; ++i) {
398 if (isspace(buf[i])) {
403 if (!isspace(buf[0])) {
404 if (!strncasecmp(header, "Content-type:", 13)) {
405 memcpy (content_type, &header[13], headerlen - 12);
406 content_type_len = striplt (content_type);
408 extract_key(content_type_name, content_type, content_type_len, HKEY("name"));
409 extract_key(charset, content_type, content_type_len, HKEY("charset"));
410 extract_key(boundary, header, headerlen, HKEY("boundary"));
412 /* Deal with weird headers */
413 if (strchr(content_type, ' '))
414 *(strchr(content_type, ' ')) = '\0';
415 if (strchr(content_type, ';'))
416 *(strchr(content_type, ';')) = '\0';
418 if (!strncasecmp(header, "Content-Disposition:", 20)) {
419 memcpy (disposition, &header[20], headerlen - 19);
420 disposition_len = striplt(disposition);
421 extract_key(content_disposition_name, disposition, disposition_len, HKEY("name"));
422 extract_key(filename, disposition, disposition_len, HKEY("filename"));
424 if (!strncasecmp(header, "Content-ID:", 11)) {
425 strcpy(id, &header[11]);
427 stripallbut(id, '<', '>');
429 if (!strncasecmp(header, "Content-length: ", 15)) {
431 safestrncpy(clbuf, &header[15], sizeof clbuf);
433 content_length = (size_t) atol(clbuf);
435 if (!strncasecmp(header, "Content-transfer-encoding: ", 26)) {
436 strcpy(encoding, &header[26]);
442 if ((headerlen + buflen + 2) < SIZ) {
443 memcpy(&header[headerlen], buf, buflen);
445 header[headerlen] = '\0';
447 } while ((!IsEmptyStr(buf)) && (*ptr != 0));
449 if (strchr(disposition, ';'))
450 *(strchr(disposition, ';')) = '\0';
451 striplt(disposition);
452 if (strchr(content_type, ';'))
453 *(strchr(content_type, ';')) = '\0';
454 striplt(content_type);
456 if (!IsEmptyStr(boundary)) {
462 /* If this is a multipart message, then recursively process it */
466 /* Tell the client about this message's multipartedness */
467 if (PreMultiPartCallBack != NULL) {
468 PreMultiPartCallBack("", "", partnum, "",
469 NULL, content_type, charset,
470 0, encoding, id, userdata);
473 /* Figure out where the boundaries are */
474 startary_len = snprintf(startary, SIZ, "--%s", boundary);
475 snprintf(endary, SIZ, "--%s--", boundary);
479 next_boundary = NULL;
480 for (srch=ptr; srch<content_end; ++srch) {
481 if (!memcmp(srch, startary, startary_len)) {
482 next_boundary = srch;
487 if ( (part_start != NULL) && (next_boundary != NULL) ) {
488 part_end = next_boundary;
489 --part_end; /* omit the trailing LF */
491 --part_end; /* omit the trailing CR */
494 if (!IsEmptyStr(partnum)) {
495 snprintf(nested_partnum,
496 sizeof nested_partnum,
501 snprintf(nested_partnum,
502 sizeof nested_partnum,
505 the_mime_parser(nested_partnum,
506 part_start, part_end,
508 PreMultiPartCallBack,
509 PostMultiPartCallBack,
514 if (next_boundary != NULL) {
515 /* If we pass out of scope, don't attempt to
516 * read past the end boundary. */
517 if (!strcmp(next_boundary, endary)) {
521 /* Set up for the next part. */
522 part_start = strstr(next_boundary, "\n");
524 /* Determine whether newlines are LF or CRLF */
525 evaluate_crlf_ptr = part_start;
527 if (!memcmp(evaluate_crlf_ptr, "\r\n", 2)) {
534 /* Advance past the LF ... now we're in the next part */
540 /* Invalid end of multipart. Bail out! */
543 } while ( (ptr < content_end) && (next_boundary != NULL) );
545 if (PostMultiPartCallBack != NULL) {
546 PostMultiPartCallBack("", "", partnum, "", NULL,
547 content_type, charset, 0, encoding, id, userdata);
552 /* If it's not a multipart message, then do something with it */
556 while (ptr < content_end) {
560 part_end = content_end;
563 /* The following code will truncate the MIME part to the size
564 * specified by the Content-length: header. We have commented it
565 * out because these headers have a tendency to be wrong.
567 * if ( (content_length > 0) && (length > content_length) ) {
568 * length = content_length;
572 /* Sometimes the "name" field is tacked on to Content-type,
573 * and sometimes it's tacked on to Content-disposition. Use
574 * whichever one we have.
576 if (strlen(content_disposition_name) > strlen(content_type_name)) {
577 name = content_disposition_name;
580 name = content_type_name;
583 /* Ok, we've got a non-multipart part here, so do something with it.
587 content_type, charset, encoding, disposition, id,
589 CallBack, NULL, NULL,
590 userdata, dont_decode
594 * Now if it's an encapsulated message/rfc822 then we have to recurse into it
596 if (!strcasecmp(content_type, "message/rfc822")) {
598 if (PreMultiPartCallBack != NULL) {
599 PreMultiPartCallBack("", "", partnum, "",
600 NULL, content_type, charset,
601 0, encoding, id, userdata);
603 if (CallBack != NULL) {
604 if (strlen(partnum) > 0) {
605 snprintf(nested_partnum,
606 sizeof nested_partnum,
611 snprintf(nested_partnum,
612 sizeof nested_partnum,
615 the_mime_parser(nested_partnum,
616 part_start, part_end,
618 PreMultiPartCallBack,
619 PostMultiPartCallBack,
624 if (PostMultiPartCallBack != NULL) {
625 PostMultiPartCallBack("", "", partnum, "", NULL,
626 content_type, charset, 0, encoding, id, userdata);
634 end_parser: /* free the buffers! end the oppression!! */
641 * Entry point for the MIME parser.
642 * (This function expects to be fed HEADERS + CONTENT)
643 * Note: NULL can be supplied as content_end; in this case, the message is
644 * considered to have ended when the parser encounters a 0x00 byte.
646 void mime_parser(char *content_start,
662 void (*PreMultiPartCallBack)
675 void (*PostMultiPartCallBack)
693 the_mime_parser("", content_start, content_end,
695 PreMultiPartCallBack,
696 PostMultiPartCallBack,
697 userdata, dont_decode);
705 typedef struct _MimeGuess {
709 const char *MimeString;
712 MimeGuess MyMimes [] = {
740 const char *GuessMimeType(const char *data, size_t dlen)
744 while (MyMimes[MimeIndex].PatternLen != 0)
746 if ((MyMimes[MimeIndex].PatternLen +
747 MyMimes[MimeIndex].PatternOffset < dlen) &&
748 strncmp(MyMimes[MimeIndex].Pattern,
749 &data[MyMimes[MimeIndex].PatternOffset],
750 MyMimes[MimeIndex].PatternLen) == 0)
752 return MyMimes[MimeIndex].MimeString;
757 * ok, our simple minded algorythm didn't find anything,
758 * let the big chegger try it, he wil default to application/octet-stream
760 return (xdg_mime_get_mime_type_for_data(data, dlen));
764 const char* GuessMimeByFilename(const char *what, size_t len)
766 /* we know some hardcoded on our own, try them... */
767 if ((len > 3) && !strncasecmp(&what[len - 4], ".gif", 4))
769 else if ((len > 2) && !strncasecmp(&what[len - 3], ".js", 3))
770 return "text/javascript";
771 else if ((len > 3) && !strncasecmp(&what[len - 4], ".txt", 4))
773 else if ((len > 3) && !strncasecmp(&what[len - 4], ".css", 4))
775 else if ((len > 3) && !strncasecmp(&what[len - 4], ".jpg", 4))
777 else if ((len > 3) && !strncasecmp(&what[len - 4], ".png", 4))
779 else if ((len > 3) && !strncasecmp(&what[len - 4], ".ico", 4))
780 return "image/x-icon";
781 else if ((len > 3) && !strncasecmp(&what[len - 4], ".vcf", 4))
782 return "text/x-vcard";
783 else if ((len > 4) && !strncasecmp(&what[len - 5], ".html", 5))
785 else if ((len > 3) && !strncasecmp(&what[len - 4], ".htm", 4))
787 else if ((len > 3) && !strncasecmp(&what[len - 4], ".wml", 4))
788 return "text/vnd.wap.wml";
789 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wmls", 5))
790 return "text/vnd.wap.wmlscript";
791 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wmlc", 5))
792 return "application/vnd.wap.wmlc";
793 else if ((len > 5) && !strncasecmp(&what[len - 6], ".wmlsc", 6))
794 return "application/vnd.wap.wmlscriptc";
795 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wbmp", 5))
796 return "image/vnd.wap.wbmp";
798 /* and let xdgmime do the fallback. */
799 return xdg_mime_get_mime_type_from_file_name(what);
802 static HashList *IconHash = NULL;
804 typedef struct IconName IconName;
811 static void DeleteIcon(void *IconNamePtr)
813 IconName *Icon = (IconName*) IconNamePtr;
814 free(Icon->FlatName);
815 free(Icon->FileName);
820 static const char *PrintFlat(void *IconNamePtr)
822 IconName *Icon = (IconName*) IconNamePtr;
823 return Icon->FlatName;
825 static const char *PrintFile(void *IconNamePtr)
827 IconName *Icon = (IconName*) IconNamePtr;
828 return Icon->FileName;
832 #define GENSTR "x-generic"
833 #define IGNORE_PREFIX_1 "gnome-mime"
834 int LoadIconDir(const char *DirName)
837 struct dirent *filedir_entry;
842 filedir = opendir (DirName);
843 IconHash = NewHash(1, NULL);
844 if (filedir == NULL) {
848 while ((filedir_entry = readdir(filedir)))
852 #ifdef _DIRENT_HAVE_D_NAMELEN
853 d_namelen = filedir_entry->d_namelen;
855 d_namelen = strlen(filedir_entry->d_name);
857 d_without_ext = d_namelen;
858 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
860 if ((d_without_ext == 0) || (d_namelen < 3))
863 if ((sizeof(IGNORE_PREFIX_1) < d_namelen) &&
864 (strncmp(IGNORE_PREFIX_1,
865 filedir_entry->d_name,
866 sizeof(IGNORE_PREFIX_1) - 1) == 0)) {
867 PStart = filedir_entry->d_name + sizeof(IGNORE_PREFIX_1);
868 d_without_ext -= sizeof(IGNORE_PREFIX_1);
871 PStart = filedir_entry->d_name;
873 Icon = malloc(sizeof(IconName));
875 Icon->FileName = malloc(d_namelen + 1);
876 memcpy(Icon->FileName, filedir_entry->d_name, d_namelen + 1);
878 Icon->FlatName = malloc(d_without_ext + 1);
879 memcpy(Icon->FlatName, PStart, d_without_ext);
880 Icon->FlatName[d_without_ext] = '\0';
881 /* Try to find Minor type in image-jpeg */
882 MinorPtr = strchr(Icon->FlatName, '-');
883 if (MinorPtr != NULL) {
885 MinorLen = 1 + d_without_ext - (MinorPtr - Icon->FlatName + 1);
886 if ((MinorLen == sizeof(GENSTR)) &&
887 (strncmp(MinorPtr + 1, GENSTR, sizeof(GENSTR)) == 0)) {
888 /* ok, we found a generic filename. cut the generic. */
890 d_without_ext = d_without_ext - (MinorPtr - Icon->FlatName);
892 else { /* Map the major / minor separator to / */
897 // PrintHash(IconHash, PrintFlat, PrintFile);
898 // printf("%s - %s\n", Icon->FlatName, Icon->FileName);
899 Put(IconHash, Icon->FlatName, d_without_ext, Icon, DeleteIcon);
900 // PrintHash(IconHash, PrintFlat, PrintFile);
906 const char *GetIconFilename(char *MimeType, size_t len)
914 GetHash(IconHash, MimeType, len, &vIcon), Icon = (IconName*) vIcon;
915 /* didn't find the exact mimetype? try major only. */
918 pMinor = strchr(MimeType, '/');
919 if (pMinor != NULL) {
921 GetHash(IconHash, MimeType, pMinor - MimeType, &vIcon),
922 Icon = (IconName*) vIcon;
929 /*printf("Getting: [%s] == [%s] -> [%s]\n", MimeType, Icon->FlatName, Icon->FileName);*/
930 return Icon->FileName;
933 void ShutDownLibCitadelMime(void)
935 DeleteHash(&IconHash);