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 unsigned int decode_hex(char *Source)
78 ret += (*Source - '0');
80 else if (*Source > 'Z') {
81 ret += (*Source - 'a' + 10);
84 ret += (*Source - 'A' + 10);
89 if (*(Source + 1) < 'A') {
90 ret += (*(Source + 1) - '0');
92 else if (*(Source + 1) > 'Z') {
93 ret += (*(Source + 1) - 'a' + 10);
96 ret += (*(Source + 1) - 'A' + 10);
104 * Convert "quoted-printable" to binary. Returns number of bytes decoded.
105 * according to RFC2045 section 6.7
107 int CtdlDecodeQuotedPrintable(char *decoded, char *encoded, int sourcelen) {
109 int decoded_length = 0;
112 while (pos < sourcelen)
114 if (!strncmp(&encoded[pos], "=\r\n", 3))
118 else if (!strncmp(&encoded[pos], "=\n", 2))
122 else if (encoded[pos] == '=')
125 ch = decode_hex(&encoded[pos+1]);
127 decoded[decoded_length++] = ch;
131 decoded[decoded_length++] = encoded[pos];
135 decoded[decoded_length] = 0;
136 return(decoded_length);
141 * Given a message or message-part body and a length, handle any necessary
142 * decoding and pass the request up the stack.
144 void mime_decode(char *partnum,
145 char *part_start, size_t length,
146 char *content_type, char *charset, char *encoding,
149 char *name, char *filename,
162 void (*PreMultiPartCallBack)
174 void (*PostMultiPartCallBack)
192 size_t bytes_decoded = 0;
194 /* Some encodings aren't really encodings */
195 if (!strcasecmp(encoding, "7bit"))
196 strcpy(encoding, "");
197 if (!strcasecmp(encoding, "8bit"))
198 strcpy(encoding, "");
199 if (!strcasecmp(encoding, "binary"))
200 strcpy(encoding, "");
202 /* If this part is not encoded, send as-is */
203 if ( (strlen(encoding) == 0) || (dont_decode)) {
204 if (CallBack != NULL) {
205 CallBack(name, filename, fixed_partnum(partnum),
206 disposition, part_start,
207 content_type, charset, length, encoding, id, userdata);
212 /* Fail silently if we hit an unknown encoding. */
213 if ((strcasecmp(encoding, "base64"))
214 && (strcasecmp(encoding, "quoted-printable"))) {
219 * Allocate a buffer for the decoded data. The output buffer is slightly
220 * larger than the input buffer; this assumes that the decoded data
221 * will never be significantly larger than the encoded data. This is a
222 * safe assumption with base64, uuencode, and quoted-printable.
224 decoded = malloc(length + 32768);
225 if (decoded == NULL) {
229 if (!strcasecmp(encoding, "base64")) {
230 bytes_decoded = CtdlDecodeBase64(decoded, part_start, length);
232 else if (!strcasecmp(encoding, "quoted-printable")) {
233 bytes_decoded = CtdlDecodeQuotedPrintable(decoded, part_start, length);
236 if (bytes_decoded > 0) if (CallBack != NULL) {
237 CallBack(name, filename, fixed_partnum(partnum),
238 disposition, decoded,
239 content_type, charset, bytes_decoded, "binary", id, userdata);
246 * Break out the components of a multipart message
247 * (This function expects to be fed HEADERS + CONTENT)
248 * Note: NULL can be supplied as content_end; in this case, the message is
249 * considered to have ended when the parser encounters a 0x00 byte.
251 void the_mime_parser(char *partnum,
252 char *content_start, char *content_end,
265 void (*PreMultiPartCallBack)
277 void (*PostMultiPartCallBack)
296 char *part_start, *part_end = NULL;
301 size_t startary_len = 0;
306 size_t content_length;
311 char *content_type_name;
312 char *content_disposition_name;
318 char nested_partnum[256];
320 char *evaluate_crlf_ptr = NULL;
327 boundary = malloc(SIZ);
328 memset(boundary, 0, SIZ);
330 startary = malloc(SIZ);
331 memset(startary, 0, SIZ);
333 endary = malloc(SIZ);
334 memset(endary, 0, SIZ);
336 header = malloc(SIZ);
337 memset(header, 0, SIZ);
339 content_type = malloc(SIZ);
340 memset(content_type, 0, SIZ);
342 charset = malloc(SIZ);
343 memset(charset, 0, SIZ);
345 encoding = malloc(SIZ);
346 memset(encoding, 0, SIZ);
348 content_type_name = malloc(SIZ);
349 memset(content_type_name, 0, SIZ);
351 content_disposition_name = malloc(SIZ);
352 memset(content_disposition_name, 0, SIZ);
354 filename = malloc(SIZ);
355 memset(filename, 0, SIZ);
357 disposition = malloc(SIZ);
358 memset(disposition, 0, SIZ);
363 /* If the caller didn't supply an endpointer, generate one by measure */
364 if (content_end == NULL) {
365 content_end = &content_start[strlen(content_start)];
368 /* Learn interesting things from the headers */
372 ptr = memreadlinelen(ptr, buf, SIZ, &buflen);
373 if (ptr >= content_end) {
377 for (i = 0; i < buflen; ++i) {
378 if (isspace(buf[i])) {
383 if (!isspace(buf[0])) {
384 if (!strncasecmp(header, "Content-type:", 13)) {
385 strcpy(content_type, &header[13]);
386 striplt(content_type);
387 extract_key(content_type_name, content_type, "name");
388 extract_key(charset, content_type, "charset");
389 extract_key(boundary, header, "boundary");
390 /* Deal with weird headers */
391 if (strchr(content_type, ' '))
392 *(strchr(content_type, ' ')) = '\0';
393 if (strchr(content_type, ';'))
394 *(strchr(content_type, ';')) = '\0';
396 if (!strncasecmp(header, "Content-Disposition:", 20)) {
397 strcpy(disposition, &header[20]);
398 striplt(disposition);
399 extract_key(content_disposition_name, disposition, "name");
400 extract_key(filename, disposition, "filename");
402 if (!strncasecmp(header, "Content-ID:", 11)) {
403 strcpy(id, &header[11]);
405 stripallbut(id, '<', '>');
407 if (!strncasecmp(header, "Content-length: ", 15)) {
409 safestrncpy(clbuf, &header[15], sizeof clbuf);
411 content_length = (size_t) atol(clbuf);
413 if (!strncasecmp(header, "Content-transfer-encoding: ", 26)) {
414 strcpy(encoding, &header[26]);
420 if ((headerlen + buflen + 2) < SIZ) {
421 memcpy(&header[headerlen], buf, buflen);
423 header[headerlen] = '\0';
425 } while ((!IsEmptyStr(buf)) && (*ptr != 0));
427 if (strchr(disposition, ';'))
428 *(strchr(disposition, ';')) = '\0';
429 striplt(disposition);
430 if (strchr(content_type, ';'))
431 *(strchr(content_type, ';')) = '\0';
432 striplt(content_type);
434 if (!IsEmptyStr(boundary)) {
440 /* If this is a multipart message, then recursively process it */
444 /* Tell the client about this message's multipartedness */
445 if (PreMultiPartCallBack != NULL) {
446 PreMultiPartCallBack("", "", partnum, "",
447 NULL, content_type, charset,
448 0, encoding, id, userdata);
451 /* Figure out where the boundaries are */
452 snprintf(startary, SIZ, "--%s", boundary);
453 snprintf(endary, SIZ, "--%s--", boundary);
454 startary_len = strlen(startary);
458 next_boundary = NULL;
459 for (srch=ptr; srch<content_end; ++srch) {
460 if (!memcmp(srch, startary, startary_len)) {
461 next_boundary = srch;
466 if ( (part_start != NULL) && (next_boundary != NULL) ) {
467 part_end = next_boundary;
468 --part_end; /* omit the trailing LF */
470 --part_end; /* omit the trailing CR */
473 if (!IsEmptyStr(partnum)) {
474 snprintf(nested_partnum,
475 sizeof nested_partnum,
480 snprintf(nested_partnum,
481 sizeof nested_partnum,
484 the_mime_parser(nested_partnum,
485 part_start, part_end,
487 PreMultiPartCallBack,
488 PostMultiPartCallBack,
493 if (next_boundary != NULL) {
494 /* If we pass out of scope, don't attempt to
495 * read past the end boundary. */
496 if (!strcmp(next_boundary, endary)) {
500 /* Set up for the next part. */
501 part_start = strstr(next_boundary, "\n");
503 /* Determine whether newlines are LF or CRLF */
504 evaluate_crlf_ptr = part_start;
506 if (!memcmp(evaluate_crlf_ptr, "\r\n", 2)) {
513 /* Advance past the LF ... now we're in the next part */
519 /* Invalid end of multipart. Bail out! */
522 } while ( (ptr < content_end) && (next_boundary != NULL) );
524 if (PostMultiPartCallBack != NULL) {
525 PostMultiPartCallBack("", "", partnum, "", NULL,
526 content_type, charset, 0, encoding, id, userdata);
531 /* If it's not a multipart message, then do something with it */
535 while (ptr < content_end) {
539 part_end = content_end;
542 /* The following code will truncate the MIME part to the size
543 * specified by the Content-length: header. We have commented it
544 * out because these headers have a tendency to be wrong.
546 * if ( (content_length > 0) && (length > content_length) ) {
547 * length = content_length;
551 /* Sometimes the "name" field is tacked on to Content-type,
552 * and sometimes it's tacked on to Content-disposition. Use
553 * whichever one we have.
555 if (strlen(content_disposition_name) > strlen(content_type_name)) {
556 name = content_disposition_name;
559 name = content_type_name;
562 /* Ok, we've got a non-multipart part here, so do something with it.
566 content_type, charset, encoding, disposition, id,
568 CallBack, NULL, NULL,
569 userdata, dont_decode
573 * Now if it's an encapsulated message/rfc822 then we have to recurse into it
575 if (!strcasecmp(content_type, "message/rfc822")) {
577 if (PreMultiPartCallBack != NULL) {
578 PreMultiPartCallBack("", "", partnum, "",
579 NULL, content_type, charset,
580 0, encoding, id, userdata);
582 if (CallBack != NULL) {
583 if (strlen(partnum) > 0) {
584 snprintf(nested_partnum,
585 sizeof nested_partnum,
590 snprintf(nested_partnum,
591 sizeof nested_partnum,
594 the_mime_parser(nested_partnum,
595 part_start, part_end,
597 PreMultiPartCallBack,
598 PostMultiPartCallBack,
603 if (PostMultiPartCallBack != NULL) {
604 PostMultiPartCallBack("", "", partnum, "", NULL,
605 content_type, charset, 0, encoding, id, userdata);
613 end_parser: /* free the buffers! end the oppression!! */
621 free(content_type_name);
622 free(content_disposition_name);
631 * Entry point for the MIME parser.
632 * (This function expects to be fed HEADERS + CONTENT)
633 * Note: NULL can be supplied as content_end; in this case, the message is
634 * considered to have ended when the parser encounters a 0x00 byte.
636 void mime_parser(char *content_start,
652 void (*PreMultiPartCallBack)
665 void (*PostMultiPartCallBack)
683 the_mime_parser("", content_start, content_end,
685 PreMultiPartCallBack,
686 PostMultiPartCallBack,
687 userdata, dont_decode);
695 typedef struct _MimeGuess {
699 const char *MimeString;
702 MimeGuess MyMimes [] = {
730 const char *GuessMimeType(const char *data, size_t dlen)
734 while (MyMimes[MimeIndex].PatternLen != 0)
736 if ((MyMimes[MimeIndex].PatternLen +
737 MyMimes[MimeIndex].PatternOffset < dlen) &&
738 strncmp(MyMimes[MimeIndex].Pattern,
739 &data[MyMimes[MimeIndex].PatternOffset],
740 MyMimes[MimeIndex].PatternLen) == 0)
742 return MyMimes[MimeIndex].MimeString;
747 * ok, our simple minded algorythm didn't find anything,
748 * let the big chegger try it, he wil default to application/octet-stream
750 return (xdg_mime_get_mime_type_for_data(data, dlen));
754 const char* GuessMimeByFilename(const char *what, size_t len)
756 /* we know some hardcoded on our own, try them... */
757 if ((len > 3) && !strncasecmp(&what[len - 4], ".gif", 4))
759 else if ((len > 2) && !strncasecmp(&what[len - 3], ".js", 3))
760 return "text/javascript";
761 else if ((len > 3) && !strncasecmp(&what[len - 4], ".txt", 4))
763 else if ((len > 3) && !strncasecmp(&what[len - 4], ".css", 4))
765 else if ((len > 3) && !strncasecmp(&what[len - 4], ".jpg", 4))
767 else if ((len > 3) && !strncasecmp(&what[len - 4], ".png", 4))
769 else if ((len > 3) && !strncasecmp(&what[len - 4], ".ico", 4))
770 return "image/x-icon";
771 else if ((len > 3) && !strncasecmp(&what[len - 4], ".vcf", 4))
772 return "text/x-vcard";
773 else if ((len > 4) && !strncasecmp(&what[len - 5], ".html", 5))
775 else if ((len > 3) && !strncasecmp(&what[len - 4], ".htm", 4))
777 else if ((len > 3) && !strncasecmp(&what[len - 4], ".wml", 4))
778 return "text/vnd.wap.wml";
779 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wmls", 5))
780 return "text/vnd.wap.wmlscript";
781 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wmlc", 5))
782 return "application/vnd.wap.wmlc";
783 else if ((len > 5) && !strncasecmp(&what[len - 6], ".wmlsc", 6))
784 return "application/vnd.wap.wmlscriptc";
785 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wbmp", 5))
786 return "image/vnd.wap.wbmp";
788 /* and let xdgmime do the fallback. */
789 return xdg_mime_get_mime_type_from_file_name(what);
792 static HashList *IconHash = NULL;
794 typedef struct IconName IconName;
801 static void DeleteIcon(void *IconNamePtr)
803 IconName *Icon = (IconName*) IconNamePtr;
804 free(Icon->FlatName);
805 free(Icon->FileName);
810 static const char *PrintFlat(void *IconNamePtr)
812 IconName *Icon = (IconName*) IconNamePtr;
813 return Icon->FlatName;
815 static const char *PrintFile(void *IconNamePtr)
817 IconName *Icon = (IconName*) IconNamePtr;
818 return Icon->FileName;
822 #define GENSTR "x-generic"
823 #define IGNORE_PREFIX_1 "gnome-mime"
824 int LoadIconDir(const char *DirName)
827 struct dirent *filedir_entry;
832 filedir = opendir (DirName);
833 IconHash = NewHash(1, NULL);
834 if (filedir == NULL) {
838 while ((filedir_entry = readdir(filedir)))
842 #ifdef _DIRENT_HAVE_D_NAMELEN
843 d_namelen = filedir_entry->d_namelen;
845 d_namelen = strlen(filedir_entry->d_name);
847 d_without_ext = d_namelen;
848 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
850 if ((d_without_ext == 0) || (d_namelen < 3))
853 if ((sizeof(IGNORE_PREFIX_1) < d_namelen) &&
854 (strncmp(IGNORE_PREFIX_1,
855 filedir_entry->d_name,
856 sizeof(IGNORE_PREFIX_1) - 1) == 0)) {
857 PStart = filedir_entry->d_name + sizeof(IGNORE_PREFIX_1);
858 d_without_ext -= sizeof(IGNORE_PREFIX_1);
861 PStart = filedir_entry->d_name;
863 Icon = malloc(sizeof(IconName));
865 Icon->FileName = malloc(d_namelen + 1);
866 memcpy(Icon->FileName, filedir_entry->d_name, d_namelen + 1);
868 Icon->FlatName = malloc(d_without_ext + 1);
869 memcpy(Icon->FlatName, PStart, d_without_ext);
870 Icon->FlatName[d_without_ext] = '\0';
871 /* Try to find Minor type in image-jpeg */
872 MinorPtr = strchr(Icon->FlatName, '-');
873 if (MinorPtr != NULL) {
875 MinorLen = 1 + d_without_ext - (MinorPtr - Icon->FlatName + 1);
876 if ((MinorLen == sizeof(GENSTR)) &&
877 (strncmp(MinorPtr + 1, GENSTR, sizeof(GENSTR)) == 0)) {
878 /* ok, we found a generic filename. cut the generic. */
880 d_without_ext = d_without_ext - (MinorPtr - Icon->FlatName);
882 else { /* Map the major / minor separator to / */
887 // PrintHash(IconHash, PrintFlat, PrintFile);
888 // printf("%s - %s\n", Icon->FlatName, Icon->FileName);
889 Put(IconHash, Icon->FlatName, d_without_ext, Icon, DeleteIcon);
890 // PrintHash(IconHash, PrintFlat, PrintFile);
896 const char *GetIconFilename(char *MimeType, size_t len)
904 GetHash(IconHash, MimeType, len, &vIcon), Icon = (IconName*) vIcon;
905 /* didn't find the exact mimetype? try major only. */
908 pMinor = strchr(MimeType, '/');
909 if (pMinor != NULL) {
911 GetHash(IconHash, MimeType, pMinor - MimeType, &vIcon),
912 Icon = (IconName*) vIcon;
919 /*printf("Getting: [%s] == [%s] -> [%s]\n", MimeType, Icon->FlatName, Icon->FileName);*/
920 return Icon->FileName;
923 void ShutDownLibCitadelMime(void)
925 DeleteHash(&IconHash);