2 * Another stupid program, this one parsing the headers of an
3 * email to figure out authorship and subject
10 static FILE *cmitmsg, *patchfile, *fin, *fout;
12 static int keep_subject;
13 static int keep_non_patch_brackets_in_subject;
14 static const char *metainfo_charset;
15 static struct strbuf line = STRBUF_INIT;
16 static struct strbuf name = STRBUF_INIT;
17 static struct strbuf email = STRBUF_INIT;
20 TE_DONTCARE, TE_QP, TE_BASE64
26 static struct strbuf charset = STRBUF_INIT;
27 static int patch_lines;
28 static struct strbuf **p_hdr_data, **s_hdr_data;
29 static int use_scissors;
30 static int use_inbody_headers = 1;
32 #define MAX_HDR_PARSED 10
33 #define MAX_BOUNDARIES 5
35 static void cleanup_space(struct strbuf *sb);
38 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
40 struct strbuf *src = name;
41 if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
42 strchr(name->buf, '<') || strchr(name->buf, '>'))
47 strbuf_addbuf(out, src);
50 static void parse_bogus_from(const struct strbuf *line)
52 /* John Doe <johndoe> */
55 /* This is fallback, so do not bother if we already have an
61 bra = strchr(line->buf, '<');
64 ket = strchr(bra, '>');
69 strbuf_add(&email, bra + 1, ket - bra - 1);
72 strbuf_add(&name, line->buf, bra - line->buf);
74 get_sane_name(&name, &name, &email);
77 static void handle_from(const struct strbuf *from)
83 strbuf_init(&f, from->len);
84 strbuf_addbuf(&f, from);
86 at = strchr(f.buf, '@');
88 parse_bogus_from(from);
93 * If we already have one email, don't take any confusing lines
95 if (email.len && strchr(at + 1, '@')) {
100 /* Pick up the string around '@', possibly delimited with <>
101 * pair; that is the email part.
113 el = strcspn(at, " \n\t\r\v\f>");
114 strbuf_reset(&email);
115 strbuf_add(&email, at, el);
116 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
118 /* The remainder is name. It could be
120 * - "John Doe <john.doe@xz>" (a), or
121 * - "john.doe@xz (John Doe)" (b), or
122 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
124 * but we have removed the email part, so
126 * - remove extra spaces which could stay after email (case 'c'), and
127 * - trim from both ends, possibly removing the () pair at the end
128 * (cases 'a' and 'b').
132 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
133 strbuf_remove(&f, 0, 1);
134 strbuf_setlen(&f, f.len - 1);
137 get_sane_name(&name, &f, &email);
141 static void handle_header(struct strbuf **out, const struct strbuf *line)
144 *out = xmalloc(sizeof(struct strbuf));
145 strbuf_init(*out, line->len);
149 strbuf_addbuf(*out, line);
152 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
153 * to have enough heuristics to grok MIME encoded patches often found
154 * on our mailing lists. For example, we do not even treat header lines
155 * case insensitively.
158 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
160 const char *ends, *ap = strcasestr(line, name);
163 strbuf_setlen(attr, 0);
173 sz = strcspn(ap, ends);
174 strbuf_add(attr, ap, sz);
178 static struct strbuf *content[MAX_BOUNDARIES];
180 static struct strbuf **content_top = content;
182 static void handle_content_type(struct strbuf *line)
184 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
185 strbuf_init(boundary, line->len);
187 if (!strcasestr(line->buf, "text/"))
188 message_type = TYPE_OTHER;
189 if (slurp_attr(line->buf, "boundary=", boundary)) {
190 strbuf_insert(boundary, 0, "--", 2);
191 if (++content_top > &content[MAX_BOUNDARIES]) {
192 fprintf(stderr, "Too many boundaries to handle\n");
195 *content_top = boundary;
198 slurp_attr(line->buf, "charset=", &charset);
201 strbuf_release(boundary);
206 static void handle_content_transfer_encoding(const struct strbuf *line)
208 if (strcasestr(line->buf, "base64"))
209 transfer_encoding = TE_BASE64;
210 else if (strcasestr(line->buf, "quoted-printable"))
211 transfer_encoding = TE_QP;
213 transfer_encoding = TE_DONTCARE;
216 static int is_multipart_boundary(const struct strbuf *line)
218 return (((*content_top)->len <= line->len) &&
219 !memcmp(line->buf, (*content_top)->buf, (*content_top)->len));
222 static void cleanup_subject(struct strbuf *subject)
226 while (at < subject->len) {
230 switch (subject->buf[at]) {
232 if (subject->len <= at + 3)
234 if ((subject->buf[at + 1] == 'e' ||
235 subject->buf[at + 1] == 'E') &&
236 subject->buf[at + 2] == ':') {
237 strbuf_remove(subject, at, 3);
242 case ' ': case '\t': case ':':
243 strbuf_remove(subject, at, 1);
246 pos = strchr(subject->buf + at, ']');
249 remove = pos - subject->buf + at + 1;
250 if (!keep_non_patch_brackets_in_subject ||
252 memmem(subject->buf + at, remove, "PATCH", 5)))
253 strbuf_remove(subject, at, remove);
257 * If the input had a space after the ], keep
258 * it. We don't bother with finding the end of
259 * the space, since we later normalize it
262 if (isspace(subject->buf[at]))
269 strbuf_trim(subject);
272 static void cleanup_space(struct strbuf *sb)
275 for (pos = 0; pos < sb->len; pos++) {
276 if (isspace(sb->buf[pos])) {
278 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
279 strbuf_remove(sb, pos + 1, cnt);
284 static void decode_header(struct strbuf *line);
285 static const char *header[MAX_HDR_PARSED] = {
286 "From","Subject","Date",
289 static inline int cmp_header(const struct strbuf *line, const char *hdr)
291 int len = strlen(hdr);
292 return !strncasecmp(line->buf, hdr, len) && line->len > len &&
293 line->buf[len] == ':' && isspace(line->buf[len + 1]);
296 static int check_header(const struct strbuf *line,
297 struct strbuf *hdr_data[], int overwrite)
300 struct strbuf sb = STRBUF_INIT;
301 /* search for the interesting parts */
302 for (i = 0; header[i]; i++) {
303 int len = strlen(header[i]);
304 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
305 /* Unwrap inline B and Q encoding, and optionally
306 * normalize the meta information to utf8.
308 strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
310 handle_header(&hdr_data[i], &sb);
312 goto check_header_out;
317 if (cmp_header(line, "Content-Type")) {
318 len = strlen("Content-Type: ");
319 strbuf_add(&sb, line->buf + len, line->len - len);
321 strbuf_insert(&sb, 0, "Content-Type: ", len);
322 handle_content_type(&sb);
324 goto check_header_out;
326 if (cmp_header(line, "Content-Transfer-Encoding")) {
327 len = strlen("Content-Transfer-Encoding: ");
328 strbuf_add(&sb, line->buf + len, line->len - len);
330 handle_content_transfer_encoding(&sb);
332 goto check_header_out;
335 /* for inbody stuff */
336 if (!prefixcmp(line->buf, ">From") && isspace(line->buf[5])) {
337 ret = 1; /* Should this return 0? */
338 goto check_header_out;
340 if (!prefixcmp(line->buf, "[PATCH]") && isspace(line->buf[7])) {
341 for (i = 0; header[i]; i++) {
342 if (!memcmp("Subject", header[i], 7)) {
343 handle_header(&hdr_data[i], line);
345 goto check_header_out;
355 static int is_rfc2822_header(const struct strbuf *line)
358 * The section that defines the loosest possible
359 * field name is "3.6.8 Optional fields".
361 * optional-field = field-name ":" unstructured CRLF
362 * field-name = 1*ftext
363 * ftext = %d33-57 / %59-126
366 char *cp = line->buf;
368 /* Count mbox From headers as headers */
369 if (!prefixcmp(cp, "From ") || !prefixcmp(cp, ">From "))
372 while ((ch = *cp++)) {
375 if ((33 <= ch && ch <= 57) ||
376 (59 <= ch && ch <= 126))
383 static int read_one_header_line(struct strbuf *line, FILE *in)
385 /* Get the first part of the line. */
386 if (strbuf_getline(line, in, '\n'))
390 * Is it an empty line or not a valid rfc2822 header?
391 * If so, stop here, and return false ("not a header")
394 if (!line->len || !is_rfc2822_header(line)) {
395 /* Re-add the newline */
396 strbuf_addch(line, '\n');
401 * Now we need to eat all the continuation lines..
402 * Yuck, 2822 header "folding"
406 struct strbuf continuation = STRBUF_INIT;
408 peek = fgetc(in); ungetc(peek, in);
409 if (peek != ' ' && peek != '\t')
411 if (strbuf_getline(&continuation, in, '\n'))
413 continuation.buf[0] = ' ';
414 strbuf_rtrim(&continuation);
415 strbuf_addbuf(line, &continuation);
421 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
423 const char *in = q_seg->buf;
425 struct strbuf *out = xmalloc(sizeof(struct strbuf));
426 strbuf_init(out, q_seg->len);
428 while ((c = *in++) != 0) {
432 break; /* drop trailing newline */
433 strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
436 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
438 strbuf_addch(out, c);
443 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
445 /* Decode in..ep, possibly in-place to ot */
446 int c, pos = 0, acc = 0;
447 const char *in = b_seg->buf;
448 struct strbuf *out = xmalloc(sizeof(struct strbuf));
449 strbuf_init(out, b_seg->len);
451 while ((c = *in++) != 0) {
456 else if ('A' <= c && c <= 'Z')
458 else if ('a' <= c && c <= 'z')
460 else if ('0' <= c && c <= '9')
463 continue; /* garbage */
469 strbuf_addch(out, (acc | (c >> 4)));
473 strbuf_addch(out, (acc | (c >> 2)));
477 strbuf_addch(out, (acc | c));
485 static void convert_to_utf8(struct strbuf *line, const char *charset)
489 if (!charset || !*charset)
491 if (!strcasecmp(metainfo_charset, charset))
493 out = reencode_string(line->buf, metainfo_charset, charset);
495 die("cannot convert from %s to %s",
496 charset, metainfo_charset);
497 strbuf_attach(line, out, strlen(out), strlen(out));
500 static int decode_header_bq(struct strbuf *it)
503 struct strbuf outbuf = STRBUF_INIT, *dec;
504 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
508 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
510 strbuf_reset(&charset_q);
511 strbuf_reset(&piecebuf);
516 * We are about to process an encoded-word
517 * that begins at ep, but there is something
518 * before the encoded word.
521 for (scan = in; scan < ep; scan++)
525 if (scan != ep || in == it->buf) {
527 * We should not lose that "something",
528 * unless we have just processed an
529 * encoded-word, and there is only LWS
530 * before the one we are about to process.
532 strbuf_add(&outbuf, in, ep - in);
536 * ep : "=?iso-2022-jp?B?GyR...?= foo"
537 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
541 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
542 goto decode_header_bq_out;
544 if (cp + 3 - it->buf > it->len)
545 goto decode_header_bq_out;
546 strbuf_add(&charset_q, ep, cp - ep);
549 if (!encoding || cp[2] != '?')
550 goto decode_header_bq_out;
551 ep = strstr(cp + 3, "?=");
553 goto decode_header_bq_out;
554 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
555 switch (tolower(encoding)) {
557 goto decode_header_bq_out;
559 dec = decode_b_segment(&piecebuf);
562 dec = decode_q_segment(&piecebuf, 1);
565 if (metainfo_charset)
566 convert_to_utf8(dec, charset_q.buf);
568 strbuf_addbuf(&outbuf, dec);
573 strbuf_addstr(&outbuf, in);
575 strbuf_addbuf(it, &outbuf);
576 decode_header_bq_out:
577 strbuf_release(&outbuf);
578 strbuf_release(&charset_q);
579 strbuf_release(&piecebuf);
583 static void decode_header(struct strbuf *it)
585 if (decode_header_bq(it))
587 /* otherwise "it" is a straight copy of the input.
588 * This can be binary guck but there is no charset specified.
590 if (metainfo_charset)
591 convert_to_utf8(it, "");
594 static void decode_transfer_encoding(struct strbuf *line)
598 switch (transfer_encoding) {
600 ret = decode_q_segment(line, 0);
603 ret = decode_b_segment(line);
610 strbuf_addbuf(line, ret);
615 static void handle_filter(struct strbuf *line);
617 static int find_boundary(void)
619 while (!strbuf_getline(&line, fin, '\n')) {
620 if (*content_top && is_multipart_boundary(&line))
626 static int handle_boundary(void)
628 struct strbuf newline = STRBUF_INIT;
630 strbuf_addch(&newline, '\n');
632 if (line.len >= (*content_top)->len + 2 &&
633 !memcmp(line.buf + (*content_top)->len, "--", 2)) {
634 /* we hit an end boundary */
635 /* pop the current boundary off the stack */
636 strbuf_release(*content_top);
640 /* technically won't happen as is_multipart_boundary()
641 will fail first. But just in case..
643 if (--content_top < content) {
644 fprintf(stderr, "Detected mismatched boundaries, "
648 handle_filter(&newline);
649 strbuf_release(&newline);
651 /* skip to the next boundary */
652 if (!find_boundary())
657 /* set some defaults */
658 transfer_encoding = TE_DONTCARE;
659 strbuf_reset(&charset);
660 message_type = TYPE_TEXT;
662 /* slurp in this section's info */
663 while (read_one_header_line(&line, fin))
664 check_header(&line, p_hdr_data, 0);
666 strbuf_release(&newline);
668 if (strbuf_getline(&line, fin, '\n'))
670 strbuf_addch(&line, '\n');
674 static inline int patchbreak(const struct strbuf *line)
678 /* Beginning of a "diff -" header? */
679 if (!prefixcmp(line->buf, "diff -"))
682 /* CVS "Index: " line? */
683 if (!prefixcmp(line->buf, "Index: "))
687 * "--- <filename>" starts patches without headers
688 * "---<sp>*" is a manual separator
693 if (!prefixcmp(line->buf, "---")) {
694 /* space followed by a filename? */
695 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
697 /* Just whitespace? */
698 for (i = 3; i < line->len; i++) {
699 unsigned char c = line->buf[i];
710 static int is_scissors_line(const struct strbuf *line)
712 size_t i, len = line->len;
713 int scissors = 0, gap = 0;
714 int first_nonblank = -1;
715 int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
716 const char *buf = line->buf;
718 for (i = 0; i < len; i++) {
719 if (isspace(buf[i])) {
720 if (in_perforation) {
727 if (first_nonblank < 0)
735 (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
736 !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
747 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
748 * Even though there can be arbitrary cruft on the same line
749 * (e.g. "cut here"), in order to avoid misidentification, the
750 * perforation must occupy more than a third of the visible
751 * width of the line, and dashes and scissors must occupy more
752 * than half of the perforation.
755 visible = last_nonblank - first_nonblank + 1;
756 return (scissors && 8 <= visible &&
757 visible < perforation * 3 &&
758 gap * 2 < perforation);
761 static int handle_commit_msg(struct strbuf *line)
763 static int still_looking = 1;
769 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
773 if (use_inbody_headers && still_looking) {
774 still_looking = check_header(line, s_hdr_data, 0);
778 /* Only trim the first (blank) line of the commit message
779 * when ignoring in-body headers.
783 /* normalize the log message to UTF-8. */
784 if (metainfo_charset)
785 convert_to_utf8(line, charset.buf);
787 if (use_scissors && is_scissors_line(line)) {
789 if (fseek(cmitmsg, 0L, SEEK_SET))
790 die_errno("Could not rewind output message file");
791 if (ftruncate(fileno(cmitmsg), 0))
792 die_errno("Could not truncate output message file at scissors");
796 * We may have already read "secondary headers"; purge
797 * them to give ourselves a clean restart.
799 for (i = 0; header[i]; i++) {
801 strbuf_release(s_hdr_data[i]);
802 s_hdr_data[i] = NULL;
807 if (patchbreak(line)) {
813 fputs(line->buf, cmitmsg);
817 static void handle_patch(const struct strbuf *line)
819 fwrite(line->buf, 1, line->len, patchfile);
823 static void handle_filter(struct strbuf *line)
825 static int filter = 0;
827 /* filter tells us which part we left off on */
830 if (!handle_commit_msg(line))
839 static void handle_body(void)
841 struct strbuf prev = STRBUF_INIT;
843 /* Skip up to the first boundary */
845 if (!find_boundary())
846 goto handle_body_out;
850 /* process any boundary lines */
851 if (*content_top && is_multipart_boundary(&line)) {
852 /* flush any leftover */
854 handle_filter(&prev);
857 if (!handle_boundary())
858 goto handle_body_out;
861 /* Unwrap transfer encoding */
862 decode_transfer_encoding(&line);
864 switch (transfer_encoding) {
868 struct strbuf **lines, **it, *sb;
870 /* Prepend any previous partial lines */
871 strbuf_insert(&line, 0, prev.buf, prev.len);
874 /* binary data most likely doesn't have newlines */
875 if (message_type != TYPE_TEXT) {
876 handle_filter(&line);
880 * This is a decoded line that may contain
881 * multiple new lines. Pass only one chunk
882 * at a time to handle_filter()
884 lines = strbuf_split(&line, '\n');
885 for (it = lines; (sb = *it); it++) {
886 if (*(it + 1) == NULL) /* The last line */
887 if (sb->buf[sb->len - 1] != '\n') {
888 /* Partial line, save it for later. */
889 strbuf_addbuf(&prev, sb);
895 * The partial chunk is saved in "prev" and will be
896 * appended by the next iteration of read_line_with_nul().
898 strbuf_list_free(lines);
902 handle_filter(&line);
905 } while (!strbuf_getwholeline(&line, fin, '\n'));
908 strbuf_release(&prev);
911 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
913 const char *sp = data->buf;
915 char *ep = strchr(sp, '\n');
921 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
928 static void handle_info(void)
933 for (i = 0; header[i]; i++) {
934 /* only print inbody headers if we output a patch file */
935 if (patch_lines && s_hdr_data[i])
937 else if (p_hdr_data[i])
942 if (!memcmp(header[i], "Subject", 7)) {
944 cleanup_subject(hdr);
947 output_header_lines(fout, "Subject", hdr);
948 } else if (!memcmp(header[i], "From", 4)) {
951 fprintf(fout, "Author: %s\n", name.buf);
952 fprintf(fout, "Email: %s\n", email.buf);
955 fprintf(fout, "%s: %s\n", header[i], hdr->buf);
961 static int mailinfo(FILE *in, FILE *out, const char *msg, const char *patch)
967 cmitmsg = fopen(msg, "w");
972 patchfile = fopen(patch, "w");
979 p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
980 s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
984 } while (isspace(peek));
987 /* process the email header */
988 while (read_one_header_line(&line, fin))
989 check_header(&line, p_hdr_data, 1);
997 static int git_mailinfo_config(const char *var, const char *value, void *unused)
999 if (prefixcmp(var, "mailinfo."))
1000 return git_default_config(var, value, unused);
1001 if (!strcmp(var, "mailinfo.scissors")) {
1002 use_scissors = git_config_bool(var, value);
1005 /* perhaps others here */
1009 static const char mailinfo_usage[] =
1010 "git mailinfo [-k|-b] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] msg patch < mail >info";
1012 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1014 const char *def_charset;
1016 /* NEEDSWORK: might want to do the optional .git/ directory
1019 git_config(git_mailinfo_config, NULL);
1021 def_charset = get_commit_output_encoding();
1022 metainfo_charset = def_charset;
1024 while (1 < argc && argv[1][0] == '-') {
1025 if (!strcmp(argv[1], "-k"))
1027 else if (!strcmp(argv[1], "-b"))
1028 keep_non_patch_brackets_in_subject = 1;
1029 else if (!strcmp(argv[1], "-u"))
1030 metainfo_charset = def_charset;
1031 else if (!strcmp(argv[1], "-n"))
1032 metainfo_charset = NULL;
1033 else if (!prefixcmp(argv[1], "--encoding="))
1034 metainfo_charset = argv[1] + 11;
1035 else if (!strcmp(argv[1], "--scissors"))
1037 else if (!strcmp(argv[1], "--no-scissors"))
1039 else if (!strcmp(argv[1], "--no-inbody-headers"))
1040 use_inbody_headers = 0;
1042 usage(mailinfo_usage);
1047 usage(mailinfo_usage);
1049 return !!mailinfo(stdin, stdout, argv[1], argv[2]);