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 const char *metainfo_charset;
14 static struct strbuf line = STRBUF_INIT;
15 static struct strbuf name = STRBUF_INIT;
16 static struct strbuf email = STRBUF_INIT;
19 TE_DONTCARE, TE_QP, TE_BASE64,
22 TYPE_TEXT, TYPE_OTHER,
25 static struct strbuf charset = STRBUF_INIT;
26 static int patch_lines;
27 static struct strbuf **p_hdr_data, **s_hdr_data;
28 static int use_scissors;
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);
163 strbuf_setlen(attr, 0);
173 sz = strcspn(ap, ends);
174 strbuf_add(attr, ap, sz);
178 static struct strbuf *content[MAX_BOUNDARIES];
180 static struct strbuf **content_top = content;
182 static void handle_content_type(struct strbuf *line)
184 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
185 strbuf_init(boundary, line->len);
187 if (!strcasestr(line->buf, "text/"))
188 message_type = TYPE_OTHER;
189 if (slurp_attr(line->buf, "boundary=", boundary)) {
190 strbuf_insert(boundary, 0, "--", 2);
191 if (++content_top > &content[MAX_BOUNDARIES]) {
192 fprintf(stderr, "Too many boundaries to handle\n");
195 *content_top = boundary;
198 slurp_attr(line->buf, "charset=", &charset);
201 strbuf_release(boundary);
206 static void handle_content_transfer_encoding(const struct strbuf *line)
208 if (strcasestr(line->buf, "base64"))
209 transfer_encoding = TE_BASE64;
210 else if (strcasestr(line->buf, "quoted-printable"))
211 transfer_encoding = TE_QP;
213 transfer_encoding = TE_DONTCARE;
216 static int is_multipart_boundary(const struct strbuf *line)
218 return (((*content_top)->len <= line->len) &&
219 !memcmp(line->buf, (*content_top)->buf, (*content_top)->len));
222 static void cleanup_subject(struct strbuf *subject)
226 while (subject->len) {
227 switch (*subject->buf) {
229 if (subject->len <= 3)
231 if (!memcmp(subject->buf + 1, "e:", 2)) {
232 strbuf_remove(subject, 0, 3);
236 case ' ': case '\t': case ':':
237 strbuf_remove(subject, 0, 1);
240 if ((pos = strchr(subject->buf, ']'))) {
241 remove = pos - subject->buf;
242 if (remove <= (subject->len - remove) * 2) {
243 strbuf_remove(subject, 0, remove + 1);
247 strbuf_remove(subject, 0, 1);
250 strbuf_trim(subject);
255 static void cleanup_space(struct strbuf *sb)
258 for (pos = 0; pos < sb->len; pos++) {
259 if (isspace(sb->buf[pos])) {
261 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
262 strbuf_remove(sb, pos + 1, cnt);
267 static void decode_header(struct strbuf *line);
268 static const char *header[MAX_HDR_PARSED] = {
269 "From","Subject","Date",
272 static inline int cmp_header(const struct strbuf *line, const char *hdr)
274 int len = strlen(hdr);
275 return !strncasecmp(line->buf, hdr, len) && line->len > len &&
276 line->buf[len] == ':' && isspace(line->buf[len + 1]);
279 static int check_header(const struct strbuf *line,
280 struct strbuf *hdr_data[], int overwrite)
283 struct strbuf sb = STRBUF_INIT;
284 /* search for the interesting parts */
285 for (i = 0; header[i]; i++) {
286 int len = strlen(header[i]);
287 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
288 /* Unwrap inline B and Q encoding, and optionally
289 * normalize the meta information to utf8.
291 strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
293 handle_header(&hdr_data[i], &sb);
295 goto check_header_out;
300 if (cmp_header(line, "Content-Type")) {
301 len = strlen("Content-Type: ");
302 strbuf_add(&sb, line->buf + len, line->len - len);
304 strbuf_insert(&sb, 0, "Content-Type: ", len);
305 handle_content_type(&sb);
307 goto check_header_out;
309 if (cmp_header(line, "Content-Transfer-Encoding")) {
310 len = strlen("Content-Transfer-Encoding: ");
311 strbuf_add(&sb, line->buf + len, line->len - len);
313 handle_content_transfer_encoding(&sb);
315 goto check_header_out;
318 /* for inbody stuff */
319 if (!prefixcmp(line->buf, ">From") && isspace(line->buf[5])) {
320 ret = 1; /* Should this return 0? */
321 goto check_header_out;
323 if (!prefixcmp(line->buf, "[PATCH]") && isspace(line->buf[7])) {
324 for (i = 0; header[i]; i++) {
325 if (!memcmp("Subject", header[i], 7)) {
326 handle_header(&hdr_data[i], line);
328 goto check_header_out;
338 static int is_rfc2822_header(const struct strbuf *line)
341 * The section that defines the loosest possible
342 * field name is "3.6.8 Optional fields".
344 * optional-field = field-name ":" unstructured CRLF
345 * field-name = 1*ftext
346 * ftext = %d33-57 / %59-126
349 char *cp = line->buf;
351 /* Count mbox From headers as headers */
352 if (!prefixcmp(cp, "From ") || !prefixcmp(cp, ">From "))
355 while ((ch = *cp++)) {
358 if ((33 <= ch && ch <= 57) ||
359 (59 <= ch && ch <= 126))
366 static int read_one_header_line(struct strbuf *line, FILE *in)
368 /* Get the first part of the line. */
369 if (strbuf_getline(line, in, '\n'))
373 * Is it an empty line or not a valid rfc2822 header?
374 * If so, stop here, and return false ("not a header")
377 if (!line->len || !is_rfc2822_header(line)) {
378 /* Re-add the newline */
379 strbuf_addch(line, '\n');
384 * Now we need to eat all the continuation lines..
385 * Yuck, 2822 header "folding"
389 struct strbuf continuation = STRBUF_INIT;
391 peek = fgetc(in); ungetc(peek, in);
392 if (peek != ' ' && peek != '\t')
394 if (strbuf_getline(&continuation, in, '\n'))
396 continuation.buf[0] = '\n';
397 strbuf_rtrim(&continuation);
398 strbuf_addbuf(line, &continuation);
404 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
406 const char *in = q_seg->buf;
408 struct strbuf *out = xmalloc(sizeof(struct strbuf));
409 strbuf_init(out, q_seg->len);
411 while ((c = *in++) != 0) {
415 break; /* drop trailing newline */
416 strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
419 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
421 strbuf_addch(out, c);
426 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
428 /* Decode in..ep, possibly in-place to ot */
429 int c, pos = 0, acc = 0;
430 const char *in = b_seg->buf;
431 struct strbuf *out = xmalloc(sizeof(struct strbuf));
432 strbuf_init(out, b_seg->len);
434 while ((c = *in++) != 0) {
439 else if ('A' <= c && c <= 'Z')
441 else if ('a' <= c && c <= 'z')
443 else if ('0' <= c && c <= '9')
446 continue; /* garbage */
452 strbuf_addch(out, (acc | (c >> 4)));
456 strbuf_addch(out, (acc | (c >> 2)));
460 strbuf_addch(out, (acc | c));
469 * When there is no known charset, guess.
471 * Right now we assume that if the target is UTF-8 (the default),
472 * and it already looks like UTF-8 (which includes US-ASCII as its
473 * subset, of course) then that is what it is and there is nothing
476 * Otherwise, we default to assuming it is Latin1 for historical
479 static const char *guess_charset(const struct strbuf *line, const char *target_charset)
481 if (is_encoding_utf8(target_charset)) {
482 if (is_utf8(line->buf))
488 static void convert_to_utf8(struct strbuf *line, const char *charset)
492 if (!charset || !*charset) {
493 charset = guess_charset(line, metainfo_charset);
498 if (!strcasecmp(metainfo_charset, charset))
500 out = reencode_string(line->buf, metainfo_charset, charset);
502 die("cannot convert from %s to %s",
503 charset, metainfo_charset);
504 strbuf_attach(line, out, strlen(out), strlen(out));
507 static int decode_header_bq(struct strbuf *it)
510 struct strbuf outbuf = STRBUF_INIT, *dec;
511 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
515 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
517 strbuf_reset(&charset_q);
518 strbuf_reset(&piecebuf);
523 * We are about to process an encoded-word
524 * that begins at ep, but there is something
525 * before the encoded word.
528 for (scan = in; scan < ep; scan++)
532 if (scan != ep || in == it->buf) {
534 * We should not lose that "something",
535 * unless we have just processed an
536 * encoded-word, and there is only LWS
537 * before the one we are about to process.
539 strbuf_add(&outbuf, in, ep - in);
543 * ep : "=?iso-2022-jp?B?GyR...?= foo"
544 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
548 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
549 goto decode_header_bq_out;
551 if (cp + 3 - it->buf > it->len)
552 goto decode_header_bq_out;
553 strbuf_add(&charset_q, ep, cp - ep);
556 if (!encoding || cp[2] != '?')
557 goto decode_header_bq_out;
558 ep = strstr(cp + 3, "?=");
560 goto decode_header_bq_out;
561 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
562 switch (tolower(encoding)) {
564 goto decode_header_bq_out;
566 dec = decode_b_segment(&piecebuf);
569 dec = decode_q_segment(&piecebuf, 1);
572 if (metainfo_charset)
573 convert_to_utf8(dec, charset_q.buf);
575 strbuf_addbuf(&outbuf, dec);
580 strbuf_addstr(&outbuf, in);
582 strbuf_addbuf(it, &outbuf);
583 decode_header_bq_out:
584 strbuf_release(&outbuf);
585 strbuf_release(&charset_q);
586 strbuf_release(&piecebuf);
590 static void decode_header(struct strbuf *it)
592 if (decode_header_bq(it))
594 /* otherwise "it" is a straight copy of the input.
595 * This can be binary guck but there is no charset specified.
597 if (metainfo_charset)
598 convert_to_utf8(it, "");
601 static void decode_transfer_encoding(struct strbuf *line)
605 switch (transfer_encoding) {
607 ret = decode_q_segment(line, 0);
610 ret = decode_b_segment(line);
617 strbuf_addbuf(line, ret);
622 static void handle_filter(struct strbuf *line);
624 static int find_boundary(void)
626 while (!strbuf_getline(&line, fin, '\n')) {
627 if (*content_top && is_multipart_boundary(&line))
633 static int handle_boundary(void)
635 struct strbuf newline = STRBUF_INIT;
637 strbuf_addch(&newline, '\n');
639 if (line.len >= (*content_top)->len + 2 &&
640 !memcmp(line.buf + (*content_top)->len, "--", 2)) {
641 /* we hit an end boundary */
642 /* pop the current boundary off the stack */
643 strbuf_release(*content_top);
647 /* technically won't happen as is_multipart_boundary()
648 will fail first. But just in case..
650 if (--content_top < content) {
651 fprintf(stderr, "Detected mismatched boundaries, "
655 handle_filter(&newline);
656 strbuf_release(&newline);
658 /* skip to the next boundary */
659 if (!find_boundary())
664 /* set some defaults */
665 transfer_encoding = TE_DONTCARE;
666 strbuf_reset(&charset);
667 message_type = TYPE_TEXT;
669 /* slurp in this section's info */
670 while (read_one_header_line(&line, fin))
671 check_header(&line, p_hdr_data, 0);
673 strbuf_release(&newline);
675 if (strbuf_getline(&line, fin, '\n'))
677 strbuf_addch(&line, '\n');
681 static inline int patchbreak(const struct strbuf *line)
685 /* Beginning of a "diff -" header? */
686 if (!prefixcmp(line->buf, "diff -"))
689 /* CVS "Index: " line? */
690 if (!prefixcmp(line->buf, "Index: "))
694 * "--- <filename>" starts patches without headers
695 * "---<sp>*" is a manual separator
700 if (!prefixcmp(line->buf, "---")) {
701 /* space followed by a filename? */
702 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
704 /* Just whitespace? */
705 for (i = 3; i < line->len; i++) {
706 unsigned char c = line->buf[i];
717 static int is_scissors_line(const struct strbuf *line)
719 size_t i, len = line->len;
720 int scissors = 0, gap = 0;
721 int first_nonblank = -1;
722 int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
723 const char *buf = line->buf;
725 for (i = 0; i < len; i++) {
726 if (isspace(buf[i])) {
727 if (in_perforation) {
734 if (first_nonblank < 0)
742 (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2))) {
753 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
754 * Even though there can be arbitrary cruft on the same line
755 * (e.g. "cut here"), in order to avoid misidentification, the
756 * perforation must occupy more than a third of the visible
757 * width of the line, and dashes and scissors must occupy more
758 * than half of the perforation.
761 visible = last_nonblank - first_nonblank + 1;
762 return (scissors && 8 <= visible &&
763 visible < perforation * 3 &&
764 gap * 2 < perforation);
767 static int handle_commit_msg(struct strbuf *line)
769 static int still_looking = 1;
780 if (use_inbody_headers && still_looking) {
781 still_looking = check_header(line, s_hdr_data, 0);
785 /* Only trim the first (blank) line of the commit message
786 * when ignoring in-body headers.
790 /* normalize the log message to UTF-8. */
791 if (metainfo_charset)
792 convert_to_utf8(line, charset.buf);
794 if (use_scissors && is_scissors_line(line)) {
796 if (fseek(cmitmsg, 0L, SEEK_SET))
797 die_errno("Could not rewind output message file");
798 if (ftruncate(fileno(cmitmsg), 0))
799 die_errno("Could not truncate output message file at scissors");
803 * We may have already read "secondary headers"; purge
804 * them to give ourselves a clean restart.
806 for (i = 0; header[i]; i++) {
808 strbuf_release(s_hdr_data[i]);
809 s_hdr_data[i] = NULL;
814 if (patchbreak(line)) {
820 fputs(line->buf, cmitmsg);
824 static void handle_patch(const struct strbuf *line)
826 fwrite(line->buf, 1, line->len, patchfile);
830 static void handle_filter(struct strbuf *line)
832 static int filter = 0;
834 /* filter tells us which part we left off on */
837 if (!handle_commit_msg(line))
846 static void handle_body(void)
848 struct strbuf prev = STRBUF_INIT;
850 /* Skip up to the first boundary */
852 if (!find_boundary())
853 goto handle_body_out;
857 /* process any boundary lines */
858 if (*content_top && is_multipart_boundary(&line)) {
859 /* flush any leftover */
861 handle_filter(&prev);
864 if (!handle_boundary())
865 goto handle_body_out;
868 /* Unwrap transfer encoding */
869 decode_transfer_encoding(&line);
871 switch (transfer_encoding) {
875 struct strbuf **lines, **it, *sb;
877 /* Prepend any previous partial lines */
878 strbuf_insert(&line, 0, prev.buf, prev.len);
881 /* binary data most likely doesn't have newlines */
882 if (message_type != TYPE_TEXT) {
883 handle_filter(&line);
887 * This is a decoded line that may contain
888 * multiple new lines. Pass only one chunk
889 * at a time to handle_filter()
891 lines = strbuf_split(&line, '\n');
892 for (it = lines; (sb = *it); it++) {
893 if (*(it + 1) == NULL) /* The last line */
894 if (sb->buf[sb->len - 1] != '\n') {
895 /* Partial line, save it for later. */
896 strbuf_addbuf(&prev, sb);
902 * The partial chunk is saved in "prev" and will be
903 * appended by the next iteration of read_line_with_nul().
905 strbuf_list_free(lines);
909 handle_filter(&line);
912 } while (!strbuf_getwholeline(&line, fin, '\n'));
915 strbuf_release(&prev);
918 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
920 const char *sp = data->buf;
922 char *ep = strchr(sp, '\n');
928 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
935 static void handle_info(void)
940 for (i = 0; header[i]; i++) {
941 /* only print inbody headers if we output a patch file */
942 if (patch_lines && s_hdr_data[i])
944 else if (p_hdr_data[i])
949 if (!memcmp(header[i], "Subject", 7)) {
951 cleanup_subject(hdr);
954 output_header_lines(fout, "Subject", hdr);
955 } else if (!memcmp(header[i], "From", 4)) {
958 fprintf(fout, "Author: %s\n", name.buf);
959 fprintf(fout, "Email: %s\n", email.buf);
962 fprintf(fout, "%s: %s\n", header[i], hdr->buf);
968 static int mailinfo(FILE *in, FILE *out, const char *msg, const char *patch)
974 cmitmsg = fopen(msg, "w");
979 patchfile = fopen(patch, "w");
986 p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
987 s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
991 } while (isspace(peek));
994 /* process the email header */
995 while (read_one_header_line(&line, fin))
996 check_header(&line, p_hdr_data, 1);
1004 static int git_mailinfo_config(const char *var, const char *value, void *unused)
1006 if (prefixcmp(var, "mailinfo."))
1007 return git_default_config(var, value, unused);
1008 if (!strcmp(var, "mailinfo.scissors")) {
1009 use_scissors = git_config_bool(var, value);
1012 /* perhaps others here */
1016 static const char mailinfo_usage[] =
1017 "git mailinfo [-k] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] msg patch < mail >info";
1019 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1021 const char *def_charset;
1023 /* NEEDSWORK: might want to do the optional .git/ directory
1026 git_config(git_mailinfo_config, NULL);
1028 def_charset = (git_commit_encoding ? git_commit_encoding : "UTF-8");
1029 metainfo_charset = def_charset;
1031 while (1 < argc && argv[1][0] == '-') {
1032 if (!strcmp(argv[1], "-k"))
1034 else if (!strcmp(argv[1], "-u"))
1035 metainfo_charset = def_charset;
1036 else if (!strcmp(argv[1], "-n"))
1037 metainfo_charset = NULL;
1038 else if (!prefixcmp(argv[1], "--encoding="))
1039 metainfo_charset = argv[1] + 11;
1040 else if (!strcmp(argv[1], "--scissors"))
1042 else if (!strcmp(argv[1], "--no-scissors"))
1044 else if (!strcmp(argv[1], "--no-inbody-headers"))
1045 use_inbody_headers = 0;
1047 usage(mailinfo_usage);
1052 usage(mailinfo_usage);
1054 return !!mailinfo(stdin, stdout, argv[1], argv[2]);