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.
118 if (f
.buf
[0] == '(' && f
.len
&& f
.buf
[f
.len
- 1] == ')') {
119 strbuf_remove(&f
, 0, 1);
120 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 (((*content_top
)->len
<= line
->len
) &&
207 !memcmp(line
->buf
, (*content_top
)->buf
, (*content_top
)->len
));
210 static void cleanup_subject(struct strbuf
*subject
)
214 while (subject
->len
) {
215 switch (*subject
->buf
) {
217 if (subject
->len
<= 3)
219 if (!memcmp(subject
->buf
+ 1, "e:", 2)) {
220 strbuf_remove(subject
, 0, 3);
224 case ' ': case '\t': case ':':
225 strbuf_remove(subject
, 0, 1);
228 if ((pos
= strchr(subject
->buf
, ']'))) {
229 remove
= pos
- subject
->buf
;
230 if (remove
<= (subject
->len
- remove
) * 2) {
231 strbuf_remove(subject
, 0, remove
+ 1);
235 strbuf_remove(subject
, 0, 1);
238 strbuf_trim(subject
);
243 static void cleanup_space(struct strbuf
*sb
)
246 for (pos
= 0; pos
< sb
->len
; pos
++) {
247 if (isspace(sb
->buf
[pos
])) {
249 for (cnt
= 0; isspace(sb
->buf
[pos
+ cnt
+ 1]); cnt
++);
250 strbuf_remove(sb
, pos
+ 1, cnt
);
255 static void decode_header(struct strbuf
*line
);
256 static const char *header
[MAX_HDR_PARSED
] = {
257 "From","Subject","Date",
260 static inline int cmp_header(const struct strbuf
*line
, const char *hdr
)
262 int len
= strlen(hdr
);
263 return !strncasecmp(line
->buf
, hdr
, len
) && line
->len
> len
&&
264 line
->buf
[len
] == ':' && isspace(line
->buf
[len
+ 1]);
267 static int check_header(const struct strbuf
*line
,
268 struct strbuf
*hdr_data
[], int overwrite
)
271 struct strbuf sb
= STRBUF_INIT
;
272 /* search for the interesting parts */
273 for (i
= 0; header
[i
]; i
++) {
274 int len
= strlen(header
[i
]);
275 if ((!hdr_data
[i
] || overwrite
) && cmp_header(line
, header
[i
])) {
276 /* Unwrap inline B and Q encoding, and optionally
277 * normalize the meta information to utf8.
279 strbuf_add(&sb
, line
->buf
+ len
+ 2, line
->len
- len
- 2);
281 handle_header(&hdr_data
[i
], &sb
);
283 goto check_header_out
;
288 if (cmp_header(line
, "Content-Type")) {
289 len
= strlen("Content-Type: ");
290 strbuf_add(&sb
, line
->buf
+ len
, line
->len
- len
);
292 strbuf_insert(&sb
, 0, "Content-Type: ", len
);
293 handle_content_type(&sb
);
295 goto check_header_out
;
297 if (cmp_header(line
, "Content-Transfer-Encoding")) {
298 len
= strlen("Content-Transfer-Encoding: ");
299 strbuf_add(&sb
, line
->buf
+ len
, line
->len
- len
);
301 handle_content_transfer_encoding(&sb
);
303 goto check_header_out
;
306 /* for inbody stuff */
307 if (!prefixcmp(line
->buf
, ">From") && isspace(line
->buf
[5])) {
308 ret
= 1; /* Should this return 0? */
309 goto check_header_out
;
311 if (!prefixcmp(line
->buf
, "[PATCH]") && isspace(line
->buf
[7])) {
312 for (i
= 0; header
[i
]; i
++) {
313 if (!memcmp("Subject", header
[i
], 7)) {
314 handle_header(&hdr_data
[i
], line
);
316 goto check_header_out
;
326 static int is_rfc2822_header(const struct strbuf
*line
)
329 * The section that defines the loosest possible
330 * field name is "3.6.8 Optional fields".
332 * optional-field = field-name ":" unstructured CRLF
333 * field-name = 1*ftext
334 * ftext = %d33-57 / %59-126
337 char *cp
= line
->buf
;
339 /* Count mbox From headers as headers */
340 if (!prefixcmp(cp
, "From ") || !prefixcmp(cp
, ">From "))
343 while ((ch
= *cp
++)) {
346 if ((33 <= ch
&& ch
<= 57) ||
347 (59 <= ch
&& ch
<= 126))
354 static int read_one_header_line(struct strbuf
*line
, FILE *in
)
356 /* Get the first part of the line. */
357 if (strbuf_getline(line
, in
, '\n'))
361 * Is it an empty line or not a valid rfc2822 header?
362 * If so, stop here, and return false ("not a header")
365 if (!line
->len
|| !is_rfc2822_header(line
)) {
366 /* Re-add the newline */
367 strbuf_addch(line
, '\n');
372 * Now we need to eat all the continuation lines..
373 * Yuck, 2822 header "folding"
377 struct strbuf continuation
= STRBUF_INIT
;
379 peek
= fgetc(in
); ungetc(peek
, in
);
380 if (peek
!= ' ' && peek
!= '\t')
382 if (strbuf_getline(&continuation
, in
, '\n'))
384 continuation
.buf
[0] = '\n';
385 strbuf_rtrim(&continuation
);
386 strbuf_addbuf(line
, &continuation
);
392 static struct strbuf
*decode_q_segment(const struct strbuf
*q_seg
, int rfc2047
)
394 const char *in
= q_seg
->buf
;
396 struct strbuf
*out
= xmalloc(sizeof(struct strbuf
));
397 strbuf_init(out
, q_seg
->len
);
399 while ((c
= *in
++) != 0) {
403 break; /* drop trailing newline */
404 strbuf_addch(out
, (hexval(d
) << 4) | hexval(*in
++));
407 if (rfc2047
&& c
== '_') /* rfc2047 4.2 (2) */
409 strbuf_addch(out
, c
);
414 static struct strbuf
*decode_b_segment(const struct strbuf
*b_seg
)
416 /* Decode in..ep, possibly in-place to ot */
417 int c
, pos
= 0, acc
= 0;
418 const char *in
= b_seg
->buf
;
419 struct strbuf
*out
= xmalloc(sizeof(struct strbuf
));
420 strbuf_init(out
, b_seg
->len
);
422 while ((c
= *in
++) != 0) {
427 else if ('A' <= c
&& c
<= 'Z')
429 else if ('a' <= c
&& c
<= 'z')
431 else if ('0' <= c
&& c
<= '9')
434 /* padding is almost like (c == 0), except we do
435 * not output NUL resulting only from it;
436 * for now we just trust the data.
441 continue; /* garbage */
447 strbuf_addch(out
, (acc
| (c
>> 4)));
451 strbuf_addch(out
, (acc
| (c
>> 2)));
455 strbuf_addch(out
, (acc
| c
));
464 * When there is no known charset, guess.
466 * Right now we assume that if the target is UTF-8 (the default),
467 * and it already looks like UTF-8 (which includes US-ASCII as its
468 * subset, of course) then that is what it is and there is nothing
471 * Otherwise, we default to assuming it is Latin1 for historical
474 static const char *guess_charset(const struct strbuf
*line
, const char *target_charset
)
476 if (is_encoding_utf8(target_charset
)) {
477 if (is_utf8(line
->buf
))
483 static void convert_to_utf8(struct strbuf
*line
, const char *charset
)
487 if (!charset
|| !*charset
) {
488 charset
= guess_charset(line
, metainfo_charset
);
493 if (!strcmp(metainfo_charset
, charset
))
495 out
= reencode_string(line
->buf
, metainfo_charset
, charset
);
497 die("cannot convert from %s to %s\n",
498 charset
, metainfo_charset
);
499 strbuf_attach(line
, out
, strlen(out
), strlen(out
));
502 static int decode_header_bq(struct strbuf
*it
)
505 struct strbuf outbuf
= STRBUF_INIT
, *dec
;
506 struct strbuf charset_q
= STRBUF_INIT
, piecebuf
= STRBUF_INIT
;
510 while (in
- it
->buf
<= it
->len
&& (ep
= strstr(in
, "=?")) != NULL
) {
512 strbuf_reset(&charset_q
);
513 strbuf_reset(&piecebuf
);
517 strbuf_add(&outbuf
, in
, ep
- in
);
521 * ep : "=?iso-2022-jp?B?GyR...?= foo"
522 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
526 if (ep
- it
->buf
>= it
->len
|| !(cp
= strchr(ep
, '?')))
527 goto decode_header_bq_out
;
529 if (cp
+ 3 - it
->buf
> it
->len
)
530 goto decode_header_bq_out
;
531 strbuf_add(&charset_q
, ep
, cp
- ep
);
532 strbuf_tolower(&charset_q
);
535 if (!encoding
|| cp
[2] != '?')
536 goto decode_header_bq_out
;
537 ep
= strstr(cp
+ 3, "?=");
539 goto decode_header_bq_out
;
540 strbuf_add(&piecebuf
, cp
+ 3, ep
- cp
- 3);
541 switch (tolower(encoding
)) {
543 goto decode_header_bq_out
;
545 dec
= decode_b_segment(&piecebuf
);
548 dec
= decode_q_segment(&piecebuf
, 1);
551 if (metainfo_charset
)
552 convert_to_utf8(dec
, charset_q
.buf
);
554 strbuf_addbuf(&outbuf
, dec
);
559 strbuf_addstr(&outbuf
, in
);
561 strbuf_addbuf(it
, &outbuf
);
562 decode_header_bq_out
:
563 strbuf_release(&outbuf
);
564 strbuf_release(&charset_q
);
565 strbuf_release(&piecebuf
);
569 static void decode_header(struct strbuf
*it
)
571 if (decode_header_bq(it
))
573 /* otherwise "it" is a straight copy of the input.
574 * This can be binary guck but there is no charset specified.
576 if (metainfo_charset
)
577 convert_to_utf8(it
, "");
580 static void decode_transfer_encoding(struct strbuf
*line
)
584 switch (transfer_encoding
) {
586 ret
= decode_q_segment(line
, 0);
589 ret
= decode_b_segment(line
);
596 strbuf_addbuf(line
, ret
);
601 static void handle_filter(struct strbuf
*line
);
603 static int find_boundary(void)
605 while (!strbuf_getline(&line
, fin
, '\n')) {
606 if (is_multipart_boundary(&line
))
612 static int handle_boundary(void)
614 struct strbuf newline
= STRBUF_INIT
;
616 strbuf_addch(&newline
, '\n');
618 if (line
.len
>= (*content_top
)->len
+ 2 &&
619 !memcmp(line
.buf
+ (*content_top
)->len
, "--", 2)) {
620 /* we hit an end boundary */
621 /* pop the current boundary off the stack */
622 strbuf_release(*content_top
);
626 /* technically won't happen as is_multipart_boundary()
627 will fail first. But just in case..
629 if (content_top
-- < content
) {
630 fprintf(stderr
, "Detected mismatched boundaries, "
634 handle_filter(&newline
);
635 strbuf_release(&newline
);
637 /* skip to the next boundary */
638 if (!find_boundary())
643 /* set some defaults */
644 transfer_encoding
= TE_DONTCARE
;
645 strbuf_reset(&charset
);
646 message_type
= TYPE_TEXT
;
648 /* slurp in this section's info */
649 while (read_one_header_line(&line
, fin
))
650 check_header(&line
, p_hdr_data
, 0);
652 strbuf_release(&newline
);
654 if (strbuf_getline(&line
, fin
, '\n'))
656 strbuf_addch(&line
, '\n');
660 static inline int patchbreak(const struct strbuf
*line
)
664 /* Beginning of a "diff -" header? */
665 if (!prefixcmp(line
->buf
, "diff -"))
668 /* CVS "Index: " line? */
669 if (!prefixcmp(line
->buf
, "Index: "))
673 * "--- <filename>" starts patches without headers
674 * "---<sp>*" is a manual separator
679 if (!prefixcmp(line
->buf
, "---")) {
680 /* space followed by a filename? */
681 if (line
->buf
[3] == ' ' && !isspace(line
->buf
[4]))
683 /* Just whitespace? */
684 for (i
= 3; i
< line
->len
; i
++) {
685 unsigned char c
= line
->buf
[i
];
696 static int handle_commit_msg(struct strbuf
*line
)
698 static int still_looking
= 1;
707 if ((still_looking
= check_header(line
, s_hdr_data
, 0)) != 0)
711 /* normalize the log message to UTF-8. */
712 if (metainfo_charset
)
713 convert_to_utf8(line
, charset
.buf
);
715 if (patchbreak(line
)) {
721 fputs(line
->buf
, cmitmsg
);
725 static void handle_patch(const struct strbuf
*line
)
727 fwrite(line
->buf
, 1, line
->len
, patchfile
);
731 static void handle_filter(struct strbuf
*line
)
733 static int filter
= 0;
735 /* filter tells us which part we left off on */
738 if (!handle_commit_msg(line
))
747 static void handle_body(void)
750 struct strbuf prev
= STRBUF_INIT
;
752 /* Skip up to the first boundary */
754 if (!find_boundary())
755 goto handle_body_out
;
759 strbuf_setlen(&line
, line
.len
+ len
);
761 /* process any boundary lines */
762 if (*content_top
&& is_multipart_boundary(&line
)) {
763 /* flush any leftover */
765 handle_filter(&prev
);
768 if (!handle_boundary())
769 goto handle_body_out
;
772 /* Unwrap transfer encoding */
773 decode_transfer_encoding(&line
);
775 switch (transfer_encoding
) {
779 struct strbuf
**lines
, **it
, *sb
;
781 /* Prepend any previous partial lines */
782 strbuf_insert(&line
, 0, prev
.buf
, prev
.len
);
785 /* binary data most likely doesn't have newlines */
786 if (message_type
!= TYPE_TEXT
) {
787 handle_filter(&line
);
791 * This is a decoded line that may contain
792 * multiple new lines. Pass only one chunk
793 * at a time to handle_filter()
795 lines
= strbuf_split(&line
, '\n');
796 for (it
= lines
; (sb
= *it
); it
++) {
797 if (*(it
+ 1) == NULL
) /* The last line */
798 if (sb
->buf
[sb
->len
- 1] != '\n') {
799 /* Partial line, save it for later. */
800 strbuf_addbuf(&prev
, sb
);
806 * The partial chunk is saved in "prev" and will be
807 * appended by the next iteration of read_line_with_nul().
809 strbuf_list_free(lines
);
813 handle_filter(&line
);
817 if (strbuf_avail(&line
) < 100)
818 strbuf_grow(&line
, 100);
819 } while ((len
= read_line_with_nul(line
.buf
, strbuf_avail(&line
), fin
)));
822 strbuf_release(&prev
);
825 static void output_header_lines(FILE *fout
, const char *hdr
, const struct strbuf
*data
)
827 const char *sp
= data
->buf
;
829 char *ep
= strchr(sp
, '\n');
835 fprintf(fout
, "%s: %.*s\n", hdr
, len
, sp
);
842 static void handle_info(void)
847 for (i
= 0; header
[i
]; i
++) {
848 /* only print inbody headers if we output a patch file */
849 if (patch_lines
&& s_hdr_data
[i
])
851 else if (p_hdr_data
[i
])
856 if (!memcmp(header
[i
], "Subject", 7)) {
858 cleanup_subject(hdr
);
861 output_header_lines(fout
, "Subject", hdr
);
862 } else if (!memcmp(header
[i
], "From", 4)) {
864 fprintf(fout
, "Author: %s\n", name
.buf
);
865 fprintf(fout
, "Email: %s\n", email
.buf
);
868 fprintf(fout
, "%s: %s\n", header
[i
], hdr
->buf
);
874 static int mailinfo(FILE *in
, FILE *out
, int ks
, const char *encoding
,
875 const char *msg
, const char *patch
)
879 metainfo_charset
= encoding
;
883 cmitmsg
= fopen(msg
, "w");
888 patchfile
= fopen(patch
, "w");
895 p_hdr_data
= xcalloc(MAX_HDR_PARSED
, sizeof(*p_hdr_data
));
896 s_hdr_data
= xcalloc(MAX_HDR_PARSED
, sizeof(*s_hdr_data
));
900 } while (isspace(peek
));
903 /* process the email header */
904 while (read_one_header_line(&line
, fin
))
905 check_header(&line
, p_hdr_data
, 1);
913 static const char mailinfo_usage
[] =
914 "git mailinfo [-k] [-u | --encoding=<encoding> | -n] msg patch <mail >info";
916 int cmd_mailinfo(int argc
, const char **argv
, const char *prefix
)
918 const char *def_charset
;
920 /* NEEDSWORK: might want to do the optional .git/ directory
923 git_config(git_default_config
, NULL
);
925 def_charset
= (git_commit_encoding
? git_commit_encoding
: "utf-8");
926 metainfo_charset
= def_charset
;
928 while (1 < argc
&& argv
[1][0] == '-') {
929 if (!strcmp(argv
[1], "-k"))
931 else if (!strcmp(argv
[1], "-u"))
932 metainfo_charset
= def_charset
;
933 else if (!strcmp(argv
[1], "-n"))
934 metainfo_charset
= NULL
;
935 else if (!prefixcmp(argv
[1], "--encoding="))
936 metainfo_charset
= argv
[1] + 11;
938 usage(mailinfo_usage
);
943 usage(mailinfo_usage
);
945 return !!mailinfo(stdin
, stdout
, keep_subject
, metainfo_charset
, argv
[1], argv
[2]);