2 * This is the MIME parser for Citadel.
4 * Copyright (c) 1998-2010 by the citadel.org development team.
5 * This code is distributed under the GNU General Public License v3.
13 #include <sys/types.h>
17 #include <sys/types.h>
21 #include "xdgmime/xdgmime.h"
22 #include "libcitadel.h"
23 #include "libcitadellocal.h"
25 void extract_key(char *target, char *source, long sourcelen, char *key, long keylen, char KeyEnd)
27 char *sptr, *ptr = NULL;
28 int double_quotes = 0;
29 long RealKeyLen = keylen;
35 ptr = bmstrcasestr_len(sptr, sourcelen - (sptr - source),
39 while (isspace(*(ptr + RealKeyLen)))
41 if (*(ptr + RealKeyLen) == KeyEnd)
48 sptr = ptr + RealKeyLen + 1;
58 strcpy(target, (ptr + RealKeyLen));
60 for (ptr=target; (*ptr != 0); ptr++) {
62 /* A semicolon means we've hit the end of the key, unless we're inside double quotes */
63 if ( (double_quotes != 1) && (*ptr == ';')) {
67 /* if we find double quotes, we've got a great set of string boundaries */
70 if (double_quotes == 1) {
83 * For non-multipart messages, we need to generate a quickie partnum of "1"
84 * to return to callback functions. Some callbacks demand it.
86 char *fixed_partnum(char *supplied_partnum) {
87 if (supplied_partnum == NULL) return "1";
88 if (strlen(supplied_partnum)==0) return "1";
89 return supplied_partnum;
93 static inline unsigned int _decode_hex(char *Source)
96 if ((*Source >= '0') && (*Source <= '9')) {
97 ret += (*Source - '0');
99 else if ((*Source >= 'A') && (*Source <= 'F')) {
100 ret += (*Source - 'A' + 10);
102 else if ((*Source >= 'a') && (*Source <= 'f')) {
103 ret += (*Source - 'a' + 10);
111 if ((*(Source + 1) >= '0') && (*(Source + 1) <= '9')) {
112 ret |= (*(Source + 1) - '0');
114 else if ((*(Source + 1) >= 'A') && (*(Source + 1) <= 'F')) {
115 ret |= (*(Source + 1) - 'A' + 10);
117 else if ((*(Source + 1) >= 'a') && (*(Source + 1) <= 'f')) {
118 ret |= (*(Source + 1) - 'a' + 10);
126 unsigned int decode_hex(char *Source) {return _decode_hex(Source);}
129 * Convert "quoted-printable" to binary. Returns number of bytes decoded.
130 * according to RFC2045 section 6.7
132 int CtdlDecodeQuotedPrintable(char *decoded, char *encoded, int sourcelen) {
134 int decoded_length = 0;
137 while (pos < sourcelen)
139 if (!strncmp(&encoded[pos], "=\r\n", 3))
143 else if (!strncmp(&encoded[pos], "=\n", 2))
147 else if (encoded[pos] == '=')
150 ch = _decode_hex(&encoded[pos+1]);
152 decoded[decoded_length++] = ch;
156 decoded[decoded_length++] = encoded[pos];
160 decoded[decoded_length] = 0;
161 return(decoded_length);
166 * Given a message or message-part body and a length, handle any necessary
167 * decoding and pass the request up the stack.
169 void mime_decode(char *partnum,
170 char *part_start, size_t length,
171 char *content_type, char *charset, char *encoding,
174 char *name, char *filename,
175 MimeParserCallBackType CallBack,
176 MimeParserCallBackType PreMultiPartCallBack,
177 MimeParserCallBackType PostMultiPartCallBack,
183 size_t bytes_decoded = 0;
185 /* Some encodings aren't really encodings */
186 if (!strcasecmp(encoding, "7bit"))
187 strcpy(encoding, "");
188 if (!strcasecmp(encoding, "8bit"))
189 strcpy(encoding, "");
190 if (!strcasecmp(encoding, "binary"))
191 strcpy(encoding, "");
193 /* If this part is not encoded, send as-is */
194 if ( (strlen(encoding) == 0) || (dont_decode)) {
195 if (CallBack != NULL) {
196 CallBack(name, filename, fixed_partnum(partnum),
197 disposition, part_start,
198 content_type, charset, length, encoding, id, userdata);
203 /* Fail silently if we hit an unknown encoding. */
204 if ((strcasecmp(encoding, "base64"))
205 && (strcasecmp(encoding, "quoted-printable"))) {
210 * Allocate a buffer for the decoded data. The output buffer is slightly
211 * larger than the input buffer; this assumes that the decoded data
212 * will never be significantly larger than the encoded data. This is a
213 * safe assumption with base64, uuencode, and quoted-printable.
215 decoded = malloc(length + 32768);
216 if (decoded == NULL) {
220 if (!strcasecmp(encoding, "base64")) {
221 bytes_decoded = CtdlDecodeBase64(decoded, part_start, length);
223 else if (!strcasecmp(encoding, "quoted-printable")) {
224 bytes_decoded = CtdlDecodeQuotedPrintable(decoded, part_start, length);
227 if (bytes_decoded > 0) if (CallBack != NULL) {
228 CallBack(name, filename, fixed_partnum(partnum),
229 disposition, decoded,
230 content_type, charset, bytes_decoded, "binary", id, userdata);
237 * Break out the components of a multipart message
238 * (This function expects to be fed HEADERS + CONTENT)
239 * Note: NULL can be supplied as content_end; in this case, the message is
240 * considered to have ended when the parser encounters a 0x00 byte.
242 void the_mime_parser(char *partnum,
243 char *content_start, char *content_end,
244 MimeParserCallBackType CallBack,
245 MimeParserCallBackType PreMultiPartCallBack,
246 MimeParserCallBackType PostMultiPartCallBack,
253 char *part_start, *part_end = NULL;
258 size_t startary_len = 0;
263 size_t content_type_len;
264 size_t content_length;
267 size_t disposition_len;
270 char *content_type_name;
271 char *content_disposition_name;
277 char nested_partnum[256];
279 char *evaluate_crlf_ptr = NULL;
286 boundary = malloc(SIZ * 12);
289 startary = boundary + SIZ * 1;
292 endary = boundary + SIZ * 2;
295 header = boundary + SIZ * 3;
298 content_type = boundary + SIZ * 4;
299 *content_type = '\0';
301 charset = boundary + SIZ * 5;
304 encoding = boundary + SIZ * 6;
307 content_type_name = boundary + SIZ * 7;
308 *content_type_name = '\0';
310 content_disposition_name = boundary + SIZ * 8;
311 *content_disposition_name = '\0';
313 filename = boundary + SIZ * 9;
316 disposition = boundary + SIZ * 10;
319 id = boundary + SIZ * 11;
322 /* If the caller didn't supply an endpointer, generate one by measure */
323 if (content_end == NULL) {
324 content_end = &content_start[strlen(content_start)];
327 /* Learn interesting things from the headers */
331 ptr = memreadlinelen(ptr, buf, SIZ, &buflen);
332 if (ptr >= content_end) {
336 for (i = 0; i < buflen; ++i) {
337 if (isspace(buf[i])) {
342 if (!isspace(buf[0])) {
343 if (!strncasecmp(header, "Content-type:", 13)) {
344 memcpy (content_type, &header[13], headerlen - 12);
345 content_type_len = striplt (content_type);
347 extract_key(content_type_name, content_type, content_type_len, HKEY("name"), '=');
348 extract_key(charset, content_type, content_type_len, HKEY("charset"), '=');
349 extract_key(boundary, header, headerlen, HKEY("boundary"), '=');
351 /* Deal with weird headers */
352 if (strchr(content_type, ' '))
353 *(strchr(content_type, ' ')) = '\0';
354 if (strchr(content_type, ';'))
355 *(strchr(content_type, ';')) = '\0';
357 else if (!strncasecmp(header, "Content-Disposition:", 20)) {
358 memcpy (disposition, &header[20], headerlen - 19);
359 disposition_len = striplt(disposition);
360 extract_key(content_disposition_name, disposition, disposition_len, HKEY("name"), '=');
361 extract_key(filename, disposition, disposition_len, HKEY("filename"), '=');
363 else if (!strncasecmp(header, "Content-ID:", 11)) {
364 strcpy(id, &header[11]);
366 stripallbut(id, '<', '>');
368 else if (!strncasecmp(header, "Content-length: ", 15)) {
370 safestrncpy(clbuf, &header[15], sizeof clbuf);
372 content_length = (size_t) atol(clbuf);
374 else if (!strncasecmp(header, "Content-transfer-encoding: ", 26)) {
375 strcpy(encoding, &header[26]);
381 if ((headerlen + buflen + 2) < SIZ) {
382 memcpy(&header[headerlen], buf, buflen);
384 header[headerlen] = '\0';
386 } while ((!IsEmptyStr(buf)) && (*ptr != 0));
388 if (strchr(disposition, ';'))
389 *(strchr(disposition, ';')) = '\0';
390 striplt(disposition);
391 if (strchr(content_type, ';'))
392 *(strchr(content_type, ';')) = '\0';
393 striplt(content_type);
395 if (!IsEmptyStr(boundary)) {
401 /* If this is a multipart message, then recursively process it */
405 /* Tell the client about this message's multipartedness */
406 if (PreMultiPartCallBack != NULL) {
407 PreMultiPartCallBack("", "", partnum, "",
408 NULL, content_type, charset,
409 0, encoding, id, userdata);
412 /* Figure out where the boundaries are */
413 startary_len = snprintf(startary, SIZ, "--%s", boundary);
414 snprintf(endary, SIZ, "--%s--", boundary);
418 next_boundary = NULL;
419 for (srch=ptr; srch<content_end; ++srch) {
420 if (!memcmp(srch, startary, startary_len)) {
421 next_boundary = srch;
426 if ( (part_start != NULL) && (next_boundary != NULL) ) {
427 part_end = next_boundary;
428 --part_end; /* omit the trailing LF */
430 --part_end; /* omit the trailing CR */
433 if (!IsEmptyStr(partnum)) {
434 snprintf(nested_partnum,
435 sizeof nested_partnum,
440 snprintf(nested_partnum,
441 sizeof nested_partnum,
444 the_mime_parser(nested_partnum,
445 part_start, part_end,
447 PreMultiPartCallBack,
448 PostMultiPartCallBack,
453 if (next_boundary != NULL) {
454 /* If we pass out of scope, don't attempt to
455 * read past the end boundary. */
456 if (!strcmp(next_boundary, endary)) {
460 /* Set up for the next part. */
461 part_start = strstr(next_boundary, "\n");
463 /* Determine whether newlines are LF or CRLF */
464 evaluate_crlf_ptr = part_start;
466 if (!memcmp(evaluate_crlf_ptr, "\r\n", 2)) {
473 /* Advance past the LF ... now we're in the next part */
479 /* Invalid end of multipart. Bail out! */
482 } while ( (ptr < content_end) && (next_boundary != NULL) );
484 if (PostMultiPartCallBack != NULL) {
485 PostMultiPartCallBack("", "", partnum, "", NULL,
486 content_type, charset, 0, encoding, id, userdata);
491 /* If it's not a multipart message, then do something with it */
495 while (ptr < content_end) {
499 part_end = content_end;
502 /* The following code will truncate the MIME part to the size
503 * specified by the Content-length: header. We have commented it
504 * out because these headers have a tendency to be wrong.
506 * if ( (content_length > 0) && (length > content_length) ) {
507 * length = content_length;
511 /* Sometimes the "name" field is tacked on to Content-type,
512 * and sometimes it's tacked on to Content-disposition. Use
513 * whichever one we have.
515 if (strlen(content_disposition_name) > strlen(content_type_name)) {
516 name = content_disposition_name;
519 name = content_type_name;
522 /* Ok, we've got a non-multipart part here, so do something with it.
526 content_type, charset, encoding, disposition, id,
528 CallBack, NULL, NULL,
529 userdata, dont_decode
533 * Now if it's an encapsulated message/rfc822 then we have to recurse into it
535 if (!strcasecmp(content_type, "message/rfc822")) {
537 if (PreMultiPartCallBack != NULL) {
538 PreMultiPartCallBack("", "", partnum, "",
539 NULL, content_type, charset,
540 0, encoding, id, userdata);
542 if (CallBack != NULL) {
543 if (strlen(partnum) > 0) {
544 snprintf(nested_partnum,
545 sizeof nested_partnum,
550 snprintf(nested_partnum,
551 sizeof nested_partnum,
554 the_mime_parser(nested_partnum,
555 part_start, part_end,
557 PreMultiPartCallBack,
558 PostMultiPartCallBack,
563 if (PostMultiPartCallBack != NULL) {
564 PostMultiPartCallBack("", "", partnum, "", NULL,
565 content_type, charset, 0, encoding, id, userdata);
573 end_parser: /* free the buffers! end the oppression!! */
580 * Entry point for the MIME parser.
581 * (This function expects to be fed HEADERS + CONTENT)
582 * Note: NULL can be supplied as content_end; in this case, the message is
583 * considered to have ended when the parser encounters a 0x00 byte.
585 void mime_parser(char *content_start,
587 MimeParserCallBackType CallBack,
588 MimeParserCallBackType PreMultiPartCallBack,
589 MimeParserCallBackType PostMultiPartCallBack,
594 the_mime_parser("", content_start, content_end,
596 PreMultiPartCallBack,
597 PostMultiPartCallBack,
598 userdata, dont_decode);
606 typedef struct _MimeGuess {
610 const char *MimeString;
613 MimeGuess MyMimes [] = {
641 const char *GuessMimeType(const char *data, size_t dlen)
645 while (MyMimes[MimeIndex].PatternLen != 0)
647 if ((MyMimes[MimeIndex].PatternLen +
648 MyMimes[MimeIndex].PatternOffset < dlen) &&
649 strncmp(MyMimes[MimeIndex].Pattern,
650 &data[MyMimes[MimeIndex].PatternOffset],
651 MyMimes[MimeIndex].PatternLen) == 0)
653 return MyMimes[MimeIndex].MimeString;
658 * ok, our simple minded algorythm didn't find anything,
659 * let the big chegger try it, he wil default to application/octet-stream
661 return (xdg_mime_get_mime_type_for_data(data, dlen));
665 const char* GuessMimeByFilename(const char *what, size_t len)
667 /* we know some hardcoded on our own, try them... */
668 if ((len > 3) && !strncasecmp(&what[len - 4], ".gif", 4))
670 else if ((len > 2) && !strncasecmp(&what[len - 3], ".js", 3))
671 return "text/javascript";
672 else if ((len > 3) && !strncasecmp(&what[len - 4], ".txt", 4))
674 else if ((len > 3) && !strncasecmp(&what[len - 4], ".css", 4))
676 else if ((len > 3) && !strncasecmp(&what[len - 4], ".jpg", 4))
678 else if ((len > 3) && !strncasecmp(&what[len - 4], ".png", 4))
680 else if ((len > 3) && !strncasecmp(&what[len - 4], ".ico", 4))
681 return "image/x-icon";
682 else if ((len > 3) && !strncasecmp(&what[len - 4], ".vcf", 4))
683 return "text/x-vcard";
684 else if ((len > 4) && !strncasecmp(&what[len - 5], ".html", 5))
686 else if ((len > 3) && !strncasecmp(&what[len - 4], ".htm", 4))
688 else if ((len > 3) && !strncasecmp(&what[len - 4], ".wml", 4))
689 return "text/vnd.wap.wml";
690 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wmls", 5))
691 return "text/vnd.wap.wmlscript";
692 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wmlc", 5))
693 return "application/vnd.wap.wmlc";
694 else if ((len > 5) && !strncasecmp(&what[len - 6], ".wmlsc", 6))
695 return "application/vnd.wap.wmlscriptc";
696 else if ((len > 4) && !strncasecmp(&what[len - 5], ".wbmp", 5))
697 return "image/vnd.wap.wbmp";
699 /* and let xdgmime do the fallback. */
700 return xdg_mime_get_mime_type_from_file_name(what);
703 static HashList *IconHash = NULL;
705 typedef struct IconName IconName;
712 static void DeleteIcon(void *IconNamePtr)
714 IconName *Icon = (IconName*) IconNamePtr;
715 free(Icon->FlatName);
716 free(Icon->FileName);
721 static const char *PrintFlat(void *IconNamePtr)
723 IconName *Icon = (IconName*) IconNamePtr;
724 return Icon->FlatName;
726 static const char *PrintFile(void *IconNamePtr)
728 IconName *Icon = (IconName*) IconNamePtr;
729 return Icon->FileName;
733 #define GENSTR "x-generic"
734 #define IGNORE_PREFIX_1 "gnome-mime"
735 int LoadIconDir(const char *DirName)
738 struct dirent *filedir_entry;
743 filedir = opendir (DirName);
744 IconHash = NewHash(1, NULL);
745 if (filedir == NULL) {
749 while ((filedir_entry = readdir(filedir)))
753 #ifdef _DIRENT_HAVE_D_NAMELEN
754 d_namelen = filedir_entry->d_namelen;
756 d_namelen = strlen(filedir_entry->d_name);
758 d_without_ext = d_namelen;
759 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
761 if ((d_without_ext == 0) || (d_namelen < 3))
764 if ((sizeof(IGNORE_PREFIX_1) < d_namelen) &&
765 (strncmp(IGNORE_PREFIX_1,
766 filedir_entry->d_name,
767 sizeof(IGNORE_PREFIX_1) - 1) == 0)) {
768 PStart = filedir_entry->d_name + sizeof(IGNORE_PREFIX_1);
769 d_without_ext -= sizeof(IGNORE_PREFIX_1);
772 PStart = filedir_entry->d_name;
774 Icon = malloc(sizeof(IconName));
776 Icon->FileName = malloc(d_namelen + 1);
777 memcpy(Icon->FileName, filedir_entry->d_name, d_namelen + 1);
779 Icon->FlatName = malloc(d_without_ext + 1);
780 memcpy(Icon->FlatName, PStart, d_without_ext);
781 Icon->FlatName[d_without_ext] = '\0';
782 /* Try to find Minor type in image-jpeg */
783 MinorPtr = strchr(Icon->FlatName, '-');
784 if (MinorPtr != NULL) {
786 MinorLen = 1 + d_without_ext - (MinorPtr - Icon->FlatName + 1);
787 if ((MinorLen == sizeof(GENSTR)) &&
788 (strncmp(MinorPtr + 1, GENSTR, sizeof(GENSTR)) == 0)) {
789 /* ok, we found a generic filename. cut the generic. */
791 d_without_ext = d_without_ext - (MinorPtr - Icon->FlatName);
793 else { /* Map the major / minor separator to / */
798 // PrintHash(IconHash, PrintFlat, PrintFile);
799 // printf("%s - %s\n", Icon->FlatName, Icon->FileName);
800 Put(IconHash, Icon->FlatName, d_without_ext, Icon, DeleteIcon);
801 // PrintHash(IconHash, PrintFlat, PrintFile);
807 const char *GetIconFilename(char *MimeType, size_t len)
815 GetHash(IconHash, MimeType, len, &vIcon), Icon = (IconName*) vIcon;
816 /* didn't find the exact mimetype? try major only. */
819 pMinor = strchr(MimeType, '/');
820 if (pMinor != NULL) {
822 GetHash(IconHash, MimeType, pMinor - MimeType, &vIcon),
823 Icon = (IconName*) vIcon;
830 /*printf("Getting: [%s] == [%s] -> [%s]\n", MimeType, Icon->FlatName, Icon->FileName);*/
831 return Icon->FileName;
834 void ShutDownLibCitadelMime(void)
836 DeleteHash(&IconHash);