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, char *key)
30 char looking_for[256];
31 int double_quotes = 0;
33 snprintf(looking_for, sizeof looking_for, "%s=", key);
35 ptr = bmstrcasestr(source, looking_for);
40 strcpy(target, (ptr + strlen(looking_for)));
42 for (ptr=target; (*ptr != 0); ++ptr) {
44 /* A semicolon means we've hit the end of the key, unless we're inside double quotes */
45 if ( (double_quotes != 1) && (*ptr == ';')) {
49 /* if we find double quotes, we've got a great set of string boundaries */
52 if (double_quotes == 1) {
64 * For non-multipart messages, we need to generate a quickie partnum of "1"
65 * to return to callback functions. Some callbacks demand it.
67 char *fixed_partnum(char *supplied_partnum) {
68 if (supplied_partnum == NULL) return "1";
69 if (strlen(supplied_partnum)==0) return "1";
70 return supplied_partnum;
74 inline unsigned int decode_hex(char *Source)
78 ret += (*Source - '0');
81 ret += (*Source - 'A' + 10);
84 if (*(Source + 1) < 'A') {
85 ret += (*(Source + 1) - '0');
88 ret += (*(Source + 1) - 'A' + 10);
96 * Convert "quoted-printable" to binary. Returns number of bytes decoded.
97 * according to RFC2045 section 6.7
99 int CtdlDecodeQuotedPrintable(char *decoded, char *encoded, int sourcelen) {
101 int decoded_length = 0;
104 while (pos < sourcelen)
106 if (!strncmp(&encoded[pos], "=\r\n", 3))
110 else if (!strncmp(&encoded[pos], "=\n", 2))
114 else if (encoded[pos] == '=')
117 ch = decode_hex(&encoded[pos+1]);
119 decoded[decoded_length++] = ch;
123 decoded[decoded_length++] = encoded[pos];
127 decoded[decoded_length] = 0;
128 return(decoded_length);
133 * Given a message or message-part body and a length, handle any necessary
134 * decoding and pass the request up the stack.
136 void mime_decode(char *partnum,
137 char *part_start, size_t length,
138 char *content_type, char *charset, char *encoding,
141 char *name, char *filename,
154 void (*PreMultiPartCallBack)
166 void (*PostMultiPartCallBack)
184 size_t bytes_decoded = 0;
186 /* Some encodings aren't really encodings */
187 if (!strcasecmp(encoding, "7bit"))
188 strcpy(encoding, "");
189 if (!strcasecmp(encoding, "8bit"))
190 strcpy(encoding, "");
191 if (!strcasecmp(encoding, "binary"))
192 strcpy(encoding, "");
194 /* If this part is not encoded, send as-is */
195 if ( (strlen(encoding) == 0) || (dont_decode)) {
196 if (CallBack != NULL) {
197 CallBack(name, filename, fixed_partnum(partnum),
198 disposition, part_start,
199 content_type, charset, length, encoding, id, userdata);
204 /* Fail silently if we hit an unknown encoding. */
205 if ((strcasecmp(encoding, "base64"))
206 && (strcasecmp(encoding, "quoted-printable"))) {
211 * Allocate a buffer for the decoded data. The output buffer is slightly
212 * larger than the input buffer; this assumes that the decoded data
213 * will never be significantly larger than the encoded data. This is a
214 * safe assumption with base64, uuencode, and quoted-printable.
216 decoded = malloc(length + 32768);
217 if (decoded == NULL) {
221 if (!strcasecmp(encoding, "base64")) {
222 bytes_decoded = CtdlDecodeBase64(decoded, part_start, length);
224 else if (!strcasecmp(encoding, "quoted-printable")) {
225 bytes_decoded = CtdlDecodeQuotedPrintable(decoded, part_start, length);
228 if (bytes_decoded > 0) if (CallBack != NULL) {
229 CallBack(name, filename, fixed_partnum(partnum),
230 disposition, decoded,
231 content_type, charset, bytes_decoded, "binary", id, userdata);
238 * Break out the components of a multipart message
239 * (This function expects to be fed HEADERS + CONTENT)
240 * Note: NULL can be supplied as content_end; in this case, the message is
241 * considered to have ended when the parser encounters a 0x00 byte.
243 void the_mime_parser(char *partnum,
244 char *content_start, char *content_end,
257 void (*PreMultiPartCallBack)
269 void (*PostMultiPartCallBack)
288 char *part_start, *part_end = NULL;
293 size_t startary_len = 0;
298 size_t content_length;
303 char *content_type_name;
304 char *content_disposition_name;
310 char nested_partnum[256];
312 char *evaluate_crlf_ptr = NULL;
319 boundary = malloc(SIZ);
320 memset(boundary, 0, SIZ);
322 startary = malloc(SIZ);
323 memset(startary, 0, SIZ);
325 endary = malloc(SIZ);
326 memset(endary, 0, SIZ);
328 header = malloc(SIZ);
329 memset(header, 0, SIZ);
331 content_type = malloc(SIZ);
332 memset(content_type, 0, SIZ);
334 charset = malloc(SIZ);
335 memset(charset, 0, SIZ);
337 encoding = malloc(SIZ);
338 memset(encoding, 0, SIZ);
340 content_type_name = malloc(SIZ);
341 memset(content_type_name, 0, SIZ);
343 content_disposition_name = malloc(SIZ);
344 memset(content_disposition_name, 0, SIZ);
346 filename = malloc(SIZ);
347 memset(filename, 0, SIZ);
349 disposition = malloc(SIZ);
350 memset(disposition, 0, SIZ);
355 /* If the caller didn't supply an endpointer, generate one by measure */
356 if (content_end == NULL) {
357 content_end = &content_start[strlen(content_start)];
360 /* Learn interesting things from the headers */
364 ptr = memreadlinelen(ptr, buf, SIZ, &buflen);
365 if (ptr >= content_end) {
369 for (i = 0; i < buflen; ++i) {
370 if (isspace(buf[i])) {
375 if (!isspace(buf[0])) {
376 if (!strncasecmp(header, "Content-type:", 13)) {
377 strcpy(content_type, &header[13]);
378 striplt(content_type);
379 extract_key(content_type_name, content_type, "name");
380 extract_key(charset, content_type, "charset");
381 extract_key(boundary, header, "boundary");
382 /* Deal with weird headers */
383 if (strchr(content_type, ' '))
384 *(strchr(content_type, ' ')) = '\0';
385 if (strchr(content_type, ';'))
386 *(strchr(content_type, ';')) = '\0';
388 if (!strncasecmp(header, "Content-Disposition:", 20)) {
389 strcpy(disposition, &header[20]);
390 striplt(disposition);
391 extract_key(content_disposition_name, disposition, "name");
392 extract_key(filename, disposition, "filename");
394 if (!strncasecmp(header, "Content-ID:", 11)) {
395 strcpy(id, &header[11]);
397 stripallbut(id, '<', '>');
399 if (!strncasecmp(header, "Content-length: ", 15)) {
401 safestrncpy(clbuf, &header[15], sizeof clbuf);
403 content_length = (size_t) atol(clbuf);
405 if (!strncasecmp(header, "Content-transfer-encoding: ", 26)) {
406 strcpy(encoding, &header[26]);
412 if ((headerlen + buflen + 2) < SIZ) {
413 memcpy(&header[headerlen], buf, buflen);
415 header[headerlen] = '\0';
417 } while ((!IsEmptyStr(buf)) && (*ptr != 0));
419 if (strchr(disposition, ';'))
420 *(strchr(disposition, ';')) = '\0';
421 striplt(disposition);
422 if (strchr(content_type, ';'))
423 *(strchr(content_type, ';')) = '\0';
424 striplt(content_type);
426 if (!IsEmptyStr(boundary)) {
432 /* If this is a multipart message, then recursively process it */
436 /* Tell the client about this message's multipartedness */
437 if (PreMultiPartCallBack != NULL) {
438 PreMultiPartCallBack("", "", partnum, "",
439 NULL, content_type, charset,
440 0, encoding, id, userdata);
443 /* Figure out where the boundaries are */
444 snprintf(startary, SIZ, "--%s", boundary);
445 snprintf(endary, SIZ, "--%s--", boundary);
446 startary_len = strlen(startary);
450 next_boundary = NULL;
451 for (srch=ptr; srch<content_end; ++srch) {
452 if (!memcmp(srch, startary, startary_len)) {
453 next_boundary = srch;
458 if ( (part_start != NULL) && (next_boundary != NULL) ) {
459 part_end = next_boundary;
460 --part_end; /* omit the trailing LF */
462 --part_end; /* omit the trailing CR */
465 if (!IsEmptyStr(partnum)) {
466 snprintf(nested_partnum,
467 sizeof nested_partnum,
472 snprintf(nested_partnum,
473 sizeof nested_partnum,
476 the_mime_parser(nested_partnum,
477 part_start, part_end,
479 PreMultiPartCallBack,
480 PostMultiPartCallBack,
485 if (next_boundary != NULL) {
486 /* If we pass out of scope, don't attempt to
487 * read past the end boundary. */
488 if (!strcmp(next_boundary, endary)) {
492 /* Set up for the next part. */
493 part_start = strstr(next_boundary, "\n");
495 /* Determine whether newlines are LF or CRLF */
496 evaluate_crlf_ptr = part_start;
498 if (!memcmp(evaluate_crlf_ptr, "\r\n", 2)) {
505 /* Advance past the LF ... now we're in the next part */
511 /* Invalid end of multipart. Bail out! */
514 } while ( (ptr < content_end) && (next_boundary != NULL) );
516 if (PostMultiPartCallBack != NULL) {
517 PostMultiPartCallBack("", "", partnum, "", NULL,
518 content_type, charset, 0, encoding, id, userdata);
523 /* If it's not a multipart message, then do something with it */
527 while (ptr < content_end) {
531 part_end = content_end;
534 /* The following code will truncate the MIME part to the size
535 * specified by the Content-length: header. We have commented it
536 * out because these headers have a tendency to be wrong.
538 * if ( (content_length > 0) && (length > content_length) ) {
539 * length = content_length;
543 /* Sometimes the "name" field is tacked on to Content-type,
544 * and sometimes it's tacked on to Content-disposition. Use
545 * whichever one we have.
547 if (strlen(content_disposition_name) > strlen(content_type_name)) {
548 name = content_disposition_name;
551 name = content_type_name;
554 /* Ok, we've got a non-multipart part here, so do something with it.
558 content_type, charset, encoding, disposition, id,
560 CallBack, NULL, NULL,
561 userdata, dont_decode
565 * Now if it's an encapsulated message/rfc822 then we have to recurse into it
567 if (!strcasecmp(content_type, "message/rfc822")) {
569 if (PreMultiPartCallBack != NULL) {
570 PreMultiPartCallBack("", "", partnum, "",
571 NULL, content_type, charset,
572 0, encoding, id, userdata);
574 if (CallBack != NULL) {
575 if (strlen(partnum) > 0) {
576 snprintf(nested_partnum,
577 sizeof nested_partnum,
582 snprintf(nested_partnum,
583 sizeof nested_partnum,
586 the_mime_parser(nested_partnum,
587 part_start, part_end,
589 PreMultiPartCallBack,
590 PostMultiPartCallBack,
595 if (PostMultiPartCallBack != NULL) {
596 PostMultiPartCallBack("", "", partnum, "", NULL,
597 content_type, charset, 0, encoding, id, userdata);
605 end_parser: /* free the buffers! end the oppression!! */
613 free(content_type_name);
614 free(content_disposition_name);
623 * Entry point for the MIME parser.
624 * (This function expects to be fed HEADERS + CONTENT)
625 * Note: NULL can be supplied as content_end; in this case, the message is
626 * considered to have ended when the parser encounters a 0x00 byte.
628 void mime_parser(char *content_start,
644 void (*PreMultiPartCallBack)
657 void (*PostMultiPartCallBack)
675 the_mime_parser("", content_start, content_end,
677 PreMultiPartCallBack,
678 PostMultiPartCallBack,
679 userdata, dont_decode);
687 typedef struct _MimeGuess {
691 const char *MimeString;
694 MimeGuess MyMimes [] = {
722 const char *GuessMimeType(const char *data, size_t dlen)
726 while (MyMimes[MimeIndex].PatternLen != 0)
728 if ((MyMimes[MimeIndex].PatternLen +
729 MyMimes[MimeIndex].PatternOffset < dlen) &&
730 strncmp(MyMimes[MimeIndex].Pattern,
731 &data[MyMimes[MimeIndex].PatternOffset],
732 MyMimes[MimeIndex].PatternLen) == 0)
734 return MyMimes[MimeIndex].MimeString;
739 * ok, our simple minded algorythm didn't find anything,
740 * let the big chegger try it, he wil default to application/octet-stream
742 return (xdg_mime_get_mime_type_for_data(data, dlen));
746 const char* GuessMimeByFilename(const char *what, size_t len)
748 /* we know some hardcoded on our own, try them... */
749 if ((len > 3) && !strncasecmp(&what[len - 4], ".gif", 4))
751 else if ((len > 2) && !strncasecmp(&what[len - 3], ".js", 3))
752 return "text/javascript";
753 else if ((len > 3) && !strncasecmp(&what[len - 4], ".txt", 4))
755 else if ((len > 3) && !strncasecmp(&what[len - 4], ".css", 4))
757 else if ((len > 3) && !strncasecmp(&what[len - 4], ".jpg", 4))
759 else if ((len > 3) && !strncasecmp(&what[len - 4], ".png", 4))
761 else if ((len > 3) && !strncasecmp(&what[len - 4], ".ico", 4))
762 return "image/x-icon";
763 else if ((len > 3) && !strncasecmp(&what[len - 4], ".vcf", 4))
764 return "text/x-vcard";
765 else if ((len > 4) && !strncasecmp(&what[len - 5], ".html", 5))
767 else if ((len > 3) && !strncasecmp(&what[len - 4], ".htm", 4))
769 else if ((len > 3) && !strncasecmp(&what[len - 4], ".wml", 4))
770 return "text/vnd.wap.wml";
771 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wmls", 5))
772 return "text/vnd.wap.wmlscript";
773 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wmlc", 5))
774 return "application/vnd.wap.wmlc";
775 else if ((len > 5) && !strncasecmp(&what[len - 6], ".wmlsc", 6))
776 return "application/vnd.wap.wmlscriptc";
777 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wbmp", 5))
778 return "image/vnd.wap.wbmp";
780 /* and let xdgmime do the fallback. */
781 return xdg_mime_get_mime_type_from_file_name(what);
784 static HashList *IconHash = NULL;
786 typedef struct IconName IconName;
793 static void DeleteIcon(void *IconNamePtr)
795 IconName *Icon = (IconName*) IconNamePtr;
796 free(Icon->FlatName);
797 free(Icon->FileName);
802 static const char *PrintFlat(void *IconNamePtr)
804 IconName *Icon = (IconName*) IconNamePtr;
805 return Icon->FlatName;
807 static const char *PrintFile(void *IconNamePtr)
809 IconName *Icon = (IconName*) IconNamePtr;
810 return Icon->FileName;
814 #define GENSTR "x-generic"
815 #define IGNORE_PREFIX_1 "gnome-mime"
816 int LoadIconDir(const char *DirName)
819 struct dirent *filedir_entry;
824 filedir = opendir (DirName);
825 IconHash = NewHash(1, NULL);
826 if (filedir == NULL) {
830 while ((filedir_entry = readdir(filedir)))
834 #ifdef _DIRENT_HAVE_D_NAMELEN
835 d_namelen = filedir_entry->d_namelen;
837 d_namelen = strlen(filedir_entry->d_name);
839 d_without_ext = d_namelen;
840 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
842 if ((d_without_ext == 0) || (d_namelen < 3))
845 if ((sizeof(IGNORE_PREFIX_1) < d_namelen) &&
846 (strncmp(IGNORE_PREFIX_1,
847 filedir_entry->d_name,
848 sizeof(IGNORE_PREFIX_1) - 1) == 0)) {
849 PStart = filedir_entry->d_name + sizeof(IGNORE_PREFIX_1);
850 d_without_ext -= sizeof(IGNORE_PREFIX_1);
853 PStart = filedir_entry->d_name;
855 Icon = malloc(sizeof(IconName));
857 Icon->FileName = malloc(d_namelen + 1);
858 memcpy(Icon->FileName, filedir_entry->d_name, d_namelen + 1);
860 Icon->FlatName = malloc(d_without_ext + 1);
861 memcpy(Icon->FlatName, PStart, d_without_ext);
862 Icon->FlatName[d_without_ext] = '\0';
863 /* Try to find Minor type in image-jpeg */
864 MinorPtr = strchr(Icon->FlatName, '-');
865 if (MinorPtr != NULL) {
867 MinorLen = 1 + d_without_ext - (MinorPtr - Icon->FlatName + 1);
868 if ((MinorLen == sizeof(GENSTR)) &&
869 (strncmp(MinorPtr + 1, GENSTR, sizeof(GENSTR)) == 0)) {
870 /* ok, we found a generic filename. cut the generic. */
872 d_without_ext = d_without_ext - (MinorPtr - Icon->FlatName);
874 else { /* Map the major / minor separator to / */
879 // PrintHash(IconHash, PrintFlat, PrintFile);
880 // printf("%s - %s\n", Icon->FlatName, Icon->FileName);
881 Put(IconHash, Icon->FlatName, d_without_ext, Icon, DeleteIcon);
882 // PrintHash(IconHash, PrintFlat, PrintFile);
888 const char *GetIconFilename(char *MimeType, size_t len)
896 GetHash(IconHash, MimeType, len, &vIcon), Icon = (IconName*) vIcon;
897 /* didn't find the exact mimetype? try major only. */
900 pMinor = strchr(MimeType, '/');
901 if (pMinor != NULL) {
903 GetHash(IconHash, MimeType, pMinor - MimeType, &vIcon),
904 Icon = (IconName*) vIcon;
911 /*printf("Getting: [%s] == [%s] -> [%s]\n", MimeType, Icon->FlatName, Icon->FileName);*/
912 return Icon->FileName;
915 void ShutDownLibCitadelMime(void)
917 DeleteHash(&IconHash);