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
23 static struct strbuf charset
= STRBUF_INIT
;
24 static int patch_lines
;
25 static struct strbuf
**p_hdr_data
, **s_hdr_data
;
26 static int use_scissors
;
27 static int use_inbody_headers
= 1;
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
);
160 strbuf_setlen(attr
, 0);
170 sz
= strcspn(ap
, ends
);
171 strbuf_add(attr
, ap
, sz
);
175 static struct strbuf
*content
[MAX_BOUNDARIES
];
177 static struct strbuf
**content_top
= content
;
179 static void handle_content_type(struct strbuf
*line
)
181 struct strbuf
*boundary
= xmalloc(sizeof(struct strbuf
));
182 strbuf_init(boundary
, line
->len
);
184 if (slurp_attr(line
->buf
, "boundary=", boundary
)) {
185 strbuf_insert(boundary
, 0, "--", 2);
186 if (++content_top
> &content
[MAX_BOUNDARIES
]) {
187 fprintf(stderr
, "Too many boundaries to handle\n");
190 *content_top
= boundary
;
193 slurp_attr(line
->buf
, "charset=", &charset
);
196 strbuf_release(boundary
);
201 static void handle_content_transfer_encoding(const struct strbuf
*line
)
203 if (strcasestr(line
->buf
, "base64"))
204 transfer_encoding
= TE_BASE64
;
205 else if (strcasestr(line
->buf
, "quoted-printable"))
206 transfer_encoding
= TE_QP
;
208 transfer_encoding
= TE_DONTCARE
;
211 static int is_multipart_boundary(const struct strbuf
*line
)
213 return (((*content_top
)->len
<= line
->len
) &&
214 !memcmp(line
->buf
, (*content_top
)->buf
, (*content_top
)->len
));
217 static void cleanup_subject(struct strbuf
*subject
)
221 while (at
< subject
->len
) {
225 switch (subject
->buf
[at
]) {
227 if (subject
->len
<= at
+ 3)
229 if ((subject
->buf
[at
+ 1] == 'e' ||
230 subject
->buf
[at
+ 1] == 'E') &&
231 subject
->buf
[at
+ 2] == ':') {
232 strbuf_remove(subject
, at
, 3);
237 case ' ': case '\t': case ':':
238 strbuf_remove(subject
, at
, 1);
241 pos
= strchr(subject
->buf
+ at
, ']');
244 remove
= pos
- subject
->buf
+ at
+ 1;
245 if (!keep_non_patch_brackets_in_subject
||
247 memmem(subject
->buf
+ at
, remove
, "PATCH", 5)))
248 strbuf_remove(subject
, at
, remove
);
252 * If the input had a space after the ], keep
253 * it. We don't bother with finding the end of
254 * the space, since we later normalize it
257 if (isspace(subject
->buf
[at
]))
264 strbuf_trim(subject
);
267 static void cleanup_space(struct strbuf
*sb
)
270 for (pos
= 0; pos
< sb
->len
; pos
++) {
271 if (isspace(sb
->buf
[pos
])) {
273 for (cnt
= 0; isspace(sb
->buf
[pos
+ cnt
+ 1]); cnt
++);
274 strbuf_remove(sb
, pos
+ 1, cnt
);
279 static void decode_header(struct strbuf
*line
);
280 static const char *header
[MAX_HDR_PARSED
] = {
281 "From","Subject","Date",
284 static inline int cmp_header(const struct strbuf
*line
, const char *hdr
)
286 int len
= strlen(hdr
);
287 return !strncasecmp(line
->buf
, hdr
, len
) && line
->len
> len
&&
288 line
->buf
[len
] == ':' && isspace(line
->buf
[len
+ 1]);
291 static int check_header(const struct strbuf
*line
,
292 struct strbuf
*hdr_data
[], int overwrite
)
295 struct strbuf sb
= STRBUF_INIT
;
296 /* search for the interesting parts */
297 for (i
= 0; header
[i
]; i
++) {
298 int len
= strlen(header
[i
]);
299 if ((!hdr_data
[i
] || overwrite
) && cmp_header(line
, header
[i
])) {
300 /* Unwrap inline B and Q encoding, and optionally
301 * normalize the meta information to utf8.
303 strbuf_add(&sb
, line
->buf
+ len
+ 2, line
->len
- len
- 2);
305 handle_header(&hdr_data
[i
], &sb
);
307 goto check_header_out
;
312 if (cmp_header(line
, "Content-Type")) {
313 len
= strlen("Content-Type: ");
314 strbuf_add(&sb
, line
->buf
+ len
, line
->len
- len
);
316 strbuf_insert(&sb
, 0, "Content-Type: ", len
);
317 handle_content_type(&sb
);
319 goto check_header_out
;
321 if (cmp_header(line
, "Content-Transfer-Encoding")) {
322 len
= strlen("Content-Transfer-Encoding: ");
323 strbuf_add(&sb
, line
->buf
+ len
, line
->len
- len
);
325 handle_content_transfer_encoding(&sb
);
327 goto check_header_out
;
330 /* for inbody stuff */
331 if (starts_with(line
->buf
, ">From") && isspace(line
->buf
[5])) {
332 ret
= 1; /* Should this return 0? */
333 goto check_header_out
;
335 if (starts_with(line
->buf
, "[PATCH]") && isspace(line
->buf
[7])) {
336 for (i
= 0; header
[i
]; i
++) {
337 if (!memcmp("Subject", header
[i
], 7)) {
338 handle_header(&hdr_data
[i
], line
);
340 goto check_header_out
;
350 static int is_rfc2822_header(const struct strbuf
*line
)
353 * The section that defines the loosest possible
354 * field name is "3.6.8 Optional fields".
356 * optional-field = field-name ":" unstructured CRLF
357 * field-name = 1*ftext
358 * ftext = %d33-57 / %59-126
361 char *cp
= line
->buf
;
363 /* Count mbox From headers as headers */
364 if (starts_with(cp
, "From ") || starts_with(cp
, ">From "))
367 while ((ch
= *cp
++)) {
370 if ((33 <= ch
&& ch
<= 57) ||
371 (59 <= ch
&& ch
<= 126))
378 static int read_one_header_line(struct strbuf
*line
, FILE *in
)
380 /* Get the first part of the line. */
381 if (strbuf_getline(line
, in
, '\n'))
385 * Is it an empty line or not a valid rfc2822 header?
386 * If so, stop here, and return false ("not a header")
389 if (!line
->len
|| !is_rfc2822_header(line
)) {
390 /* Re-add the newline */
391 strbuf_addch(line
, '\n');
396 * Now we need to eat all the continuation lines..
397 * Yuck, 2822 header "folding"
401 struct strbuf continuation
= STRBUF_INIT
;
403 peek
= fgetc(in
); ungetc(peek
, in
);
404 if (peek
!= ' ' && peek
!= '\t')
406 if (strbuf_getline(&continuation
, in
, '\n'))
408 continuation
.buf
[0] = ' ';
409 strbuf_rtrim(&continuation
);
410 strbuf_addbuf(line
, &continuation
);
416 static struct strbuf
*decode_q_segment(const struct strbuf
*q_seg
, int rfc2047
)
418 const char *in
= q_seg
->buf
;
420 struct strbuf
*out
= xmalloc(sizeof(struct strbuf
));
421 strbuf_init(out
, q_seg
->len
);
423 while ((c
= *in
++) != 0) {
427 break; /* drop trailing newline */
428 strbuf_addch(out
, (hexval(d
) << 4) | hexval(*in
++));
431 if (rfc2047
&& c
== '_') /* rfc2047 4.2 (2) */
433 strbuf_addch(out
, c
);
438 static struct strbuf
*decode_b_segment(const struct strbuf
*b_seg
)
440 /* Decode in..ep, possibly in-place to ot */
441 int c
, pos
= 0, acc
= 0;
442 const char *in
= b_seg
->buf
;
443 struct strbuf
*out
= xmalloc(sizeof(struct strbuf
));
444 strbuf_init(out
, b_seg
->len
);
446 while ((c
= *in
++) != 0) {
451 else if ('A' <= c
&& c
<= 'Z')
453 else if ('a' <= c
&& c
<= 'z')
455 else if ('0' <= c
&& c
<= '9')
458 continue; /* garbage */
464 strbuf_addch(out
, (acc
| (c
>> 4)));
468 strbuf_addch(out
, (acc
| (c
>> 2)));
472 strbuf_addch(out
, (acc
| c
));
480 static void convert_to_utf8(struct strbuf
*line
, const char *charset
)
484 if (!charset
|| !*charset
)
487 if (same_encoding(metainfo_charset
, charset
))
489 out
= reencode_string(line
->buf
, metainfo_charset
, charset
);
491 die("cannot convert from %s to %s",
492 charset
, metainfo_charset
);
493 strbuf_attach(line
, out
, strlen(out
), strlen(out
));
496 static int decode_header_bq(struct strbuf
*it
)
499 struct strbuf outbuf
= STRBUF_INIT
, *dec
;
500 struct strbuf charset_q
= STRBUF_INIT
, piecebuf
= STRBUF_INIT
;
504 while (in
- it
->buf
<= it
->len
&& (ep
= strstr(in
, "=?")) != NULL
) {
506 strbuf_reset(&charset_q
);
507 strbuf_reset(&piecebuf
);
512 * We are about to process an encoded-word
513 * that begins at ep, but there is something
514 * before the encoded word.
517 for (scan
= in
; scan
< ep
; scan
++)
521 if (scan
!= ep
|| in
== it
->buf
) {
523 * We should not lose that "something",
524 * unless we have just processed an
525 * encoded-word, and there is only LWS
526 * before the one we are about to process.
528 strbuf_add(&outbuf
, in
, ep
- in
);
532 * ep : "=?iso-2022-jp?B?GyR...?= foo"
533 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
537 if (ep
- it
->buf
>= it
->len
|| !(cp
= strchr(ep
, '?')))
538 goto decode_header_bq_out
;
540 if (cp
+ 3 - it
->buf
> it
->len
)
541 goto decode_header_bq_out
;
542 strbuf_add(&charset_q
, ep
, cp
- ep
);
545 if (!encoding
|| cp
[2] != '?')
546 goto decode_header_bq_out
;
547 ep
= strstr(cp
+ 3, "?=");
549 goto decode_header_bq_out
;
550 strbuf_add(&piecebuf
, cp
+ 3, ep
- cp
- 3);
551 switch (tolower(encoding
)) {
553 goto decode_header_bq_out
;
555 dec
= decode_b_segment(&piecebuf
);
558 dec
= decode_q_segment(&piecebuf
, 1);
561 if (metainfo_charset
)
562 convert_to_utf8(dec
, charset_q
.buf
);
564 strbuf_addbuf(&outbuf
, dec
);
569 strbuf_addstr(&outbuf
, in
);
571 strbuf_addbuf(it
, &outbuf
);
572 decode_header_bq_out
:
573 strbuf_release(&outbuf
);
574 strbuf_release(&charset_q
);
575 strbuf_release(&piecebuf
);
579 static void decode_header(struct strbuf
*it
)
581 if (decode_header_bq(it
))
583 /* otherwise "it" is a straight copy of the input.
584 * This can be binary guck but there is no charset specified.
586 if (metainfo_charset
)
587 convert_to_utf8(it
, "");
590 static void decode_transfer_encoding(struct strbuf
*line
)
594 switch (transfer_encoding
) {
596 ret
= decode_q_segment(line
, 0);
599 ret
= decode_b_segment(line
);
606 strbuf_addbuf(line
, ret
);
611 static void handle_filter(struct strbuf
*line
);
613 static int find_boundary(void)
615 while (!strbuf_getline(&line
, fin
, '\n')) {
616 if (*content_top
&& is_multipart_boundary(&line
))
622 static int handle_boundary(void)
624 struct strbuf newline
= STRBUF_INIT
;
626 strbuf_addch(&newline
, '\n');
628 if (line
.len
>= (*content_top
)->len
+ 2 &&
629 !memcmp(line
.buf
+ (*content_top
)->len
, "--", 2)) {
630 /* we hit an end boundary */
631 /* pop the current boundary off the stack */
632 strbuf_release(*content_top
);
636 /* technically won't happen as is_multipart_boundary()
637 will fail first. But just in case..
639 if (--content_top
< content
) {
640 fprintf(stderr
, "Detected mismatched boundaries, "
644 handle_filter(&newline
);
645 strbuf_release(&newline
);
647 /* skip to the next boundary */
648 if (!find_boundary())
653 /* set some defaults */
654 transfer_encoding
= TE_DONTCARE
;
655 strbuf_reset(&charset
);
657 /* slurp in this section's info */
658 while (read_one_header_line(&line
, fin
))
659 check_header(&line
, p_hdr_data
, 0);
661 strbuf_release(&newline
);
663 if (strbuf_getline(&line
, fin
, '\n'))
665 strbuf_addch(&line
, '\n');
669 static inline int patchbreak(const struct strbuf
*line
)
673 /* Beginning of a "diff -" header? */
674 if (starts_with(line
->buf
, "diff -"))
677 /* CVS "Index: " line? */
678 if (starts_with(line
->buf
, "Index: "))
682 * "--- <filename>" starts patches without headers
683 * "---<sp>*" is a manual separator
688 if (starts_with(line
->buf
, "---")) {
689 /* space followed by a filename? */
690 if (line
->buf
[3] == ' ' && !isspace(line
->buf
[4]))
692 /* Just whitespace? */
693 for (i
= 3; i
< line
->len
; i
++) {
694 unsigned char c
= line
->buf
[i
];
705 static int is_scissors_line(const struct strbuf
*line
)
707 size_t i
, len
= line
->len
;
708 int scissors
= 0, gap
= 0;
709 int first_nonblank
= -1;
710 int last_nonblank
= 0, visible
, perforation
= 0, in_perforation
= 0;
711 const char *buf
= line
->buf
;
713 for (i
= 0; i
< len
; i
++) {
714 if (isspace(buf
[i
])) {
715 if (in_perforation
) {
722 if (first_nonblank
< 0)
730 (!memcmp(buf
+ i
, ">8", 2) || !memcmp(buf
+ i
, "8<", 2) ||
731 !memcmp(buf
+ i
, ">%", 2) || !memcmp(buf
+ i
, "%<", 2))) {
742 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
743 * Even though there can be arbitrary cruft on the same line
744 * (e.g. "cut here"), in order to avoid misidentification, the
745 * perforation must occupy more than a third of the visible
746 * width of the line, and dashes and scissors must occupy more
747 * than half of the perforation.
750 visible
= last_nonblank
- first_nonblank
+ 1;
751 return (scissors
&& 8 <= visible
&&
752 visible
< perforation
* 3 &&
753 gap
* 2 < perforation
);
756 static int handle_commit_msg(struct strbuf
*line
)
758 static int still_looking
= 1;
764 if (!line
->len
|| (line
->len
== 1 && line
->buf
[0] == '\n'))
768 if (use_inbody_headers
&& still_looking
) {
769 still_looking
= check_header(line
, s_hdr_data
, 0);
773 /* Only trim the first (blank) line of the commit message
774 * when ignoring in-body headers.
778 /* normalize the log message to UTF-8. */
779 if (metainfo_charset
)
780 convert_to_utf8(line
, charset
.buf
);
782 if (use_scissors
&& is_scissors_line(line
)) {
784 if (fseek(cmitmsg
, 0L, SEEK_SET
))
785 die_errno("Could not rewind output message file");
786 if (ftruncate(fileno(cmitmsg
), 0))
787 die_errno("Could not truncate output message file at scissors");
791 * We may have already read "secondary headers"; purge
792 * them to give ourselves a clean restart.
794 for (i
= 0; header
[i
]; i
++) {
796 strbuf_release(s_hdr_data
[i
]);
797 s_hdr_data
[i
] = NULL
;
802 if (patchbreak(line
)) {
808 fputs(line
->buf
, cmitmsg
);
812 static void handle_patch(const struct strbuf
*line
)
814 fwrite(line
->buf
, 1, line
->len
, patchfile
);
818 static void handle_filter(struct strbuf
*line
)
820 static int filter
= 0;
822 /* filter tells us which part we left off on */
825 if (!handle_commit_msg(line
))
834 static void handle_body(void)
836 struct strbuf prev
= STRBUF_INIT
;
838 /* Skip up to the first boundary */
840 if (!find_boundary())
841 goto handle_body_out
;
845 /* process any boundary lines */
846 if (*content_top
&& is_multipart_boundary(&line
)) {
847 /* flush any leftover */
849 handle_filter(&prev
);
852 if (!handle_boundary())
853 goto handle_body_out
;
856 /* Unwrap transfer encoding */
857 decode_transfer_encoding(&line
);
859 switch (transfer_encoding
) {
863 struct strbuf
**lines
, **it
, *sb
;
865 /* Prepend any previous partial lines */
866 strbuf_insert(&line
, 0, prev
.buf
, prev
.len
);
870 * This is a decoded line that may contain
871 * multiple new lines. Pass only one chunk
872 * at a time to handle_filter()
874 lines
= strbuf_split(&line
, '\n');
875 for (it
= lines
; (sb
= *it
); it
++) {
876 if (*(it
+ 1) == NULL
) /* The last line */
877 if (sb
->buf
[sb
->len
- 1] != '\n') {
878 /* Partial line, save it for later. */
879 strbuf_addbuf(&prev
, sb
);
885 * The partial chunk is saved in "prev" and will be
886 * appended by the next iteration of read_line_with_nul().
888 strbuf_list_free(lines
);
892 handle_filter(&line
);
895 } while (!strbuf_getwholeline(&line
, fin
, '\n'));
898 strbuf_release(&prev
);
901 static void output_header_lines(FILE *fout
, const char *hdr
, const struct strbuf
*data
)
903 const char *sp
= data
->buf
;
905 char *ep
= strchr(sp
, '\n');
911 fprintf(fout
, "%s: %.*s\n", hdr
, len
, sp
);
918 static void handle_info(void)
923 for (i
= 0; header
[i
]; i
++) {
924 /* only print inbody headers if we output a patch file */
925 if (patch_lines
&& s_hdr_data
[i
])
927 else if (p_hdr_data
[i
])
932 if (!memcmp(header
[i
], "Subject", 7)) {
934 cleanup_subject(hdr
);
937 output_header_lines(fout
, "Subject", hdr
);
938 } else if (!memcmp(header
[i
], "From", 4)) {
941 fprintf(fout
, "Author: %s\n", name
.buf
);
942 fprintf(fout
, "Email: %s\n", email
.buf
);
945 fprintf(fout
, "%s: %s\n", header
[i
], hdr
->buf
);
951 static int mailinfo(FILE *in
, FILE *out
, const char *msg
, const char *patch
)
957 cmitmsg
= fopen(msg
, "w");
962 patchfile
= fopen(patch
, "w");
969 p_hdr_data
= xcalloc(MAX_HDR_PARSED
, sizeof(*p_hdr_data
));
970 s_hdr_data
= xcalloc(MAX_HDR_PARSED
, sizeof(*s_hdr_data
));
974 } while (isspace(peek
));
977 /* process the email header */
978 while (read_one_header_line(&line
, fin
))
979 check_header(&line
, p_hdr_data
, 1);
987 static int git_mailinfo_config(const char *var
, const char *value
, void *unused
)
989 if (!starts_with(var
, "mailinfo."))
990 return git_default_config(var
, value
, unused
);
991 if (!strcmp(var
, "mailinfo.scissors")) {
992 use_scissors
= git_config_bool(var
, value
);
995 /* perhaps others here */
999 static const char mailinfo_usage
[] =
1000 "git mailinfo [-k|-b] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] msg patch < mail >info";
1002 int cmd_mailinfo(int argc
, const char **argv
, const char *prefix
)
1004 const char *def_charset
;
1006 /* NEEDSWORK: might want to do the optional .git/ directory
1009 git_config(git_mailinfo_config
, NULL
);
1011 def_charset
= get_commit_output_encoding();
1012 metainfo_charset
= def_charset
;
1014 while (1 < argc
&& argv
[1][0] == '-') {
1015 if (!strcmp(argv
[1], "-k"))
1017 else if (!strcmp(argv
[1], "-b"))
1018 keep_non_patch_brackets_in_subject
= 1;
1019 else if (!strcmp(argv
[1], "-u"))
1020 metainfo_charset
= def_charset
;
1021 else if (!strcmp(argv
[1], "-n"))
1022 metainfo_charset
= NULL
;
1023 else if (starts_with(argv
[1], "--encoding="))
1024 metainfo_charset
= argv
[1] + 11;
1025 else if (!strcmp(argv
[1], "--scissors"))
1027 else if (!strcmp(argv
[1], "--no-scissors"))
1029 else if (!strcmp(argv
[1], "--no-inbody-headers"))
1030 use_inbody_headers
= 0;
1032 usage(mailinfo_usage
);
1037 usage(mailinfo_usage
);
1039 return !!mailinfo(stdin
, stdout
, argv
[1], argv
[2]);