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);
164 strbuf_setlen(attr, 0);
174 sz = strcspn(ap, ends);
175 strbuf_add(attr, ap, sz);
179 static struct strbuf *content[MAX_BOUNDARIES];
181 static struct strbuf **content_top = content;
183 static void handle_content_type(struct strbuf *line)
185 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
186 strbuf_init(boundary, line->len);
188 if (!strcasestr(line->buf, "text/"))
189 message_type = TYPE_OTHER;
190 if (slurp_attr(line->buf, "boundary=", boundary)) {
191 strbuf_insert(boundary, 0, "--", 2);
192 if (++content_top > &content[MAX_BOUNDARIES]) {
193 fprintf(stderr, "Too many boundaries to handle\n");
196 *content_top = boundary;
199 slurp_attr(line->buf, "charset=", &charset);
202 strbuf_release(boundary);
207 static void handle_content_transfer_encoding(const struct strbuf *line)
209 if (strcasestr(line->buf, "base64"))
210 transfer_encoding = TE_BASE64;
211 else if (strcasestr(line->buf, "quoted-printable"))
212 transfer_encoding = TE_QP;
214 transfer_encoding = TE_DONTCARE;
217 static int is_multipart_boundary(const struct strbuf *line)
219 return (((*content_top)->len <= line->len) &&
220 !memcmp(line->buf, (*content_top)->buf, (*content_top)->len));
223 static void cleanup_subject(struct strbuf *subject)
227 while (at < subject->len) {
231 switch (subject->buf[at]) {
233 if (subject->len <= at + 3)
235 if ((subject->buf[at + 1] == 'e' ||
236 subject->buf[at + 1] == 'E') &&
237 subject->buf[at + 2] == ':') {
238 strbuf_remove(subject, at, 3);
243 case ' ': case '\t': case ':':
244 strbuf_remove(subject, at, 1);
247 pos = strchr(subject->buf + at, ']');
250 remove = pos - subject->buf + at + 1;
251 if (!keep_non_patch_brackets_in_subject ||
253 memmem(subject->buf + at, remove, "PATCH", 5)))
254 strbuf_remove(subject, at, remove);
258 * If the input had a space after the ], keep
259 * it. We don't bother with finding the end of
260 * the space, since we later normalize it
263 if (isspace(subject->buf[at]))
270 strbuf_trim(subject);
273 static void cleanup_space(struct strbuf *sb)
276 for (pos = 0; pos < sb->len; pos++) {
277 if (isspace(sb->buf[pos])) {
279 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
280 strbuf_remove(sb, pos + 1, cnt);
285 static void decode_header(struct strbuf *line);
286 static const char *header[MAX_HDR_PARSED] = {
287 "From","Subject","Date",
290 static inline int cmp_header(const struct strbuf *line, const char *hdr)
292 int len = strlen(hdr);
293 return !strncasecmp(line->buf, hdr, len) && line->len > len &&
294 line->buf[len] == ':' && isspace(line->buf[len + 1]);
297 static int check_header(const struct strbuf *line,
298 struct strbuf *hdr_data[], int overwrite)
301 struct strbuf sb = STRBUF_INIT;
302 /* search for the interesting parts */
303 for (i = 0; header[i]; i++) {
304 int len = strlen(header[i]);
305 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
306 /* Unwrap inline B and Q encoding, and optionally
307 * normalize the meta information to utf8.
309 strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
311 handle_header(&hdr_data[i], &sb);
313 goto check_header_out;
318 if (cmp_header(line, "Content-Type")) {
319 len = strlen("Content-Type: ");
320 strbuf_add(&sb, line->buf + len, line->len - len);
322 strbuf_insert(&sb, 0, "Content-Type: ", len);
323 handle_content_type(&sb);
325 goto check_header_out;
327 if (cmp_header(line, "Content-Transfer-Encoding")) {
328 len = strlen("Content-Transfer-Encoding: ");
329 strbuf_add(&sb, line->buf + len, line->len - len);
331 handle_content_transfer_encoding(&sb);
333 goto check_header_out;
336 /* for inbody stuff */
337 if (!prefixcmp(line->buf, ">From") && isspace(line->buf[5])) {
338 ret = 1; /* Should this return 0? */
339 goto check_header_out;
341 if (!prefixcmp(line->buf, "[PATCH]") && isspace(line->buf[7])) {
342 for (i = 0; header[i]; i++) {
343 if (!memcmp("Subject", header[i], 7)) {
344 handle_header(&hdr_data[i], line);
346 goto check_header_out;
356 static int is_rfc2822_header(const struct strbuf *line)
359 * The section that defines the loosest possible
360 * field name is "3.6.8 Optional fields".
362 * optional-field = field-name ":" unstructured CRLF
363 * field-name = 1*ftext
364 * ftext = %d33-57 / %59-126
367 char *cp = line->buf;
369 /* Count mbox From headers as headers */
370 if (!prefixcmp(cp, "From ") || !prefixcmp(cp, ">From "))
373 while ((ch = *cp++)) {
376 if ((33 <= ch && ch <= 57) ||
377 (59 <= ch && ch <= 126))
384 static int read_one_header_line(struct strbuf *line, FILE *in)
386 /* Get the first part of the line. */
387 if (strbuf_getline(line, in, '\n'))
391 * Is it an empty line or not a valid rfc2822 header?
392 * If so, stop here, and return false ("not a header")
395 if (!line->len || !is_rfc2822_header(line)) {
396 /* Re-add the newline */
397 strbuf_addch(line, '\n');
402 * Now we need to eat all the continuation lines..
403 * Yuck, 2822 header "folding"
407 struct strbuf continuation = STRBUF_INIT;
409 peek = fgetc(in); ungetc(peek, in);
410 if (peek != ' ' && peek != '\t')
412 if (strbuf_getline(&continuation, in, '\n'))
414 continuation.buf[0] = ' ';
415 strbuf_rtrim(&continuation);
416 strbuf_addbuf(line, &continuation);
422 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
424 const char *in = q_seg->buf;
426 struct strbuf *out = xmalloc(sizeof(struct strbuf));
427 strbuf_init(out, q_seg->len);
429 while ((c = *in++) != 0) {
433 break; /* drop trailing newline */
434 strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
437 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
439 strbuf_addch(out, c);
444 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
446 /* Decode in..ep, possibly in-place to ot */
447 int c, pos = 0, acc = 0;
448 const char *in = b_seg->buf;
449 struct strbuf *out = xmalloc(sizeof(struct strbuf));
450 strbuf_init(out, b_seg->len);
452 while ((c = *in++) != 0) {
457 else if ('A' <= c && c <= 'Z')
459 else if ('a' <= c && c <= 'z')
461 else if ('0' <= c && c <= '9')
464 continue; /* garbage */
470 strbuf_addch(out, (acc | (c >> 4)));
474 strbuf_addch(out, (acc | (c >> 2)));
478 strbuf_addch(out, (acc | c));
486 static void convert_to_utf8(struct strbuf *line, const char *charset)
490 if (!charset || !*charset)
492 if (!strcasecmp(metainfo_charset, charset))
494 out = reencode_string(line->buf, metainfo_charset, charset);
496 die("cannot convert from %s to %s",
497 charset, metainfo_charset);
498 strbuf_attach(line, out, strlen(out), strlen(out));
501 static int decode_header_bq(struct strbuf *it)
504 struct strbuf outbuf = STRBUF_INIT, *dec;
505 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
509 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
511 strbuf_reset(&charset_q);
512 strbuf_reset(&piecebuf);
517 * We are about to process an encoded-word
518 * that begins at ep, but there is something
519 * before the encoded word.
522 for (scan = in; scan < ep; scan++)
526 if (scan != ep || in == it->buf) {
528 * We should not lose that "something",
529 * unless we have just processed an
530 * encoded-word, and there is only LWS
531 * before the one we are about to process.
533 strbuf_add(&outbuf, in, ep - in);
537 * ep : "=?iso-2022-jp?B?GyR...?= foo"
538 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
542 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
543 goto decode_header_bq_out;
545 if (cp + 3 - it->buf > it->len)
546 goto decode_header_bq_out;
547 strbuf_add(&charset_q, ep, cp - ep);
550 if (!encoding || cp[2] != '?')
551 goto decode_header_bq_out;
552 ep = strstr(cp + 3, "?=");
554 goto decode_header_bq_out;
555 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
556 switch (tolower(encoding)) {
558 goto decode_header_bq_out;
560 dec = decode_b_segment(&piecebuf);
563 dec = decode_q_segment(&piecebuf, 1);
566 if (metainfo_charset)
567 convert_to_utf8(dec, charset_q.buf);
569 strbuf_addbuf(&outbuf, dec);
574 strbuf_addstr(&outbuf, in);
576 strbuf_addbuf(it, &outbuf);
577 decode_header_bq_out:
578 strbuf_release(&outbuf);
579 strbuf_release(&charset_q);
580 strbuf_release(&piecebuf);
584 static void decode_header(struct strbuf *it)
586 if (decode_header_bq(it))
588 /* otherwise "it" is a straight copy of the input.
589 * This can be binary guck but there is no charset specified.
591 if (metainfo_charset)
592 convert_to_utf8(it, "");
595 static void decode_transfer_encoding(struct strbuf *line)
599 switch (transfer_encoding) {
601 ret = decode_q_segment(line, 0);
604 ret = decode_b_segment(line);
611 strbuf_addbuf(line, ret);
616 static void handle_filter(struct strbuf *line);
618 static int find_boundary(void)
620 while (!strbuf_getline(&line, fin, '\n')) {
621 if (*content_top && is_multipart_boundary(&line))
627 static int handle_boundary(void)
629 struct strbuf newline = STRBUF_INIT;
631 strbuf_addch(&newline, '\n');
633 if (line.len >= (*content_top)->len + 2 &&
634 !memcmp(line.buf + (*content_top)->len, "--", 2)) {
635 /* we hit an end boundary */
636 /* pop the current boundary off the stack */
637 strbuf_release(*content_top);
641 /* technically won't happen as is_multipart_boundary()
642 will fail first. But just in case..
644 if (--content_top < content) {
645 fprintf(stderr, "Detected mismatched boundaries, "
649 handle_filter(&newline);
650 strbuf_release(&newline);
652 /* skip to the next boundary */
653 if (!find_boundary())
658 /* set some defaults */
659 transfer_encoding = TE_DONTCARE;
660 strbuf_reset(&charset);
661 message_type = TYPE_TEXT;
663 /* slurp in this section's info */
664 while (read_one_header_line(&line, fin))
665 check_header(&line, p_hdr_data, 0);
667 strbuf_release(&newline);
669 if (strbuf_getline(&line, fin, '\n'))
671 strbuf_addch(&line, '\n');
675 static inline int patchbreak(const struct strbuf *line)
679 /* Beginning of a "diff -" header? */
680 if (!prefixcmp(line->buf, "diff -"))
683 /* CVS "Index: " line? */
684 if (!prefixcmp(line->buf, "Index: "))
688 * "--- <filename>" starts patches without headers
689 * "---<sp>*" is a manual separator
694 if (!prefixcmp(line->buf, "---")) {
695 /* space followed by a filename? */
696 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
698 /* Just whitespace? */
699 for (i = 3; i < line->len; i++) {
700 unsigned char c = line->buf[i];
711 static int is_scissors_line(const struct strbuf *line)
713 size_t i, len = line->len;
714 int scissors = 0, gap = 0;
715 int first_nonblank = -1;
716 int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
717 const char *buf = line->buf;
719 for (i = 0; i < len; i++) {
720 if (isspace(buf[i])) {
721 if (in_perforation) {
728 if (first_nonblank < 0)
736 (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
737 !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
748 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
749 * Even though there can be arbitrary cruft on the same line
750 * (e.g. "cut here"), in order to avoid misidentification, the
751 * perforation must occupy more than a third of the visible
752 * width of the line, and dashes and scissors must occupy more
753 * than half of the perforation.
756 visible = last_nonblank - first_nonblank + 1;
757 return (scissors && 8 <= visible &&
758 visible < perforation * 3 &&
759 gap * 2 < perforation);
762 static int handle_commit_msg(struct strbuf *line)
764 static int still_looking = 1;
770 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
774 if (use_inbody_headers && still_looking) {
775 still_looking = check_header(line, s_hdr_data, 0);
779 /* Only trim the first (blank) line of the commit message
780 * when ignoring in-body headers.
784 /* normalize the log message to UTF-8. */
785 if (metainfo_charset)
786 convert_to_utf8(line, charset.buf);
788 if (use_scissors && is_scissors_line(line)) {
790 if (fseek(cmitmsg, 0L, SEEK_SET))
791 die_errno("Could not rewind output message file");
792 if (ftruncate(fileno(cmitmsg), 0))
793 die_errno("Could not truncate output message file at scissors");
797 * We may have already read "secondary headers"; purge
798 * them to give ourselves a clean restart.
800 for (i = 0; header[i]; i++) {
802 strbuf_release(s_hdr_data[i]);
803 s_hdr_data[i] = NULL;
808 if (patchbreak(line)) {
814 fputs(line->buf, cmitmsg);
818 static void handle_patch(const struct strbuf *line)
820 fwrite(line->buf, 1, line->len, patchfile);
824 static void handle_filter(struct strbuf *line)
826 static int filter = 0;
828 /* filter tells us which part we left off on */
831 if (!handle_commit_msg(line))
840 static void handle_body(void)
842 struct strbuf prev = STRBUF_INIT;
844 /* Skip up to the first boundary */
846 if (!find_boundary())
847 goto handle_body_out;
851 /* process any boundary lines */
852 if (*content_top && is_multipart_boundary(&line)) {
853 /* flush any leftover */
855 handle_filter(&prev);
858 if (!handle_boundary())
859 goto handle_body_out;
862 /* Unwrap transfer encoding */
863 decode_transfer_encoding(&line);
865 switch (transfer_encoding) {
869 struct strbuf **lines, **it, *sb;
871 /* Prepend any previous partial lines */
872 strbuf_insert(&line, 0, prev.buf, prev.len);
875 /* binary data most likely doesn't have newlines */
876 if (message_type != TYPE_TEXT) {
877 handle_filter(&line);
881 * This is a decoded line that may contain
882 * multiple new lines. Pass only one chunk
883 * at a time to handle_filter()
885 lines = strbuf_split(&line, '\n');
886 for (it = lines; (sb = *it); it++) {
887 if (*(it + 1) == NULL) /* The last line */
888 if (sb->buf[sb->len - 1] != '\n') {
889 /* Partial line, save it for later. */
890 strbuf_addbuf(&prev, sb);
896 * The partial chunk is saved in "prev" and will be
897 * appended by the next iteration of read_line_with_nul().
899 strbuf_list_free(lines);
903 handle_filter(&line);
906 } while (!strbuf_getwholeline(&line, fin, '\n'));
909 strbuf_release(&prev);
912 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
914 const char *sp = data->buf;
916 char *ep = strchr(sp, '\n');
922 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
929 static void handle_info(void)
934 for (i = 0; header[i]; i++) {
935 /* only print inbody headers if we output a patch file */
936 if (patch_lines && s_hdr_data[i])
938 else if (p_hdr_data[i])
943 if (!memcmp(header[i], "Subject", 7)) {
945 cleanup_subject(hdr);
948 output_header_lines(fout, "Subject", hdr);
949 } else if (!memcmp(header[i], "From", 4)) {
952 fprintf(fout, "Author: %s\n", name.buf);
953 fprintf(fout, "Email: %s\n", email.buf);
956 fprintf(fout, "%s: %s\n", header[i], hdr->buf);
962 static int mailinfo(FILE *in, FILE *out, const char *msg, const char *patch)
968 cmitmsg = fopen(msg, "w");
973 patchfile = fopen(patch, "w");
980 p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
981 s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
985 } while (isspace(peek));
988 /* process the email header */
989 while (read_one_header_line(&line, fin))
990 check_header(&line, p_hdr_data, 1);
998 static int git_mailinfo_config(const char *var, const char *value, void *unused)
1000 if (prefixcmp(var, "mailinfo."))
1001 return git_default_config(var, value, unused);
1002 if (!strcmp(var, "mailinfo.scissors")) {
1003 use_scissors = git_config_bool(var, value);
1006 /* perhaps others here */
1010 static const char mailinfo_usage[] =
1011 "git mailinfo [-k|-b] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] msg patch < mail >info";
1013 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1015 const char *def_charset;
1017 /* NEEDSWORK: might want to do the optional .git/ directory
1020 git_config(git_mailinfo_config, NULL);
1022 def_charset = get_commit_output_encoding();
1023 metainfo_charset = def_charset;
1025 while (1 < argc && argv[1][0] == '-') {
1026 if (!strcmp(argv[1], "-k"))
1028 else if (!strcmp(argv[1], "-b"))
1029 keep_non_patch_brackets_in_subject = 1;
1030 else if (!strcmp(argv[1], "-u"))
1031 metainfo_charset = def_charset;
1032 else if (!strcmp(argv[1], "-n"))
1033 metainfo_charset = NULL;
1034 else if (!prefixcmp(argv[1], "--encoding="))
1035 metainfo_charset = argv[1] + 11;
1036 else if (!strcmp(argv[1], "--scissors"))
1038 else if (!strcmp(argv[1], "--no-scissors"))
1040 else if (!strcmp(argv[1], "--no-inbody-headers"))
1041 use_inbody_headers = 0;
1043 usage(mailinfo_usage);
1048 usage(mailinfo_usage);
1050 return !!mailinfo(stdin, stdout, argv[1], argv[2]);