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 if (slurp_attr(line
->buf
, "charset=", &charset
))
197 strbuf_tolower(&charset
);
200 strbuf_release(boundary
);
205 static void handle_content_transfer_encoding(const struct strbuf
*line
)
207 if (strcasestr(line
->buf
, "base64"))
208 transfer_encoding
= TE_BASE64
;
209 else if (strcasestr(line
->buf
, "quoted-printable"))
210 transfer_encoding
= TE_QP
;
212 transfer_encoding
= TE_DONTCARE
;
215 static int is_multipart_boundary(const struct strbuf
*line
)
217 return (((*content_top
)->len
<= line
->len
) &&
218 !memcmp(line
->buf
, (*content_top
)->buf
, (*content_top
)->len
));
221 static void cleanup_subject(struct strbuf
*subject
)
225 int brackets_removed
= 0;
227 while (subject
->len
) {
228 switch (*subject
->buf
) {
230 if (subject
->len
<= 3)
232 if (!memcmp(subject
->buf
+ 1, "e:", 2)) {
233 strbuf_remove(subject
, 0, 3);
237 case ' ': case '\t': case ':':
238 strbuf_remove(subject
, 0, 1);
241 /* remove only one set of square brackets */
242 if (brackets_removed
)
245 if ((pos
= strchr(subject
->buf
, ']'))) {
246 remove
= pos
- subject
->buf
;
247 if (remove
<= (subject
->len
- remove
) * 2) {
248 strbuf_remove(subject
, 0, remove
+ 1);
249 brackets_removed
= 1;
253 strbuf_remove(subject
, 0, 1);
256 strbuf_trim(subject
);
261 static void cleanup_space(struct strbuf
*sb
)
264 for (pos
= 0; pos
< sb
->len
; pos
++) {
265 if (isspace(sb
->buf
[pos
])) {
267 for (cnt
= 0; isspace(sb
->buf
[pos
+ cnt
+ 1]); cnt
++);
268 strbuf_remove(sb
, pos
+ 1, cnt
);
273 static void decode_header(struct strbuf
*line
);
274 static const char *header
[MAX_HDR_PARSED
] = {
275 "From","Subject","Date",
278 static inline int cmp_header(const struct strbuf
*line
, const char *hdr
)
280 int len
= strlen(hdr
);
281 return !strncasecmp(line
->buf
, hdr
, len
) && line
->len
> len
&&
282 line
->buf
[len
] == ':' && isspace(line
->buf
[len
+ 1]);
285 static int check_header(const struct strbuf
*line
,
286 struct strbuf
*hdr_data
[], int overwrite
)
289 struct strbuf sb
= STRBUF_INIT
;
290 /* search for the interesting parts */
291 for (i
= 0; header
[i
]; i
++) {
292 int len
= strlen(header
[i
]);
293 if ((!hdr_data
[i
] || overwrite
) && cmp_header(line
, header
[i
])) {
294 /* Unwrap inline B and Q encoding, and optionally
295 * normalize the meta information to utf8.
297 strbuf_add(&sb
, line
->buf
+ len
+ 2, line
->len
- len
- 2);
299 handle_header(&hdr_data
[i
], &sb
);
301 goto check_header_out
;
306 if (cmp_header(line
, "Content-Type")) {
307 len
= strlen("Content-Type: ");
308 strbuf_add(&sb
, line
->buf
+ len
, line
->len
- len
);
310 strbuf_insert(&sb
, 0, "Content-Type: ", len
);
311 handle_content_type(&sb
);
313 goto check_header_out
;
315 if (cmp_header(line
, "Content-Transfer-Encoding")) {
316 len
= strlen("Content-Transfer-Encoding: ");
317 strbuf_add(&sb
, line
->buf
+ len
, line
->len
- len
);
319 handle_content_transfer_encoding(&sb
);
321 goto check_header_out
;
324 /* for inbody stuff */
325 if (!prefixcmp(line
->buf
, ">From") && isspace(line
->buf
[5])) {
326 ret
= 1; /* Should this return 0? */
327 goto check_header_out
;
329 if (!prefixcmp(line
->buf
, "[PATCH]") && isspace(line
->buf
[7])) {
330 for (i
= 0; header
[i
]; i
++) {
331 if (!memcmp("Subject", header
[i
], 7)) {
332 handle_header(&hdr_data
[i
], line
);
334 goto check_header_out
;
344 static int is_rfc2822_header(const struct strbuf
*line
)
347 * The section that defines the loosest possible
348 * field name is "3.6.8 Optional fields".
350 * optional-field = field-name ":" unstructured CRLF
351 * field-name = 1*ftext
352 * ftext = %d33-57 / %59-126
355 char *cp
= line
->buf
;
357 /* Count mbox From headers as headers */
358 if (!prefixcmp(cp
, "From ") || !prefixcmp(cp
, ">From "))
361 while ((ch
= *cp
++)) {
364 if ((33 <= ch
&& ch
<= 57) ||
365 (59 <= ch
&& ch
<= 126))
372 static int read_one_header_line(struct strbuf
*line
, FILE *in
)
374 /* Get the first part of the line. */
375 if (strbuf_getline(line
, in
, '\n'))
379 * Is it an empty line or not a valid rfc2822 header?
380 * If so, stop here, and return false ("not a header")
383 if (!line
->len
|| !is_rfc2822_header(line
)) {
384 /* Re-add the newline */
385 strbuf_addch(line
, '\n');
390 * Now we need to eat all the continuation lines..
391 * Yuck, 2822 header "folding"
395 struct strbuf continuation
= STRBUF_INIT
;
397 peek
= fgetc(in
); ungetc(peek
, in
);
398 if (peek
!= ' ' && peek
!= '\t')
400 if (strbuf_getline(&continuation
, in
, '\n'))
402 continuation
.buf
[0] = '\n';
403 strbuf_rtrim(&continuation
);
404 strbuf_addbuf(line
, &continuation
);
410 static struct strbuf
*decode_q_segment(const struct strbuf
*q_seg
, int rfc2047
)
412 const char *in
= q_seg
->buf
;
414 struct strbuf
*out
= xmalloc(sizeof(struct strbuf
));
415 strbuf_init(out
, q_seg
->len
);
417 while ((c
= *in
++) != 0) {
421 break; /* drop trailing newline */
422 strbuf_addch(out
, (hexval(d
) << 4) | hexval(*in
++));
425 if (rfc2047
&& c
== '_') /* rfc2047 4.2 (2) */
427 strbuf_addch(out
, c
);
432 static struct strbuf
*decode_b_segment(const struct strbuf
*b_seg
)
434 /* Decode in..ep, possibly in-place to ot */
435 int c
, pos
= 0, acc
= 0;
436 const char *in
= b_seg
->buf
;
437 struct strbuf
*out
= xmalloc(sizeof(struct strbuf
));
438 strbuf_init(out
, b_seg
->len
);
440 while ((c
= *in
++) != 0) {
445 else if ('A' <= c
&& c
<= 'Z')
447 else if ('a' <= c
&& c
<= 'z')
449 else if ('0' <= c
&& c
<= '9')
452 continue; /* garbage */
458 strbuf_addch(out
, (acc
| (c
>> 4)));
462 strbuf_addch(out
, (acc
| (c
>> 2)));
466 strbuf_addch(out
, (acc
| c
));
475 * When there is no known charset, guess.
477 * Right now we assume that if the target is UTF-8 (the default),
478 * and it already looks like UTF-8 (which includes US-ASCII as its
479 * subset, of course) then that is what it is and there is nothing
482 * Otherwise, we default to assuming it is Latin1 for historical
485 static const char *guess_charset(const struct strbuf
*line
, const char *target_charset
)
487 if (is_encoding_utf8(target_charset
)) {
488 if (is_utf8(line
->buf
))
494 static void convert_to_utf8(struct strbuf
*line
, const char *charset
)
498 if (!charset
|| !*charset
) {
499 charset
= guess_charset(line
, metainfo_charset
);
504 if (!strcmp(metainfo_charset
, charset
))
506 out
= reencode_string(line
->buf
, metainfo_charset
, charset
);
508 die("cannot convert from %s to %s",
509 charset
, metainfo_charset
);
510 strbuf_attach(line
, out
, strlen(out
), strlen(out
));
513 static int decode_header_bq(struct strbuf
*it
)
516 struct strbuf outbuf
= STRBUF_INIT
, *dec
;
517 struct strbuf charset_q
= STRBUF_INIT
, piecebuf
= STRBUF_INIT
;
521 while (in
- it
->buf
<= it
->len
&& (ep
= strstr(in
, "=?")) != NULL
) {
523 strbuf_reset(&charset_q
);
524 strbuf_reset(&piecebuf
);
529 * We are about to process an encoded-word
530 * that begins at ep, but there is something
531 * before the encoded word.
534 for (scan
= in
; scan
< ep
; scan
++)
538 if (scan
!= ep
|| in
== it
->buf
) {
540 * We should not lose that "something",
541 * unless we have just processed an
542 * encoded-word, and there is only LWS
543 * before the one we are about to process.
545 strbuf_add(&outbuf
, in
, ep
- in
);
549 * ep : "=?iso-2022-jp?B?GyR...?= foo"
550 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
554 if (ep
- it
->buf
>= it
->len
|| !(cp
= strchr(ep
, '?')))
555 goto decode_header_bq_out
;
557 if (cp
+ 3 - it
->buf
> it
->len
)
558 goto decode_header_bq_out
;
559 strbuf_add(&charset_q
, ep
, cp
- ep
);
560 strbuf_tolower(&charset_q
);
563 if (!encoding
|| cp
[2] != '?')
564 goto decode_header_bq_out
;
565 ep
= strstr(cp
+ 3, "?=");
567 goto decode_header_bq_out
;
568 strbuf_add(&piecebuf
, cp
+ 3, ep
- cp
- 3);
569 switch (tolower(encoding
)) {
571 goto decode_header_bq_out
;
573 dec
= decode_b_segment(&piecebuf
);
576 dec
= decode_q_segment(&piecebuf
, 1);
579 if (metainfo_charset
)
580 convert_to_utf8(dec
, charset_q
.buf
);
582 strbuf_addbuf(&outbuf
, dec
);
587 strbuf_addstr(&outbuf
, in
);
589 strbuf_addbuf(it
, &outbuf
);
590 decode_header_bq_out
:
591 strbuf_release(&outbuf
);
592 strbuf_release(&charset_q
);
593 strbuf_release(&piecebuf
);
597 static void decode_header(struct strbuf
*it
)
599 if (decode_header_bq(it
))
601 /* otherwise "it" is a straight copy of the input.
602 * This can be binary guck but there is no charset specified.
604 if (metainfo_charset
)
605 convert_to_utf8(it
, "");
608 static void decode_transfer_encoding(struct strbuf
*line
)
612 switch (transfer_encoding
) {
614 ret
= decode_q_segment(line
, 0);
617 ret
= decode_b_segment(line
);
624 strbuf_addbuf(line
, ret
);
629 static void handle_filter(struct strbuf
*line
);
631 static int find_boundary(void)
633 while (!strbuf_getline(&line
, fin
, '\n')) {
634 if (*content_top
&& is_multipart_boundary(&line
))
640 static int handle_boundary(void)
642 struct strbuf newline
= STRBUF_INIT
;
644 strbuf_addch(&newline
, '\n');
646 if (line
.len
>= (*content_top
)->len
+ 2 &&
647 !memcmp(line
.buf
+ (*content_top
)->len
, "--", 2)) {
648 /* we hit an end boundary */
649 /* pop the current boundary off the stack */
650 strbuf_release(*content_top
);
654 /* technically won't happen as is_multipart_boundary()
655 will fail first. But just in case..
657 if (--content_top
< content
) {
658 fprintf(stderr
, "Detected mismatched boundaries, "
662 handle_filter(&newline
);
663 strbuf_release(&newline
);
665 /* skip to the next boundary */
666 if (!find_boundary())
671 /* set some defaults */
672 transfer_encoding
= TE_DONTCARE
;
673 strbuf_reset(&charset
);
674 message_type
= TYPE_TEXT
;
676 /* slurp in this section's info */
677 while (read_one_header_line(&line
, fin
))
678 check_header(&line
, p_hdr_data
, 0);
680 strbuf_release(&newline
);
682 if (strbuf_getline(&line
, fin
, '\n'))
684 strbuf_addch(&line
, '\n');
688 static inline int patchbreak(const struct strbuf
*line
)
692 /* Beginning of a "diff -" header? */
693 if (!prefixcmp(line
->buf
, "diff -"))
696 /* CVS "Index: " line? */
697 if (!prefixcmp(line
->buf
, "Index: "))
701 * "--- <filename>" starts patches without headers
702 * "---<sp>*" is a manual separator
707 if (!prefixcmp(line
->buf
, "---")) {
708 /* space followed by a filename? */
709 if (line
->buf
[3] == ' ' && !isspace(line
->buf
[4]))
711 /* Just whitespace? */
712 for (i
= 3; i
< line
->len
; i
++) {
713 unsigned char c
= line
->buf
[i
];
724 static int handle_commit_msg(struct strbuf
*line
)
726 static int still_looking
= 1;
735 if ((still_looking
= check_header(line
, s_hdr_data
, 0)) != 0)
739 /* normalize the log message to UTF-8. */
740 if (metainfo_charset
)
741 convert_to_utf8(line
, charset
.buf
);
743 if (patchbreak(line
)) {
749 fputs(line
->buf
, cmitmsg
);
753 static void handle_patch(const struct strbuf
*line
)
755 fwrite(line
->buf
, 1, line
->len
, patchfile
);
759 static void handle_filter(struct strbuf
*line
)
761 static int filter
= 0;
763 /* filter tells us which part we left off on */
766 if (!handle_commit_msg(line
))
775 static void handle_body(void)
778 struct strbuf prev
= STRBUF_INIT
;
780 /* Skip up to the first boundary */
782 if (!find_boundary())
783 goto handle_body_out
;
787 strbuf_setlen(&line
, line
.len
+ len
);
789 /* process any boundary lines */
790 if (*content_top
&& is_multipart_boundary(&line
)) {
791 /* flush any leftover */
793 handle_filter(&prev
);
796 if (!handle_boundary())
797 goto handle_body_out
;
800 /* Unwrap transfer encoding */
801 decode_transfer_encoding(&line
);
803 switch (transfer_encoding
) {
807 struct strbuf
**lines
, **it
, *sb
;
809 /* Prepend any previous partial lines */
810 strbuf_insert(&line
, 0, prev
.buf
, prev
.len
);
813 /* binary data most likely doesn't have newlines */
814 if (message_type
!= TYPE_TEXT
) {
815 handle_filter(&line
);
819 * This is a decoded line that may contain
820 * multiple new lines. Pass only one chunk
821 * at a time to handle_filter()
823 lines
= strbuf_split(&line
, '\n');
824 for (it
= lines
; (sb
= *it
); it
++) {
825 if (*(it
+ 1) == NULL
) /* The last line */
826 if (sb
->buf
[sb
->len
- 1] != '\n') {
827 /* Partial line, save it for later. */
828 strbuf_addbuf(&prev
, sb
);
834 * The partial chunk is saved in "prev" and will be
835 * appended by the next iteration of read_line_with_nul().
837 strbuf_list_free(lines
);
841 handle_filter(&line
);
845 if (strbuf_avail(&line
) < 100)
846 strbuf_grow(&line
, 100);
847 } while ((len
= read_line_with_nul(line
.buf
, strbuf_avail(&line
), fin
)));
850 strbuf_release(&prev
);
853 static void output_header_lines(FILE *fout
, const char *hdr
, const struct strbuf
*data
)
855 const char *sp
= data
->buf
;
857 char *ep
= strchr(sp
, '\n');
863 fprintf(fout
, "%s: %.*s\n", hdr
, len
, sp
);
870 static void handle_info(void)
875 for (i
= 0; header
[i
]; i
++) {
876 /* only print inbody headers if we output a patch file */
877 if (patch_lines
&& s_hdr_data
[i
])
879 else if (p_hdr_data
[i
])
884 if (!memcmp(header
[i
], "Subject", 7)) {
886 cleanup_subject(hdr
);
889 output_header_lines(fout
, "Subject", hdr
);
890 } else if (!memcmp(header
[i
], "From", 4)) {
893 fprintf(fout
, "Author: %s\n", name
.buf
);
894 fprintf(fout
, "Email: %s\n", email
.buf
);
897 fprintf(fout
, "%s: %s\n", header
[i
], hdr
->buf
);
903 static int mailinfo(FILE *in
, FILE *out
, int ks
, const char *encoding
,
904 const char *msg
, const char *patch
)
908 metainfo_charset
= encoding
;
912 cmitmsg
= fopen(msg
, "w");
917 patchfile
= fopen(patch
, "w");
924 p_hdr_data
= xcalloc(MAX_HDR_PARSED
, sizeof(*p_hdr_data
));
925 s_hdr_data
= xcalloc(MAX_HDR_PARSED
, sizeof(*s_hdr_data
));
929 } while (isspace(peek
));
932 /* process the email header */
933 while (read_one_header_line(&line
, fin
))
934 check_header(&line
, p_hdr_data
, 1);
942 static const char mailinfo_usage
[] =
943 "git mailinfo [-k] [-u | --encoding=<encoding> | -n] msg patch <mail >info";
945 int cmd_mailinfo(int argc
, const char **argv
, const char *prefix
)
947 const char *def_charset
;
949 /* NEEDSWORK: might want to do the optional .git/ directory
952 git_config(git_default_config
, NULL
);
954 def_charset
= (git_commit_encoding
? git_commit_encoding
: "utf-8");
955 metainfo_charset
= def_charset
;
957 while (1 < argc
&& argv
[1][0] == '-') {
958 if (!strcmp(argv
[1], "-k"))
960 else if (!strcmp(argv
[1], "-u"))
961 metainfo_charset
= def_charset
;
962 else if (!strcmp(argv
[1], "-n"))
963 metainfo_charset
= NULL
;
964 else if (!prefixcmp(argv
[1], "--encoding="))
965 metainfo_charset
= argv
[1] + 11;
967 usage(mailinfo_usage
);
972 usage(mailinfo_usage
);
974 return !!mailinfo(stdin
, stdout
, keep_subject
, metainfo_charset
, argv
[1], argv
[2]);