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 get_sane_name(struct strbuf
*out
, struct strbuf
*name
, struct strbuf
*email
)
34 struct strbuf
*src
= name
;
35 if (name
->len
< 3 || 60 < name
->len
|| strchr(name
->buf
, '@') ||
36 strchr(name
->buf
, '<') || strchr(name
->buf
, '>'))
41 strbuf_addbuf(out
, src
);
44 static void parse_bogus_from(const struct strbuf
*line
)
46 /* John Doe <johndoe> */
49 /* This is fallback, so do not bother if we already have an
55 bra
= strchr(line
->buf
, '<');
58 ket
= strchr(bra
, '>');
63 strbuf_add(&email
, bra
+ 1, ket
- bra
- 1);
66 strbuf_add(&name
, line
->buf
, bra
- line
->buf
);
68 get_sane_name(&name
, &name
, &email
);
71 static void handle_from(const struct strbuf
*from
)
77 strbuf_init(&f
, from
->len
);
78 strbuf_addbuf(&f
, from
);
80 at
= strchr(f
.buf
, '@');
82 parse_bogus_from(from
);
87 * If we already have one email, don't take any confusing lines
89 if (email
.len
&& strchr(at
+ 1, '@')) {
94 /* Pick up the string around '@', possibly delimited with <>
95 * pair; that is the email part.
107 el
= strcspn(at
, " \n\t\r\v\f>");
108 strbuf_reset(&email
);
109 strbuf_add(&email
, at
, el
);
110 strbuf_remove(&f
, at
- f
.buf
, el
+ 1);
112 /* The remainder is name. It could be "John Doe <john.doe@xz>"
113 * or "john.doe@xz (John Doe)", but we have removed the
114 * email part, so trim from both ends, possibly removing
115 * the () pair at the end.
119 strbuf_remove(&name
, 0, 1);
120 if (f
.len
&& f
.buf
[f
.len
- 1] == ')')
121 strbuf_setlen(&f
, f
.len
- 1);
123 get_sane_name(&name
, &f
, &email
);
127 static void handle_header(struct strbuf
**out
, const struct strbuf
*line
)
130 *out
= xmalloc(sizeof(struct strbuf
));
131 strbuf_init(*out
, line
->len
);
135 strbuf_addbuf(*out
, line
);
138 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
139 * to have enough heuristics to grok MIME encoded patches often found
140 * on our mailing lists. For example, we do not even treat header lines
141 * case insensitively.
144 static int slurp_attr(const char *line
, const char *name
, struct strbuf
*attr
)
146 const char *ends
, *ap
= strcasestr(line
, name
);
150 strbuf_setlen(attr
, 0);
160 sz
= strcspn(ap
, ends
);
161 strbuf_add(attr
, ap
, sz
);
165 static struct strbuf
*content
[MAX_BOUNDARIES
];
167 static struct strbuf
**content_top
= content
;
169 static void handle_content_type(struct strbuf
*line
)
171 struct strbuf
*boundary
= xmalloc(sizeof(struct strbuf
));
172 strbuf_init(boundary
, line
->len
);
174 if (!strcasestr(line
->buf
, "text/"))
175 message_type
= TYPE_OTHER
;
176 if (slurp_attr(line
->buf
, "boundary=", boundary
)) {
177 strbuf_insert(boundary
, 0, "--", 2);
178 if (content_top
++ >= &content
[MAX_BOUNDARIES
]) {
179 fprintf(stderr
, "Too many boundaries to handle\n");
182 *content_top
= boundary
;
185 if (slurp_attr(line
->buf
, "charset=", &charset
))
186 strbuf_tolower(&charset
);
189 strbuf_release(boundary
);
194 static void handle_content_transfer_encoding(const struct strbuf
*line
)
196 if (strcasestr(line
->buf
, "base64"))
197 transfer_encoding
= TE_BASE64
;
198 else if (strcasestr(line
->buf
, "quoted-printable"))
199 transfer_encoding
= TE_QP
;
201 transfer_encoding
= TE_DONTCARE
;
204 static int is_multipart_boundary(const struct strbuf
*line
)
206 return !strbuf_cmp(line
, *content_top
);
209 static void cleanup_subject(struct strbuf
*subject
)
213 while (subject
->len
) {
214 switch (*subject
->buf
) {
216 if (subject
->len
<= 3)
218 if (!memcmp(subject
->buf
+ 1, "e:", 2)) {
219 strbuf_remove(subject
, 0, 3);
223 case ' ': case '\t': case ':':
224 strbuf_remove(subject
, 0, 1);
227 if ((pos
= strchr(subject
->buf
, ']'))) {
228 remove
= pos
- subject
->buf
;
229 if (remove
<= (subject
->len
- remove
) * 2) {
230 strbuf_remove(subject
, 0, remove
+ 1);
234 strbuf_remove(subject
, 0, 1);
237 strbuf_trim(subject
);
242 static void cleanup_space(struct strbuf
*sb
)
245 for (pos
= 0; pos
< sb
->len
; pos
++) {
246 if (isspace(sb
->buf
[pos
])) {
248 for (cnt
= 0; isspace(sb
->buf
[pos
+ cnt
+ 1]); cnt
++);
249 strbuf_remove(sb
, pos
+ 1, cnt
);
254 static void decode_header(struct strbuf
*line
);
255 static const char *header
[MAX_HDR_PARSED
] = {
256 "From","Subject","Date",
259 static inline int cmp_header(const struct strbuf
*line
, const char *hdr
)
261 int len
= strlen(hdr
);
262 return !strncasecmp(line
->buf
, hdr
, len
) && line
->len
> len
&&
263 line
->buf
[len
] == ':' && isspace(line
->buf
[len
+ 1]);
266 static int check_header(const struct strbuf
*line
,
267 struct strbuf
*hdr_data
[], int overwrite
)
270 struct strbuf sb
= STRBUF_INIT
;
271 /* search for the interesting parts */
272 for (i
= 0; header
[i
]; i
++) {
273 int len
= strlen(header
[i
]);
274 if ((!hdr_data
[i
] || overwrite
) && cmp_header(line
, header
[i
])) {
275 /* Unwrap inline B and Q encoding, and optionally
276 * normalize the meta information to utf8.
278 strbuf_add(&sb
, line
->buf
+ len
+ 2, line
->len
- len
- 2);
280 handle_header(&hdr_data
[i
], &sb
);
282 goto check_header_out
;
287 if (cmp_header(line
, "Content-Type")) {
288 len
= strlen("Content-Type: ");
289 strbuf_add(&sb
, line
->buf
+ len
, line
->len
- len
);
291 strbuf_insert(&sb
, 0, "Content-Type: ", len
);
292 handle_content_type(&sb
);
294 goto check_header_out
;
296 if (cmp_header(line
, "Content-Transfer-Encoding")) {
297 len
= strlen("Content-Transfer-Encoding: ");
298 strbuf_add(&sb
, line
->buf
+ len
, line
->len
- len
);
300 handle_content_transfer_encoding(&sb
);
302 goto check_header_out
;
305 /* for inbody stuff */
306 if (!prefixcmp(line
->buf
, ">From") && isspace(line
->buf
[5])) {
307 ret
= 1; /* Should this return 0? */
308 goto check_header_out
;
310 if (!prefixcmp(line
->buf
, "[PATCH]") && isspace(line
->buf
[7])) {
311 for (i
= 0; header
[i
]; i
++) {
312 if (!memcmp("Subject", header
[i
], 7)) {
313 handle_header(&hdr_data
[i
], line
);
315 goto check_header_out
;
325 static int is_rfc2822_header(const struct strbuf
*line
)
328 * The section that defines the loosest possible
329 * field name is "3.6.8 Optional fields".
331 * optional-field = field-name ":" unstructured CRLF
332 * field-name = 1*ftext
333 * ftext = %d33-57 / %59-126
336 char *cp
= line
->buf
;
338 /* Count mbox From headers as headers */
339 if (!prefixcmp(cp
, "From ") || !prefixcmp(cp
, ">From "))
342 while ((ch
= *cp
++)) {
345 if ((33 <= ch
&& ch
<= 57) ||
346 (59 <= ch
&& ch
<= 126))
353 static int read_one_header_line(struct strbuf
*line
, FILE *in
)
355 /* Get the first part of the line. */
356 if (strbuf_getline(line
, in
, '\n'))
360 * Is it an empty line or not a valid rfc2822 header?
361 * If so, stop here, and return false ("not a header")
364 if (!line
->len
|| !is_rfc2822_header(line
)) {
365 /* Re-add the newline */
366 strbuf_addch(line
, '\n');
371 * Now we need to eat all the continuation lines..
372 * Yuck, 2822 header "folding"
376 struct strbuf continuation
= STRBUF_INIT
;
378 peek
= fgetc(in
); ungetc(peek
, in
);
379 if (peek
!= ' ' && peek
!= '\t')
381 if (strbuf_getline(&continuation
, in
, '\n'))
383 continuation
.buf
[0] = '\n';
384 strbuf_rtrim(&continuation
);
385 strbuf_addbuf(line
, &continuation
);
391 static struct strbuf
*decode_q_segment(const struct strbuf
*q_seg
, int rfc2047
)
393 const char *in
= q_seg
->buf
;
395 struct strbuf
*out
= xmalloc(sizeof(struct strbuf
));
396 strbuf_init(out
, q_seg
->len
);
398 while ((c
= *in
++) != 0) {
402 break; /* drop trailing newline */
403 strbuf_addch(out
, (hexval(d
) << 4) | hexval(*in
++));
406 if (rfc2047
&& c
== '_') /* rfc2047 4.2 (2) */
408 strbuf_addch(out
, c
);
413 static struct strbuf
*decode_b_segment(const struct strbuf
*b_seg
)
415 /* Decode in..ep, possibly in-place to ot */
416 int c
, pos
= 0, acc
= 0;
417 const char *in
= b_seg
->buf
;
418 struct strbuf
*out
= xmalloc(sizeof(struct strbuf
));
419 strbuf_init(out
, b_seg
->len
);
421 while ((c
= *in
++) != 0) {
426 else if ('A' <= c
&& c
<= 'Z')
428 else if ('a' <= c
&& c
<= 'z')
430 else if ('0' <= c
&& c
<= '9')
433 /* padding is almost like (c == 0), except we do
434 * not output NUL resulting only from it;
435 * for now we just trust the data.
440 continue; /* garbage */
446 strbuf_addch(out
, (acc
| (c
>> 4)));
450 strbuf_addch(out
, (acc
| (c
>> 2)));
454 strbuf_addch(out
, (acc
| c
));
463 * When there is no known charset, guess.
465 * Right now we assume that if the target is UTF-8 (the default),
466 * and it already looks like UTF-8 (which includes US-ASCII as its
467 * subset, of course) then that is what it is and there is nothing
470 * Otherwise, we default to assuming it is Latin1 for historical
473 static const char *guess_charset(const struct strbuf
*line
, const char *target_charset
)
475 if (is_encoding_utf8(target_charset
)) {
476 if (is_utf8(line
->buf
))
482 static void convert_to_utf8(struct strbuf
*line
, const char *charset
)
486 if (!charset
|| !*charset
) {
487 charset
= guess_charset(line
, metainfo_charset
);
492 if (!strcmp(metainfo_charset
, charset
))
494 out
= reencode_string(line
->buf
, metainfo_charset
, charset
);
496 die("cannot convert from %s to %s\n",
497 charset
, metainfo_charset
);
498 strbuf_attach(line
, out
, strlen(out
), strlen(out
));
501 static int decode_header_bq(struct strbuf
*it
)
504 struct strbuf outbuf
= STRBUF_INIT
, *dec
;
505 struct strbuf charset_q
= STRBUF_INIT
, piecebuf
= STRBUF_INIT
;
509 while (in
- it
->buf
<= it
->len
&& (ep
= strstr(in
, "=?")) != NULL
) {
511 strbuf_reset(&charset_q
);
512 strbuf_reset(&piecebuf
);
516 strbuf_add(&outbuf
, in
, ep
- in
);
520 * ep : "=?iso-2022-jp?B?GyR...?= foo"
521 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
525 if (ep
- it
->buf
>= it
->len
|| !(cp
= strchr(ep
, '?')))
526 goto decode_header_bq_out
;
528 if (cp
+ 3 - it
->buf
> it
->len
)
529 goto decode_header_bq_out
;
530 strbuf_add(&charset_q
, ep
, cp
- ep
);
531 strbuf_tolower(&charset_q
);
534 if (!encoding
|| cp
[2] != '?')
535 goto decode_header_bq_out
;
536 ep
= strstr(cp
+ 3, "?=");
538 goto decode_header_bq_out
;
539 strbuf_add(&piecebuf
, cp
+ 3, ep
- cp
- 3);
540 switch (tolower(encoding
)) {
542 goto decode_header_bq_out
;
544 dec
= decode_b_segment(&piecebuf
);
547 dec
= decode_q_segment(&piecebuf
, 1);
550 if (metainfo_charset
)
551 convert_to_utf8(dec
, charset_q
.buf
);
553 strbuf_addbuf(&outbuf
, dec
);
558 strbuf_addstr(&outbuf
, in
);
560 strbuf_addbuf(it
, &outbuf
);
561 decode_header_bq_out
:
562 strbuf_release(&outbuf
);
563 strbuf_release(&charset_q
);
564 strbuf_release(&piecebuf
);
568 static void decode_header(struct strbuf
*it
)
570 if (decode_header_bq(it
))
572 /* otherwise "it" is a straight copy of the input.
573 * This can be binary guck but there is no charset specified.
575 if (metainfo_charset
)
576 convert_to_utf8(it
, "");
579 static void decode_transfer_encoding(struct strbuf
*line
)
583 switch (transfer_encoding
) {
585 ret
= decode_q_segment(line
, 0);
588 ret
= decode_b_segment(line
);
595 strbuf_addbuf(line
, ret
);
600 static void handle_filter(struct strbuf
*line
);
602 static int find_boundary(void)
604 while (!strbuf_getline(&line
, fin
, '\n')) {
605 if (is_multipart_boundary(&line
))
611 static int handle_boundary(void)
613 struct strbuf newline
= STRBUF_INIT
;
615 strbuf_addch(&newline
, '\n');
617 if (line
.len
>= (*content_top
)->len
+ 2 &&
618 !memcmp(line
.buf
+ (*content_top
)->len
, "--", 2)) {
619 /* we hit an end boundary */
620 /* pop the current boundary off the stack */
621 strbuf_release(*content_top
);
625 /* technically won't happen as is_multipart_boundary()
626 will fail first. But just in case..
628 if (content_top
-- < content
) {
629 fprintf(stderr
, "Detected mismatched boundaries, "
633 handle_filter(&newline
);
634 strbuf_release(&newline
);
636 /* skip to the next boundary */
637 if (!find_boundary())
642 /* set some defaults */
643 transfer_encoding
= TE_DONTCARE
;
644 strbuf_reset(&charset
);
645 message_type
= TYPE_TEXT
;
647 /* slurp in this section's info */
648 while (read_one_header_line(&line
, fin
))
649 check_header(&line
, p_hdr_data
, 0);
651 strbuf_release(&newline
);
652 /* eat the blank line after section info */
653 return (strbuf_getline(&line
, fin
, '\n') == 0);
656 static inline int patchbreak(const struct strbuf
*line
)
660 /* Beginning of a "diff -" header? */
661 if (!prefixcmp(line
->buf
, "diff -"))
664 /* CVS "Index: " line? */
665 if (!prefixcmp(line
->buf
, "Index: "))
669 * "--- <filename>" starts patches without headers
670 * "---<sp>*" is a manual separator
675 if (!prefixcmp(line
->buf
, "---")) {
676 /* space followed by a filename? */
677 if (line
->buf
[3] == ' ' && !isspace(line
->buf
[4]))
679 /* Just whitespace? */
680 for (i
= 3; i
< line
->len
; i
++) {
681 unsigned char c
= line
->buf
[i
];
692 static int handle_commit_msg(struct strbuf
*line
)
694 static int still_looking
= 1;
703 if ((still_looking
= check_header(line
, s_hdr_data
, 0)) != 0)
707 /* normalize the log message to UTF-8. */
708 if (metainfo_charset
)
709 convert_to_utf8(line
, charset
.buf
);
711 if (patchbreak(line
)) {
717 fputs(line
->buf
, cmitmsg
);
721 static void handle_patch(const struct strbuf
*line
)
723 fwrite(line
->buf
, 1, line
->len
, patchfile
);
727 static void handle_filter(struct strbuf
*line
)
729 static int filter
= 0;
731 /* filter tells us which part we left off on */
734 if (!handle_commit_msg(line
))
743 static void handle_body(void)
746 struct strbuf prev
= STRBUF_INIT
;
748 /* Skip up to the first boundary */
750 if (!find_boundary())
751 goto handle_body_out
;
755 strbuf_setlen(&line
, line
.len
+ len
);
757 /* process any boundary lines */
758 if (*content_top
&& is_multipart_boundary(&line
)) {
759 /* flush any leftover */
761 handle_filter(&line
);
763 if (!handle_boundary())
764 goto handle_body_out
;
767 /* Unwrap transfer encoding */
768 decode_transfer_encoding(&line
);
770 switch (transfer_encoding
) {
774 struct strbuf
**lines
, **it
, *sb
;
776 /* Prepend any previous partial lines */
777 strbuf_insert(&line
, 0, prev
.buf
, prev
.len
);
780 /* binary data most likely doesn't have newlines */
781 if (message_type
!= TYPE_TEXT
) {
782 handle_filter(&line
);
786 * This is a decoded line that may contain
787 * multiple new lines. Pass only one chunk
788 * at a time to handle_filter()
790 lines
= strbuf_split(&line
, '\n');
791 for (it
= lines
; (sb
= *it
); it
++) {
792 if (*(it
+ 1) == NULL
) /* The last line */
793 if (sb
->buf
[sb
->len
- 1] != '\n') {
794 /* Partial line, save it for later. */
795 strbuf_addbuf(&prev
, sb
);
801 * The partial chunk is saved in "prev" and will be
802 * appended by the next iteration of read_line_with_nul().
804 strbuf_list_free(lines
);
808 handle_filter(&line
);
812 if (strbuf_avail(&line
) < 100)
813 strbuf_grow(&line
, 100);
814 } while ((len
= read_line_with_nul(line
.buf
, strbuf_avail(&line
), fin
)));
817 strbuf_release(&prev
);
820 static void output_header_lines(FILE *fout
, const char *hdr
, const struct strbuf
*data
)
822 const char *sp
= data
->buf
;
824 char *ep
= strchr(sp
, '\n');
830 fprintf(fout
, "%s: %.*s\n", hdr
, len
, sp
);
837 static void handle_info(void)
842 for (i
= 0; header
[i
]; i
++) {
843 /* only print inbody headers if we output a patch file */
844 if (patch_lines
&& s_hdr_data
[i
])
846 else if (p_hdr_data
[i
])
851 if (!memcmp(header
[i
], "Subject", 7)) {
853 cleanup_subject(hdr
);
856 output_header_lines(fout
, "Subject", hdr
);
857 } else if (!memcmp(header
[i
], "From", 4)) {
859 fprintf(fout
, "Author: %s\n", name
.buf
);
860 fprintf(fout
, "Email: %s\n", email
.buf
);
863 fprintf(fout
, "%s: %s\n", header
[i
], hdr
->buf
);
869 static int mailinfo(FILE *in
, FILE *out
, int ks
, const char *encoding
,
870 const char *msg
, const char *patch
)
874 metainfo_charset
= encoding
;
878 cmitmsg
= fopen(msg
, "w");
883 patchfile
= fopen(patch
, "w");
890 p_hdr_data
= xcalloc(MAX_HDR_PARSED
, sizeof(*p_hdr_data
));
891 s_hdr_data
= xcalloc(MAX_HDR_PARSED
, sizeof(*s_hdr_data
));
895 } while (isspace(peek
));
898 /* process the email header */
899 while (read_one_header_line(&line
, fin
))
900 check_header(&line
, p_hdr_data
, 1);
908 static const char mailinfo_usage
[] =
909 "git mailinfo [-k] [-u | --encoding=<encoding> | -n] msg patch <mail >info";
911 int cmd_mailinfo(int argc
, const char **argv
, const char *prefix
)
913 const char *def_charset
;
915 /* NEEDSWORK: might want to do the optional .git/ directory
918 git_config(git_default_config
, NULL
);
920 def_charset
= (git_commit_encoding
? git_commit_encoding
: "utf-8");
921 metainfo_charset
= def_charset
;
923 while (1 < argc
&& argv
[1][0] == '-') {
924 if (!strcmp(argv
[1], "-k"))
926 else if (!strcmp(argv
[1], "-u"))
927 metainfo_charset
= def_charset
;
928 else if (!strcmp(argv
[1], "-n"))
929 metainfo_charset
= NULL
;
930 else if (!prefixcmp(argv
[1], "--encoding="))
931 metainfo_charset
= argv
[1] + 11;
933 usage(mailinfo_usage
);
938 usage(mailinfo_usage
);
940 return !!mailinfo(stdin
, stdout
, keep_subject
, metainfo_charset
, argv
[1], argv
[2]);