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,
119 char *name, char *filename,
131 void (*PreMultiPartCallBack)
142 void (*PostMultiPartCallBack)
159 size_t bytes_decoded = 0;
161 /* Some encodings aren't really encodings */
162 if (!strcasecmp(encoding, "7bit"))
163 strcpy(encoding, "");
164 if (!strcasecmp(encoding, "8bit"))
165 strcpy(encoding, "");
166 if (!strcasecmp(encoding, "binary"))
167 strcpy(encoding, "");
169 /* If this part is not encoded, send as-is */
170 if ( (strlen(encoding) == 0) || (dont_decode)) {
171 if (CallBack != NULL) {
172 CallBack(name, filename, fixed_partnum(partnum),
173 disposition, part_start,
174 content_type, charset, length, encoding, userdata);
179 /* Fail silently if we hit an unknown encoding. */
180 if ((strcasecmp(encoding, "base64"))
181 && (strcasecmp(encoding, "quoted-printable"))) {
186 * Allocate a buffer for the decoded data. The output buffer is slightly
187 * larger than the input buffer; this assumes that the decoded data
188 * will never be significantly larger than the encoded data. This is a
189 * safe assumption with base64, uuencode, and quoted-printable.
191 decoded = malloc(length + 32768);
192 if (decoded == NULL) {
196 if (!strcasecmp(encoding, "base64")) {
197 bytes_decoded = CtdlDecodeBase64(decoded, part_start, length);
199 else if (!strcasecmp(encoding, "quoted-printable")) {
200 bytes_decoded = CtdlDecodeQuotedPrintable(decoded, part_start, length);
203 if (bytes_decoded > 0) if (CallBack != NULL) {
204 CallBack(name, filename, fixed_partnum(partnum),
205 disposition, decoded,
206 content_type, charset, bytes_decoded, "binary", userdata);
213 * Break out the components of a multipart message
214 * (This function expects to be fed HEADERS + CONTENT)
215 * Note: NULL can be supplied as content_end; in this case, the message is
216 * considered to have ended when the parser encounters a 0x00 byte.
218 void the_mime_parser(char *partnum,
219 char *content_start, char *content_end,
231 void (*PreMultiPartCallBack)
242 void (*PostMultiPartCallBack)
260 char *part_start, *part_end = NULL;
265 size_t startary_len = 0;
270 size_t content_length;
274 char *content_type_name;
275 char *content_disposition_name;
281 char nested_partnum[256];
283 char *evaluate_crlf_ptr = NULL;
290 boundary = malloc(SIZ);
291 memset(boundary, 0, SIZ);
293 startary = malloc(SIZ);
294 memset(startary, 0, SIZ);
296 endary = malloc(SIZ);
297 memset(endary, 0, SIZ);
299 header = malloc(SIZ);
300 memset(header, 0, SIZ);
302 content_type = malloc(SIZ);
303 memset(content_type, 0, SIZ);
305 charset = malloc(SIZ);
306 memset(charset, 0, SIZ);
308 encoding = malloc(SIZ);
309 memset(encoding, 0, SIZ);
311 content_type_name = malloc(SIZ);
312 memset(content_type_name, 0, SIZ);
314 content_disposition_name = malloc(SIZ);
315 memset(content_disposition_name, 0, SIZ);
317 filename = malloc(SIZ);
318 memset(filename, 0, SIZ);
320 disposition = malloc(SIZ);
321 memset(disposition, 0, SIZ);
323 /* If the caller didn't supply an endpointer, generate one by measure */
324 if (content_end == NULL) {
325 content_end = &content_start[strlen(content_start)];
328 /* Learn interesting things from the headers */
332 ptr = memreadlinelen(ptr, buf, SIZ, &buflen);
333 if (ptr >= content_end) {
337 for (i = 0; i < buflen; ++i) {
338 if (isspace(buf[i])) {
343 if (!isspace(buf[0])) {
344 if (!strncasecmp(header, "Content-type:", 13)) {
345 strcpy(content_type, &header[13]);
346 striplt(content_type);
347 extract_key(content_type_name, content_type, "name");
348 extract_key(charset, content_type, "charset");
349 extract_key(boundary, header, "boundary");
350 /* Deal with weird headers */
351 if (strchr(content_type, ' '))
352 *(strchr(content_type, ' ')) = '\0';
353 if (strchr(content_type, ';'))
354 *(strchr(content_type, ';')) = '\0';
356 if (!strncasecmp(header, "Content-Disposition:", 20)) {
357 strcpy(disposition, &header[20]);
358 striplt(disposition);
359 extract_key(content_disposition_name, disposition, "name");
360 extract_key(filename, disposition, "filename");
362 if (!strncasecmp(header, "Content-length: ", 15)) {
364 safestrncpy(clbuf, &header[15], sizeof clbuf);
366 content_length = (size_t) atol(clbuf);
368 if (!strncasecmp(header, "Content-transfer-encoding: ", 26)) {
369 strcpy(encoding, &header[26]);
375 if ((headerlen + buflen + 2) < SIZ) {
376 memcpy(&header[headerlen], buf, buflen);
378 header[headerlen] = '\0';
380 } while ((!IsEmptyStr(buf)) && (*ptr != 0));
382 if (strchr(disposition, ';'))
383 *(strchr(disposition, ';')) = '\0';
384 striplt(disposition);
385 if (strchr(content_type, ';'))
386 *(strchr(content_type, ';')) = '\0';
387 striplt(content_type);
389 if (!IsEmptyStr(boundary)) {
395 /* If this is a multipart message, then recursively process it */
399 /* Tell the client about this message's multipartedness */
400 if (PreMultiPartCallBack != NULL) {
401 PreMultiPartCallBack("", "", partnum, "",
402 NULL, content_type, charset,
403 0, encoding, userdata);
406 /* Figure out where the boundaries are */
407 snprintf(startary, SIZ, "--%s", boundary);
408 snprintf(endary, SIZ, "--%s--", boundary);
409 startary_len = strlen(startary);
413 next_boundary = NULL;
414 for (srch=ptr; srch<content_end; ++srch) {
415 if (!memcmp(srch, startary, startary_len)) {
416 next_boundary = srch;
421 if ( (part_start != NULL) && (next_boundary != NULL) ) {
422 part_end = next_boundary;
423 --part_end; /* omit the trailing LF */
425 --part_end; /* omit the trailing CR */
428 if (!IsEmptyStr(partnum)) {
429 snprintf(nested_partnum,
430 sizeof nested_partnum,
435 snprintf(nested_partnum,
436 sizeof nested_partnum,
439 the_mime_parser(nested_partnum,
440 part_start, part_end,
442 PreMultiPartCallBack,
443 PostMultiPartCallBack,
448 if (next_boundary != NULL) {
449 /* If we pass out of scope, don't attempt to
450 * read past the end boundary. */
451 if (!strcmp(next_boundary, endary)) {
455 /* Set up for the next part. */
456 part_start = strstr(next_boundary, "\n");
458 /* Determine whether newlines are LF or CRLF */
459 evaluate_crlf_ptr = part_start;
461 if (!memcmp(evaluate_crlf_ptr, "\r\n", 2)) {
468 /* Advance past the LF ... now we're in the next part */
474 /* Invalid end of multipart. Bail out! */
477 } while ( (ptr < content_end) && (next_boundary != NULL) );
479 if (PostMultiPartCallBack != NULL) {
480 PostMultiPartCallBack("", "", partnum, "", NULL,
481 content_type, charset, 0, encoding, userdata);
486 /* If it's not a multipart message, then do something with it */
490 while (ptr < content_end) {
494 part_end = content_end;
497 * I thought there was an off-by-one error here, but there isn't.
498 * This probably means that there's an off-by-one error somewhere
499 * else ... or maybe only in certain messages?
504 /* Truncate if the header told us to */
505 if ( (content_length > 0) && (length > content_length) ) {
506 length = content_length;
509 /* Sometimes the "name" field is tacked on to Content-type,
510 * and sometimes it's tacked on to Content-disposition. Use
511 * whichever one we have.
513 if (strlen(content_disposition_name) > strlen(content_type_name)) {
514 name = content_disposition_name;
517 name = content_type_name;
520 /* Ok, we've got a non-multipart part here, so do something with it.
524 content_type, charset, encoding, disposition,
526 CallBack, NULL, NULL,
527 userdata, dont_decode
531 * Now if it's an encapsulated message/rfc822 then we have to recurse into it
533 if (!strcasecmp(content_type, "message/rfc822")) {
535 if (PreMultiPartCallBack != NULL) {
536 PreMultiPartCallBack("", "", partnum, "",
537 NULL, content_type, charset,
538 0, encoding, userdata);
540 if (CallBack != NULL) {
541 if (strlen(partnum) > 0) {
542 snprintf(nested_partnum,
543 sizeof nested_partnum,
548 snprintf(nested_partnum,
549 sizeof nested_partnum,
552 the_mime_parser(nested_partnum,
553 part_start, part_end,
555 PreMultiPartCallBack,
556 PostMultiPartCallBack,
561 if (PostMultiPartCallBack != NULL) {
562 PostMultiPartCallBack("", "", partnum, "", NULL,
563 content_type, charset, 0, encoding, userdata);
571 end_parser: /* free the buffers! end the oppression!! */
579 free(content_type_name);
580 free(content_disposition_name);
588 * Entry point for the MIME parser.
589 * (This function expects to be fed HEADERS + CONTENT)
590 * Note: NULL can be supplied as content_end; in this case, the message is
591 * considered to have ended when the parser encounters a 0x00 byte.
593 void mime_parser(char *content_start,
608 void (*PreMultiPartCallBack)
620 void (*PostMultiPartCallBack)
637 the_mime_parser("", content_start, content_end,
639 PreMultiPartCallBack,
640 PostMultiPartCallBack,
641 userdata, dont_decode);
649 typedef struct _MimeGuess {
653 const char *MimeString;
656 MimeGuess MyMimes [] = {
684 const char *GuessMimeType(char *data, size_t dlen)
688 while (MyMimes[MimeIndex].PatternLen != 0)
690 if ((MyMimes[MimeIndex].PatternLen +
691 MyMimes[MimeIndex].PatternOffset < dlen) &&
692 strncmp(MyMimes[MimeIndex].Pattern,
693 &data[MyMimes[MimeIndex].PatternOffset],
694 MyMimes[MimeIndex].PatternLen) == 0)
696 return MyMimes[MimeIndex].MimeString;
701 * ok, our simple minded algorythm didn't find anything,
702 * let the big chegger try it, he wil default to application/octet-stream
704 return (xdg_mime_get_mime_type_for_data(data, dlen));
708 const char* GuessMimeByFilename(const char *what, size_t len)
710 /* we know some hardcoded on our own, try them... */
711 if (!strncasecmp(&what[len - 4], ".gif", 4))
713 else if (!strncasecmp(&what[len - 3], ".js", 3))
714 return "text/javascript";
715 else if (!strncasecmp(&what[len - 4], ".txt", 4))
717 else if (!strncasecmp(&what[len - 4], ".css", 4))
719 else if (!strncasecmp(&what[len - 4], ".jpg", 4))
721 else if (!strncasecmp(&what[len - 4], ".png", 4))
723 else if (!strncasecmp(&what[len - 4], ".ico", 4))
724 return "image/x-icon";
725 else if (!strncasecmp(&what[len - 5], ".html", 5))
727 else if (!strncasecmp(&what[len - 4], ".htm", 4))
729 else if (!strncasecmp(&what[len - 4], ".wml", 4))
730 return "text/vnd.wap.wml";
731 else if (!strncasecmp(&what[len - 5], ".wmls", 5))
732 return "text/vnd.wap.wmlscript";
733 else if (!strncasecmp(&what[len - 5], ".wmlc", 5))
734 return "application/vnd.wap.wmlc";
735 else if (!strncasecmp(&what[len - 6], ".wmlsc", 6))
736 return "application/vnd.wap.wmlscriptc";
737 else if (!strncasecmp(&what[len - 5], ".wbmp", 5))
738 return "image/vnd.wap.wbmp";
740 /* and let xdgmime do the fallback. */
741 return xdg_mime_get_mime_type_from_file_name(what);
744 static HashList *IconHash = NULL;
746 typedef struct IconName IconName;
753 static void DeleteIcon(void *IconNamePtr)
755 IconName *Icon = (IconName*) IconNamePtr;
756 free(Icon->FlatName);
757 free(Icon->FileName);
760 static const char *PrintFlat(void *IconNamePtr)
762 IconName *Icon = (IconName*) IconNamePtr;
763 return Icon->FlatName;
765 static const char *PrintFile(void *IconNamePtr)
767 IconName *Icon = (IconName*) IconNamePtr;
768 return Icon->FileName;
770 #define GENSTR "x-generic"
771 #define IGNORE_PREFIX_1 "gnome-mime"
772 int LoadIconDir(const char *DirName)
775 struct dirent *filedir_entry;
780 filedir = opendir (DirName);
781 IconHash = NewHash();
782 if (filedir == NULL) {
786 while ((filedir_entry = readdir(filedir)))
790 #ifdef _DIRENT_HAVE_D_NAMELEN
791 d_namelen = filedir_entry->d_namelen;
793 d_namelen = strlen(filedir_entry->d_name);
795 d_without_ext = d_namelen;
796 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
798 if ((d_without_ext == 0) || (d_namelen < 3))
801 if ((sizeof(IGNORE_PREFIX_1) < d_namelen) &&
802 (strncmp(IGNORE_PREFIX_1,
803 filedir_entry->d_name,
804 sizeof(IGNORE_PREFIX_1) - 1) == 0)) {
805 PStart = filedir_entry->d_name + sizeof(IGNORE_PREFIX_1);
806 d_without_ext -= sizeof(IGNORE_PREFIX_1);
809 PStart = filedir_entry->d_name;
811 Icon = malloc(sizeof(IconName));
813 Icon->FileName = malloc(d_namelen + 1);
814 memcpy(Icon->FileName, filedir_entry->d_name, d_namelen + 1);
816 Icon->FlatName = malloc(d_without_ext + 1);
817 memcpy(Icon->FlatName, PStart, d_without_ext);
818 Icon->FlatName[d_without_ext] = '\0';
819 /* Try to find Minor type in image-jpeg */
820 MinorPtr = strchr(Icon->FlatName, '-');
821 if (MinorPtr != NULL) {
823 MinorLen = 1 + d_without_ext - (MinorPtr - Icon->FlatName + 1);
824 if ((MinorLen == sizeof(GENSTR)) &&
825 (strncmp(MinorPtr + 1, GENSTR, sizeof(GENSTR)) == 0)) {
826 /* ok, we found a generic filename. cut the generic. */
828 d_without_ext = d_without_ext - (MinorPtr - Icon->FlatName);
830 else { /* Map the major / minor separator to / */
835 // PrintHash(IconHash, PrintFlat, PrintFile);
836 // printf("%s - %s\n", Icon->FlatName, Icon->FileName);
837 Put(IconHash, Icon->FlatName, d_without_ext, Icon, DeleteIcon);
838 // PrintHash(IconHash, PrintFlat, PrintFile);
843 const char *GetIconFilename(char *MimeType, size_t len)
850 GetHash(IconHash, MimeType, len, (void**)&Icon);
851 /* didn't find the exact mimetype? try major only. */
854 pMinor = strchr(MimeType, '/');
855 if (pMinor != NULL) {
857 GetHash(IconHash, MimeType, pMinor - MimeType, (void**)&Icon);
864 /*printf("Getting: [%s] == [%s] -> [%s]\n", MimeType, Icon->FlatName, Icon->FileName);*/
865 return Icon->FileName;
868 void ShutDownLibCitadel(void)
870 DeleteHash(&IconHash);