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)
30 int double_quotes = 0;
32 ptr = bmstrcasestr_len(source, sourcelen, key, keylen);
38 strcpy(target, (ptr + keylen));
40 for (ptr=target; (*ptr != 0); ++ptr) {
42 /* A semicolon means we've hit the end of the key, unless we're inside double quotes */
43 if ( (double_quotes != 1) && (*ptr == ';')) {
47 /* if we find double quotes, we've got a great set of string boundaries */
50 if (double_quotes == 1) {
63 * For non-multipart messages, we need to generate a quickie partnum of "1"
64 * to return to callback functions. Some callbacks demand it.
66 char *fixed_partnum(char *supplied_partnum) {
67 if (supplied_partnum == NULL) return "1";
68 if (strlen(supplied_partnum)==0) return "1";
69 return supplied_partnum;
73 static inline unsigned int _decode_hex(char *Source)
76 if ((*Source >= '0') && (*Source <= '9')) {
77 ret += (*Source - '0');
79 else if ((*Source >= 'A') && (*Source <= 'F')) {
80 ret += (*Source - 'A' + 10);
82 else if ((*Source >= 'a') && (*Source <= 'f')) {
83 ret += (*Source - 'a' + 10);
91 if ((*(Source + 1) >= '0') && (*(Source + 1) <= '9')) {
92 ret |= (*(Source + 1) - '0');
94 else if ((*(Source + 1) >= 'A') && (*(Source + 1) <= 'F')) {
95 ret |= (*(Source + 1) - 'A' + 10);
97 else if ((*(Source + 1) >= 'a') && (*(Source + 1) <= 'f')) {
98 ret |= (*(Source + 1) - 'a' + 10);
106 unsigned int decode_hex(char *Source) {return _decode_hex(Source);}
109 * Convert "quoted-printable" to binary. Returns number of bytes decoded.
110 * according to RFC2045 section 6.7
112 int CtdlDecodeQuotedPrintable(char *decoded, char *encoded, int sourcelen) {
114 int decoded_length = 0;
117 while (pos < sourcelen)
119 if (!strncmp(&encoded[pos], "=\r\n", 3))
123 else if (!strncmp(&encoded[pos], "=\n", 2))
127 else if (encoded[pos] == '=')
130 ch = _decode_hex(&encoded[pos+1]);
132 decoded[decoded_length++] = ch;
136 decoded[decoded_length++] = encoded[pos];
140 decoded[decoded_length] = 0;
141 return(decoded_length);
146 * Given a message or message-part body and a length, handle any necessary
147 * decoding and pass the request up the stack.
149 void mime_decode(char *partnum,
150 char *part_start, size_t length,
151 char *content_type, char *charset, char *encoding,
154 char *name, char *filename,
167 void (*PreMultiPartCallBack)
179 void (*PostMultiPartCallBack)
197 size_t bytes_decoded = 0;
199 /* Some encodings aren't really encodings */
200 if (!strcasecmp(encoding, "7bit"))
201 strcpy(encoding, "");
202 if (!strcasecmp(encoding, "8bit"))
203 strcpy(encoding, "");
204 if (!strcasecmp(encoding, "binary"))
205 strcpy(encoding, "");
207 /* If this part is not encoded, send as-is */
208 if ( (strlen(encoding) == 0) || (dont_decode)) {
209 if (CallBack != NULL) {
210 CallBack(name, filename, fixed_partnum(partnum),
211 disposition, part_start,
212 content_type, charset, length, encoding, id, userdata);
217 /* Fail silently if we hit an unknown encoding. */
218 if ((strcasecmp(encoding, "base64"))
219 && (strcasecmp(encoding, "quoted-printable"))) {
224 * Allocate a buffer for the decoded data. The output buffer is slightly
225 * larger than the input buffer; this assumes that the decoded data
226 * will never be significantly larger than the encoded data. This is a
227 * safe assumption with base64, uuencode, and quoted-printable.
229 decoded = malloc(length + 32768);
230 if (decoded == NULL) {
234 if (!strcasecmp(encoding, "base64")) {
235 bytes_decoded = CtdlDecodeBase64(decoded, part_start, length);
237 else if (!strcasecmp(encoding, "quoted-printable")) {
238 bytes_decoded = CtdlDecodeQuotedPrintable(decoded, part_start, length);
241 if (bytes_decoded > 0) if (CallBack != NULL) {
242 CallBack(name, filename, fixed_partnum(partnum),
243 disposition, decoded,
244 content_type, charset, bytes_decoded, "binary", id, userdata);
251 * Break out the components of a multipart message
252 * (This function expects to be fed HEADERS + CONTENT)
253 * Note: NULL can be supplied as content_end; in this case, the message is
254 * considered to have ended when the parser encounters a 0x00 byte.
256 void the_mime_parser(char *partnum,
257 char *content_start, char *content_end,
270 void (*PreMultiPartCallBack)
282 void (*PostMultiPartCallBack)
301 char *part_start, *part_end = NULL;
306 size_t startary_len = 0;
311 size_t content_type_len;
312 size_t content_length;
315 size_t disposition_len;
318 char *content_type_name;
319 char *content_disposition_name;
325 char nested_partnum[256];
327 char *evaluate_crlf_ptr = NULL;
334 boundary = malloc(SIZ * 12);
337 startary = boundary + SIZ * 1;
340 endary = boundary + SIZ * 2;
343 header = boundary + SIZ * 3;
346 content_type = boundary + SIZ * 4;
347 *content_type = '\0';
349 charset = boundary + SIZ * 5;
352 encoding = boundary + SIZ * 6;
355 content_type_name = boundary + SIZ * 7;
356 *content_type_name = '\0';
358 content_disposition_name = boundary + SIZ * 8;
359 *content_disposition_name = '\0';
361 filename = boundary + SIZ * 9;
364 disposition = boundary + SIZ * 10;
367 id = boundary + SIZ * 11;
370 /* If the caller didn't supply an endpointer, generate one by measure */
371 if (content_end == NULL) {
372 content_end = &content_start[strlen(content_start)];
375 /* Learn interesting things from the headers */
379 ptr = memreadlinelen(ptr, buf, SIZ, &buflen);
380 if (ptr >= content_end) {
384 for (i = 0; i < buflen; ++i) {
385 if (isspace(buf[i])) {
390 if (!isspace(buf[0])) {
391 if (!strncasecmp(header, "Content-type:", 13)) {
392 memcpy (content_type, &header[13], headerlen - 12);
393 content_type_len = striplt (content_type);
395 extract_key(content_type_name, content_type, content_type_len, HKEY("name="));
396 extract_key(charset, content_type, content_type_len, HKEY("charset="));
397 extract_key(boundary, header, headerlen, HKEY("boundary="));
399 /* Deal with weird headers */
400 if (strchr(content_type, ' '))
401 *(strchr(content_type, ' ')) = '\0';
402 if (strchr(content_type, ';'))
403 *(strchr(content_type, ';')) = '\0';
405 else if (!strncasecmp(header, "Content-Disposition:", 20)) {
406 memcpy (disposition, &header[20], headerlen - 19);
407 disposition_len = striplt(disposition);
408 extract_key(content_disposition_name, disposition, disposition_len, HKEY("name="));
409 extract_key(filename, disposition, disposition_len, HKEY("filename="));
411 else if (!strncasecmp(header, "Content-ID:", 11)) {
412 strcpy(id, &header[11]);
414 stripallbut(id, '<', '>');
416 else if (!strncasecmp(header, "Content-length: ", 15)) {
418 safestrncpy(clbuf, &header[15], sizeof clbuf);
420 content_length = (size_t) atol(clbuf);
422 else if (!strncasecmp(header, "Content-transfer-encoding: ", 26)) {
423 strcpy(encoding, &header[26]);
429 if ((headerlen + buflen + 2) < SIZ) {
430 memcpy(&header[headerlen], buf, buflen);
432 header[headerlen] = '\0';
434 } while ((!IsEmptyStr(buf)) && (*ptr != 0));
436 if (strchr(disposition, ';'))
437 *(strchr(disposition, ';')) = '\0';
438 striplt(disposition);
439 if (strchr(content_type, ';'))
440 *(strchr(content_type, ';')) = '\0';
441 striplt(content_type);
443 if (!IsEmptyStr(boundary)) {
449 /* If this is a multipart message, then recursively process it */
453 /* Tell the client about this message's multipartedness */
454 if (PreMultiPartCallBack != NULL) {
455 PreMultiPartCallBack("", "", partnum, "",
456 NULL, content_type, charset,
457 0, encoding, id, userdata);
460 /* Figure out where the boundaries are */
461 startary_len = snprintf(startary, SIZ, "--%s", boundary);
462 snprintf(endary, SIZ, "--%s--", boundary);
466 next_boundary = NULL;
467 for (srch=ptr; srch<content_end; ++srch) {
468 if (!memcmp(srch, startary, startary_len)) {
469 next_boundary = srch;
474 if ( (part_start != NULL) && (next_boundary != NULL) ) {
475 part_end = next_boundary;
476 --part_end; /* omit the trailing LF */
478 --part_end; /* omit the trailing CR */
481 if (!IsEmptyStr(partnum)) {
482 snprintf(nested_partnum,
483 sizeof nested_partnum,
488 snprintf(nested_partnum,
489 sizeof nested_partnum,
492 the_mime_parser(nested_partnum,
493 part_start, part_end,
495 PreMultiPartCallBack,
496 PostMultiPartCallBack,
501 if (next_boundary != NULL) {
502 /* If we pass out of scope, don't attempt to
503 * read past the end boundary. */
504 if (!strcmp(next_boundary, endary)) {
508 /* Set up for the next part. */
509 part_start = strstr(next_boundary, "\n");
511 /* Determine whether newlines are LF or CRLF */
512 evaluate_crlf_ptr = part_start;
514 if (!memcmp(evaluate_crlf_ptr, "\r\n", 2)) {
521 /* Advance past the LF ... now we're in the next part */
527 /* Invalid end of multipart. Bail out! */
530 } while ( (ptr < content_end) && (next_boundary != NULL) );
532 if (PostMultiPartCallBack != NULL) {
533 PostMultiPartCallBack("", "", partnum, "", NULL,
534 content_type, charset, 0, encoding, id, userdata);
539 /* If it's not a multipart message, then do something with it */
543 while (ptr < content_end) {
547 part_end = content_end;
550 /* The following code will truncate the MIME part to the size
551 * specified by the Content-length: header. We have commented it
552 * out because these headers have a tendency to be wrong.
554 * if ( (content_length > 0) && (length > content_length) ) {
555 * length = content_length;
559 /* Sometimes the "name" field is tacked on to Content-type,
560 * and sometimes it's tacked on to Content-disposition. Use
561 * whichever one we have.
563 if (strlen(content_disposition_name) > strlen(content_type_name)) {
564 name = content_disposition_name;
567 name = content_type_name;
570 /* Ok, we've got a non-multipart part here, so do something with it.
574 content_type, charset, encoding, disposition, id,
576 CallBack, NULL, NULL,
577 userdata, dont_decode
581 * Now if it's an encapsulated message/rfc822 then we have to recurse into it
583 if (!strcasecmp(content_type, "message/rfc822")) {
585 if (PreMultiPartCallBack != NULL) {
586 PreMultiPartCallBack("", "", partnum, "",
587 NULL, content_type, charset,
588 0, encoding, id, userdata);
590 if (CallBack != NULL) {
591 if (strlen(partnum) > 0) {
592 snprintf(nested_partnum,
593 sizeof nested_partnum,
598 snprintf(nested_partnum,
599 sizeof nested_partnum,
602 the_mime_parser(nested_partnum,
603 part_start, part_end,
605 PreMultiPartCallBack,
606 PostMultiPartCallBack,
611 if (PostMultiPartCallBack != NULL) {
612 PostMultiPartCallBack("", "", partnum, "", NULL,
613 content_type, charset, 0, encoding, id, userdata);
621 end_parser: /* free the buffers! end the oppression!! */
628 * Entry point for the MIME parser.
629 * (This function expects to be fed HEADERS + CONTENT)
630 * Note: NULL can be supplied as content_end; in this case, the message is
631 * considered to have ended when the parser encounters a 0x00 byte.
633 void mime_parser(char *content_start,
649 void (*PreMultiPartCallBack)
662 void (*PostMultiPartCallBack)
680 the_mime_parser("", content_start, content_end,
682 PreMultiPartCallBack,
683 PostMultiPartCallBack,
684 userdata, dont_decode);
692 typedef struct _MimeGuess {
696 const char *MimeString;
699 MimeGuess MyMimes [] = {
727 const char *GuessMimeType(const char *data, size_t dlen)
731 while (MyMimes[MimeIndex].PatternLen != 0)
733 if ((MyMimes[MimeIndex].PatternLen +
734 MyMimes[MimeIndex].PatternOffset < dlen) &&
735 strncmp(MyMimes[MimeIndex].Pattern,
736 &data[MyMimes[MimeIndex].PatternOffset],
737 MyMimes[MimeIndex].PatternLen) == 0)
739 return MyMimes[MimeIndex].MimeString;
744 * ok, our simple minded algorythm didn't find anything,
745 * let the big chegger try it, he wil default to application/octet-stream
747 return (xdg_mime_get_mime_type_for_data(data, dlen));
751 const char* GuessMimeByFilename(const char *what, size_t len)
753 /* we know some hardcoded on our own, try them... */
754 if ((len > 3) && !strncasecmp(&what[len - 4], ".gif", 4))
756 else if ((len > 2) && !strncasecmp(&what[len - 3], ".js", 3))
757 return "text/javascript";
758 else if ((len > 3) && !strncasecmp(&what[len - 4], ".txt", 4))
760 else if ((len > 3) && !strncasecmp(&what[len - 4], ".css", 4))
762 else if ((len > 3) && !strncasecmp(&what[len - 4], ".jpg", 4))
764 else if ((len > 3) && !strncasecmp(&what[len - 4], ".png", 4))
766 else if ((len > 3) && !strncasecmp(&what[len - 4], ".ico", 4))
767 return "image/x-icon";
768 else if ((len > 3) && !strncasecmp(&what[len - 4], ".vcf", 4))
769 return "text/x-vcard";
770 else if ((len > 4) && !strncasecmp(&what[len - 5], ".html", 5))
772 else if ((len > 3) && !strncasecmp(&what[len - 4], ".htm", 4))
774 else if ((len > 3) && !strncasecmp(&what[len - 4], ".wml", 4))
775 return "text/vnd.wap.wml";
776 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wmls", 5))
777 return "text/vnd.wap.wmlscript";
778 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wmlc", 5))
779 return "application/vnd.wap.wmlc";
780 else if ((len > 5) && !strncasecmp(&what[len - 6], ".wmlsc", 6))
781 return "application/vnd.wap.wmlscriptc";
782 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wbmp", 5))
783 return "image/vnd.wap.wbmp";
785 /* and let xdgmime do the fallback. */
786 return xdg_mime_get_mime_type_from_file_name(what);
789 static HashList *IconHash = NULL;
791 typedef struct IconName IconName;
798 static void DeleteIcon(void *IconNamePtr)
800 IconName *Icon = (IconName*) IconNamePtr;
801 free(Icon->FlatName);
802 free(Icon->FileName);
807 static const char *PrintFlat(void *IconNamePtr)
809 IconName *Icon = (IconName*) IconNamePtr;
810 return Icon->FlatName;
812 static const char *PrintFile(void *IconNamePtr)
814 IconName *Icon = (IconName*) IconNamePtr;
815 return Icon->FileName;
819 #define GENSTR "x-generic"
820 #define IGNORE_PREFIX_1 "gnome-mime"
821 int LoadIconDir(const char *DirName)
824 struct dirent *filedir_entry;
829 filedir = opendir (DirName);
830 IconHash = NewHash(1, NULL);
831 if (filedir == NULL) {
835 while ((filedir_entry = readdir(filedir)))
839 #ifdef _DIRENT_HAVE_D_NAMELEN
840 d_namelen = filedir_entry->d_namelen;
842 d_namelen = strlen(filedir_entry->d_name);
844 d_without_ext = d_namelen;
845 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
847 if ((d_without_ext == 0) || (d_namelen < 3))
850 if ((sizeof(IGNORE_PREFIX_1) < d_namelen) &&
851 (strncmp(IGNORE_PREFIX_1,
852 filedir_entry->d_name,
853 sizeof(IGNORE_PREFIX_1) - 1) == 0)) {
854 PStart = filedir_entry->d_name + sizeof(IGNORE_PREFIX_1);
855 d_without_ext -= sizeof(IGNORE_PREFIX_1);
858 PStart = filedir_entry->d_name;
860 Icon = malloc(sizeof(IconName));
862 Icon->FileName = malloc(d_namelen + 1);
863 memcpy(Icon->FileName, filedir_entry->d_name, d_namelen + 1);
865 Icon->FlatName = malloc(d_without_ext + 1);
866 memcpy(Icon->FlatName, PStart, d_without_ext);
867 Icon->FlatName[d_without_ext] = '\0';
868 /* Try to find Minor type in image-jpeg */
869 MinorPtr = strchr(Icon->FlatName, '-');
870 if (MinorPtr != NULL) {
872 MinorLen = 1 + d_without_ext - (MinorPtr - Icon->FlatName + 1);
873 if ((MinorLen == sizeof(GENSTR)) &&
874 (strncmp(MinorPtr + 1, GENSTR, sizeof(GENSTR)) == 0)) {
875 /* ok, we found a generic filename. cut the generic. */
877 d_without_ext = d_without_ext - (MinorPtr - Icon->FlatName);
879 else { /* Map the major / minor separator to / */
884 // PrintHash(IconHash, PrintFlat, PrintFile);
885 // printf("%s - %s\n", Icon->FlatName, Icon->FileName);
886 Put(IconHash, Icon->FlatName, d_without_ext, Icon, DeleteIcon);
887 // PrintHash(IconHash, PrintFlat, PrintFile);
893 const char *GetIconFilename(char *MimeType, size_t len)
901 GetHash(IconHash, MimeType, len, &vIcon), Icon = (IconName*) vIcon;
902 /* didn't find the exact mimetype? try major only. */
905 pMinor = strchr(MimeType, '/');
906 if (pMinor != NULL) {
908 GetHash(IconHash, MimeType, pMinor - MimeType, &vIcon),
909 Icon = (IconName*) vIcon;
916 /*printf("Getting: [%s] == [%s] -> [%s]\n", MimeType, Icon->FlatName, Icon->FileName);*/
917 return Icon->FileName;
920 void ShutDownLibCitadelMime(void)
922 DeleteHash(&IconHash);