2 * Another stupid program, this one parsing the headers of an
3 * email to figure out authorship and subject
10 static FILE *cmitmsg, *patchfile;
12 static const char *metainfo_charset;
21 int keep_non_patch_brackets_in_subject;
24 int use_inbody_headers;
28 int filter_stage; /* still reading log or are we copying patch? */
29 int header_stage; /* still checking in-body headers? */
33 TE_DONTCARE, TE_QP, TE_BASE64
36 static struct strbuf charset = STRBUF_INIT;
37 static struct strbuf **p_hdr_data, **s_hdr_data;
39 #define MAX_BOUNDARIES 5
41 static void cleanup_space(struct strbuf *sb)
44 for (pos = 0; pos < sb->len; pos++) {
45 if (isspace(sb->buf[pos])) {
47 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
48 strbuf_remove(sb, pos + 1, cnt);
53 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
55 struct strbuf *src = name;
56 if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
57 strchr(name->buf, '<') || strchr(name->buf, '>'))
62 strbuf_addbuf(out, src);
65 static void parse_bogus_from(struct mailinfo *mi, const struct strbuf *line)
67 /* John Doe <johndoe> */
70 /* This is fallback, so do not bother if we already have an
76 bra = strchr(line->buf, '<');
79 ket = strchr(bra, '>');
83 strbuf_reset(&mi->email);
84 strbuf_add(&mi->email, bra + 1, ket - bra - 1);
86 strbuf_reset(&mi->name);
87 strbuf_add(&mi->name, line->buf, bra - line->buf);
88 strbuf_trim(&mi->name);
89 get_sane_name(&mi->name, &mi->name, &mi->email);
92 static void handle_from(struct mailinfo *mi, const struct strbuf *from)
98 strbuf_init(&f, from->len);
99 strbuf_addbuf(&f, from);
101 at = strchr(f.buf, '@');
103 parse_bogus_from(mi, from);
108 * If we already have one email, don't take any confusing lines
110 if (mi->email.len && strchr(at + 1, '@')) {
115 /* Pick up the string around '@', possibly delimited with <>
116 * pair; that is the email part.
128 el = strcspn(at, " \n\t\r\v\f>");
129 strbuf_reset(&mi->email);
130 strbuf_add(&mi->email, at, el);
131 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
133 /* The remainder is name. It could be
135 * - "John Doe <john.doe@xz>" (a), or
136 * - "john.doe@xz (John Doe)" (b), or
137 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
139 * but we have removed the email part, so
141 * - remove extra spaces which could stay after email (case 'c'), and
142 * - trim from both ends, possibly removing the () pair at the end
143 * (cases 'a' and 'b').
147 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
148 strbuf_remove(&f, 0, 1);
149 strbuf_setlen(&f, f.len - 1);
152 get_sane_name(&mi->name, &f, &mi->email);
156 static void handle_header(struct strbuf **out, const struct strbuf *line)
159 *out = xmalloc(sizeof(struct strbuf));
160 strbuf_init(*out, line->len);
164 strbuf_addbuf(*out, line);
167 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
168 * to have enough heuristics to grok MIME encoded patches often found
169 * on our mailing lists. For example, we do not even treat header lines
170 * case insensitively.
173 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
175 const char *ends, *ap = strcasestr(line, name);
178 strbuf_setlen(attr, 0);
188 sz = strcspn(ap, ends);
189 strbuf_add(attr, ap, sz);
193 static struct strbuf *content[MAX_BOUNDARIES];
195 static struct strbuf **content_top = content;
197 static void handle_content_type(struct strbuf *line)
199 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
200 strbuf_init(boundary, line->len);
202 if (slurp_attr(line->buf, "boundary=", boundary)) {
203 strbuf_insert(boundary, 0, "--", 2);
204 if (++content_top >= &content[MAX_BOUNDARIES]) {
205 fprintf(stderr, "Too many boundaries to handle\n");
208 *content_top = boundary;
211 slurp_attr(line->buf, "charset=", &charset);
214 strbuf_release(boundary);
219 static void handle_message_id(struct mailinfo *mi, const struct strbuf *line)
221 if (mi->add_message_id)
222 mi->message_id = strdup(line->buf);
225 static void handle_content_transfer_encoding(const struct strbuf *line)
227 if (strcasestr(line->buf, "base64"))
228 transfer_encoding = TE_BASE64;
229 else if (strcasestr(line->buf, "quoted-printable"))
230 transfer_encoding = TE_QP;
232 transfer_encoding = TE_DONTCARE;
235 static int is_multipart_boundary(const struct strbuf *line)
237 return (((*content_top)->len <= line->len) &&
238 !memcmp(line->buf, (*content_top)->buf, (*content_top)->len));
241 static void cleanup_subject(struct mailinfo *mi, struct strbuf *subject)
245 while (at < subject->len) {
249 switch (subject->buf[at]) {
251 if (subject->len <= at + 3)
253 if ((subject->buf[at + 1] == 'e' ||
254 subject->buf[at + 1] == 'E') &&
255 subject->buf[at + 2] == ':') {
256 strbuf_remove(subject, at, 3);
261 case ' ': case '\t': case ':':
262 strbuf_remove(subject, at, 1);
265 pos = strchr(subject->buf + at, ']');
268 remove = pos - subject->buf + at + 1;
269 if (!mi->keep_non_patch_brackets_in_subject ||
271 memmem(subject->buf + at, remove, "PATCH", 5)))
272 strbuf_remove(subject, at, remove);
276 * If the input had a space after the ], keep
277 * it. We don't bother with finding the end of
278 * the space, since we later normalize it
281 if (isspace(subject->buf[at]))
288 strbuf_trim(subject);
291 #define MAX_HDR_PARSED 10
292 static const char *header[MAX_HDR_PARSED] = {
293 "From","Subject","Date",
296 static inline int cmp_header(const struct strbuf *line, const char *hdr)
298 int len = strlen(hdr);
299 return !strncasecmp(line->buf, hdr, len) && line->len > len &&
300 line->buf[len] == ':' && isspace(line->buf[len + 1]);
303 static int is_format_patch_separator(const char *line, int len)
305 static const char SAMPLE[] =
306 "From e6807f3efca28b30decfecb1732a56c7db1137ee Mon Sep 17 00:00:00 2001\n";
309 if (len != strlen(SAMPLE))
311 if (!skip_prefix(line, "From ", &cp))
313 if (strspn(cp, "0123456789abcdef") != 40)
316 return !memcmp(SAMPLE + (cp - line), cp, strlen(SAMPLE) - (cp - line));
319 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
321 const char *in = q_seg->buf;
323 struct strbuf *out = xmalloc(sizeof(struct strbuf));
324 strbuf_init(out, q_seg->len);
326 while ((c = *in++) != 0) {
330 break; /* drop trailing newline */
331 strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
334 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
336 strbuf_addch(out, c);
341 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
343 /* Decode in..ep, possibly in-place to ot */
344 int c, pos = 0, acc = 0;
345 const char *in = b_seg->buf;
346 struct strbuf *out = xmalloc(sizeof(struct strbuf));
347 strbuf_init(out, b_seg->len);
349 while ((c = *in++) != 0) {
354 else if ('A' <= c && c <= 'Z')
356 else if ('a' <= c && c <= 'z')
358 else if ('0' <= c && c <= '9')
361 continue; /* garbage */
367 strbuf_addch(out, (acc | (c >> 4)));
371 strbuf_addch(out, (acc | (c >> 2)));
375 strbuf_addch(out, (acc | c));
383 static void convert_to_utf8(struct strbuf *line, const char *charset)
387 if (!charset || !*charset)
390 if (same_encoding(metainfo_charset, charset))
392 out = reencode_string(line->buf, metainfo_charset, charset);
394 die("cannot convert from %s to %s",
395 charset, metainfo_charset);
396 strbuf_attach(line, out, strlen(out), strlen(out));
399 static void decode_header(struct strbuf *it)
402 struct strbuf outbuf = STRBUF_INIT, *dec;
403 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
406 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
408 strbuf_reset(&charset_q);
409 strbuf_reset(&piecebuf);
413 * We are about to process an encoded-word
414 * that begins at ep, but there is something
415 * before the encoded word.
418 for (scan = in; scan < ep; scan++)
422 if (scan != ep || in == it->buf) {
424 * We should not lose that "something",
425 * unless we have just processed an
426 * encoded-word, and there is only LWS
427 * before the one we are about to process.
429 strbuf_add(&outbuf, in, ep - in);
433 * ep : "=?iso-2022-jp?B?GyR...?= foo"
434 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
438 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
441 if (cp + 3 - it->buf > it->len)
443 strbuf_add(&charset_q, ep, cp - ep);
446 if (!encoding || cp[2] != '?')
448 ep = strstr(cp + 3, "?=");
451 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
452 switch (tolower(encoding)) {
456 dec = decode_b_segment(&piecebuf);
459 dec = decode_q_segment(&piecebuf, 1);
462 if (metainfo_charset)
463 convert_to_utf8(dec, charset_q.buf);
465 strbuf_addbuf(&outbuf, dec);
470 strbuf_addstr(&outbuf, in);
472 strbuf_addbuf(it, &outbuf);
474 strbuf_release(&outbuf);
475 strbuf_release(&charset_q);
476 strbuf_release(&piecebuf);
479 static int check_header(struct mailinfo *mi,
480 const struct strbuf *line,
481 struct strbuf *hdr_data[], int overwrite)
484 struct strbuf sb = STRBUF_INIT;
486 /* search for the interesting parts */
487 for (i = 0; header[i]; i++) {
488 int len = strlen(header[i]);
489 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
490 /* Unwrap inline B and Q encoding, and optionally
491 * normalize the meta information to utf8.
493 strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
495 handle_header(&hdr_data[i], &sb);
497 goto check_header_out;
502 if (cmp_header(line, "Content-Type")) {
503 len = strlen("Content-Type: ");
504 strbuf_add(&sb, line->buf + len, line->len - len);
506 strbuf_insert(&sb, 0, "Content-Type: ", len);
507 handle_content_type(&sb);
509 goto check_header_out;
511 if (cmp_header(line, "Content-Transfer-Encoding")) {
512 len = strlen("Content-Transfer-Encoding: ");
513 strbuf_add(&sb, line->buf + len, line->len - len);
515 handle_content_transfer_encoding(&sb);
517 goto check_header_out;
519 if (cmp_header(line, "Message-Id")) {
520 len = strlen("Message-Id: ");
521 strbuf_add(&sb, line->buf + len, line->len - len);
523 handle_message_id(mi, &sb);
525 goto check_header_out;
528 /* for inbody stuff */
529 if (starts_with(line->buf, ">From") && isspace(line->buf[5])) {
530 ret = is_format_patch_separator(line->buf + 1, line->len - 1);
531 goto check_header_out;
533 if (starts_with(line->buf, "[PATCH]") && isspace(line->buf[7])) {
534 for (i = 0; header[i]; i++) {
535 if (!strcmp("Subject", header[i])) {
536 handle_header(&hdr_data[i], line);
538 goto check_header_out;
548 static void decode_transfer_encoding(struct strbuf *line)
552 switch (transfer_encoding) {
554 ret = decode_q_segment(line, 0);
557 ret = decode_b_segment(line);
564 strbuf_addbuf(line, ret);
569 static inline int patchbreak(const struct strbuf *line)
573 /* Beginning of a "diff -" header? */
574 if (starts_with(line->buf, "diff -"))
577 /* CVS "Index: " line? */
578 if (starts_with(line->buf, "Index: "))
582 * "--- <filename>" starts patches without headers
583 * "---<sp>*" is a manual separator
588 if (starts_with(line->buf, "---")) {
589 /* space followed by a filename? */
590 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
592 /* Just whitespace? */
593 for (i = 3; i < line->len; i++) {
594 unsigned char c = line->buf[i];
605 static int is_scissors_line(const struct strbuf *line)
607 size_t i, len = line->len;
608 int scissors = 0, gap = 0;
609 int first_nonblank = -1;
610 int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
611 const char *buf = line->buf;
613 for (i = 0; i < len; i++) {
614 if (isspace(buf[i])) {
615 if (in_perforation) {
622 if (first_nonblank < 0)
630 (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
631 !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
642 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
643 * Even though there can be arbitrary cruft on the same line
644 * (e.g. "cut here"), in order to avoid misidentification, the
645 * perforation must occupy more than a third of the visible
646 * width of the line, and dashes and scissors must occupy more
647 * than half of the perforation.
650 visible = last_nonblank - first_nonblank + 1;
651 return (scissors && 8 <= visible &&
652 visible < perforation * 3 &&
653 gap * 2 < perforation);
656 static int handle_commit_msg(struct mailinfo *mi, struct strbuf *line)
661 if (mi->header_stage) {
662 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
666 if (mi->use_inbody_headers && mi->header_stage) {
667 mi->header_stage = check_header(mi, line, s_hdr_data, 0);
668 if (mi->header_stage)
671 /* Only trim the first (blank) line of the commit message
672 * when ignoring in-body headers.
674 mi->header_stage = 0;
676 /* normalize the log message to UTF-8. */
677 if (metainfo_charset)
678 convert_to_utf8(line, charset.buf);
680 if (mi->use_scissors && is_scissors_line(line)) {
682 if (fseek(cmitmsg, 0L, SEEK_SET))
683 die_errno("Could not rewind output message file");
684 if (ftruncate(fileno(cmitmsg), 0))
685 die_errno("Could not truncate output message file at scissors");
686 mi->header_stage = 1;
689 * We may have already read "secondary headers"; purge
690 * them to give ourselves a clean restart.
692 for (i = 0; header[i]; i++) {
694 strbuf_release(s_hdr_data[i]);
695 s_hdr_data[i] = NULL;
700 if (patchbreak(line)) {
702 fprintf(cmitmsg, "Message-Id: %s\n", mi->message_id);
708 fputs(line->buf, cmitmsg);
712 static void handle_patch(struct mailinfo *mi, const struct strbuf *line)
714 fwrite(line->buf, 1, line->len, patchfile);
718 static void handle_filter(struct mailinfo *mi, struct strbuf *line)
720 switch (mi->filter_stage) {
722 if (!handle_commit_msg(mi, line))
726 handle_patch(mi, line);
731 static int is_rfc2822_header(const struct strbuf *line)
734 * The section that defines the loosest possible
735 * field name is "3.6.8 Optional fields".
737 * optional-field = field-name ":" unstructured CRLF
738 * field-name = 1*ftext
739 * ftext = %d33-57 / %59-126
742 char *cp = line->buf;
744 /* Count mbox From headers as headers */
745 if (starts_with(cp, "From ") || starts_with(cp, ">From "))
748 while ((ch = *cp++)) {
751 if ((33 <= ch && ch <= 57) ||
752 (59 <= ch && ch <= 126))
759 static int read_one_header_line(struct strbuf *line, FILE *in)
761 struct strbuf continuation = STRBUF_INIT;
763 /* Get the first part of the line. */
764 if (strbuf_getline(line, in, '\n'))
768 * Is it an empty line or not a valid rfc2822 header?
769 * If so, stop here, and return false ("not a header")
772 if (!line->len || !is_rfc2822_header(line)) {
773 /* Re-add the newline */
774 strbuf_addch(line, '\n');
779 * Now we need to eat all the continuation lines..
780 * Yuck, 2822 header "folding"
785 peek = fgetc(in); ungetc(peek, in);
786 if (peek != ' ' && peek != '\t')
788 if (strbuf_getline(&continuation, in, '\n'))
790 continuation.buf[0] = ' ';
791 strbuf_rtrim(&continuation);
792 strbuf_addbuf(line, &continuation);
794 strbuf_release(&continuation);
799 static int find_boundary(struct mailinfo *mi, struct strbuf *line)
801 while (!strbuf_getline(line, mi->input, '\n')) {
802 if (*content_top && is_multipart_boundary(line))
808 static int handle_boundary(struct mailinfo *mi, struct strbuf *line)
810 struct strbuf newline = STRBUF_INIT;
812 strbuf_addch(&newline, '\n');
814 if (line->len >= (*content_top)->len + 2 &&
815 !memcmp(line->buf + (*content_top)->len, "--", 2)) {
816 /* we hit an end boundary */
817 /* pop the current boundary off the stack */
818 strbuf_release(*content_top);
822 /* technically won't happen as is_multipart_boundary()
823 will fail first. But just in case..
825 if (--content_top < content) {
826 fprintf(stderr, "Detected mismatched boundaries, "
830 handle_filter(mi, &newline);
831 strbuf_release(&newline);
833 /* skip to the next boundary */
834 if (!find_boundary(mi, line))
839 /* set some defaults */
840 transfer_encoding = TE_DONTCARE;
841 strbuf_reset(&charset);
843 /* slurp in this section's info */
844 while (read_one_header_line(line, mi->input))
845 check_header(mi, line, p_hdr_data, 0);
847 strbuf_release(&newline);
849 if (strbuf_getline(line, mi->input, '\n'))
851 strbuf_addch(line, '\n');
855 static void handle_body(struct mailinfo *mi, struct strbuf *line)
857 struct strbuf prev = STRBUF_INIT;
859 /* Skip up to the first boundary */
861 if (!find_boundary(mi, line))
862 goto handle_body_out;
866 /* process any boundary lines */
867 if (*content_top && is_multipart_boundary(line)) {
868 /* flush any leftover */
870 handle_filter(mi, &prev);
873 if (!handle_boundary(mi, line))
874 goto handle_body_out;
877 /* Unwrap transfer encoding */
878 decode_transfer_encoding(line);
880 switch (transfer_encoding) {
884 struct strbuf **lines, **it, *sb;
886 /* Prepend any previous partial lines */
887 strbuf_insert(line, 0, prev.buf, prev.len);
891 * This is a decoded line that may contain
892 * multiple new lines. Pass only one chunk
893 * at a time to handle_filter()
895 lines = strbuf_split(line, '\n');
896 for (it = lines; (sb = *it); it++) {
897 if (*(it + 1) == NULL) /* The last line */
898 if (sb->buf[sb->len - 1] != '\n') {
899 /* Partial line, save it for later. */
900 strbuf_addbuf(&prev, sb);
903 handle_filter(mi, sb);
906 * The partial chunk is saved in "prev" and will be
907 * appended by the next iteration of read_line_with_nul().
909 strbuf_list_free(lines);
913 handle_filter(mi, line);
916 } while (!strbuf_getwholeline(line, mi->input, '\n'));
919 strbuf_release(&prev);
922 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
924 const char *sp = data->buf;
926 char *ep = strchr(sp, '\n');
932 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
939 static void handle_info(struct mailinfo *mi)
944 for (i = 0; header[i]; i++) {
945 /* only print inbody headers if we output a patch file */
946 if (mi->patch_lines && s_hdr_data[i])
948 else if (p_hdr_data[i])
953 if (!strcmp(header[i], "Subject")) {
954 if (!mi->keep_subject) {
955 cleanup_subject(mi, hdr);
958 output_header_lines(mi->output, "Subject", hdr);
959 } else if (!strcmp(header[i], "From")) {
961 handle_from(mi, hdr);
962 fprintf(mi->output, "Author: %s\n", mi->name.buf);
963 fprintf(mi->output, "Email: %s\n", mi->email.buf);
966 fprintf(mi->output, "%s: %s\n", header[i], hdr->buf);
969 fprintf(mi->output, "\n");
972 static int mailinfo(struct mailinfo *mi, const char *msg, const char *patch)
975 struct strbuf line = STRBUF_INIT;
977 cmitmsg = fopen(msg, "w");
982 patchfile = fopen(patch, "w");
989 p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
990 s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
993 peek = fgetc(mi->input);
994 } while (isspace(peek));
995 ungetc(peek, mi->input);
997 /* process the email header */
998 while (read_one_header_line(&line, mi->input))
999 check_header(mi, &line, p_hdr_data, 1);
1001 handle_body(mi, &line);
1005 strbuf_release(&line);
1009 static int git_mailinfo_config(const char *var, const char *value, void *mi_)
1011 struct mailinfo *mi = mi_;
1013 if (!starts_with(var, "mailinfo."))
1014 return git_default_config(var, value, NULL);
1015 if (!strcmp(var, "mailinfo.scissors")) {
1016 mi->use_scissors = git_config_bool(var, value);
1019 /* perhaps others here */
1023 static void setup_mailinfo(struct mailinfo *mi)
1025 memset(mi, 0, sizeof(*mi));
1026 strbuf_init(&mi->name, 0);
1027 strbuf_init(&mi->email, 0);
1028 mi->header_stage = 1;
1029 mi->use_inbody_headers = 1;
1030 git_config(git_mailinfo_config, &mi);
1033 static void clear_mailinfo(struct mailinfo *mi)
1035 strbuf_release(&mi->name);
1036 strbuf_release(&mi->email);
1037 free(mi->message_id);
1040 static const char mailinfo_usage[] =
1041 "git mailinfo [-k | -b] [-m | --message-id] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] <msg> <patch> < mail >info";
1043 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1045 const char *def_charset;
1049 /* NEEDSWORK: might want to do the optional .git/ directory
1052 setup_mailinfo(&mi);
1054 def_charset = get_commit_output_encoding();
1055 metainfo_charset = def_charset;
1057 while (1 < argc && argv[1][0] == '-') {
1058 if (!strcmp(argv[1], "-k"))
1059 mi.keep_subject = 1;
1060 else if (!strcmp(argv[1], "-b"))
1061 mi.keep_non_patch_brackets_in_subject = 1;
1062 else if (!strcmp(argv[1], "-m") || !strcmp(argv[1], "--message-id"))
1063 mi.add_message_id = 1;
1064 else if (!strcmp(argv[1], "-u"))
1065 metainfo_charset = def_charset;
1066 else if (!strcmp(argv[1], "-n"))
1067 metainfo_charset = NULL;
1068 else if (starts_with(argv[1], "--encoding="))
1069 metainfo_charset = argv[1] + 11;
1070 else if (!strcmp(argv[1], "--scissors"))
1071 mi.use_scissors = 1;
1072 else if (!strcmp(argv[1], "--no-scissors"))
1073 mi.use_scissors = 0;
1074 else if (!strcmp(argv[1], "--no-inbody-headers"))
1075 mi.use_inbody_headers = 0;
1077 usage(mailinfo_usage);
1082 usage(mailinfo_usage);
1086 status = !!mailinfo(&mi, argv[1], argv[2]);
1087 clear_mailinfo(&mi);