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;
18 static char *message_id;
21 TE_DONTCARE, TE_QP, TE_BASE64
24 static struct strbuf charset = STRBUF_INIT;
25 static int patch_lines;
26 static struct strbuf **p_hdr_data, **s_hdr_data;
27 static int use_scissors;
28 static int add_message_id;
29 static int use_inbody_headers = 1;
31 #define MAX_BOUNDARIES 5
33 static void cleanup_space(struct strbuf *sb)
36 for (pos = 0; pos < sb->len; pos++) {
37 if (isspace(sb->buf[pos])) {
39 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
40 strbuf_remove(sb, pos + 1, cnt);
45 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
47 struct strbuf *src = name;
48 if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
49 strchr(name->buf, '<') || strchr(name->buf, '>'))
54 strbuf_addbuf(out, src);
57 static void parse_bogus_from(const struct strbuf *line)
59 /* John Doe <johndoe> */
62 /* This is fallback, so do not bother if we already have an
68 bra = strchr(line->buf, '<');
71 ket = strchr(bra, '>');
76 strbuf_add(&email, bra + 1, ket - bra - 1);
79 strbuf_add(&name, line->buf, bra - line->buf);
81 get_sane_name(&name, &name, &email);
84 static void handle_from(const struct strbuf *from)
90 strbuf_init(&f, from->len);
91 strbuf_addbuf(&f, from);
93 at = strchr(f.buf, '@');
95 parse_bogus_from(from);
100 * If we already have one email, don't take any confusing lines
102 if (email.len && strchr(at + 1, '@')) {
107 /* Pick up the string around '@', possibly delimited with <>
108 * pair; that is the email part.
120 el = strcspn(at, " \n\t\r\v\f>");
121 strbuf_reset(&email);
122 strbuf_add(&email, at, el);
123 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
125 /* The remainder is name. It could be
127 * - "John Doe <john.doe@xz>" (a), or
128 * - "john.doe@xz (John Doe)" (b), or
129 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
131 * but we have removed the email part, so
133 * - remove extra spaces which could stay after email (case 'c'), and
134 * - trim from both ends, possibly removing the () pair at the end
135 * (cases 'a' and 'b').
139 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
140 strbuf_remove(&f, 0, 1);
141 strbuf_setlen(&f, f.len - 1);
144 get_sane_name(&name, &f, &email);
148 static void handle_header(struct strbuf **out, const struct strbuf *line)
151 *out = xmalloc(sizeof(struct strbuf));
152 strbuf_init(*out, line->len);
156 strbuf_addbuf(*out, line);
159 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
160 * to have enough heuristics to grok MIME encoded patches often found
161 * on our mailing lists. For example, we do not even treat header lines
162 * case insensitively.
165 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
167 const char *ends, *ap = strcasestr(line, name);
170 strbuf_setlen(attr, 0);
180 sz = strcspn(ap, ends);
181 strbuf_add(attr, ap, sz);
185 static struct strbuf *content[MAX_BOUNDARIES];
187 static struct strbuf **content_top = content;
189 static void handle_content_type(struct strbuf *line)
191 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
192 strbuf_init(boundary, line->len);
194 if (slurp_attr(line->buf, "boundary=", boundary)) {
195 strbuf_insert(boundary, 0, "--", 2);
196 if (++content_top >= &content[MAX_BOUNDARIES]) {
197 fprintf(stderr, "Too many boundaries to handle\n");
200 *content_top = boundary;
203 slurp_attr(line->buf, "charset=", &charset);
206 strbuf_release(boundary);
211 static void handle_message_id(const struct strbuf *line)
214 message_id = strdup(line->buf);
217 static void handle_content_transfer_encoding(const struct strbuf *line)
219 if (strcasestr(line->buf, "base64"))
220 transfer_encoding = TE_BASE64;
221 else if (strcasestr(line->buf, "quoted-printable"))
222 transfer_encoding = TE_QP;
224 transfer_encoding = TE_DONTCARE;
227 static int is_multipart_boundary(const struct strbuf *line)
229 return (((*content_top)->len <= line->len) &&
230 !memcmp(line->buf, (*content_top)->buf, (*content_top)->len));
233 static void cleanup_subject(struct strbuf *subject)
237 while (at < subject->len) {
241 switch (subject->buf[at]) {
243 if (subject->len <= at + 3)
245 if ((subject->buf[at + 1] == 'e' ||
246 subject->buf[at + 1] == 'E') &&
247 subject->buf[at + 2] == ':') {
248 strbuf_remove(subject, at, 3);
253 case ' ': case '\t': case ':':
254 strbuf_remove(subject, at, 1);
257 pos = strchr(subject->buf + at, ']');
260 remove = pos - subject->buf + at + 1;
261 if (!keep_non_patch_brackets_in_subject ||
263 memmem(subject->buf + at, remove, "PATCH", 5)))
264 strbuf_remove(subject, at, remove);
268 * If the input had a space after the ], keep
269 * it. We don't bother with finding the end of
270 * the space, since we later normalize it
273 if (isspace(subject->buf[at]))
280 strbuf_trim(subject);
283 #define MAX_HDR_PARSED 10
284 static const char *header[MAX_HDR_PARSED] = {
285 "From","Subject","Date",
288 static inline int cmp_header(const struct strbuf *line, const char *hdr)
290 int len = strlen(hdr);
291 return !strncasecmp(line->buf, hdr, len) && line->len > len &&
292 line->buf[len] == ':' && isspace(line->buf[len + 1]);
295 static int is_format_patch_separator(const char *line, int len)
297 static const char SAMPLE[] =
298 "From e6807f3efca28b30decfecb1732a56c7db1137ee Mon Sep 17 00:00:00 2001\n";
301 if (len != strlen(SAMPLE))
303 if (!skip_prefix(line, "From ", &cp))
305 if (strspn(cp, "0123456789abcdef") != 40)
308 return !memcmp(SAMPLE + (cp - line), cp, strlen(SAMPLE) - (cp - line));
311 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
313 const char *in = q_seg->buf;
315 struct strbuf *out = xmalloc(sizeof(struct strbuf));
316 strbuf_init(out, q_seg->len);
318 while ((c = *in++) != 0) {
322 break; /* drop trailing newline */
323 strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
326 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
328 strbuf_addch(out, c);
333 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
335 /* Decode in..ep, possibly in-place to ot */
336 int c, pos = 0, acc = 0;
337 const char *in = b_seg->buf;
338 struct strbuf *out = xmalloc(sizeof(struct strbuf));
339 strbuf_init(out, b_seg->len);
341 while ((c = *in++) != 0) {
346 else if ('A' <= c && c <= 'Z')
348 else if ('a' <= c && c <= 'z')
350 else if ('0' <= c && c <= '9')
353 continue; /* garbage */
359 strbuf_addch(out, (acc | (c >> 4)));
363 strbuf_addch(out, (acc | (c >> 2)));
367 strbuf_addch(out, (acc | c));
375 static void convert_to_utf8(struct strbuf *line, const char *charset)
379 if (!charset || !*charset)
382 if (same_encoding(metainfo_charset, charset))
384 out = reencode_string(line->buf, metainfo_charset, charset);
386 die("cannot convert from %s to %s",
387 charset, metainfo_charset);
388 strbuf_attach(line, out, strlen(out), strlen(out));
391 static void decode_header(struct strbuf *it)
394 struct strbuf outbuf = STRBUF_INIT, *dec;
395 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
398 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
400 strbuf_reset(&charset_q);
401 strbuf_reset(&piecebuf);
405 * We are about to process an encoded-word
406 * that begins at ep, but there is something
407 * before the encoded word.
410 for (scan = in; scan < ep; scan++)
414 if (scan != ep || in == it->buf) {
416 * We should not lose that "something",
417 * unless we have just processed an
418 * encoded-word, and there is only LWS
419 * before the one we are about to process.
421 strbuf_add(&outbuf, in, ep - in);
425 * ep : "=?iso-2022-jp?B?GyR...?= foo"
426 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
430 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
433 if (cp + 3 - it->buf > it->len)
435 strbuf_add(&charset_q, ep, cp - ep);
438 if (!encoding || cp[2] != '?')
440 ep = strstr(cp + 3, "?=");
443 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
444 switch (tolower(encoding)) {
448 dec = decode_b_segment(&piecebuf);
451 dec = decode_q_segment(&piecebuf, 1);
454 if (metainfo_charset)
455 convert_to_utf8(dec, charset_q.buf);
457 strbuf_addbuf(&outbuf, dec);
462 strbuf_addstr(&outbuf, in);
464 strbuf_addbuf(it, &outbuf);
466 strbuf_release(&outbuf);
467 strbuf_release(&charset_q);
468 strbuf_release(&piecebuf);
471 static int check_header(const struct strbuf *line,
472 struct strbuf *hdr_data[], int overwrite)
475 struct strbuf sb = STRBUF_INIT;
476 /* search for the interesting parts */
477 for (i = 0; header[i]; i++) {
478 int len = strlen(header[i]);
479 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
480 /* Unwrap inline B and Q encoding, and optionally
481 * normalize the meta information to utf8.
483 strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
485 handle_header(&hdr_data[i], &sb);
487 goto check_header_out;
492 if (cmp_header(line, "Content-Type")) {
493 len = strlen("Content-Type: ");
494 strbuf_add(&sb, line->buf + len, line->len - len);
496 strbuf_insert(&sb, 0, "Content-Type: ", len);
497 handle_content_type(&sb);
499 goto check_header_out;
501 if (cmp_header(line, "Content-Transfer-Encoding")) {
502 len = strlen("Content-Transfer-Encoding: ");
503 strbuf_add(&sb, line->buf + len, line->len - len);
505 handle_content_transfer_encoding(&sb);
507 goto check_header_out;
509 if (cmp_header(line, "Message-Id")) {
510 len = strlen("Message-Id: ");
511 strbuf_add(&sb, line->buf + len, line->len - len);
513 handle_message_id(&sb);
515 goto check_header_out;
518 /* for inbody stuff */
519 if (starts_with(line->buf, ">From") && isspace(line->buf[5])) {
520 ret = is_format_patch_separator(line->buf + 1, line->len - 1);
521 goto check_header_out;
523 if (starts_with(line->buf, "[PATCH]") && isspace(line->buf[7])) {
524 for (i = 0; header[i]; i++) {
525 if (!strcmp("Subject", header[i])) {
526 handle_header(&hdr_data[i], line);
528 goto check_header_out;
538 static void decode_transfer_encoding(struct strbuf *line)
542 switch (transfer_encoding) {
544 ret = decode_q_segment(line, 0);
547 ret = decode_b_segment(line);
554 strbuf_addbuf(line, ret);
559 static inline int patchbreak(const struct strbuf *line)
563 /* Beginning of a "diff -" header? */
564 if (starts_with(line->buf, "diff -"))
567 /* CVS "Index: " line? */
568 if (starts_with(line->buf, "Index: "))
572 * "--- <filename>" starts patches without headers
573 * "---<sp>*" is a manual separator
578 if (starts_with(line->buf, "---")) {
579 /* space followed by a filename? */
580 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
582 /* Just whitespace? */
583 for (i = 3; i < line->len; i++) {
584 unsigned char c = line->buf[i];
595 static int is_scissors_line(const struct strbuf *line)
597 size_t i, len = line->len;
598 int scissors = 0, gap = 0;
599 int first_nonblank = -1;
600 int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
601 const char *buf = line->buf;
603 for (i = 0; i < len; i++) {
604 if (isspace(buf[i])) {
605 if (in_perforation) {
612 if (first_nonblank < 0)
620 (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
621 !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
632 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
633 * Even though there can be arbitrary cruft on the same line
634 * (e.g. "cut here"), in order to avoid misidentification, the
635 * perforation must occupy more than a third of the visible
636 * width of the line, and dashes and scissors must occupy more
637 * than half of the perforation.
640 visible = last_nonblank - first_nonblank + 1;
641 return (scissors && 8 <= visible &&
642 visible < perforation * 3 &&
643 gap * 2 < perforation);
646 static int handle_commit_msg(struct strbuf *line, int *still_looking)
651 if (*still_looking) {
652 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
656 if (use_inbody_headers && *still_looking) {
657 *still_looking = check_header(line, s_hdr_data, 0);
661 /* Only trim the first (blank) line of the commit message
662 * when ignoring in-body headers.
666 /* normalize the log message to UTF-8. */
667 if (metainfo_charset)
668 convert_to_utf8(line, charset.buf);
670 if (use_scissors && is_scissors_line(line)) {
672 if (fseek(cmitmsg, 0L, SEEK_SET))
673 die_errno("Could not rewind output message file");
674 if (ftruncate(fileno(cmitmsg), 0))
675 die_errno("Could not truncate output message file at scissors");
679 * We may have already read "secondary headers"; purge
680 * them to give ourselves a clean restart.
682 for (i = 0; header[i]; i++) {
684 strbuf_release(s_hdr_data[i]);
685 s_hdr_data[i] = NULL;
690 if (patchbreak(line)) {
692 fprintf(cmitmsg, "Message-Id: %s\n", message_id);
698 fputs(line->buf, cmitmsg);
702 static void handle_patch(const struct strbuf *line)
704 fwrite(line->buf, 1, line->len, patchfile);
708 static void handle_filter(struct strbuf *line, int *filter_stage, int *header_stage)
710 switch (*filter_stage) {
712 if (!handle_commit_msg(line, header_stage))
721 static int is_rfc2822_header(const struct strbuf *line)
724 * The section that defines the loosest possible
725 * field name is "3.6.8 Optional fields".
727 * optional-field = field-name ":" unstructured CRLF
728 * field-name = 1*ftext
729 * ftext = %d33-57 / %59-126
732 char *cp = line->buf;
734 /* Count mbox From headers as headers */
735 if (starts_with(cp, "From ") || starts_with(cp, ">From "))
738 while ((ch = *cp++)) {
741 if ((33 <= ch && ch <= 57) ||
742 (59 <= ch && ch <= 126))
749 static int read_one_header_line(struct strbuf *line, FILE *in)
751 struct strbuf continuation = STRBUF_INIT;
753 /* Get the first part of the line. */
754 if (strbuf_getline(line, in, '\n'))
758 * Is it an empty line or not a valid rfc2822 header?
759 * If so, stop here, and return false ("not a header")
762 if (!line->len || !is_rfc2822_header(line)) {
763 /* Re-add the newline */
764 strbuf_addch(line, '\n');
769 * Now we need to eat all the continuation lines..
770 * Yuck, 2822 header "folding"
775 peek = fgetc(in); ungetc(peek, in);
776 if (peek != ' ' && peek != '\t')
778 if (strbuf_getline(&continuation, in, '\n'))
780 continuation.buf[0] = ' ';
781 strbuf_rtrim(&continuation);
782 strbuf_addbuf(line, &continuation);
784 strbuf_release(&continuation);
789 static int find_boundary(void)
791 while (!strbuf_getline(&line, fin, '\n')) {
792 if (*content_top && is_multipart_boundary(&line))
798 static int handle_boundary(struct strbuf *line, int *filter_stage, int *header_stage)
800 struct strbuf newline = STRBUF_INIT;
802 strbuf_addch(&newline, '\n');
804 if (line->len >= (*content_top)->len + 2 &&
805 !memcmp(line->buf + (*content_top)->len, "--", 2)) {
806 /* we hit an end boundary */
807 /* pop the current boundary off the stack */
808 strbuf_release(*content_top);
812 /* technically won't happen as is_multipart_boundary()
813 will fail first. But just in case..
815 if (--content_top < content) {
816 fprintf(stderr, "Detected mismatched boundaries, "
820 handle_filter(&newline, filter_stage, header_stage);
821 strbuf_release(&newline);
823 /* skip to the next boundary */
824 if (!find_boundary())
829 /* set some defaults */
830 transfer_encoding = TE_DONTCARE;
831 strbuf_reset(&charset);
833 /* slurp in this section's info */
834 while (read_one_header_line(line, fin))
835 check_header(line, p_hdr_data, 0);
837 strbuf_release(&newline);
839 if (strbuf_getline(line, fin, '\n'))
841 strbuf_addch(line, '\n');
845 static void handle_body(struct strbuf *line)
847 struct strbuf prev = STRBUF_INIT;
848 int filter_stage = 0;
849 int header_stage = 1;
851 /* Skip up to the first boundary */
853 if (!find_boundary())
854 goto handle_body_out;
858 /* process any boundary lines */
859 if (*content_top && is_multipart_boundary(line)) {
860 /* flush any leftover */
862 handle_filter(&prev, &filter_stage, &header_stage);
865 if (!handle_boundary(line, &filter_stage, &header_stage))
866 goto handle_body_out;
869 /* Unwrap transfer encoding */
870 decode_transfer_encoding(line);
872 switch (transfer_encoding) {
876 struct strbuf **lines, **it, *sb;
878 /* Prepend any previous partial lines */
879 strbuf_insert(line, 0, prev.buf, prev.len);
883 * This is a decoded line that may contain
884 * multiple new lines. Pass only one chunk
885 * at a time to handle_filter()
887 lines = strbuf_split(line, '\n');
888 for (it = lines; (sb = *it); it++) {
889 if (*(it + 1) == NULL) /* The last line */
890 if (sb->buf[sb->len - 1] != '\n') {
891 /* Partial line, save it for later. */
892 strbuf_addbuf(&prev, sb);
895 handle_filter(sb, &filter_stage, &header_stage);
898 * The partial chunk is saved in "prev" and will be
899 * appended by the next iteration of read_line_with_nul().
901 strbuf_list_free(lines);
905 handle_filter(line, &filter_stage, &header_stage);
908 } while (!strbuf_getwholeline(line, fin, '\n'));
911 strbuf_release(&prev);
914 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
916 const char *sp = data->buf;
918 char *ep = strchr(sp, '\n');
924 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
931 static void handle_info(void)
936 for (i = 0; header[i]; i++) {
937 /* only print inbody headers if we output a patch file */
938 if (patch_lines && s_hdr_data[i])
940 else if (p_hdr_data[i])
945 if (!strcmp(header[i], "Subject")) {
947 cleanup_subject(hdr);
950 output_header_lines(fout, "Subject", hdr);
951 } else if (!strcmp(header[i], "From")) {
954 fprintf(fout, "Author: %s\n", name.buf);
955 fprintf(fout, "Email: %s\n", email.buf);
958 fprintf(fout, "%s: %s\n", header[i], hdr->buf);
964 static int mailinfo(FILE *in, FILE *out, const char *msg, const char *patch)
970 cmitmsg = fopen(msg, "w");
975 patchfile = fopen(patch, "w");
982 p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
983 s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
987 } while (isspace(peek));
990 /* process the email header */
991 while (read_one_header_line(&line, fin))
992 check_header(&line, p_hdr_data, 1);
1002 static int git_mailinfo_config(const char *var, const char *value, void *unused)
1004 if (!starts_with(var, "mailinfo."))
1005 return git_default_config(var, value, unused);
1006 if (!strcmp(var, "mailinfo.scissors")) {
1007 use_scissors = git_config_bool(var, value);
1010 /* perhaps others here */
1014 static const char mailinfo_usage[] =
1015 "git mailinfo [-k | -b] [-m | --message-id] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] <msg> <patch> < mail >info";
1017 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1019 const char *def_charset;
1021 /* NEEDSWORK: might want to do the optional .git/ directory
1024 git_config(git_mailinfo_config, NULL);
1026 def_charset = get_commit_output_encoding();
1027 metainfo_charset = def_charset;
1029 while (1 < argc && argv[1][0] == '-') {
1030 if (!strcmp(argv[1], "-k"))
1032 else if (!strcmp(argv[1], "-b"))
1033 keep_non_patch_brackets_in_subject = 1;
1034 else if (!strcmp(argv[1], "-m") || !strcmp(argv[1], "--message-id"))
1036 else if (!strcmp(argv[1], "-u"))
1037 metainfo_charset = def_charset;
1038 else if (!strcmp(argv[1], "-n"))
1039 metainfo_charset = NULL;
1040 else if (starts_with(argv[1], "--encoding="))
1041 metainfo_charset = argv[1] + 11;
1042 else if (!strcmp(argv[1], "--scissors"))
1044 else if (!strcmp(argv[1], "--no-scissors"))
1046 else if (!strcmp(argv[1], "--no-inbody-headers"))
1047 use_inbody_headers = 0;
1049 usage(mailinfo_usage);
1054 usage(mailinfo_usage);
1056 return !!mailinfo(stdin, stdout, argv[1], argv[2]);