2 * Another stupid program, this one parsing the headers of an
3 * email to figure out authorship and subject
9 static FILE *cmitmsg
, *patchfile
, *fin
, *fout
;
11 static int keep_subject
;
12 static const char *metainfo_charset
;
13 static char line
[1000];
14 static char name
[1000];
15 static char email
[1000];
18 TE_DONTCARE
, TE_QP
, TE_BASE64
,
21 TYPE_TEXT
, TYPE_OTHER
,
24 static char charset
[256];
25 static int patch_lines
;
26 static char **p_hdr_data
, **s_hdr_data
;
28 #define MAX_HDR_PARSED 10
29 #define MAX_BOUNDARIES 5
31 static char *sanity_check(char *name
, char *email
)
33 int len
= strlen(name
);
34 if (len
< 3 || len
> 60)
36 if (strchr(name
, '@') || strchr(name
, '<') || strchr(name
, '>'))
41 static int bogus_from(char *line
)
43 /* John Doe <johndoe> */
44 char *bra
, *ket
, *dst
, *cp
;
46 /* This is fallback, so do not bother if we already have an
52 bra
= strchr(line
, '<');
55 ket
= strchr(bra
, '>');
59 for (dst
= email
, cp
= bra
+1; cp
< ket
; )
62 for (cp
= line
; isspace(*cp
); cp
++)
64 for (bra
--; isspace(*bra
); bra
--)
66 cp
= sanity_check(cp
, email
);
71 static int handle_from(char *in_line
)
77 strcpy(line
, in_line
);
78 at
= strchr(line
, '@');
80 return bogus_from(line
);
83 * If we already have one email, don't take any confusing lines
85 if (*email
&& strchr(at
+1, '@'))
88 /* Pick up the string around '@', possibly delimited with <>
89 * pair; that is the email part. White them out while copying.
103 unsigned char c
= *at
;
104 if (!c
|| c
== '>' || isspace(c
)) {
114 /* The remainder is name. It could be "John Doe <john.doe@xz>"
115 * or "john.doe@xz (John Doe)", but we have whited out the
116 * email part, so trim from both ends, possibly removing
117 * the () pair at the end.
119 at
= line
+ strlen(line
);
121 unsigned char c
= *--at
;
123 at
[(c
== ')') ? 0 : 1] = 0;
130 unsigned char c
= *at
;
131 if (!c
|| !isspace(c
)) {
138 at
= sanity_check(at
, email
);
143 static int handle_header(char *line
, char *data
, int ofs
)
148 strcpy(data
, line
+ofs
);
153 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
154 * to have enough heuristics to grok MIME encoded patches often found
155 * on our mailing lists. For example, we do not even treat header lines
156 * case insensitively.
159 static int slurp_attr(const char *line
, const char *name
, char *attr
)
161 const char *ends
, *ap
= strcasestr(line
, name
);
175 sz
= strcspn(ap
, ends
);
176 memcpy(attr
, ap
, sz
);
181 struct content_type
{
186 static struct content_type content
[MAX_BOUNDARIES
];
188 static struct content_type
*content_top
= content
;
190 static int handle_content_type(char *line
)
194 if (strcasestr(line
, "text/") == NULL
)
195 message_type
= TYPE_OTHER
;
196 if (slurp_attr(line
, "boundary=", boundary
+ 2)) {
197 memcpy(boundary
, "--", 2);
198 if (content_top
++ >= &content
[MAX_BOUNDARIES
]) {
199 fprintf(stderr
, "Too many boundaries to handle\n");
202 content_top
->boundary_len
= strlen(boundary
);
203 content_top
->boundary
= xmalloc(content_top
->boundary_len
+1);
204 strcpy(content_top
->boundary
, boundary
);
206 if (slurp_attr(line
, "charset=", charset
)) {
208 for (i
= 0; (c
= charset
[i
]) != 0; i
++)
209 charset
[i
] = tolower(c
);
214 static int handle_content_transfer_encoding(char *line
)
216 if (strcasestr(line
, "base64"))
217 transfer_encoding
= TE_BASE64
;
218 else if (strcasestr(line
, "quoted-printable"))
219 transfer_encoding
= TE_QP
;
221 transfer_encoding
= TE_DONTCARE
;
225 static int is_multipart_boundary(const char *line
)
227 return (!memcmp(line
, content_top
->boundary
, content_top
->boundary_len
));
230 static int eatspace(char *line
)
232 int len
= strlen(line
);
233 while (len
> 0 && isspace(line
[len
-1]))
238 static char *cleanup_subject(char *subject
)
247 if (!memcmp("e:", subject
+1, 2)) {
252 case ' ': case '\t': case ':':
257 p
= strchr(subject
, ']');
263 remove
= p
- subject
;
264 if (remove
<= len
*2) {
275 static void cleanup_space(char *buf
)
278 while ((c
= *buf
) != 0) {
284 int len
= strlen(buf
);
285 memmove(buf
, buf
+1, len
);
292 static void decode_header(char *it
);
293 static char *header
[MAX_HDR_PARSED
] = {
294 "From","Subject","Date",
297 static int check_header(char *line
, char **hdr_data
, int overwrite
)
301 /* search for the interesting parts */
302 for (i
= 0; header
[i
]; i
++) {
303 int len
= strlen(header
[i
]);
304 if ((!hdr_data
[i
] || overwrite
) &&
305 !strncasecmp(line
, header
[i
], len
) &&
306 line
[len
] == ':' && isspace(line
[len
+ 1])) {
307 /* Unwrap inline B and Q encoding, and optionally
308 * normalize the meta information to utf8.
310 decode_header(line
+ len
+ 2);
311 hdr_data
[i
] = xmalloc(1000 * sizeof(char));
312 if (! handle_header(line
, hdr_data
[i
], len
+ 2)) {
319 if (!strncasecmp(line
, "Content-Type", 12) &&
320 line
[12] == ':' && isspace(line
[12 + 1])) {
321 decode_header(line
+ 12 + 2);
322 if (! handle_content_type(line
)) {
326 if (!strncasecmp(line
, "Content-Transfer-Encoding", 25) &&
327 line
[25] == ':' && isspace(line
[25 + 1])) {
328 decode_header(line
+ 25 + 2);
329 if (! handle_content_transfer_encoding(line
)) {
334 /* for inbody stuff */
335 if (!memcmp(">From", line
, 5) && isspace(line
[5]))
337 if (!memcmp("[PATCH]", line
, 7) && isspace(line
[7])) {
338 for (i
= 0; header
[i
]; i
++) {
339 if (!memcmp("Subject: ", header
[i
], 9)) {
340 if (! handle_header(line
, hdr_data
[i
], 0)) {
351 static int is_rfc2822_header(char *line
)
354 * The section that defines the loosest possible
355 * field name is "3.6.8 Optional fields".
357 * optional-field = field-name ":" unstructured CRLF
358 * field-name = 1*ftext
359 * ftext = %d33-57 / %59-126
364 /* Count mbox From headers as headers */
365 if (!memcmp(line
, "From ", 5) || !memcmp(line
, ">From ", 6))
368 while ((ch
= *cp
++)) {
371 if ((33 <= ch
&& ch
<= 57) ||
372 (59 <= ch
&& ch
<= 126))
380 * sz is size of 'line' buffer in bytes. Must be reasonably
381 * long enough to hold one physical real-world e-mail line.
383 static int read_one_header_line(char *line
, int sz
, FILE *in
)
388 * We will read at most (sz-1) bytes and then potentially
389 * re-add NUL after it. Accessing line[sz] after this is safe
390 * and we can allow len to grow up to and including sz.
394 /* Get the first part of the line. */
395 if (!fgets(line
, sz
, in
))
399 * Is it an empty line or not a valid rfc2822 header?
400 * If so, stop here, and return false ("not a header")
402 len
= eatspace(line
);
403 if (!len
|| !is_rfc2822_header(line
)) {
404 /* Re-add the newline */
406 line
[len
+ 1] = '\0';
411 * Now we need to eat all the continuation lines..
412 * Yuck, 2822 header "folding"
416 static char continuation
[1000];
418 peek
= fgetc(in
); ungetc(peek
, in
);
419 if (peek
!= ' ' && peek
!= '\t')
421 if (!fgets(continuation
, sizeof(continuation
), in
))
423 addlen
= eatspace(continuation
);
425 if (addlen
>= sz
- len
)
426 addlen
= sz
- len
- 1;
427 memcpy(line
+ len
, continuation
, addlen
);
436 static int decode_q_segment(char *in
, char *ot
, char *ep
, int rfc2047
)
439 while ((c
= *in
++) != 0 && (in
<= ep
)) {
443 break; /* drop trailing newline */
444 *ot
++ = ((hexval(d
) << 4) | hexval(*in
++));
447 if (rfc2047
&& c
== '_') /* rfc2047 4.2 (2) */
455 static int decode_b_segment(char *in
, char *ot
, char *ep
)
457 /* Decode in..ep, possibly in-place to ot */
458 int c
, pos
= 0, acc
= 0;
460 while ((c
= *in
++) != 0 && (in
<= ep
)) {
465 else if ('A' <= c
&& c
<= 'Z')
467 else if ('a' <= c
&& c
<= 'z')
469 else if ('0' <= c
&& c
<= '9')
472 /* padding is almost like (c == 0), except we do
473 * not output NUL resulting only from it;
474 * for now we just trust the data.
479 continue; /* garbage */
485 *ot
++ = (acc
| (c
>> 4));
489 *ot
++ = (acc
| (c
>> 2));
503 * When there is no known charset, guess.
505 * Right now we assume that if the target is UTF-8 (the default),
506 * and it already looks like UTF-8 (which includes US-ASCII as its
507 * subset, of course) then that is what it is and there is nothing
510 * Otherwise, we default to assuming it is Latin1 for historical
513 static const char *guess_charset(const char *line
, const char *target_charset
)
515 if (is_encoding_utf8(target_charset
)) {
522 static void convert_to_utf8(char *line
, const char *charset
)
526 if (!charset
|| !*charset
) {
527 charset
= guess_charset(line
, metainfo_charset
);
532 if (!strcmp(metainfo_charset
, charset
))
534 out
= reencode_string(line
, metainfo_charset
, charset
);
536 die("cannot convert from %s to %s\n",
537 charset
, metainfo_charset
);
542 static int decode_header_bq(char *it
)
544 char *in
, *out
, *ep
, *cp
, *sp
;
550 while ((ep
= strstr(in
, "=?")) != NULL
) {
552 char charset_q
[256], piecebuf
[256];
562 * ep : "=?iso-2022-jp?B?GyR...?= foo"
563 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
566 cp
= strchr(ep
, '?');
568 return rfc2047
; /* no munging */
569 for (sp
= ep
; sp
< cp
; sp
++)
570 charset_q
[sp
- ep
] = tolower(*sp
);
571 charset_q
[cp
- ep
] = 0;
573 if (!encoding
|| cp
[2] != '?')
574 return rfc2047
; /* no munging */
575 ep
= strstr(cp
+ 3, "?=");
577 return rfc2047
; /* no munging */
578 switch (tolower(encoding
)) {
580 return rfc2047
; /* no munging */
582 sz
= decode_b_segment(cp
+ 3, piecebuf
, ep
);
585 sz
= decode_q_segment(cp
+ 3, piecebuf
, ep
, 1);
590 if (metainfo_charset
)
591 convert_to_utf8(piecebuf
, charset_q
);
592 strcpy(out
, piecebuf
);
601 static void decode_header(char *it
)
604 if (decode_header_bq(it
))
606 /* otherwise "it" is a straight copy of the input.
607 * This can be binary guck but there is no charset specified.
609 if (metainfo_charset
)
610 convert_to_utf8(it
, "");
613 static void decode_transfer_encoding(char *line
)
617 switch (transfer_encoding
) {
619 ep
= line
+ strlen(line
);
620 decode_q_segment(line
, line
, ep
, 0);
623 ep
= line
+ strlen(line
);
624 decode_b_segment(line
, line
, ep
);
631 static int handle_filter(char *line
);
633 static int find_boundary(void)
635 while(fgets(line
, sizeof(line
), fin
) != NULL
) {
636 if (is_multipart_boundary(line
))
642 static int handle_boundary(void)
646 if (!memcmp(line
+content_top
->boundary_len
, "--", 2)) {
647 /* we hit an end boundary */
648 /* pop the current boundary off the stack */
649 free(content_top
->boundary
);
651 /* technically won't happen as is_multipart_boundary()
652 will fail first. But just in case..
654 if (content_top
-- < content
) {
655 fprintf(stderr
, "Detected mismatched boundaries, "
659 handle_filter(newline
);
661 /* skip to the next boundary */
662 if (!find_boundary())
667 /* set some defaults */
668 transfer_encoding
= TE_DONTCARE
;
670 message_type
= TYPE_TEXT
;
672 /* slurp in this section's info */
673 while (read_one_header_line(line
, sizeof(line
), fin
))
674 check_header(line
, p_hdr_data
, 0);
676 /* eat the blank line after section info */
677 return (fgets(line
, sizeof(line
), fin
) != NULL
);
680 static inline int patchbreak(const char *line
)
682 /* Beginning of a "diff -" header? */
683 if (!memcmp("diff -", line
, 6))
686 /* CVS "Index: " line? */
687 if (!memcmp("Index: ", line
, 7))
691 * "--- <filename>" starts patches without headers
692 * "---<sp>*" is a manual separator
694 if (!memcmp("---", line
, 3)) {
696 /* space followed by a filename? */
697 if (line
[0] == ' ' && !isspace(line
[1]))
699 /* Just whitespace? */
701 unsigned char c
= *line
++;
713 static int handle_commit_msg(char *line
)
715 static int still_looking
= 1;
722 if (isspace(*line
)) {
723 for (cp
= line
+ 1; *cp
; cp
++) {
730 if ((still_looking
= check_header(cp
, s_hdr_data
, 0)) != 0)
734 /* normalize the log message to UTF-8. */
735 if (metainfo_charset
)
736 convert_to_utf8(line
, charset
);
738 if (patchbreak(line
)) {
744 fputs(line
, cmitmsg
);
748 static int handle_patch(char *line
)
750 fputs(line
, patchfile
);
755 static int handle_filter(char *line
)
757 static int filter
= 0;
759 /* filter tells us which part we left off on
760 * a non-zero return indicates we hit a filter point
764 if (!handle_commit_msg(line
))
768 if (!handle_patch(line
))
778 static void handle_body(void)
781 static char newline
[2000];
782 static char *np
= newline
;
784 /* Skip up to the first boundary */
785 if (content_top
->boundary
) {
786 if (!find_boundary())
791 /* process any boundary lines */
792 if (content_top
->boundary
&& is_multipart_boundary(line
)) {
793 /* flush any leftover */
794 if ((transfer_encoding
== TE_BASE64
) &&
796 handle_filter(newline
);
798 if (!handle_boundary())
802 /* Unwrap transfer encoding */
803 decode_transfer_encoding(line
);
805 switch (transfer_encoding
) {
810 /* binary data most likely doesn't have newlines */
811 if (message_type
!= TYPE_TEXT
) {
812 rc
= handle_filter(line
);
816 /* this is a decoded line that may contain
817 * multiple new lines. Pass only one chunk
818 * at a time to handle_filter()
822 while (*op
!= '\n' && *op
!= 0)
826 /* should be sitting on a new line */
829 rc
= handle_filter(newline
);
833 /* the partial chunk is saved in newline and
834 * will be appended by the next iteration of fgets
839 rc
= handle_filter(line
);
842 /* nothing left to filter */
844 } while (fgets(line
, sizeof(line
), fin
));
849 static void handle_info(void)
855 for (i
= 0; header
[i
]; i
++) {
857 /* only print inbody headers if we output a patch file */
858 if (patch_lines
&& s_hdr_data
[i
])
860 else if (p_hdr_data
[i
])
865 if (!memcmp(header
[i
], "Subject", 7)) {
866 sub
= cleanup_subject(hdr
);
868 fprintf(fout
, "Subject: %s\n", sub
);
869 } else if (!memcmp(header
[i
], "From", 4)) {
871 fprintf(fout
, "Author: %s\n", name
);
872 fprintf(fout
, "Email: %s\n", email
);
875 fprintf(fout
, "%s: %s\n", header
[i
], hdr
);
881 static int mailinfo(FILE *in
, FILE *out
, int ks
, const char *encoding
,
882 const char *msg
, const char *patch
)
885 metainfo_charset
= encoding
;
889 cmitmsg
= fopen(msg
, "w");
894 patchfile
= fopen(patch
, "w");
901 p_hdr_data
= xcalloc(MAX_HDR_PARSED
, sizeof(char *));
902 s_hdr_data
= xcalloc(MAX_HDR_PARSED
, sizeof(char *));
904 /* process the email header */
905 while (read_one_header_line(line
, sizeof(line
), fin
))
906 check_header(line
, p_hdr_data
, 1);
914 static const char mailinfo_usage
[] =
915 "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
917 int cmd_mailinfo(int argc
, const char **argv
, const char *prefix
)
919 const char *def_charset
;
921 /* NEEDSWORK: might want to do the optional .git/ directory
924 git_config(git_default_config
);
926 def_charset
= (git_commit_encoding
? git_commit_encoding
: "utf-8");
927 metainfo_charset
= def_charset
;
929 while (1 < argc
&& argv
[1][0] == '-') {
930 if (!strcmp(argv
[1], "-k"))
932 else if (!strcmp(argv
[1], "-u"))
933 metainfo_charset
= def_charset
;
934 else if (!strcmp(argv
[1], "-n"))
935 metainfo_charset
= NULL
;
936 else if (!prefixcmp(argv
[1], "--encoding="))
937 metainfo_charset
= argv
[1] + 11;
939 usage(mailinfo_usage
);
944 usage(mailinfo_usage
);
946 return !!mailinfo(stdin
, stdout
, keep_subject
, metainfo_charset
, argv
[1], argv
[2]);