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, char KeyEnd)
29 char *sptr, *ptr = NULL;
30 int double_quotes = 0;
31 long RealKeyLen = keylen;
37 ptr = bmstrcasestr_len(sptr, sourcelen - (sptr - source),
41 while (isspace(*(ptr + RealKeyLen)))
43 if (*(ptr + RealKeyLen) == KeyEnd)
50 sptr = ptr + RealKeyLen + 1;
60 strcpy(target, (ptr + RealKeyLen));
62 for (ptr=target; (*ptr != 0); ptr++) {
64 /* A semicolon means we've hit the end of the key, unless we're inside double quotes */
65 if ( (double_quotes != 1) && (*ptr == ';')) {
69 /* if we find double quotes, we've got a great set of string boundaries */
72 if (double_quotes == 1) {
85 * For non-multipart messages, we need to generate a quickie partnum of "1"
86 * to return to callback functions. Some callbacks demand it.
88 char *fixed_partnum(char *supplied_partnum) {
89 if (supplied_partnum == NULL) return "1";
90 if (strlen(supplied_partnum)==0) return "1";
91 return supplied_partnum;
95 static inline unsigned int _decode_hex(char *Source)
98 if ((*Source >= '0') && (*Source <= '9')) {
99 ret += (*Source - '0');
101 else if ((*Source >= 'A') && (*Source <= 'F')) {
102 ret += (*Source - 'A' + 10);
104 else if ((*Source >= 'a') && (*Source <= 'f')) {
105 ret += (*Source - 'a' + 10);
113 if ((*(Source + 1) >= '0') && (*(Source + 1) <= '9')) {
114 ret |= (*(Source + 1) - '0');
116 else if ((*(Source + 1) >= 'A') && (*(Source + 1) <= 'F')) {
117 ret |= (*(Source + 1) - 'A' + 10);
119 else if ((*(Source + 1) >= 'a') && (*(Source + 1) <= 'f')) {
120 ret |= (*(Source + 1) - 'a' + 10);
128 unsigned int decode_hex(char *Source) {return _decode_hex(Source);}
131 * Convert "quoted-printable" to binary. Returns number of bytes decoded.
132 * according to RFC2045 section 6.7
134 int CtdlDecodeQuotedPrintable(char *decoded, char *encoded, int sourcelen) {
136 int decoded_length = 0;
139 while (pos < sourcelen)
141 if (!strncmp(&encoded[pos], "=\r\n", 3))
145 else if (!strncmp(&encoded[pos], "=\n", 2))
149 else if (encoded[pos] == '=')
152 ch = _decode_hex(&encoded[pos+1]);
154 decoded[decoded_length++] = ch;
158 decoded[decoded_length++] = encoded[pos];
162 decoded[decoded_length] = 0;
163 return(decoded_length);
168 * Given a message or message-part body and a length, handle any necessary
169 * decoding and pass the request up the stack.
171 void mime_decode(char *partnum,
172 char *part_start, size_t length,
173 char *content_type, char *charset, char *encoding,
176 char *name, char *filename,
189 void (*PreMultiPartCallBack)
201 void (*PostMultiPartCallBack)
219 size_t bytes_decoded = 0;
221 /* Some encodings aren't really encodings */
222 if (!strcasecmp(encoding, "7bit"))
223 strcpy(encoding, "");
224 if (!strcasecmp(encoding, "8bit"))
225 strcpy(encoding, "");
226 if (!strcasecmp(encoding, "binary"))
227 strcpy(encoding, "");
229 /* If this part is not encoded, send as-is */
230 if ( (strlen(encoding) == 0) || (dont_decode)) {
231 if (CallBack != NULL) {
232 CallBack(name, filename, fixed_partnum(partnum),
233 disposition, part_start,
234 content_type, charset, length, encoding, id, userdata);
239 /* Fail silently if we hit an unknown encoding. */
240 if ((strcasecmp(encoding, "base64"))
241 && (strcasecmp(encoding, "quoted-printable"))) {
246 * Allocate a buffer for the decoded data. The output buffer is slightly
247 * larger than the input buffer; this assumes that the decoded data
248 * will never be significantly larger than the encoded data. This is a
249 * safe assumption with base64, uuencode, and quoted-printable.
251 decoded = malloc(length + 32768);
252 if (decoded == NULL) {
256 if (!strcasecmp(encoding, "base64")) {
257 bytes_decoded = CtdlDecodeBase64(decoded, part_start, length);
259 else if (!strcasecmp(encoding, "quoted-printable")) {
260 bytes_decoded = CtdlDecodeQuotedPrintable(decoded, part_start, length);
263 if (bytes_decoded > 0) if (CallBack != NULL) {
264 CallBack(name, filename, fixed_partnum(partnum),
265 disposition, decoded,
266 content_type, charset, bytes_decoded, "binary", id, userdata);
273 * Break out the components of a multipart message
274 * (This function expects to be fed HEADERS + CONTENT)
275 * Note: NULL can be supplied as content_end; in this case, the message is
276 * considered to have ended when the parser encounters a 0x00 byte.
278 void the_mime_parser(char *partnum,
279 char *content_start, char *content_end,
292 void (*PreMultiPartCallBack)
304 void (*PostMultiPartCallBack)
323 char *part_start, *part_end = NULL;
328 size_t startary_len = 0;
333 size_t content_type_len;
334 size_t content_length;
337 size_t disposition_len;
340 char *content_type_name;
341 char *content_disposition_name;
347 char nested_partnum[256];
349 char *evaluate_crlf_ptr = NULL;
356 boundary = malloc(SIZ * 12);
359 startary = boundary + SIZ * 1;
362 endary = boundary + SIZ * 2;
365 header = boundary + SIZ * 3;
368 content_type = boundary + SIZ * 4;
369 *content_type = '\0';
371 charset = boundary + SIZ * 5;
374 encoding = boundary + SIZ * 6;
377 content_type_name = boundary + SIZ * 7;
378 *content_type_name = '\0';
380 content_disposition_name = boundary + SIZ * 8;
381 *content_disposition_name = '\0';
383 filename = boundary + SIZ * 9;
386 disposition = boundary + SIZ * 10;
389 id = boundary + SIZ * 11;
392 /* If the caller didn't supply an endpointer, generate one by measure */
393 if (content_end == NULL) {
394 content_end = &content_start[strlen(content_start)];
397 /* Learn interesting things from the headers */
401 ptr = memreadlinelen(ptr, buf, SIZ, &buflen);
402 if (ptr >= content_end) {
406 for (i = 0; i < buflen; ++i) {
407 if (isspace(buf[i])) {
412 if (!isspace(buf[0])) {
413 if (!strncasecmp(header, "Content-type:", 13)) {
414 memcpy (content_type, &header[13], headerlen - 12);
415 content_type_len = striplt (content_type);
417 extract_key(content_type_name, content_type, content_type_len, HKEY("name"), '=');
418 extract_key(charset, content_type, content_type_len, HKEY("charset"), '=');
419 extract_key(boundary, header, headerlen, HKEY("boundary"), '=');
421 /* Deal with weird headers */
422 if (strchr(content_type, ' '))
423 *(strchr(content_type, ' ')) = '\0';
424 if (strchr(content_type, ';'))
425 *(strchr(content_type, ';')) = '\0';
427 else if (!strncasecmp(header, "Content-Disposition:", 20)) {
428 memcpy (disposition, &header[20], headerlen - 19);
429 disposition_len = striplt(disposition);
430 extract_key(content_disposition_name, disposition, disposition_len, HKEY("name"), '=');
431 extract_key(filename, disposition, disposition_len, HKEY("filename"), '=');
433 else if (!strncasecmp(header, "Content-ID:", 11)) {
434 strcpy(id, &header[11]);
436 stripallbut(id, '<', '>');
438 else if (!strncasecmp(header, "Content-length: ", 15)) {
440 safestrncpy(clbuf, &header[15], sizeof clbuf);
442 content_length = (size_t) atol(clbuf);
444 else if (!strncasecmp(header, "Content-transfer-encoding: ", 26)) {
445 strcpy(encoding, &header[26]);
451 if ((headerlen + buflen + 2) < SIZ) {
452 memcpy(&header[headerlen], buf, buflen);
454 header[headerlen] = '\0';
456 } while ((!IsEmptyStr(buf)) && (*ptr != 0));
458 if (strchr(disposition, ';'))
459 *(strchr(disposition, ';')) = '\0';
460 striplt(disposition);
461 if (strchr(content_type, ';'))
462 *(strchr(content_type, ';')) = '\0';
463 striplt(content_type);
465 if (!IsEmptyStr(boundary)) {
471 /* If this is a multipart message, then recursively process it */
475 /* Tell the client about this message's multipartedness */
476 if (PreMultiPartCallBack != NULL) {
477 PreMultiPartCallBack("", "", partnum, "",
478 NULL, content_type, charset,
479 0, encoding, id, userdata);
482 /* Figure out where the boundaries are */
483 startary_len = snprintf(startary, SIZ, "--%s", boundary);
484 snprintf(endary, SIZ, "--%s--", boundary);
488 next_boundary = NULL;
489 for (srch=ptr; srch<content_end; ++srch) {
490 if (!memcmp(srch, startary, startary_len)) {
491 next_boundary = srch;
496 if ( (part_start != NULL) && (next_boundary != NULL) ) {
497 part_end = next_boundary;
498 --part_end; /* omit the trailing LF */
500 --part_end; /* omit the trailing CR */
503 if (!IsEmptyStr(partnum)) {
504 snprintf(nested_partnum,
505 sizeof nested_partnum,
510 snprintf(nested_partnum,
511 sizeof nested_partnum,
514 the_mime_parser(nested_partnum,
515 part_start, part_end,
517 PreMultiPartCallBack,
518 PostMultiPartCallBack,
523 if (next_boundary != NULL) {
524 /* If we pass out of scope, don't attempt to
525 * read past the end boundary. */
526 if (!strcmp(next_boundary, endary)) {
530 /* Set up for the next part. */
531 part_start = strstr(next_boundary, "\n");
533 /* Determine whether newlines are LF or CRLF */
534 evaluate_crlf_ptr = part_start;
536 if (!memcmp(evaluate_crlf_ptr, "\r\n", 2)) {
543 /* Advance past the LF ... now we're in the next part */
549 /* Invalid end of multipart. Bail out! */
552 } while ( (ptr < content_end) && (next_boundary != NULL) );
554 if (PostMultiPartCallBack != NULL) {
555 PostMultiPartCallBack("", "", partnum, "", NULL,
556 content_type, charset, 0, encoding, id, userdata);
561 /* If it's not a multipart message, then do something with it */
565 while (ptr < content_end) {
569 part_end = content_end;
572 /* The following code will truncate the MIME part to the size
573 * specified by the Content-length: header. We have commented it
574 * out because these headers have a tendency to be wrong.
576 * if ( (content_length > 0) && (length > content_length) ) {
577 * length = content_length;
581 /* Sometimes the "name" field is tacked on to Content-type,
582 * and sometimes it's tacked on to Content-disposition. Use
583 * whichever one we have.
585 if (strlen(content_disposition_name) > strlen(content_type_name)) {
586 name = content_disposition_name;
589 name = content_type_name;
592 /* Ok, we've got a non-multipart part here, so do something with it.
596 content_type, charset, encoding, disposition, id,
598 CallBack, NULL, NULL,
599 userdata, dont_decode
603 * Now if it's an encapsulated message/rfc822 then we have to recurse into it
605 if (!strcasecmp(content_type, "message/rfc822")) {
607 if (PreMultiPartCallBack != NULL) {
608 PreMultiPartCallBack("", "", partnum, "",
609 NULL, content_type, charset,
610 0, encoding, id, userdata);
612 if (CallBack != NULL) {
613 if (strlen(partnum) > 0) {
614 snprintf(nested_partnum,
615 sizeof nested_partnum,
620 snprintf(nested_partnum,
621 sizeof nested_partnum,
624 the_mime_parser(nested_partnum,
625 part_start, part_end,
627 PreMultiPartCallBack,
628 PostMultiPartCallBack,
633 if (PostMultiPartCallBack != NULL) {
634 PostMultiPartCallBack("", "", partnum, "", NULL,
635 content_type, charset, 0, encoding, id, userdata);
643 end_parser: /* free the buffers! end the oppression!! */
650 * Entry point for the MIME parser.
651 * (This function expects to be fed HEADERS + CONTENT)
652 * Note: NULL can be supplied as content_end; in this case, the message is
653 * considered to have ended when the parser encounters a 0x00 byte.
655 void mime_parser(char *content_start,
671 void (*PreMultiPartCallBack)
684 void (*PostMultiPartCallBack)
702 the_mime_parser("", content_start, content_end,
704 PreMultiPartCallBack,
705 PostMultiPartCallBack,
706 userdata, dont_decode);
714 typedef struct _MimeGuess {
718 const char *MimeString;
721 MimeGuess MyMimes [] = {
749 const char *GuessMimeType(const char *data, size_t dlen)
753 while (MyMimes[MimeIndex].PatternLen != 0)
755 if ((MyMimes[MimeIndex].PatternLen +
756 MyMimes[MimeIndex].PatternOffset < dlen) &&
757 strncmp(MyMimes[MimeIndex].Pattern,
758 &data[MyMimes[MimeIndex].PatternOffset],
759 MyMimes[MimeIndex].PatternLen) == 0)
761 return MyMimes[MimeIndex].MimeString;
766 * ok, our simple minded algorythm didn't find anything,
767 * let the big chegger try it, he wil default to application/octet-stream
769 return (xdg_mime_get_mime_type_for_data(data, dlen));
773 const char* GuessMimeByFilename(const char *what, size_t len)
775 /* we know some hardcoded on our own, try them... */
776 if ((len > 3) && !strncasecmp(&what[len - 4], ".gif", 4))
778 else if ((len > 2) && !strncasecmp(&what[len - 3], ".js", 3))
779 return "text/javascript";
780 else if ((len > 3) && !strncasecmp(&what[len - 4], ".txt", 4))
782 else if ((len > 3) && !strncasecmp(&what[len - 4], ".css", 4))
784 else if ((len > 3) && !strncasecmp(&what[len - 4], ".jpg", 4))
786 else if ((len > 3) && !strncasecmp(&what[len - 4], ".png", 4))
788 else if ((len > 3) && !strncasecmp(&what[len - 4], ".ico", 4))
789 return "image/x-icon";
790 else if ((len > 3) && !strncasecmp(&what[len - 4], ".vcf", 4))
791 return "text/x-vcard";
792 else if ((len > 4) && !strncasecmp(&what[len - 5], ".html", 5))
794 else if ((len > 3) && !strncasecmp(&what[len - 4], ".htm", 4))
796 else if ((len > 3) && !strncasecmp(&what[len - 4], ".wml", 4))
797 return "text/vnd.wap.wml";
798 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wmls", 5))
799 return "text/vnd.wap.wmlscript";
800 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wmlc", 5))
801 return "application/vnd.wap.wmlc";
802 else if ((len > 5) && !strncasecmp(&what[len - 6], ".wmlsc", 6))
803 return "application/vnd.wap.wmlscriptc";
804 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wbmp", 5))
805 return "image/vnd.wap.wbmp";
807 /* and let xdgmime do the fallback. */
808 return xdg_mime_get_mime_type_from_file_name(what);
811 static HashList *IconHash = NULL;
813 typedef struct IconName IconName;
820 static void DeleteIcon(void *IconNamePtr)
822 IconName *Icon = (IconName*) IconNamePtr;
823 free(Icon->FlatName);
824 free(Icon->FileName);
829 static const char *PrintFlat(void *IconNamePtr)
831 IconName *Icon = (IconName*) IconNamePtr;
832 return Icon->FlatName;
834 static const char *PrintFile(void *IconNamePtr)
836 IconName *Icon = (IconName*) IconNamePtr;
837 return Icon->FileName;
841 #define GENSTR "x-generic"
842 #define IGNORE_PREFIX_1 "gnome-mime"
843 int LoadIconDir(const char *DirName)
846 struct dirent *filedir_entry;
851 filedir = opendir (DirName);
852 IconHash = NewHash(1, NULL);
853 if (filedir == NULL) {
857 while ((filedir_entry = readdir(filedir)))
861 #ifdef _DIRENT_HAVE_D_NAMELEN
862 d_namelen = filedir_entry->d_namelen;
864 d_namelen = strlen(filedir_entry->d_name);
866 d_without_ext = d_namelen;
867 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
869 if ((d_without_ext == 0) || (d_namelen < 3))
872 if ((sizeof(IGNORE_PREFIX_1) < d_namelen) &&
873 (strncmp(IGNORE_PREFIX_1,
874 filedir_entry->d_name,
875 sizeof(IGNORE_PREFIX_1) - 1) == 0)) {
876 PStart = filedir_entry->d_name + sizeof(IGNORE_PREFIX_1);
877 d_without_ext -= sizeof(IGNORE_PREFIX_1);
880 PStart = filedir_entry->d_name;
882 Icon = malloc(sizeof(IconName));
884 Icon->FileName = malloc(d_namelen + 1);
885 memcpy(Icon->FileName, filedir_entry->d_name, d_namelen + 1);
887 Icon->FlatName = malloc(d_without_ext + 1);
888 memcpy(Icon->FlatName, PStart, d_without_ext);
889 Icon->FlatName[d_without_ext] = '\0';
890 /* Try to find Minor type in image-jpeg */
891 MinorPtr = strchr(Icon->FlatName, '-');
892 if (MinorPtr != NULL) {
894 MinorLen = 1 + d_without_ext - (MinorPtr - Icon->FlatName + 1);
895 if ((MinorLen == sizeof(GENSTR)) &&
896 (strncmp(MinorPtr + 1, GENSTR, sizeof(GENSTR)) == 0)) {
897 /* ok, we found a generic filename. cut the generic. */
899 d_without_ext = d_without_ext - (MinorPtr - Icon->FlatName);
901 else { /* Map the major / minor separator to / */
906 // PrintHash(IconHash, PrintFlat, PrintFile);
907 // printf("%s - %s\n", Icon->FlatName, Icon->FileName);
908 Put(IconHash, Icon->FlatName, d_without_ext, Icon, DeleteIcon);
909 // PrintHash(IconHash, PrintFlat, PrintFile);
915 const char *GetIconFilename(char *MimeType, size_t len)
923 GetHash(IconHash, MimeType, len, &vIcon), Icon = (IconName*) vIcon;
924 /* didn't find the exact mimetype? try major only. */
927 pMinor = strchr(MimeType, '/');
928 if (pMinor != NULL) {
930 GetHash(IconHash, MimeType, pMinor - MimeType, &vIcon),
931 Icon = (IconName*) vIcon;
938 /*printf("Getting: [%s] == [%s] -> [%s]\n", MimeType, Icon->FlatName, Icon->FileName);*/
939 return Icon->FileName;
942 void ShutDownLibCitadelMime(void)
944 DeleteHash(&IconHash);