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"
26 void extract_key(char *target, char *source, char *key)
29 char looking_for[256];
30 int double_quotes = 0;
32 snprintf(looking_for, sizeof looking_for, "%s=", key);
34 ptr = bmstrcasestr(source, looking_for);
39 strcpy(target, (ptr + strlen(looking_for)));
41 for (ptr=target; (*ptr != 0); ++ptr) {
43 /* A semicolon means we've hit the end of the key, unless we're inside double quotes */
44 if ( (double_quotes != 1) && (*ptr == ';')) {
48 /* if we find double quotes, we've got a great set of string boundaries */
51 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;
75 * Convert "quoted-printable" to binary. Returns number of bytes decoded.
76 * according to RFC2045 section 6.7
78 int CtdlDecodeQuotedPrintable(char *decoded, char *encoded, int sourcelen) {
80 int decoded_length = 0;
83 while (pos < sourcelen)
85 if (!strncmp(&encoded[pos], "=\r\n", 3))
89 else if (!strncmp(&encoded[pos], "=\n", 2))
93 else if (encoded[pos] == '=')
96 sscanf(&encoded[pos+1], "%02x", &ch);
98 decoded[decoded_length++] = ch;
102 decoded[decoded_length++] = encoded[pos];
106 decoded[decoded_length] = 0;
107 return(decoded_length);
112 * Given a message or message-part body and a length, handle any necessary
113 * decoding and pass the request up the stack.
115 void mime_decode(char *partnum,
116 char *part_start, size_t length,
117 char *content_type, char *charset, char *encoding,
120 char *name, char *filename,
133 void (*PreMultiPartCallBack)
145 void (*PostMultiPartCallBack)
163 size_t bytes_decoded = 0;
165 /* Some encodings aren't really encodings */
166 if (!strcasecmp(encoding, "7bit"))
167 strcpy(encoding, "");
168 if (!strcasecmp(encoding, "8bit"))
169 strcpy(encoding, "");
170 if (!strcasecmp(encoding, "binary"))
171 strcpy(encoding, "");
173 /* If this part is not encoded, send as-is */
174 if ( (strlen(encoding) == 0) || (dont_decode)) {
175 if (CallBack != NULL) {
176 CallBack(name, filename, fixed_partnum(partnum),
177 disposition, part_start,
178 content_type, charset, length, encoding, id, userdata);
183 /* Fail silently if we hit an unknown encoding. */
184 if ((strcasecmp(encoding, "base64"))
185 && (strcasecmp(encoding, "quoted-printable"))) {
190 * Allocate a buffer for the decoded data. The output buffer is slightly
191 * larger than the input buffer; this assumes that the decoded data
192 * will never be significantly larger than the encoded data. This is a
193 * safe assumption with base64, uuencode, and quoted-printable.
195 decoded = malloc(length + 32768);
196 if (decoded == NULL) {
200 if (!strcasecmp(encoding, "base64")) {
201 bytes_decoded = CtdlDecodeBase64(decoded, part_start, length);
203 else if (!strcasecmp(encoding, "quoted-printable")) {
204 bytes_decoded = CtdlDecodeQuotedPrintable(decoded, part_start, length);
207 if (bytes_decoded > 0) if (CallBack != NULL) {
208 CallBack(name, filename, fixed_partnum(partnum),
209 disposition, decoded,
210 content_type, charset, bytes_decoded, "binary", id, userdata);
217 * Break out the components of a multipart message
218 * (This function expects to be fed HEADERS + CONTENT)
219 * Note: NULL can be supplied as content_end; in this case, the message is
220 * considered to have ended when the parser encounters a 0x00 byte.
222 void the_mime_parser(char *partnum,
223 char *content_start, char *content_end,
236 void (*PreMultiPartCallBack)
248 void (*PostMultiPartCallBack)
267 char *part_start, *part_end = NULL;
272 size_t startary_len = 0;
277 size_t content_length;
282 char *content_type_name;
283 char *content_disposition_name;
289 char nested_partnum[256];
291 char *evaluate_crlf_ptr = NULL;
298 boundary = malloc(SIZ);
299 memset(boundary, 0, SIZ);
301 startary = malloc(SIZ);
302 memset(startary, 0, SIZ);
304 endary = malloc(SIZ);
305 memset(endary, 0, SIZ);
307 header = malloc(SIZ);
308 memset(header, 0, SIZ);
310 content_type = malloc(SIZ);
311 memset(content_type, 0, SIZ);
313 charset = malloc(SIZ);
314 memset(charset, 0, SIZ);
316 encoding = malloc(SIZ);
317 memset(encoding, 0, SIZ);
319 content_type_name = malloc(SIZ);
320 memset(content_type_name, 0, SIZ);
322 content_disposition_name = malloc(SIZ);
323 memset(content_disposition_name, 0, SIZ);
325 filename = malloc(SIZ);
326 memset(filename, 0, SIZ);
328 disposition = malloc(SIZ);
329 memset(disposition, 0, SIZ);
334 /* If the caller didn't supply an endpointer, generate one by measure */
335 if (content_end == NULL) {
336 content_end = &content_start[strlen(content_start)];
339 /* Learn interesting things from the headers */
343 ptr = memreadlinelen(ptr, buf, SIZ, &buflen);
344 if (ptr >= content_end) {
348 for (i = 0; i < buflen; ++i) {
349 if (isspace(buf[i])) {
354 if (!isspace(buf[0])) {
355 if (!strncasecmp(header, "Content-type:", 13)) {
356 strcpy(content_type, &header[13]);
357 striplt(content_type);
358 extract_key(content_type_name, content_type, "name");
359 extract_key(charset, content_type, "charset");
360 extract_key(boundary, header, "boundary");
361 /* Deal with weird headers */
362 if (strchr(content_type, ' '))
363 *(strchr(content_type, ' ')) = '\0';
364 if (strchr(content_type, ';'))
365 *(strchr(content_type, ';')) = '\0';
367 if (!strncasecmp(header, "Content-Disposition:", 20)) {
368 strcpy(disposition, &header[20]);
369 striplt(disposition);
370 extract_key(content_disposition_name, disposition, "name");
371 extract_key(filename, disposition, "filename");
373 if (!strncasecmp(header, "Content-ID:", 11)) {
374 strcpy(id, &header[11]);
376 stripallbut(id, '<', '>');
378 if (!strncasecmp(header, "Content-length: ", 15)) {
380 safestrncpy(clbuf, &header[15], sizeof clbuf);
382 content_length = (size_t) atol(clbuf);
384 if (!strncasecmp(header, "Content-transfer-encoding: ", 26)) {
385 strcpy(encoding, &header[26]);
391 if ((headerlen + buflen + 2) < SIZ) {
392 memcpy(&header[headerlen], buf, buflen);
394 header[headerlen] = '\0';
396 } while ((!IsEmptyStr(buf)) && (*ptr != 0));
398 if (strchr(disposition, ';'))
399 *(strchr(disposition, ';')) = '\0';
400 striplt(disposition);
401 if (strchr(content_type, ';'))
402 *(strchr(content_type, ';')) = '\0';
403 striplt(content_type);
405 if (!IsEmptyStr(boundary)) {
411 /* If this is a multipart message, then recursively process it */
415 /* Tell the client about this message's multipartedness */
416 if (PreMultiPartCallBack != NULL) {
417 PreMultiPartCallBack("", "", partnum, "",
418 NULL, content_type, charset,
419 0, encoding, id, userdata);
422 /* Figure out where the boundaries are */
423 snprintf(startary, SIZ, "--%s", boundary);
424 snprintf(endary, SIZ, "--%s--", boundary);
425 startary_len = strlen(startary);
429 next_boundary = NULL;
430 for (srch=ptr; srch<content_end; ++srch) {
431 if (!memcmp(srch, startary, startary_len)) {
432 next_boundary = srch;
437 if ( (part_start != NULL) && (next_boundary != NULL) ) {
438 part_end = next_boundary;
439 --part_end; /* omit the trailing LF */
441 --part_end; /* omit the trailing CR */
444 if (!IsEmptyStr(partnum)) {
445 snprintf(nested_partnum,
446 sizeof nested_partnum,
451 snprintf(nested_partnum,
452 sizeof nested_partnum,
455 the_mime_parser(nested_partnum,
456 part_start, part_end,
458 PreMultiPartCallBack,
459 PostMultiPartCallBack,
464 if (next_boundary != NULL) {
465 /* If we pass out of scope, don't attempt to
466 * read past the end boundary. */
467 if (!strcmp(next_boundary, endary)) {
471 /* Set up for the next part. */
472 part_start = strstr(next_boundary, "\n");
474 /* Determine whether newlines are LF or CRLF */
475 evaluate_crlf_ptr = part_start;
477 if (!memcmp(evaluate_crlf_ptr, "\r\n", 2)) {
484 /* Advance past the LF ... now we're in the next part */
490 /* Invalid end of multipart. Bail out! */
493 } while ( (ptr < content_end) && (next_boundary != NULL) );
495 if (PostMultiPartCallBack != NULL) {
496 PostMultiPartCallBack("", "", partnum, "", NULL,
497 content_type, charset, 0, encoding, id, userdata);
502 /* If it's not a multipart message, then do something with it */
506 while (ptr < content_end) {
510 part_end = content_end;
513 /* The following code will truncate the MIME part to the size
514 * specified by the Content-length: header. We have commented it
515 * out because these headers have a tendency to be wrong.
517 * if ( (content_length > 0) && (length > content_length) ) {
518 * length = content_length;
522 /* Sometimes the "name" field is tacked on to Content-type,
523 * and sometimes it's tacked on to Content-disposition. Use
524 * whichever one we have.
526 if (strlen(content_disposition_name) > strlen(content_type_name)) {
527 name = content_disposition_name;
530 name = content_type_name;
533 /* Ok, we've got a non-multipart part here, so do something with it.
537 content_type, charset, encoding, disposition, id,
539 CallBack, NULL, NULL,
540 userdata, dont_decode
544 * Now if it's an encapsulated message/rfc822 then we have to recurse into it
546 if (!strcasecmp(content_type, "message/rfc822")) {
548 if (PreMultiPartCallBack != NULL) {
549 PreMultiPartCallBack("", "", partnum, "",
550 NULL, content_type, charset,
551 0, encoding, id, userdata);
553 if (CallBack != NULL) {
554 if (strlen(partnum) > 0) {
555 snprintf(nested_partnum,
556 sizeof nested_partnum,
561 snprintf(nested_partnum,
562 sizeof nested_partnum,
565 the_mime_parser(nested_partnum,
566 part_start, part_end,
568 PreMultiPartCallBack,
569 PostMultiPartCallBack,
574 if (PostMultiPartCallBack != NULL) {
575 PostMultiPartCallBack("", "", partnum, "", NULL,
576 content_type, charset, 0, encoding, id, userdata);
584 end_parser: /* free the buffers! end the oppression!! */
592 free(content_type_name);
593 free(content_disposition_name);
602 * Entry point for the MIME parser.
603 * (This function expects to be fed HEADERS + CONTENT)
604 * Note: NULL can be supplied as content_end; in this case, the message is
605 * considered to have ended when the parser encounters a 0x00 byte.
607 void mime_parser(char *content_start,
623 void (*PreMultiPartCallBack)
636 void (*PostMultiPartCallBack)
654 the_mime_parser("", content_start, content_end,
656 PreMultiPartCallBack,
657 PostMultiPartCallBack,
658 userdata, dont_decode);
666 typedef struct _MimeGuess {
670 const char *MimeString;
673 MimeGuess MyMimes [] = {
701 const char *GuessMimeType(const char *data, size_t dlen)
705 while (MyMimes[MimeIndex].PatternLen != 0)
707 if ((MyMimes[MimeIndex].PatternLen +
708 MyMimes[MimeIndex].PatternOffset < dlen) &&
709 strncmp(MyMimes[MimeIndex].Pattern,
710 &data[MyMimes[MimeIndex].PatternOffset],
711 MyMimes[MimeIndex].PatternLen) == 0)
713 return MyMimes[MimeIndex].MimeString;
718 * ok, our simple minded algorythm didn't find anything,
719 * let the big chegger try it, he wil default to application/octet-stream
721 return (xdg_mime_get_mime_type_for_data(data, dlen));
725 const char* GuessMimeByFilename(const char *what, size_t len)
727 /* we know some hardcoded on our own, try them... */
728 if (!strncasecmp(&what[len - 4], ".gif", 4))
730 else if (!strncasecmp(&what[len - 3], ".js", 3))
731 return "text/javascript";
732 else if (!strncasecmp(&what[len - 4], ".txt", 4))
734 else if (!strncasecmp(&what[len - 4], ".css", 4))
736 else if (!strncasecmp(&what[len - 4], ".jpg", 4))
738 else if (!strncasecmp(&what[len - 4], ".png", 4))
740 else if (!strncasecmp(&what[len - 4], ".ico", 4))
741 return "image/x-icon";
742 else if (!strncasecmp(&what[len - 5], ".html", 5))
744 else if (!strncasecmp(&what[len - 4], ".htm", 4))
746 else if (!strncasecmp(&what[len - 4], ".wml", 4))
747 return "text/vnd.wap.wml";
748 else if (!strncasecmp(&what[len - 5], ".wmls", 5))
749 return "text/vnd.wap.wmlscript";
750 else if (!strncasecmp(&what[len - 5], ".wmlc", 5))
751 return "application/vnd.wap.wmlc";
752 else if (!strncasecmp(&what[len - 6], ".wmlsc", 6))
753 return "application/vnd.wap.wmlscriptc";
754 else if (!strncasecmp(&what[len - 5], ".wbmp", 5))
755 return "image/vnd.wap.wbmp";
757 /* and let xdgmime do the fallback. */
758 return xdg_mime_get_mime_type_from_file_name(what);
761 static HashList *IconHash = NULL;
763 typedef struct IconName IconName;
770 static void DeleteIcon(void *IconNamePtr)
772 IconName *Icon = (IconName*) IconNamePtr;
773 free(Icon->FlatName);
774 free(Icon->FileName);
779 static const char *PrintFlat(void *IconNamePtr)
781 IconName *Icon = (IconName*) IconNamePtr;
782 return Icon->FlatName;
784 static const char *PrintFile(void *IconNamePtr)
786 IconName *Icon = (IconName*) IconNamePtr;
787 return Icon->FileName;
791 #define GENSTR "x-generic"
792 #define IGNORE_PREFIX_1 "gnome-mime"
793 int LoadIconDir(const char *DirName)
796 struct dirent *filedir_entry;
801 filedir = opendir (DirName);
802 IconHash = NewHash(1, NULL);
803 if (filedir == NULL) {
807 while ((filedir_entry = readdir(filedir)))
811 #ifdef _DIRENT_HAVE_D_NAMELEN
812 d_namelen = filedir_entry->d_namelen;
814 d_namelen = strlen(filedir_entry->d_name);
816 d_without_ext = d_namelen;
817 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
819 if ((d_without_ext == 0) || (d_namelen < 3))
822 if ((sizeof(IGNORE_PREFIX_1) < d_namelen) &&
823 (strncmp(IGNORE_PREFIX_1,
824 filedir_entry->d_name,
825 sizeof(IGNORE_PREFIX_1) - 1) == 0)) {
826 PStart = filedir_entry->d_name + sizeof(IGNORE_PREFIX_1);
827 d_without_ext -= sizeof(IGNORE_PREFIX_1);
830 PStart = filedir_entry->d_name;
832 Icon = malloc(sizeof(IconName));
834 Icon->FileName = malloc(d_namelen + 1);
835 memcpy(Icon->FileName, filedir_entry->d_name, d_namelen + 1);
837 Icon->FlatName = malloc(d_without_ext + 1);
838 memcpy(Icon->FlatName, PStart, d_without_ext);
839 Icon->FlatName[d_without_ext] = '\0';
840 /* Try to find Minor type in image-jpeg */
841 MinorPtr = strchr(Icon->FlatName, '-');
842 if (MinorPtr != NULL) {
844 MinorLen = 1 + d_without_ext - (MinorPtr - Icon->FlatName + 1);
845 if ((MinorLen == sizeof(GENSTR)) &&
846 (strncmp(MinorPtr + 1, GENSTR, sizeof(GENSTR)) == 0)) {
847 /* ok, we found a generic filename. cut the generic. */
849 d_without_ext = d_without_ext - (MinorPtr - Icon->FlatName);
851 else { /* Map the major / minor separator to / */
856 // PrintHash(IconHash, PrintFlat, PrintFile);
857 // printf("%s - %s\n", Icon->FlatName, Icon->FileName);
858 Put(IconHash, Icon->FlatName, d_without_ext, Icon, DeleteIcon);
859 // PrintHash(IconHash, PrintFlat, PrintFile);
865 const char *GetIconFilename(char *MimeType, size_t len)
873 GetHash(IconHash, MimeType, len, &vIcon), Icon = (IconName*) vIcon;
874 /* didn't find the exact mimetype? try major only. */
877 pMinor = strchr(MimeType, '/');
878 if (pMinor != NULL) {
880 GetHash(IconHash, MimeType, pMinor - MimeType, &vIcon),
881 Icon = (IconName*) vIcon;
888 /*printf("Getting: [%s] == [%s] -> [%s]\n", MimeType, Icon->FlatName, Icon->FileName);*/
889 return Icon->FileName;
892 void ShutDownLibCitadel(void)
894 DeleteHash(&IconHash);