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 (!memcmp(subject->buf + at + 1, "e:", 2)) {
236 strbuf_remove(subject, at, 3);
241 case ' ': case '\t': case ':':
242 strbuf_remove(subject, at, 1);
245 pos = strchr(subject->buf + at, ']');
248 remove = pos - subject->buf + at + 1;
249 if (!keep_non_patch_brackets_in_subject ||
251 memmem(subject->buf + at, remove, "PATCH", 5)))
252 strbuf_remove(subject, at, remove);
256 * If the input had a space after the ], keep
257 * it. We don't bother with finding the end of
258 * the space, since we later normalize it
261 if (isspace(subject->buf[at]))
268 strbuf_trim(subject);
271 static void cleanup_space(struct strbuf *sb)
274 for (pos = 0; pos < sb->len; pos++) {
275 if (isspace(sb->buf[pos])) {
277 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
278 strbuf_remove(sb, pos + 1, cnt);
283 static void decode_header(struct strbuf *line);
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 check_header(const struct strbuf *line,
296 struct strbuf *hdr_data[], int overwrite)
299 struct strbuf sb = STRBUF_INIT;
300 /* search for the interesting parts */
301 for (i = 0; header[i]; i++) {
302 int len = strlen(header[i]);
303 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
304 /* Unwrap inline B and Q encoding, and optionally
305 * normalize the meta information to utf8.
307 strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
309 handle_header(&hdr_data[i], &sb);
311 goto check_header_out;
316 if (cmp_header(line, "Content-Type")) {
317 len = strlen("Content-Type: ");
318 strbuf_add(&sb, line->buf + len, line->len - len);
320 strbuf_insert(&sb, 0, "Content-Type: ", len);
321 handle_content_type(&sb);
323 goto check_header_out;
325 if (cmp_header(line, "Content-Transfer-Encoding")) {
326 len = strlen("Content-Transfer-Encoding: ");
327 strbuf_add(&sb, line->buf + len, line->len - len);
329 handle_content_transfer_encoding(&sb);
331 goto check_header_out;
334 /* for inbody stuff */
335 if (!prefixcmp(line->buf, ">From") && isspace(line->buf[5])) {
336 ret = 1; /* Should this return 0? */
337 goto check_header_out;
339 if (!prefixcmp(line->buf, "[PATCH]") && isspace(line->buf[7])) {
340 for (i = 0; header[i]; i++) {
341 if (!memcmp("Subject", header[i], 7)) {
342 handle_header(&hdr_data[i], line);
344 goto check_header_out;
354 static int is_rfc2822_header(const struct strbuf *line)
357 * The section that defines the loosest possible
358 * field name is "3.6.8 Optional fields".
360 * optional-field = field-name ":" unstructured CRLF
361 * field-name = 1*ftext
362 * ftext = %d33-57 / %59-126
365 char *cp = line->buf;
367 /* Count mbox From headers as headers */
368 if (!prefixcmp(cp, "From ") || !prefixcmp(cp, ">From "))
371 while ((ch = *cp++)) {
374 if ((33 <= ch && ch <= 57) ||
375 (59 <= ch && ch <= 126))
382 static int read_one_header_line(struct strbuf *line, FILE *in)
384 /* Get the first part of the line. */
385 if (strbuf_getline(line, in, '\n'))
389 * Is it an empty line or not a valid rfc2822 header?
390 * If so, stop here, and return false ("not a header")
393 if (!line->len || !is_rfc2822_header(line)) {
394 /* Re-add the newline */
395 strbuf_addch(line, '\n');
400 * Now we need to eat all the continuation lines..
401 * Yuck, 2822 header "folding"
405 struct strbuf continuation = STRBUF_INIT;
407 peek = fgetc(in); ungetc(peek, in);
408 if (peek != ' ' && peek != '\t')
410 if (strbuf_getline(&continuation, in, '\n'))
412 continuation.buf[0] = ' ';
413 strbuf_rtrim(&continuation);
414 strbuf_addbuf(line, &continuation);
420 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
422 const char *in = q_seg->buf;
424 struct strbuf *out = xmalloc(sizeof(struct strbuf));
425 strbuf_init(out, q_seg->len);
427 while ((c = *in++) != 0) {
431 break; /* drop trailing newline */
432 strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
435 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
437 strbuf_addch(out, c);
442 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
444 /* Decode in..ep, possibly in-place to ot */
445 int c, pos = 0, acc = 0;
446 const char *in = b_seg->buf;
447 struct strbuf *out = xmalloc(sizeof(struct strbuf));
448 strbuf_init(out, b_seg->len);
450 while ((c = *in++) != 0) {
455 else if ('A' <= c && c <= 'Z')
457 else if ('a' <= c && c <= 'z')
459 else if ('0' <= c && c <= '9')
462 continue; /* garbage */
468 strbuf_addch(out, (acc | (c >> 4)));
472 strbuf_addch(out, (acc | (c >> 2)));
476 strbuf_addch(out, (acc | c));
485 * When there is no known charset, guess.
487 * Right now we assume that if the target is UTF-8 (the default),
488 * and it already looks like UTF-8 (which includes US-ASCII as its
489 * subset, of course) then that is what it is and there is nothing
492 * Otherwise, we default to assuming it is Latin1 for historical
495 static const char *guess_charset(const struct strbuf *line, const char *target_charset)
497 if (is_encoding_utf8(target_charset)) {
498 if (is_utf8(line->buf))
504 static void convert_to_utf8(struct strbuf *line, const char *charset)
508 if (!charset || !*charset) {
509 charset = guess_charset(line, metainfo_charset);
514 if (!strcasecmp(metainfo_charset, charset))
516 out = reencode_string(line->buf, metainfo_charset, charset);
518 die("cannot convert from %s to %s",
519 charset, metainfo_charset);
520 strbuf_attach(line, out, strlen(out), strlen(out));
523 static int decode_header_bq(struct strbuf *it)
526 struct strbuf outbuf = STRBUF_INIT, *dec;
527 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
531 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
533 strbuf_reset(&charset_q);
534 strbuf_reset(&piecebuf);
539 * We are about to process an encoded-word
540 * that begins at ep, but there is something
541 * before the encoded word.
544 for (scan = in; scan < ep; scan++)
548 if (scan != ep || in == it->buf) {
550 * We should not lose that "something",
551 * unless we have just processed an
552 * encoded-word, and there is only LWS
553 * before the one we are about to process.
555 strbuf_add(&outbuf, in, ep - in);
559 * ep : "=?iso-2022-jp?B?GyR...?= foo"
560 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
564 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
565 goto decode_header_bq_out;
567 if (cp + 3 - it->buf > it->len)
568 goto decode_header_bq_out;
569 strbuf_add(&charset_q, ep, cp - ep);
572 if (!encoding || cp[2] != '?')
573 goto decode_header_bq_out;
574 ep = strstr(cp + 3, "?=");
576 goto decode_header_bq_out;
577 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
578 switch (tolower(encoding)) {
580 goto decode_header_bq_out;
582 dec = decode_b_segment(&piecebuf);
585 dec = decode_q_segment(&piecebuf, 1);
588 if (metainfo_charset)
589 convert_to_utf8(dec, charset_q.buf);
591 strbuf_addbuf(&outbuf, dec);
596 strbuf_addstr(&outbuf, in);
598 strbuf_addbuf(it, &outbuf);
599 decode_header_bq_out:
600 strbuf_release(&outbuf);
601 strbuf_release(&charset_q);
602 strbuf_release(&piecebuf);
606 static void decode_header(struct strbuf *it)
608 if (decode_header_bq(it))
610 /* otherwise "it" is a straight copy of the input.
611 * This can be binary guck but there is no charset specified.
613 if (metainfo_charset)
614 convert_to_utf8(it, "");
617 static void decode_transfer_encoding(struct strbuf *line)
621 switch (transfer_encoding) {
623 ret = decode_q_segment(line, 0);
626 ret = decode_b_segment(line);
633 strbuf_addbuf(line, ret);
638 static void handle_filter(struct strbuf *line);
640 static int find_boundary(void)
642 while (!strbuf_getline(&line, fin, '\n')) {
643 if (*content_top && is_multipart_boundary(&line))
649 static int handle_boundary(void)
651 struct strbuf newline = STRBUF_INIT;
653 strbuf_addch(&newline, '\n');
655 if (line.len >= (*content_top)->len + 2 &&
656 !memcmp(line.buf + (*content_top)->len, "--", 2)) {
657 /* we hit an end boundary */
658 /* pop the current boundary off the stack */
659 strbuf_release(*content_top);
663 /* technically won't happen as is_multipart_boundary()
664 will fail first. But just in case..
666 if (--content_top < content) {
667 fprintf(stderr, "Detected mismatched boundaries, "
671 handle_filter(&newline);
672 strbuf_release(&newline);
674 /* skip to the next boundary */
675 if (!find_boundary())
680 /* set some defaults */
681 transfer_encoding = TE_DONTCARE;
682 strbuf_reset(&charset);
683 message_type = TYPE_TEXT;
685 /* slurp in this section's info */
686 while (read_one_header_line(&line, fin))
687 check_header(&line, p_hdr_data, 0);
689 strbuf_release(&newline);
691 if (strbuf_getline(&line, fin, '\n'))
693 strbuf_addch(&line, '\n');
697 static inline int patchbreak(const struct strbuf *line)
701 /* Beginning of a "diff -" header? */
702 if (!prefixcmp(line->buf, "diff -"))
705 /* CVS "Index: " line? */
706 if (!prefixcmp(line->buf, "Index: "))
710 * "--- <filename>" starts patches without headers
711 * "---<sp>*" is a manual separator
716 if (!prefixcmp(line->buf, "---")) {
717 /* space followed by a filename? */
718 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
720 /* Just whitespace? */
721 for (i = 3; i < line->len; i++) {
722 unsigned char c = line->buf[i];
733 static int is_scissors_line(const struct strbuf *line)
735 size_t i, len = line->len;
736 int scissors = 0, gap = 0;
737 int first_nonblank = -1;
738 int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
739 const char *buf = line->buf;
741 for (i = 0; i < len; i++) {
742 if (isspace(buf[i])) {
743 if (in_perforation) {
750 if (first_nonblank < 0)
758 (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
759 !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
770 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
771 * Even though there can be arbitrary cruft on the same line
772 * (e.g. "cut here"), in order to avoid misidentification, the
773 * perforation must occupy more than a third of the visible
774 * width of the line, and dashes and scissors must occupy more
775 * than half of the perforation.
778 visible = last_nonblank - first_nonblank + 1;
779 return (scissors && 8 <= visible &&
780 visible < perforation * 3 &&
781 gap * 2 < perforation);
784 static int handle_commit_msg(struct strbuf *line)
786 static int still_looking = 1;
792 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
796 if (use_inbody_headers && still_looking) {
797 still_looking = check_header(line, s_hdr_data, 0);
801 /* Only trim the first (blank) line of the commit message
802 * when ignoring in-body headers.
806 /* normalize the log message to UTF-8. */
807 if (metainfo_charset)
808 convert_to_utf8(line, charset.buf);
810 if (use_scissors && is_scissors_line(line)) {
812 if (fseek(cmitmsg, 0L, SEEK_SET))
813 die_errno("Could not rewind output message file");
814 if (ftruncate(fileno(cmitmsg), 0))
815 die_errno("Could not truncate output message file at scissors");
819 * We may have already read "secondary headers"; purge
820 * them to give ourselves a clean restart.
822 for (i = 0; header[i]; i++) {
824 strbuf_release(s_hdr_data[i]);
825 s_hdr_data[i] = NULL;
830 if (patchbreak(line)) {
836 fputs(line->buf, cmitmsg);
840 static void handle_patch(const struct strbuf *line)
842 fwrite(line->buf, 1, line->len, patchfile);
846 static void handle_filter(struct strbuf *line)
848 static int filter = 0;
850 /* filter tells us which part we left off on */
853 if (!handle_commit_msg(line))
862 static void handle_body(void)
864 struct strbuf prev = STRBUF_INIT;
866 /* Skip up to the first boundary */
868 if (!find_boundary())
869 goto handle_body_out;
873 /* process any boundary lines */
874 if (*content_top && is_multipart_boundary(&line)) {
875 /* flush any leftover */
877 handle_filter(&prev);
880 if (!handle_boundary())
881 goto handle_body_out;
884 /* Unwrap transfer encoding */
885 decode_transfer_encoding(&line);
887 switch (transfer_encoding) {
891 struct strbuf **lines, **it, *sb;
893 /* Prepend any previous partial lines */
894 strbuf_insert(&line, 0, prev.buf, prev.len);
897 /* binary data most likely doesn't have newlines */
898 if (message_type != TYPE_TEXT) {
899 handle_filter(&line);
903 * This is a decoded line that may contain
904 * multiple new lines. Pass only one chunk
905 * at a time to handle_filter()
907 lines = strbuf_split(&line, '\n');
908 for (it = lines; (sb = *it); it++) {
909 if (*(it + 1) == NULL) /* The last line */
910 if (sb->buf[sb->len - 1] != '\n') {
911 /* Partial line, save it for later. */
912 strbuf_addbuf(&prev, sb);
918 * The partial chunk is saved in "prev" and will be
919 * appended by the next iteration of read_line_with_nul().
921 strbuf_list_free(lines);
925 handle_filter(&line);
928 } while (!strbuf_getwholeline(&line, fin, '\n'));
931 strbuf_release(&prev);
934 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
936 const char *sp = data->buf;
938 char *ep = strchr(sp, '\n');
944 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
951 static void handle_info(void)
956 for (i = 0; header[i]; i++) {
957 /* only print inbody headers if we output a patch file */
958 if (patch_lines && s_hdr_data[i])
960 else if (p_hdr_data[i])
965 if (!memcmp(header[i], "Subject", 7)) {
967 cleanup_subject(hdr);
970 output_header_lines(fout, "Subject", hdr);
971 } else if (!memcmp(header[i], "From", 4)) {
974 fprintf(fout, "Author: %s\n", name.buf);
975 fprintf(fout, "Email: %s\n", email.buf);
978 fprintf(fout, "%s: %s\n", header[i], hdr->buf);
984 static int mailinfo(FILE *in, FILE *out, const char *msg, const char *patch)
990 cmitmsg = fopen(msg, "w");
995 patchfile = fopen(patch, "w");
1002 p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
1003 s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
1007 } while (isspace(peek));
1010 /* process the email header */
1011 while (read_one_header_line(&line, fin))
1012 check_header(&line, p_hdr_data, 1);
1020 static int git_mailinfo_config(const char *var, const char *value, void *unused)
1022 if (prefixcmp(var, "mailinfo."))
1023 return git_default_config(var, value, unused);
1024 if (!strcmp(var, "mailinfo.scissors")) {
1025 use_scissors = git_config_bool(var, value);
1028 /* perhaps others here */
1032 static const char mailinfo_usage[] =
1033 "git mailinfo [-k|-b] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] msg patch < mail >info";
1035 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1037 const char *def_charset;
1039 /* NEEDSWORK: might want to do the optional .git/ directory
1042 git_config(git_mailinfo_config, NULL);
1044 def_charset = get_commit_output_encoding();
1045 metainfo_charset = def_charset;
1047 while (1 < argc && argv[1][0] == '-') {
1048 if (!strcmp(argv[1], "-k"))
1050 else if (!strcmp(argv[1], "-b"))
1051 keep_non_patch_brackets_in_subject = 1;
1052 else if (!strcmp(argv[1], "-u"))
1053 metainfo_charset = def_charset;
1054 else if (!strcmp(argv[1], "-n"))
1055 metainfo_charset = NULL;
1056 else if (!prefixcmp(argv[1], "--encoding="))
1057 metainfo_charset = argv[1] + 11;
1058 else if (!strcmp(argv[1], "--scissors"))
1060 else if (!strcmp(argv[1], "--no-scissors"))
1062 else if (!strcmp(argv[1], "--no-inbody-headers"))
1063 use_inbody_headers = 0;
1065 usage(mailinfo_usage);
1070 usage(mailinfo_usage);
1072 return !!mailinfo(stdin, stdout, argv[1], argv[2]);