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_HDR_PARSED 10
32 #define MAX_BOUNDARIES 5
34 static void cleanup_space(struct strbuf *sb);
37 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
39 struct strbuf *src = name;
40 if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
41 strchr(name->buf, '<') || strchr(name->buf, '>'))
46 strbuf_addbuf(out, src);
49 static void parse_bogus_from(const struct strbuf *line)
51 /* John Doe <johndoe> */
54 /* This is fallback, so do not bother if we already have an
60 bra = strchr(line->buf, '<');
63 ket = strchr(bra, '>');
68 strbuf_add(&email, bra + 1, ket - bra - 1);
71 strbuf_add(&name, line->buf, bra - line->buf);
73 get_sane_name(&name, &name, &email);
76 static void handle_from(const struct strbuf *from)
82 strbuf_init(&f, from->len);
83 strbuf_addbuf(&f, from);
85 at = strchr(f.buf, '@');
87 parse_bogus_from(from);
92 * If we already have one email, don't take any confusing lines
94 if (email.len && strchr(at + 1, '@')) {
99 /* Pick up the string around '@', possibly delimited with <>
100 * pair; that is the email part.
112 el = strcspn(at, " \n\t\r\v\f>");
113 strbuf_reset(&email);
114 strbuf_add(&email, at, el);
115 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
117 /* The remainder is name. It could be
119 * - "John Doe <john.doe@xz>" (a), or
120 * - "john.doe@xz (John Doe)" (b), or
121 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
123 * but we have removed the email part, so
125 * - remove extra spaces which could stay after email (case 'c'), and
126 * - trim from both ends, possibly removing the () pair at the end
127 * (cases 'a' and 'b').
131 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
132 strbuf_remove(&f, 0, 1);
133 strbuf_setlen(&f, f.len - 1);
136 get_sane_name(&name, &f, &email);
140 static void handle_header(struct strbuf **out, const struct strbuf *line)
143 *out = xmalloc(sizeof(struct strbuf));
144 strbuf_init(*out, line->len);
148 strbuf_addbuf(*out, line);
151 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
152 * to have enough heuristics to grok MIME encoded patches often found
153 * on our mailing lists. For example, we do not even treat header lines
154 * case insensitively.
157 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
159 const char *ends, *ap = strcasestr(line, name);
162 strbuf_setlen(attr, 0);
172 sz = strcspn(ap, ends);
173 strbuf_add(attr, ap, sz);
177 static struct strbuf *content[MAX_BOUNDARIES];
179 static struct strbuf **content_top = content;
181 static void handle_content_type(struct strbuf *line)
183 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
184 strbuf_init(boundary, line->len);
186 if (slurp_attr(line->buf, "boundary=", boundary)) {
187 strbuf_insert(boundary, 0, "--", 2);
188 if (++content_top > &content[MAX_BOUNDARIES]) {
189 fprintf(stderr, "Too many boundaries to handle\n");
192 *content_top = boundary;
195 slurp_attr(line->buf, "charset=", &charset);
198 strbuf_release(boundary);
203 static void handle_message_id(const struct strbuf *line)
206 message_id = strdup(line->buf);
209 static void handle_content_transfer_encoding(const struct strbuf *line)
211 if (strcasestr(line->buf, "base64"))
212 transfer_encoding = TE_BASE64;
213 else if (strcasestr(line->buf, "quoted-printable"))
214 transfer_encoding = TE_QP;
216 transfer_encoding = TE_DONTCARE;
219 static int is_multipart_boundary(const struct strbuf *line)
221 return (((*content_top)->len <= line->len) &&
222 !memcmp(line->buf, (*content_top)->buf, (*content_top)->len));
225 static void cleanup_subject(struct strbuf *subject)
229 while (at < subject->len) {
233 switch (subject->buf[at]) {
235 if (subject->len <= at + 3)
237 if ((subject->buf[at + 1] == 'e' ||
238 subject->buf[at + 1] == 'E') &&
239 subject->buf[at + 2] == ':') {
240 strbuf_remove(subject, at, 3);
245 case ' ': case '\t': case ':':
246 strbuf_remove(subject, at, 1);
249 pos = strchr(subject->buf + at, ']');
252 remove = pos - subject->buf + at + 1;
253 if (!keep_non_patch_brackets_in_subject ||
255 memmem(subject->buf + at, remove, "PATCH", 5)))
256 strbuf_remove(subject, at, remove);
260 * If the input had a space after the ], keep
261 * it. We don't bother with finding the end of
262 * the space, since we later normalize it
265 if (isspace(subject->buf[at]))
272 strbuf_trim(subject);
275 static void cleanup_space(struct strbuf *sb)
278 for (pos = 0; pos < sb->len; pos++) {
279 if (isspace(sb->buf[pos])) {
281 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
282 strbuf_remove(sb, pos + 1, cnt);
287 static void decode_header(struct strbuf *line);
288 static const char *header[MAX_HDR_PARSED] = {
289 "From","Subject","Date",
292 static inline int cmp_header(const struct strbuf *line, const char *hdr)
294 int len = strlen(hdr);
295 return !strncasecmp(line->buf, hdr, len) && line->len > len &&
296 line->buf[len] == ':' && isspace(line->buf[len + 1]);
299 static int is_format_patch_separator(const char *line, int len)
301 static const char SAMPLE[] =
302 "From e6807f3efca28b30decfecb1732a56c7db1137ee Mon Sep 17 00:00:00 2001\n";
305 if (len != strlen(SAMPLE))
307 if (!skip_prefix(line, "From ", &cp))
309 if (strspn(cp, "0123456789abcdef") != 40)
312 return !memcmp(SAMPLE + (cp - line), cp, strlen(SAMPLE) - (cp - line));
315 static int check_header(const struct strbuf *line,
316 struct strbuf *hdr_data[], int overwrite)
319 struct strbuf sb = STRBUF_INIT;
320 /* search for the interesting parts */
321 for (i = 0; header[i]; i++) {
322 int len = strlen(header[i]);
323 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
324 /* Unwrap inline B and Q encoding, and optionally
325 * normalize the meta information to utf8.
327 strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
329 handle_header(&hdr_data[i], &sb);
331 goto check_header_out;
336 if (cmp_header(line, "Content-Type")) {
337 len = strlen("Content-Type: ");
338 strbuf_add(&sb, line->buf + len, line->len - len);
340 strbuf_insert(&sb, 0, "Content-Type: ", len);
341 handle_content_type(&sb);
343 goto check_header_out;
345 if (cmp_header(line, "Content-Transfer-Encoding")) {
346 len = strlen("Content-Transfer-Encoding: ");
347 strbuf_add(&sb, line->buf + len, line->len - len);
349 handle_content_transfer_encoding(&sb);
351 goto check_header_out;
353 if (cmp_header(line, "Message-Id")) {
354 len = strlen("Message-Id: ");
355 strbuf_add(&sb, line->buf + len, line->len - len);
357 handle_message_id(&sb);
359 goto check_header_out;
362 /* for inbody stuff */
363 if (starts_with(line->buf, ">From") && isspace(line->buf[5])) {
364 ret = is_format_patch_separator(line->buf + 1, line->len - 1);
365 goto check_header_out;
367 if (starts_with(line->buf, "[PATCH]") && isspace(line->buf[7])) {
368 for (i = 0; header[i]; i++) {
369 if (!strcmp("Subject", header[i])) {
370 handle_header(&hdr_data[i], line);
372 goto check_header_out;
382 static int is_rfc2822_header(const struct strbuf *line)
385 * The section that defines the loosest possible
386 * field name is "3.6.8 Optional fields".
388 * optional-field = field-name ":" unstructured CRLF
389 * field-name = 1*ftext
390 * ftext = %d33-57 / %59-126
393 char *cp = line->buf;
395 /* Count mbox From headers as headers */
396 if (starts_with(cp, "From ") || starts_with(cp, ">From "))
399 while ((ch = *cp++)) {
402 if ((33 <= ch && ch <= 57) ||
403 (59 <= ch && ch <= 126))
410 static int read_one_header_line(struct strbuf *line, FILE *in)
412 /* Get the first part of the line. */
413 if (strbuf_getline(line, in, '\n'))
417 * Is it an empty line or not a valid rfc2822 header?
418 * If so, stop here, and return false ("not a header")
421 if (!line->len || !is_rfc2822_header(line)) {
422 /* Re-add the newline */
423 strbuf_addch(line, '\n');
428 * Now we need to eat all the continuation lines..
429 * Yuck, 2822 header "folding"
433 struct strbuf continuation = STRBUF_INIT;
435 peek = fgetc(in); ungetc(peek, in);
436 if (peek != ' ' && peek != '\t')
438 if (strbuf_getline(&continuation, in, '\n'))
440 continuation.buf[0] = ' ';
441 strbuf_rtrim(&continuation);
442 strbuf_addbuf(line, &continuation);
448 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
450 const char *in = q_seg->buf;
452 struct strbuf *out = xmalloc(sizeof(struct strbuf));
453 strbuf_init(out, q_seg->len);
455 while ((c = *in++) != 0) {
459 break; /* drop trailing newline */
460 strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
463 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
465 strbuf_addch(out, c);
470 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
472 /* Decode in..ep, possibly in-place to ot */
473 int c, pos = 0, acc = 0;
474 const char *in = b_seg->buf;
475 struct strbuf *out = xmalloc(sizeof(struct strbuf));
476 strbuf_init(out, b_seg->len);
478 while ((c = *in++) != 0) {
483 else if ('A' <= c && c <= 'Z')
485 else if ('a' <= c && c <= 'z')
487 else if ('0' <= c && c <= '9')
490 continue; /* garbage */
496 strbuf_addch(out, (acc | (c >> 4)));
500 strbuf_addch(out, (acc | (c >> 2)));
504 strbuf_addch(out, (acc | c));
512 static void convert_to_utf8(struct strbuf *line, const char *charset)
516 if (!charset || !*charset)
519 if (same_encoding(metainfo_charset, charset))
521 out = reencode_string(line->buf, metainfo_charset, charset);
523 die("cannot convert from %s to %s",
524 charset, metainfo_charset);
525 strbuf_attach(line, out, strlen(out), strlen(out));
528 static int decode_header_bq(struct strbuf *it)
531 struct strbuf outbuf = STRBUF_INIT, *dec;
532 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
536 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
538 strbuf_reset(&charset_q);
539 strbuf_reset(&piecebuf);
544 * We are about to process an encoded-word
545 * that begins at ep, but there is something
546 * before the encoded word.
549 for (scan = in; scan < ep; scan++)
553 if (scan != ep || in == it->buf) {
555 * We should not lose that "something",
556 * unless we have just processed an
557 * encoded-word, and there is only LWS
558 * before the one we are about to process.
560 strbuf_add(&outbuf, in, ep - in);
564 * ep : "=?iso-2022-jp?B?GyR...?= foo"
565 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
569 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
570 goto decode_header_bq_out;
572 if (cp + 3 - it->buf > it->len)
573 goto decode_header_bq_out;
574 strbuf_add(&charset_q, ep, cp - ep);
577 if (!encoding || cp[2] != '?')
578 goto decode_header_bq_out;
579 ep = strstr(cp + 3, "?=");
581 goto decode_header_bq_out;
582 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
583 switch (tolower(encoding)) {
585 goto decode_header_bq_out;
587 dec = decode_b_segment(&piecebuf);
590 dec = decode_q_segment(&piecebuf, 1);
593 if (metainfo_charset)
594 convert_to_utf8(dec, charset_q.buf);
596 strbuf_addbuf(&outbuf, dec);
601 strbuf_addstr(&outbuf, in);
603 strbuf_addbuf(it, &outbuf);
604 decode_header_bq_out:
605 strbuf_release(&outbuf);
606 strbuf_release(&charset_q);
607 strbuf_release(&piecebuf);
611 static void decode_header(struct strbuf *it)
613 if (decode_header_bq(it))
615 /* otherwise "it" is a straight copy of the input.
616 * This can be binary guck but there is no charset specified.
618 if (metainfo_charset)
619 convert_to_utf8(it, "");
622 static void decode_transfer_encoding(struct strbuf *line)
626 switch (transfer_encoding) {
628 ret = decode_q_segment(line, 0);
631 ret = decode_b_segment(line);
638 strbuf_addbuf(line, ret);
643 static void handle_filter(struct strbuf *line);
645 static int find_boundary(void)
647 while (!strbuf_getline(&line, fin, '\n')) {
648 if (*content_top && is_multipart_boundary(&line))
654 static int handle_boundary(void)
656 struct strbuf newline = STRBUF_INIT;
658 strbuf_addch(&newline, '\n');
660 if (line.len >= (*content_top)->len + 2 &&
661 !memcmp(line.buf + (*content_top)->len, "--", 2)) {
662 /* we hit an end boundary */
663 /* pop the current boundary off the stack */
664 strbuf_release(*content_top);
668 /* technically won't happen as is_multipart_boundary()
669 will fail first. But just in case..
671 if (--content_top < content) {
672 fprintf(stderr, "Detected mismatched boundaries, "
676 handle_filter(&newline);
677 strbuf_release(&newline);
679 /* skip to the next boundary */
680 if (!find_boundary())
685 /* set some defaults */
686 transfer_encoding = TE_DONTCARE;
687 strbuf_reset(&charset);
689 /* slurp in this section's info */
690 while (read_one_header_line(&line, fin))
691 check_header(&line, p_hdr_data, 0);
693 strbuf_release(&newline);
695 if (strbuf_getline(&line, fin, '\n'))
697 strbuf_addch(&line, '\n');
701 static inline int patchbreak(const struct strbuf *line)
705 /* Beginning of a "diff -" header? */
706 if (starts_with(line->buf, "diff -"))
709 /* CVS "Index: " line? */
710 if (starts_with(line->buf, "Index: "))
714 * "--- <filename>" starts patches without headers
715 * "---<sp>*" is a manual separator
720 if (starts_with(line->buf, "---")) {
721 /* space followed by a filename? */
722 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
724 /* Just whitespace? */
725 for (i = 3; i < line->len; i++) {
726 unsigned char c = line->buf[i];
737 static int is_scissors_line(const struct strbuf *line)
739 size_t i, len = line->len;
740 int scissors = 0, gap = 0;
741 int first_nonblank = -1;
742 int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
743 const char *buf = line->buf;
745 for (i = 0; i < len; i++) {
746 if (isspace(buf[i])) {
747 if (in_perforation) {
754 if (first_nonblank < 0)
762 (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
763 !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
774 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
775 * Even though there can be arbitrary cruft on the same line
776 * (e.g. "cut here"), in order to avoid misidentification, the
777 * perforation must occupy more than a third of the visible
778 * width of the line, and dashes and scissors must occupy more
779 * than half of the perforation.
782 visible = last_nonblank - first_nonblank + 1;
783 return (scissors && 8 <= visible &&
784 visible < perforation * 3 &&
785 gap * 2 < perforation);
788 static int handle_commit_msg(struct strbuf *line)
790 static int still_looking = 1;
796 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
800 if (use_inbody_headers && still_looking) {
801 still_looking = check_header(line, s_hdr_data, 0);
805 /* Only trim the first (blank) line of the commit message
806 * when ignoring in-body headers.
810 /* normalize the log message to UTF-8. */
811 if (metainfo_charset)
812 convert_to_utf8(line, charset.buf);
814 if (use_scissors && is_scissors_line(line)) {
816 if (fseek(cmitmsg, 0L, SEEK_SET))
817 die_errno("Could not rewind output message file");
818 if (ftruncate(fileno(cmitmsg), 0))
819 die_errno("Could not truncate output message file at scissors");
823 * We may have already read "secondary headers"; purge
824 * them to give ourselves a clean restart.
826 for (i = 0; header[i]; i++) {
828 strbuf_release(s_hdr_data[i]);
829 s_hdr_data[i] = NULL;
834 if (patchbreak(line)) {
836 fprintf(cmitmsg, "Message-Id: %s\n", message_id);
842 fputs(line->buf, cmitmsg);
846 static void handle_patch(const struct strbuf *line)
848 fwrite(line->buf, 1, line->len, patchfile);
852 static void handle_filter(struct strbuf *line)
854 static int filter = 0;
856 /* filter tells us which part we left off on */
859 if (!handle_commit_msg(line))
868 static void handle_body(void)
870 struct strbuf prev = STRBUF_INIT;
872 /* Skip up to the first boundary */
874 if (!find_boundary())
875 goto handle_body_out;
879 /* process any boundary lines */
880 if (*content_top && is_multipart_boundary(&line)) {
881 /* flush any leftover */
883 handle_filter(&prev);
886 if (!handle_boundary())
887 goto handle_body_out;
890 /* Unwrap transfer encoding */
891 decode_transfer_encoding(&line);
893 switch (transfer_encoding) {
897 struct strbuf **lines, **it, *sb;
899 /* Prepend any previous partial lines */
900 strbuf_insert(&line, 0, prev.buf, prev.len);
904 * This is a decoded line that may contain
905 * multiple new lines. Pass only one chunk
906 * at a time to handle_filter()
908 lines = strbuf_split(&line, '\n');
909 for (it = lines; (sb = *it); it++) {
910 if (*(it + 1) == NULL) /* The last line */
911 if (sb->buf[sb->len - 1] != '\n') {
912 /* Partial line, save it for later. */
913 strbuf_addbuf(&prev, sb);
919 * The partial chunk is saved in "prev" and will be
920 * appended by the next iteration of read_line_with_nul().
922 strbuf_list_free(lines);
926 handle_filter(&line);
929 } while (!strbuf_getwholeline(&line, fin, '\n'));
932 strbuf_release(&prev);
935 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
937 const char *sp = data->buf;
939 char *ep = strchr(sp, '\n');
945 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
952 static void handle_info(void)
957 for (i = 0; header[i]; i++) {
958 /* only print inbody headers if we output a patch file */
959 if (patch_lines && s_hdr_data[i])
961 else if (p_hdr_data[i])
966 if (!strcmp(header[i], "Subject")) {
968 cleanup_subject(hdr);
971 output_header_lines(fout, "Subject", hdr);
972 } else if (!strcmp(header[i], "From")) {
975 fprintf(fout, "Author: %s\n", name.buf);
976 fprintf(fout, "Email: %s\n", email.buf);
979 fprintf(fout, "%s: %s\n", header[i], hdr->buf);
985 static int mailinfo(FILE *in, FILE *out, const char *msg, const char *patch)
991 cmitmsg = fopen(msg, "w");
996 patchfile = fopen(patch, "w");
1003 p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
1004 s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
1008 } while (isspace(peek));
1011 /* process the email header */
1012 while (read_one_header_line(&line, fin))
1013 check_header(&line, p_hdr_data, 1);
1021 static int git_mailinfo_config(const char *var, const char *value, void *unused)
1023 if (!starts_with(var, "mailinfo."))
1024 return git_default_config(var, value, unused);
1025 if (!strcmp(var, "mailinfo.scissors")) {
1026 use_scissors = git_config_bool(var, value);
1029 /* perhaps others here */
1033 static const char mailinfo_usage[] =
1034 "git mailinfo [-k | -b] [-m | --message-id] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] <msg> <patch> < mail >info";
1036 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1038 const char *def_charset;
1040 /* NEEDSWORK: might want to do the optional .git/ directory
1043 git_config(git_mailinfo_config, NULL);
1045 def_charset = get_commit_output_encoding();
1046 metainfo_charset = def_charset;
1048 while (1 < argc && argv[1][0] == '-') {
1049 if (!strcmp(argv[1], "-k"))
1051 else if (!strcmp(argv[1], "-b"))
1052 keep_non_patch_brackets_in_subject = 1;
1053 else if (!strcmp(argv[1], "-m") || !strcmp(argv[1], "--message-id"))
1055 else if (!strcmp(argv[1], "-u"))
1056 metainfo_charset = def_charset;
1057 else if (!strcmp(argv[1], "-n"))
1058 metainfo_charset = NULL;
1059 else if (starts_with(argv[1], "--encoding="))
1060 metainfo_charset = argv[1] + 11;
1061 else if (!strcmp(argv[1], "--scissors"))
1063 else if (!strcmp(argv[1], "--no-scissors"))
1065 else if (!strcmp(argv[1], "--no-inbody-headers"))
1066 use_inbody_headers = 0;
1068 usage(mailinfo_usage);
1073 usage(mailinfo_usage);
1075 return !!mailinfo(stdin, stdout, argv[1], argv[2]);