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;
29 #define MAX_HDR_PARSED 10
30 #define MAX_BOUNDARIES 5
32 static void cleanup_space(struct strbuf *sb);
35 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
37 struct strbuf *src = name;
38 if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
39 strchr(name->buf, '<') || strchr(name->buf, '>'))
44 strbuf_addbuf(out, src);
47 static void parse_bogus_from(const struct strbuf *line)
49 /* John Doe <johndoe> */
52 /* This is fallback, so do not bother if we already have an
58 bra = strchr(line->buf, '<');
61 ket = strchr(bra, '>');
66 strbuf_add(&email, bra + 1, ket - bra - 1);
69 strbuf_add(&name, line->buf, bra - line->buf);
71 get_sane_name(&name, &name, &email);
74 static void handle_from(const struct strbuf *from)
80 strbuf_init(&f, from->len);
81 strbuf_addbuf(&f, from);
83 at = strchr(f.buf, '@');
85 parse_bogus_from(from);
90 * If we already have one email, don't take any confusing lines
92 if (email.len && strchr(at + 1, '@')) {
97 /* Pick up the string around '@', possibly delimited with <>
98 * pair; that is the email part.
110 el = strcspn(at, " \n\t\r\v\f>");
111 strbuf_reset(&email);
112 strbuf_add(&email, at, el);
113 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
115 /* The remainder is name. It could be
117 * - "John Doe <john.doe@xz>" (a), or
118 * - "john.doe@xz (John Doe)" (b), or
119 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
121 * but we have removed the email part, so
123 * - remove extra spaces which could stay after email (case 'c'), and
124 * - trim from both ends, possibly removing the () pair at the end
125 * (cases 'a' and 'b').
129 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
130 strbuf_remove(&f, 0, 1);
131 strbuf_setlen(&f, f.len - 1);
134 get_sane_name(&name, &f, &email);
138 static void handle_header(struct strbuf **out, const struct strbuf *line)
141 *out = xmalloc(sizeof(struct strbuf));
142 strbuf_init(*out, line->len);
146 strbuf_addbuf(*out, line);
149 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
150 * to have enough heuristics to grok MIME encoded patches often found
151 * on our mailing lists. For example, we do not even treat header lines
152 * case insensitively.
155 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
157 const char *ends, *ap = strcasestr(line, name);
161 strbuf_setlen(attr, 0);
171 sz = strcspn(ap, ends);
172 strbuf_add(attr, ap, sz);
176 static struct strbuf *content[MAX_BOUNDARIES];
178 static struct strbuf **content_top = content;
180 static void handle_content_type(struct strbuf *line)
182 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
183 strbuf_init(boundary, line->len);
185 if (!strcasestr(line->buf, "text/"))
186 message_type = TYPE_OTHER;
187 if (slurp_attr(line->buf, "boundary=", boundary)) {
188 strbuf_insert(boundary, 0, "--", 2);
189 if (++content_top > &content[MAX_BOUNDARIES]) {
190 fprintf(stderr, "Too many boundaries to handle\n");
193 *content_top = boundary;
196 slurp_attr(line->buf, "charset=", &charset);
199 strbuf_release(boundary);
204 static void handle_content_transfer_encoding(const struct strbuf *line)
206 if (strcasestr(line->buf, "base64"))
207 transfer_encoding = TE_BASE64;
208 else if (strcasestr(line->buf, "quoted-printable"))
209 transfer_encoding = TE_QP;
211 transfer_encoding = TE_DONTCARE;
214 static int is_multipart_boundary(const struct strbuf *line)
216 return (((*content_top)->len <= line->len) &&
217 !memcmp(line->buf, (*content_top)->buf, (*content_top)->len));
220 static void cleanup_subject(struct strbuf *subject)
224 int brackets_removed = 0;
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 /* remove only one set of square brackets */
241 if (brackets_removed)
244 if ((pos = strchr(subject->buf, ']'))) {
245 remove = pos - subject->buf;
246 if (remove <= (subject->len - remove) * 2) {
247 strbuf_remove(subject, 0, remove + 1);
248 brackets_removed = 1;
252 strbuf_remove(subject, 0, 1);
255 strbuf_trim(subject);
260 static void cleanup_space(struct strbuf *sb)
263 for (pos = 0; pos < sb->len; pos++) {
264 if (isspace(sb->buf[pos])) {
266 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
267 strbuf_remove(sb, pos + 1, cnt);
272 static void decode_header(struct strbuf *line);
273 static const char *header[MAX_HDR_PARSED] = {
274 "From","Subject","Date",
277 static inline int cmp_header(const struct strbuf *line, const char *hdr)
279 int len = strlen(hdr);
280 return !strncasecmp(line->buf, hdr, len) && line->len > len &&
281 line->buf[len] == ':' && isspace(line->buf[len + 1]);
284 static int check_header(const struct strbuf *line,
285 struct strbuf *hdr_data[], int overwrite)
288 struct strbuf sb = STRBUF_INIT;
289 /* search for the interesting parts */
290 for (i = 0; header[i]; i++) {
291 int len = strlen(header[i]);
292 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
293 /* Unwrap inline B and Q encoding, and optionally
294 * normalize the meta information to utf8.
296 strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
298 handle_header(&hdr_data[i], &sb);
300 goto check_header_out;
305 if (cmp_header(line, "Content-Type")) {
306 len = strlen("Content-Type: ");
307 strbuf_add(&sb, line->buf + len, line->len - len);
309 strbuf_insert(&sb, 0, "Content-Type: ", len);
310 handle_content_type(&sb);
312 goto check_header_out;
314 if (cmp_header(line, "Content-Transfer-Encoding")) {
315 len = strlen("Content-Transfer-Encoding: ");
316 strbuf_add(&sb, line->buf + len, line->len - len);
318 handle_content_transfer_encoding(&sb);
320 goto check_header_out;
323 /* for inbody stuff */
324 if (!prefixcmp(line->buf, ">From") && isspace(line->buf[5])) {
325 ret = 1; /* Should this return 0? */
326 goto check_header_out;
328 if (!prefixcmp(line->buf, "[PATCH]") && isspace(line->buf[7])) {
329 for (i = 0; header[i]; i++) {
330 if (!memcmp("Subject", header[i], 7)) {
331 handle_header(&hdr_data[i], line);
333 goto check_header_out;
343 static int is_rfc2822_header(const struct strbuf *line)
346 * The section that defines the loosest possible
347 * field name is "3.6.8 Optional fields".
349 * optional-field = field-name ":" unstructured CRLF
350 * field-name = 1*ftext
351 * ftext = %d33-57 / %59-126
354 char *cp = line->buf;
356 /* Count mbox From headers as headers */
357 if (!prefixcmp(cp, "From ") || !prefixcmp(cp, ">From "))
360 while ((ch = *cp++)) {
363 if ((33 <= ch && ch <= 57) ||
364 (59 <= ch && ch <= 126))
371 static int read_one_header_line(struct strbuf *line, FILE *in)
373 /* Get the first part of the line. */
374 if (strbuf_getline(line, in, '\n'))
378 * Is it an empty line or not a valid rfc2822 header?
379 * If so, stop here, and return false ("not a header")
382 if (!line->len || !is_rfc2822_header(line)) {
383 /* Re-add the newline */
384 strbuf_addch(line, '\n');
389 * Now we need to eat all the continuation lines..
390 * Yuck, 2822 header "folding"
394 struct strbuf continuation = STRBUF_INIT;
396 peek = fgetc(in); ungetc(peek, in);
397 if (peek != ' ' && peek != '\t')
399 if (strbuf_getline(&continuation, in, '\n'))
401 continuation.buf[0] = '\n';
402 strbuf_rtrim(&continuation);
403 strbuf_addbuf(line, &continuation);
409 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
411 const char *in = q_seg->buf;
413 struct strbuf *out = xmalloc(sizeof(struct strbuf));
414 strbuf_init(out, q_seg->len);
416 while ((c = *in++) != 0) {
420 break; /* drop trailing newline */
421 strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
424 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
426 strbuf_addch(out, c);
431 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
433 /* Decode in..ep, possibly in-place to ot */
434 int c, pos = 0, acc = 0;
435 const char *in = b_seg->buf;
436 struct strbuf *out = xmalloc(sizeof(struct strbuf));
437 strbuf_init(out, b_seg->len);
439 while ((c = *in++) != 0) {
444 else if ('A' <= c && c <= 'Z')
446 else if ('a' <= c && c <= 'z')
448 else if ('0' <= c && c <= '9')
451 continue; /* garbage */
457 strbuf_addch(out, (acc | (c >> 4)));
461 strbuf_addch(out, (acc | (c >> 2)));
465 strbuf_addch(out, (acc | c));
474 * When there is no known charset, guess.
476 * Right now we assume that if the target is UTF-8 (the default),
477 * and it already looks like UTF-8 (which includes US-ASCII as its
478 * subset, of course) then that is what it is and there is nothing
481 * Otherwise, we default to assuming it is Latin1 for historical
484 static const char *guess_charset(const struct strbuf *line, const char *target_charset)
486 if (is_encoding_utf8(target_charset)) {
487 if (is_utf8(line->buf))
493 static void convert_to_utf8(struct strbuf *line, const char *charset)
497 if (!charset || !*charset) {
498 charset = guess_charset(line, metainfo_charset);
503 if (!strcasecmp(metainfo_charset, charset))
505 out = reencode_string(line->buf, metainfo_charset, charset);
507 die("cannot convert from %s to %s",
508 charset, metainfo_charset);
509 strbuf_attach(line, out, strlen(out), strlen(out));
512 static int decode_header_bq(struct strbuf *it)
515 struct strbuf outbuf = STRBUF_INIT, *dec;
516 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
520 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
522 strbuf_reset(&charset_q);
523 strbuf_reset(&piecebuf);
528 * We are about to process an encoded-word
529 * that begins at ep, but there is something
530 * before the encoded word.
533 for (scan = in; scan < ep; scan++)
537 if (scan != ep || in == it->buf) {
539 * We should not lose that "something",
540 * unless we have just processed an
541 * encoded-word, and there is only LWS
542 * before the one we are about to process.
544 strbuf_add(&outbuf, in, ep - in);
548 * ep : "=?iso-2022-jp?B?GyR...?= foo"
549 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
553 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
554 goto decode_header_bq_out;
556 if (cp + 3 - it->buf > it->len)
557 goto decode_header_bq_out;
558 strbuf_add(&charset_q, ep, cp - ep);
561 if (!encoding || cp[2] != '?')
562 goto decode_header_bq_out;
563 ep = strstr(cp + 3, "?=");
565 goto decode_header_bq_out;
566 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
567 switch (tolower(encoding)) {
569 goto decode_header_bq_out;
571 dec = decode_b_segment(&piecebuf);
574 dec = decode_q_segment(&piecebuf, 1);
577 if (metainfo_charset)
578 convert_to_utf8(dec, charset_q.buf);
580 strbuf_addbuf(&outbuf, dec);
585 strbuf_addstr(&outbuf, in);
587 strbuf_addbuf(it, &outbuf);
588 decode_header_bq_out:
589 strbuf_release(&outbuf);
590 strbuf_release(&charset_q);
591 strbuf_release(&piecebuf);
595 static void decode_header(struct strbuf *it)
597 if (decode_header_bq(it))
599 /* otherwise "it" is a straight copy of the input.
600 * This can be binary guck but there is no charset specified.
602 if (metainfo_charset)
603 convert_to_utf8(it, "");
606 static void decode_transfer_encoding(struct strbuf *line)
610 switch (transfer_encoding) {
612 ret = decode_q_segment(line, 0);
615 ret = decode_b_segment(line);
622 strbuf_addbuf(line, ret);
627 static void handle_filter(struct strbuf *line);
629 static int find_boundary(void)
631 while (!strbuf_getline(&line, fin, '\n')) {
632 if (*content_top && is_multipart_boundary(&line))
638 static int handle_boundary(void)
640 struct strbuf newline = STRBUF_INIT;
642 strbuf_addch(&newline, '\n');
644 if (line.len >= (*content_top)->len + 2 &&
645 !memcmp(line.buf + (*content_top)->len, "--", 2)) {
646 /* we hit an end boundary */
647 /* pop the current boundary off the stack */
648 strbuf_release(*content_top);
652 /* technically won't happen as is_multipart_boundary()
653 will fail first. But just in case..
655 if (--content_top < content) {
656 fprintf(stderr, "Detected mismatched boundaries, "
660 handle_filter(&newline);
661 strbuf_release(&newline);
663 /* skip to the next boundary */
664 if (!find_boundary())
669 /* set some defaults */
670 transfer_encoding = TE_DONTCARE;
671 strbuf_reset(&charset);
672 message_type = TYPE_TEXT;
674 /* slurp in this section's info */
675 while (read_one_header_line(&line, fin))
676 check_header(&line, p_hdr_data, 0);
678 strbuf_release(&newline);
680 if (strbuf_getline(&line, fin, '\n'))
682 strbuf_addch(&line, '\n');
686 static inline int patchbreak(const struct strbuf *line)
690 /* Beginning of a "diff -" header? */
691 if (!prefixcmp(line->buf, "diff -"))
694 /* CVS "Index: " line? */
695 if (!prefixcmp(line->buf, "Index: "))
699 * "--- <filename>" starts patches without headers
700 * "---<sp>*" is a manual separator
705 if (!prefixcmp(line->buf, "---")) {
706 /* space followed by a filename? */
707 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
709 /* Just whitespace? */
710 for (i = 3; i < line->len; i++) {
711 unsigned char c = line->buf[i];
722 static int handle_commit_msg(struct strbuf *line)
724 static int still_looking = 1;
733 if ((still_looking = check_header(line, s_hdr_data, 0)) != 0)
737 /* normalize the log message to UTF-8. */
738 if (metainfo_charset)
739 convert_to_utf8(line, charset.buf);
741 if (patchbreak(line)) {
747 fputs(line->buf, cmitmsg);
751 static void handle_patch(const struct strbuf *line)
753 fwrite(line->buf, 1, line->len, patchfile);
757 static void handle_filter(struct strbuf *line)
759 static int filter = 0;
761 /* filter tells us which part we left off on */
764 if (!handle_commit_msg(line))
773 static void handle_body(void)
776 struct strbuf prev = STRBUF_INIT;
778 /* Skip up to the first boundary */
780 if (!find_boundary())
781 goto handle_body_out;
785 strbuf_setlen(&line, line.len + len);
787 /* process any boundary lines */
788 if (*content_top && is_multipart_boundary(&line)) {
789 /* flush any leftover */
791 handle_filter(&prev);
794 if (!handle_boundary())
795 goto handle_body_out;
798 /* Unwrap transfer encoding */
799 decode_transfer_encoding(&line);
801 switch (transfer_encoding) {
805 struct strbuf **lines, **it, *sb;
807 /* Prepend any previous partial lines */
808 strbuf_insert(&line, 0, prev.buf, prev.len);
811 /* binary data most likely doesn't have newlines */
812 if (message_type != TYPE_TEXT) {
813 handle_filter(&line);
817 * This is a decoded line that may contain
818 * multiple new lines. Pass only one chunk
819 * at a time to handle_filter()
821 lines = strbuf_split(&line, '\n');
822 for (it = lines; (sb = *it); it++) {
823 if (*(it + 1) == NULL) /* The last line */
824 if (sb->buf[sb->len - 1] != '\n') {
825 /* Partial line, save it for later. */
826 strbuf_addbuf(&prev, sb);
832 * The partial chunk is saved in "prev" and will be
833 * appended by the next iteration of read_line_with_nul().
835 strbuf_list_free(lines);
839 handle_filter(&line);
843 if (strbuf_avail(&line) < 100)
844 strbuf_grow(&line, 100);
845 } while ((len = read_line_with_nul(line.buf, strbuf_avail(&line), fin)));
848 strbuf_release(&prev);
851 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
853 const char *sp = data->buf;
855 char *ep = strchr(sp, '\n');
861 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
868 static void handle_info(void)
873 for (i = 0; header[i]; i++) {
874 /* only print inbody headers if we output a patch file */
875 if (patch_lines && s_hdr_data[i])
877 else if (p_hdr_data[i])
882 if (!memcmp(header[i], "Subject", 7)) {
884 cleanup_subject(hdr);
887 output_header_lines(fout, "Subject", hdr);
888 } else if (!memcmp(header[i], "From", 4)) {
891 fprintf(fout, "Author: %s\n", name.buf);
892 fprintf(fout, "Email: %s\n", email.buf);
895 fprintf(fout, "%s: %s\n", header[i], hdr->buf);
901 static int mailinfo(FILE *in, FILE *out, int ks, const char *encoding,
902 const char *msg, const char *patch)
906 metainfo_charset = encoding;
910 cmitmsg = fopen(msg, "w");
915 patchfile = fopen(patch, "w");
922 p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
923 s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
927 } while (isspace(peek));
930 /* process the email header */
931 while (read_one_header_line(&line, fin))
932 check_header(&line, p_hdr_data, 1);
940 static const char mailinfo_usage[] =
941 "git mailinfo [-k] [-u | --encoding=<encoding> | -n] msg patch <mail >info";
943 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
945 const char *def_charset;
947 /* NEEDSWORK: might want to do the optional .git/ directory
950 git_config(git_default_config, NULL);
952 def_charset = (git_commit_encoding ? git_commit_encoding : "UTF-8");
953 metainfo_charset = def_charset;
955 while (1 < argc && argv[1][0] == '-') {
956 if (!strcmp(argv[1], "-k"))
958 else if (!strcmp(argv[1], "-u"))
959 metainfo_charset = def_charset;
960 else if (!strcmp(argv[1], "-n"))
961 metainfo_charset = NULL;
962 else if (!prefixcmp(argv[1], "--encoding="))
963 metainfo_charset = argv[1] + 11;
965 usage(mailinfo_usage);
970 usage(mailinfo_usage);
972 return !!mailinfo(stdin, stdout, keep_subject, metainfo_charset, argv[1], argv[2]);