2 * Another stupid program, this one parsing the headers of an
3 * email to figure out authorship and subject
9 static FILE *cmitmsg, *patchfile, *fin, *fout;
11 static int keep_subject;
12 static const char *metainfo_charset;
13 static char line[1000];
14 static char name[1000];
15 static char email[1000];
18 TE_DONTCARE, TE_QP, TE_BASE64,
21 TYPE_TEXT, TYPE_OTHER,
24 static char charset[256];
25 static int patch_lines;
26 static char **p_hdr_data, **s_hdr_data;
28 #define MAX_HDR_PARSED 10
29 #define MAX_BOUNDARIES 5
31 static char *sanity_check(char *name, char *email)
33 int len = strlen(name);
34 if (len < 3 || len > 60)
36 if (strchr(name, '@') || strchr(name, '<') || strchr(name, '>'))
41 static int bogus_from(char *line)
43 /* John Doe <johndoe> */
44 char *bra, *ket, *dst, *cp;
46 /* This is fallback, so do not bother if we already have an
52 bra = strchr(line, '<');
55 ket = strchr(bra, '>');
59 for (dst = email, cp = bra+1; cp < ket; )
62 for (cp = line; isspace(*cp); cp++)
64 for (bra--; isspace(*bra); bra--)
66 cp = sanity_check(cp, email);
71 static int handle_from(char *in_line)
77 strcpy(line, in_line);
78 at = strchr(line, '@');
80 return bogus_from(line);
83 * If we already have one email, don't take any confusing lines
85 if (*email && strchr(at+1, '@'))
88 /* Pick up the string around '@', possibly delimited with <>
89 * pair; that is the email part. White them out while copying.
103 unsigned char c = *at;
104 if (!c || c == '>' || isspace(c)) {
114 /* The remainder is name. It could be "John Doe <john.doe@xz>"
115 * or "john.doe@xz (John Doe)", but we have whited out the
116 * email part, so trim from both ends, possibly removing
117 * the () pair at the end.
119 at = line + strlen(line);
121 unsigned char c = *--at;
123 at[(c == ')') ? 0 : 1] = 0;
130 unsigned char c = *at;
131 if (!c || !isspace(c)) {
138 at = sanity_check(at, email);
143 static int handle_header(char *line, char *data, int ofs)
148 strcpy(data, line+ofs);
153 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
154 * to have enough heuristics to grok MIME encoded patches often found
155 * on our mailing lists. For example, we do not even treat header lines
156 * case insensitively.
159 static int slurp_attr(const char *line, const char *name, char *attr)
161 const char *ends, *ap = strcasestr(line, name);
175 sz = strcspn(ap, ends);
176 memcpy(attr, ap, sz);
181 struct content_type {
186 static struct content_type content[MAX_BOUNDARIES];
188 static struct content_type *content_top = content;
190 static int handle_content_type(char *line)
194 if (strcasestr(line, "text/") == NULL)
195 message_type = TYPE_OTHER;
196 if (slurp_attr(line, "boundary=", boundary + 2)) {
197 memcpy(boundary, "--", 2);
198 if (content_top++ >= &content[MAX_BOUNDARIES]) {
199 fprintf(stderr, "Too many boundaries to handle\n");
202 content_top->boundary_len = strlen(boundary);
203 content_top->boundary = xmalloc(content_top->boundary_len+1);
204 strcpy(content_top->boundary, boundary);
206 if (slurp_attr(line, "charset=", charset)) {
208 for (i = 0; (c = charset[i]) != 0; i++)
209 charset[i] = tolower(c);
214 static int handle_content_transfer_encoding(char *line)
216 if (strcasestr(line, "base64"))
217 transfer_encoding = TE_BASE64;
218 else if (strcasestr(line, "quoted-printable"))
219 transfer_encoding = TE_QP;
221 transfer_encoding = TE_DONTCARE;
225 static int is_multipart_boundary(const char *line)
227 return (!memcmp(line, content_top->boundary, content_top->boundary_len));
230 static int eatspace(char *line)
232 int len = strlen(line);
233 while (len > 0 && isspace(line[len-1]))
238 static char *cleanup_subject(char *subject)
245 if (!memcmp("e:", subject+1, 2)) {
250 case ' ': case '\t': case ':':
255 p = strchr(subject, ']');
261 remove = p - subject;
262 if (remove <= len *2) {
273 static void cleanup_space(char *buf)
276 while ((c = *buf) != 0) {
282 int len = strlen(buf);
283 memmove(buf, buf+1, len);
290 static void decode_header(char *it, unsigned itsize);
291 static const char *header[MAX_HDR_PARSED] = {
292 "From","Subject","Date",
295 static int check_header(char *line, unsigned linesize, char **hdr_data, int overwrite)
299 /* search for the interesting parts */
300 for (i = 0; header[i]; i++) {
301 int len = strlen(header[i]);
302 if ((!hdr_data[i] || overwrite) &&
303 !strncasecmp(line, header[i], len) &&
304 line[len] == ':' && isspace(line[len + 1])) {
305 /* Unwrap inline B and Q encoding, and optionally
306 * normalize the meta information to utf8.
308 decode_header(line + len + 2, linesize - len - 2);
309 hdr_data[i] = xmalloc(1000 * sizeof(char));
310 if (! handle_header(line, hdr_data[i], len + 2)) {
317 if (!strncasecmp(line, "Content-Type", 12) &&
318 line[12] == ':' && isspace(line[12 + 1])) {
319 decode_header(line + 12 + 2, linesize - 12 - 2);
320 if (! handle_content_type(line)) {
324 if (!strncasecmp(line, "Content-Transfer-Encoding", 25) &&
325 line[25] == ':' && isspace(line[25 + 1])) {
326 decode_header(line + 25 + 2, linesize - 25 - 2);
327 if (! handle_content_transfer_encoding(line)) {
332 /* for inbody stuff */
333 if (!memcmp(">From", line, 5) && isspace(line[5]))
335 if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
336 for (i = 0; header[i]; i++) {
337 if (!memcmp("Subject: ", header[i], 9)) {
338 if (! handle_header(line, hdr_data[i], 0)) {
349 static int is_rfc2822_header(char *line)
352 * The section that defines the loosest possible
353 * field name is "3.6.8 Optional fields".
355 * optional-field = field-name ":" unstructured CRLF
356 * field-name = 1*ftext
357 * ftext = %d33-57 / %59-126
362 /* Count mbox From headers as headers */
363 if (!memcmp(line, "From ", 5) || !memcmp(line, ">From ", 6))
366 while ((ch = *cp++)) {
369 if ((33 <= ch && ch <= 57) ||
370 (59 <= ch && ch <= 126))
378 * sz is size of 'line' buffer in bytes. Must be reasonably
379 * long enough to hold one physical real-world e-mail line.
381 static int read_one_header_line(char *line, int sz, FILE *in)
386 * We will read at most (sz-1) bytes and then potentially
387 * re-add NUL after it. Accessing line[sz] after this is safe
388 * and we can allow len to grow up to and including sz.
392 /* Get the first part of the line. */
393 if (!fgets(line, sz, in))
397 * Is it an empty line or not a valid rfc2822 header?
398 * If so, stop here, and return false ("not a header")
400 len = eatspace(line);
401 if (!len || !is_rfc2822_header(line)) {
402 /* Re-add the newline */
404 line[len + 1] = '\0';
409 * Now we need to eat all the continuation lines..
410 * Yuck, 2822 header "folding"
414 static char continuation[1000];
416 peek = fgetc(in); ungetc(peek, in);
417 if (peek != ' ' && peek != '\t')
419 if (!fgets(continuation, sizeof(continuation), in))
421 addlen = eatspace(continuation);
423 if (addlen >= sz - len)
424 addlen = sz - len - 1;
425 memcpy(line + len, continuation, addlen);
435 static int decode_q_segment(char *in, char *ot, unsigned otsize, char *ep, int rfc2047)
437 char *otend = ot + otsize;
439 while ((c = *in++) != 0 && (in <= ep)) {
447 break; /* drop trailing newline */
448 *ot++ = ((hexval(d) << 4) | hexval(*in++));
451 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
459 static int decode_b_segment(char *in, char *ot, unsigned otsize, char *ep)
461 /* Decode in..ep, possibly in-place to ot */
462 int c, pos = 0, acc = 0;
463 char *otend = ot + otsize;
465 while ((c = *in++) != 0 && (in <= ep)) {
474 else if ('A' <= c && c <= 'Z')
476 else if ('a' <= c && c <= 'z')
478 else if ('0' <= c && c <= '9')
481 /* padding is almost like (c == 0), except we do
482 * not output NUL resulting only from it;
483 * for now we just trust the data.
488 continue; /* garbage */
494 *ot++ = (acc | (c >> 4));
498 *ot++ = (acc | (c >> 2));
512 * When there is no known charset, guess.
514 * Right now we assume that if the target is UTF-8 (the default),
515 * and it already looks like UTF-8 (which includes US-ASCII as its
516 * subset, of course) then that is what it is and there is nothing
519 * Otherwise, we default to assuming it is Latin1 for historical
522 static const char *guess_charset(const char *line, const char *target_charset)
524 if (is_encoding_utf8(target_charset)) {
531 static void convert_to_utf8(char *line, unsigned linesize, const char *charset)
535 if (!charset || !*charset) {
536 charset = guess_charset(line, metainfo_charset);
541 if (!strcmp(metainfo_charset, charset))
543 out = reencode_string(line, metainfo_charset, charset);
545 die("cannot convert from %s to %s\n",
546 charset, metainfo_charset);
547 strlcpy(line, out, linesize);
551 static int decode_header_bq(char *it, unsigned itsize)
553 char *in, *out, *ep, *cp, *sp;
559 while ((ep = strstr(in, "=?")) != NULL) {
561 char charset_q[256], piecebuf[256];
571 * ep : "=?iso-2022-jp?B?GyR...?= foo"
572 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
575 cp = strchr(ep, '?');
577 return rfc2047; /* no munging */
578 for (sp = ep; sp < cp; sp++)
579 charset_q[sp - ep] = tolower(*sp);
580 charset_q[cp - ep] = 0;
582 if (!encoding || cp[2] != '?')
583 return rfc2047; /* no munging */
584 ep = strstr(cp + 3, "?=");
586 return rfc2047; /* no munging */
587 switch (tolower(encoding)) {
589 return rfc2047; /* no munging */
591 sz = decode_b_segment(cp + 3, piecebuf, sizeof(piecebuf), ep);
594 sz = decode_q_segment(cp + 3, piecebuf, sizeof(piecebuf), ep, 1);
599 if (metainfo_charset)
600 convert_to_utf8(piecebuf, sizeof(piecebuf), charset_q);
602 sz = strlen(piecebuf);
603 if (outbuf + sizeof(outbuf) <= out + sz)
604 return rfc2047; /* no munging */
605 strcpy(out, piecebuf);
610 strlcpy(it, outbuf, itsize);
614 static void decode_header(char *it, unsigned itsize)
617 if (decode_header_bq(it, itsize))
619 /* otherwise "it" is a straight copy of the input.
620 * This can be binary guck but there is no charset specified.
622 if (metainfo_charset)
623 convert_to_utf8(it, itsize, "");
626 static void decode_transfer_encoding(char *line, unsigned linesize)
630 switch (transfer_encoding) {
632 ep = line + strlen(line);
633 decode_q_segment(line, line, linesize, ep, 0);
636 ep = line + strlen(line);
637 decode_b_segment(line, line, linesize, ep);
644 static int handle_filter(char *line, unsigned linesize);
646 static int find_boundary(void)
648 while(fgets(line, sizeof(line), fin) != NULL) {
649 if (is_multipart_boundary(line))
655 static int handle_boundary(void)
659 if (!memcmp(line+content_top->boundary_len, "--", 2)) {
660 /* we hit an end boundary */
661 /* pop the current boundary off the stack */
662 free(content_top->boundary);
664 /* technically won't happen as is_multipart_boundary()
665 will fail first. But just in case..
667 if (content_top-- < content) {
668 fprintf(stderr, "Detected mismatched boundaries, "
672 handle_filter(newline, sizeof(newline));
674 /* skip to the next boundary */
675 if (!find_boundary())
680 /* set some defaults */
681 transfer_encoding = TE_DONTCARE;
683 message_type = TYPE_TEXT;
685 /* slurp in this section's info */
686 while (read_one_header_line(line, sizeof(line), fin))
687 check_header(line, sizeof(line), p_hdr_data, 0);
689 /* eat the blank line after section info */
690 return (fgets(line, sizeof(line), fin) != NULL);
693 static inline int patchbreak(const char *line)
695 /* Beginning of a "diff -" header? */
696 if (!memcmp("diff -", line, 6))
699 /* CVS "Index: " line? */
700 if (!memcmp("Index: ", line, 7))
704 * "--- <filename>" starts patches without headers
705 * "---<sp>*" is a manual separator
707 if (!memcmp("---", line, 3)) {
709 /* space followed by a filename? */
710 if (line[0] == ' ' && !isspace(line[1]))
712 /* Just whitespace? */
714 unsigned char c = *line++;
726 static int handle_commit_msg(char *line, unsigned linesize)
728 static int still_looking = 1;
729 char *endline = line + linesize;
736 if (isspace(*line)) {
737 for (cp = line + 1; *cp; cp++) {
744 if ((still_looking = check_header(cp, endline - cp, s_hdr_data, 0)) != 0)
748 /* normalize the log message to UTF-8. */
749 if (metainfo_charset)
750 convert_to_utf8(line, endline - line, charset);
752 if (patchbreak(line)) {
758 fputs(line, cmitmsg);
762 static int handle_patch(char *line)
764 fputs(line, patchfile);
769 static int handle_filter(char *line, unsigned linesize)
771 static int filter = 0;
773 /* filter tells us which part we left off on
774 * a non-zero return indicates we hit a filter point
778 if (!handle_commit_msg(line, linesize))
782 if (!handle_patch(line))
792 static void handle_body(void)
795 static char newline[2000];
796 static char *np = newline;
798 /* Skip up to the first boundary */
799 if (content_top->boundary) {
800 if (!find_boundary())
805 /* process any boundary lines */
806 if (content_top->boundary && is_multipart_boundary(line)) {
807 /* flush any leftover */
808 if ((transfer_encoding == TE_BASE64) &&
810 handle_filter(newline, sizeof(newline));
812 if (!handle_boundary())
816 /* Unwrap transfer encoding */
817 decode_transfer_encoding(line, sizeof(line));
819 switch (transfer_encoding) {
824 /* binary data most likely doesn't have newlines */
825 if (message_type != TYPE_TEXT) {
826 rc = handle_filter(line, sizeof(newline));
830 /* this is a decoded line that may contain
831 * multiple new lines. Pass only one chunk
832 * at a time to handle_filter()
836 while (*op != '\n' && *op != 0)
840 /* should be sitting on a new line */
843 rc = handle_filter(newline, sizeof(newline));
847 /* the partial chunk is saved in newline and
848 * will be appended by the next iteration of fgets
853 rc = handle_filter(line, sizeof(newline));
856 /* nothing left to filter */
858 } while (fgets(line, sizeof(line), fin));
863 static void output_header_lines(FILE *fout, const char *hdr, char *data)
866 char *ep = strchr(data, '\n');
872 fprintf(fout, "%s: %.*s\n", hdr, len, data);
879 static void handle_info(void)
885 for (i = 0; header[i]; i++) {
887 /* only print inbody headers if we output a patch file */
888 if (patch_lines && s_hdr_data[i])
890 else if (p_hdr_data[i])
895 if (!memcmp(header[i], "Subject", 7)) {
899 sub = cleanup_subject(hdr);
902 output_header_lines(fout, "Subject", sub);
903 } else if (!memcmp(header[i], "From", 4)) {
905 fprintf(fout, "Author: %s\n", name);
906 fprintf(fout, "Email: %s\n", email);
909 fprintf(fout, "%s: %s\n", header[i], hdr);
915 static int mailinfo(FILE *in, FILE *out, int ks, const char *encoding,
916 const char *msg, const char *patch)
919 metainfo_charset = encoding;
923 cmitmsg = fopen(msg, "w");
928 patchfile = fopen(patch, "w");
935 p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(char *));
936 s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(char *));
938 /* process the email header */
939 while (read_one_header_line(line, sizeof(line), fin))
940 check_header(line, sizeof(line), p_hdr_data, 1);
948 static const char mailinfo_usage[] =
949 "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
951 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
953 const char *def_charset;
955 /* NEEDSWORK: might want to do the optional .git/ directory
958 git_config(git_default_config);
960 def_charset = (git_commit_encoding ? git_commit_encoding : "utf-8");
961 metainfo_charset = def_charset;
963 while (1 < argc && argv[1][0] == '-') {
964 if (!strcmp(argv[1], "-k"))
966 else if (!strcmp(argv[1], "-u"))
967 metainfo_charset = def_charset;
968 else if (!strcmp(argv[1], "-n"))
969 metainfo_charset = NULL;
970 else if (!prefixcmp(argv[1], "--encoding="))
971 metainfo_charset = argv[1] + 11;
973 usage(mailinfo_usage);
978 usage(mailinfo_usage);
980 return !!mailinfo(stdin, stdout, keep_subject, metainfo_charset, argv[1], argv[2]);