2 * Another stupid program, this one parsing the headers of an
3 * email to figure out authorship and subject
13 #include "git-compat-util.h"
17 static FILE *cmitmsg, *patchfile, *fin, *fout;
19 static int keep_subject = 0;
20 static const char *metainfo_charset = NULL;
21 static char line[1000];
22 static char date[1000];
23 static char name[1000];
24 static char email[1000];
25 static char subject[1000];
28 TE_DONTCARE, TE_QP, TE_BASE64,
30 static char charset[256];
32 static char multipart_boundary[1000];
33 static int multipart_boundary_len;
34 static int patch_lines = 0;
36 static char *sanity_check(char *name, char *email)
38 int len = strlen(name);
39 if (len < 3 || len > 60)
41 if (strchr(name, '@') || strchr(name, '<') || strchr(name, '>'))
46 static int bogus_from(char *line)
48 /* John Doe <johndoe> */
49 char *bra, *ket, *dst, *cp;
51 /* This is fallback, so do not bother if we already have an
57 bra = strchr(line, '<');
60 ket = strchr(bra, '>');
64 for (dst = email, cp = bra+1; cp < ket; )
67 for (cp = line; isspace(*cp); cp++)
69 for (bra--; isspace(*bra); bra--)
71 cp = sanity_check(cp, email);
76 static int handle_from(char *in_line)
82 strcpy(line, in_line);
83 at = strchr(line, '@');
85 return bogus_from(line);
88 * If we already have one email, don't take any confusing lines
90 if (*email && strchr(at+1, '@'))
93 /* Pick up the string around '@', possibly delimited with <>
94 * pair; that is the email part. White them out while copying.
108 unsigned char c = *at;
109 if (!c || c == '>' || isspace(c)) {
119 /* The remainder is name. It could be "John Doe <john.doe@xz>"
120 * or "john.doe@xz (John Doe)", but we have whited out the
121 * email part, so trim from both ends, possibly removing
122 * the () pair at the end.
124 at = line + strlen(line);
126 unsigned char c = *--at;
128 at[(c == ')') ? 0 : 1] = 0;
135 unsigned char c = *at;
136 if (!c || !isspace(c)) {
143 at = sanity_check(at, email);
148 static int handle_date(char *line)
154 static int handle_subject(char *line)
156 strcpy(subject, line);
160 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
161 * to have enough heuristics to grok MIME encoded patches often found
162 * on our mailing lists. For example, we do not even treat header lines
163 * case insensitively.
166 static int slurp_attr(const char *line, const char *name, char *attr)
168 char *ends, *ap = strcasestr(line, name);
182 sz = strcspn(ap, ends);
183 memcpy(attr, ap, sz);
188 static int handle_subcontent_type(char *line)
190 /* We do not want to mess with boundary. Note that we do not
191 * handle nested multipart.
193 if (strcasestr(line, "boundary=")) {
194 fprintf(stderr, "Not handling nested multipart message.\n");
197 slurp_attr(line, "charset=", charset);
200 for (i = 0; (c = charset[i]) != 0; i++)
201 charset[i] = tolower(c);
206 static int handle_content_type(char *line)
208 *multipart_boundary = 0;
209 if (slurp_attr(line, "boundary=", multipart_boundary + 2)) {
210 memcpy(multipart_boundary, "--", 2);
211 multipart_boundary_len = strlen(multipart_boundary);
213 slurp_attr(line, "charset=", charset);
217 static int handle_content_transfer_encoding(char *line)
219 if (strcasestr(line, "base64"))
220 transfer_encoding = TE_BASE64;
221 else if (strcasestr(line, "quoted-printable"))
222 transfer_encoding = TE_QP;
224 transfer_encoding = TE_DONTCARE;
228 static int is_multipart_boundary(const char *line)
230 return (!memcmp(line, multipart_boundary, multipart_boundary_len));
233 static int eatspace(char *line)
235 int len = strlen(line);
236 while (len > 0 && isspace(line[len-1]))
243 #define SEEN_SUBJECT 04
244 #define SEEN_BOGUS_UNIX_FROM 010
245 #define SEEN_PREFIX 020
247 /* First lines of body can have From:, Date:, and Subject: or empty */
248 static void handle_inbody_header(int *seen, char *line)
250 if (*seen & SEEN_PREFIX)
252 if (isspace(*line)) {
254 for (cp = line + 1; *cp; cp++) {
261 if (!memcmp(">From", line, 5) && isspace(line[5])) {
262 if (!(*seen & SEEN_BOGUS_UNIX_FROM)) {
263 *seen |= SEEN_BOGUS_UNIX_FROM;
267 if (!memcmp("From:", line, 5) && isspace(line[5])) {
268 if (!(*seen & SEEN_FROM) && handle_from(line+6)) {
273 if (!memcmp("Date:", line, 5) && isspace(line[5])) {
274 if (!(*seen & SEEN_DATE)) {
280 if (!memcmp("Subject:", line, 8) && isspace(line[8])) {
281 if (!(*seen & SEEN_SUBJECT)) {
282 handle_subject(line+9);
283 *seen |= SEEN_SUBJECT;
287 if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
288 if (!(*seen & SEEN_SUBJECT)) {
289 handle_subject(line);
290 *seen |= SEEN_SUBJECT;
294 *seen |= SEEN_PREFIX;
297 static char *cleanup_subject(char *subject)
306 if (!memcmp("e:", subject+1, 2)) {
311 case ' ': case '\t': case ':':
316 p = strchr(subject, ']');
322 remove = p - subject;
323 if (remove <= len *2) {
334 static void cleanup_space(char *buf)
337 while ((c = *buf) != 0) {
343 int len = strlen(buf);
344 memmove(buf, buf+1, len);
351 static void decode_header_bq(char *it);
352 typedef int (*header_fn_t)(char *);
359 static void check_header(char *line, struct header_def *header)
363 if (header[0].namelen <= 0) {
364 for (i = 0; header[i].name; i++)
365 header[i].namelen = strlen(header[i].name);
367 for (i = 0; header[i].name; i++) {
368 int len = header[i].namelen;
369 if (!strncasecmp(line, header[i].name, len) &&
370 line[len] == ':' && isspace(line[len + 1])) {
371 /* Unwrap inline B and Q encoding, and optionally
372 * normalize the meta information to utf8.
374 decode_header_bq(line + len + 2);
375 header[i].func(line + len + 2);
381 static void check_subheader_line(char *line)
383 static struct header_def header[] = {
384 { "Content-Type", handle_subcontent_type },
385 { "Content-Transfer-Encoding",
386 handle_content_transfer_encoding },
389 check_header(line, header);
391 static void check_header_line(char *line)
393 static struct header_def header[] = {
394 { "From", handle_from },
395 { "Date", handle_date },
396 { "Subject", handle_subject },
397 { "Content-Type", handle_content_type },
398 { "Content-Transfer-Encoding",
399 handle_content_transfer_encoding },
402 check_header(line, header);
405 static int is_rfc2822_header(char *line)
408 * The section that defines the loosest possible
409 * field name is "3.6.8 Optional fields".
411 * optional-field = field-name ":" unstructured CRLF
412 * field-name = 1*ftext
413 * ftext = %d33-57 / %59-126
417 while ((ch = *cp++)) {
420 if ((33 <= ch && ch <= 57) ||
421 (59 <= ch && ch <= 126))
428 static int read_one_header_line(char *line, int sz, FILE *in)
433 if (fgets(line + ofs, sz - ofs, in) == NULL)
435 len = eatspace(line + ofs);
436 if ((len == 0) || !is_rfc2822_header(line)) {
437 /* Re-add the newline */
438 line[ofs + len] = '\n';
439 line[ofs + len + 1] = '\0';
443 /* Yuck, 2822 header "folding" */
444 peek = fgetc(in); ungetc(peek, in);
445 if (peek != ' ' && peek != '\t')
448 /* Count mbox From headers as headers */
449 if (!ofs && !memcmp(line, "From ", 5))
454 static unsigned hexval(int c)
456 if (c >= '0' && c <= '9')
458 if (c >= 'a' && c <= 'f')
460 if (c >= 'A' && c <= 'F')
465 static int decode_q_segment(char *in, char *ot, char *ep, int rfc2047)
468 while ((c = *in++) != 0 && (in <= ep)) {
472 break; /* drop trailing newline */
473 *ot++ = ((hexval(d) << 4) | hexval(*in++));
476 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
484 static int decode_b_segment(char *in, char *ot, char *ep)
486 /* Decode in..ep, possibly in-place to ot */
487 int c, pos = 0, acc = 0;
489 while ((c = *in++) != 0 && (in <= ep)) {
494 else if ('A' <= c && c <= 'Z')
496 else if ('a' <= c && c <= 'z')
498 else if ('0' <= c && c <= '9')
501 /* padding is almost like (c == 0), except we do
502 * not output NUL resulting only from it;
503 * for now we just trust the data.
508 continue; /* garbage */
514 *ot++ = (acc | (c >> 4));
518 *ot++ = (acc | (c >> 2));
531 static void convert_to_utf8(char *line, char *charset)
535 size_t insize, outsize, nrc;
536 char outbuf[4096]; /* cheat */
537 static char latin_one[] = "latin1";
538 char *input_charset = *charset ? charset : latin_one;
539 iconv_t conv = iconv_open(metainfo_charset, input_charset);
541 if (conv == (iconv_t) -1) {
542 static int warned_latin1_once = 0;
543 if (input_charset != latin_one) {
544 fprintf(stderr, "cannot convert from %s to %s\n",
545 input_charset, metainfo_charset);
548 else if (!warned_latin1_once) {
549 warned_latin1_once = 1;
550 fprintf(stderr, "tried to convert from %s to %s, "
551 "but your iconv does not work with it.\n",
552 input_charset, metainfo_charset);
559 outsize = sizeof(outbuf);
560 nrc = iconv(conv, &in, &insize, &out, &outsize);
562 if (nrc == (size_t) -1)
565 strcpy(line, outbuf);
569 static void decode_header_bq(char *it)
571 char *in, *out, *ep, *cp, *sp;
576 while ((ep = strstr(in, "=?")) != NULL) {
578 char charset_q[256], piecebuf[256];
586 * ep : "=?iso-2022-jp?B?GyR...?= foo"
587 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
590 cp = strchr(ep, '?');
592 return; /* no munging */
593 for (sp = ep; sp < cp; sp++)
594 charset_q[sp - ep] = tolower(*sp);
595 charset_q[cp - ep] = 0;
597 if (!encoding || cp[2] != '?')
598 return; /* no munging */
599 ep = strstr(cp + 3, "?=");
601 return; /* no munging */
602 switch (tolower(encoding)) {
604 return; /* no munging */
606 sz = decode_b_segment(cp + 3, piecebuf, ep);
609 sz = decode_q_segment(cp + 3, piecebuf, ep, 1);
614 if (metainfo_charset)
615 convert_to_utf8(piecebuf, charset_q);
616 strcpy(out, piecebuf);
624 static void decode_transfer_encoding(char *line)
628 switch (transfer_encoding) {
630 ep = line + strlen(line);
631 decode_q_segment(line, line, ep, 0);
634 ep = line + strlen(line);
635 decode_b_segment(line, line, ep);
642 static void handle_info(void)
646 sub = cleanup_subject(subject);
649 cleanup_space(email);
652 fprintf(fout, "Author: %s\nEmail: %s\nSubject: %s\nDate: %s\n\n",
653 name, email, sub, date);
656 /* We are inside message body and have read line[] already.
657 * Spit out the commit log.
659 static int handle_commit_msg(int *seen)
664 if (!memcmp("diff -", line, 6) ||
665 !memcmp("---", line, 3) ||
666 !memcmp("Index: ", line, 7))
668 if ((multipart_boundary[0] && is_multipart_boundary(line))) {
669 /* We come here when the first part had only
670 * the commit message without any patch. We
671 * pretend we have not seen this line yet, and
672 * go back to the loop.
677 /* Unwrap transfer encoding and optionally
678 * normalize the log message to UTF-8.
680 decode_transfer_encoding(line);
681 if (metainfo_charset)
682 convert_to_utf8(line, charset);
684 handle_inbody_header(seen, line);
685 if (!(*seen & SEEN_PREFIX))
688 fputs(line, cmitmsg);
689 } while (fgets(line, sizeof(line), fin) != NULL);
695 /* We have done the commit message and have the first
696 * line of the patch in line[].
698 static void handle_patch(void)
701 if (multipart_boundary[0] && is_multipart_boundary(line))
703 /* Only unwrap transfer encoding but otherwise do not
704 * do anything. We do *NOT* want UTF-8 conversion
705 * here; we are dealing with the user payload.
707 decode_transfer_encoding(line);
708 fputs(line, patchfile);
710 } while (fgets(line, sizeof(line), fin) != NULL);
713 /* multipart boundary and transfer encoding are set up for us, and we
714 * are at the end of the sub header. do equivalent of handle_body up
715 * to the next boundary without closing patchfile --- we will expect
716 * that the first part to contain commit message and a patch, and
717 * handle other parts as pure patches.
719 static int handle_multipart_one_part(int *seen)
723 while (fgets(line, sizeof(line), fin) != NULL) {
726 if (is_multipart_boundary(line))
728 if (handle_commit_msg(seen))
738 static void handle_multipart_body(void)
743 /* Skip up to the first boundary */
744 while (fgets(line, sizeof(line), fin) != NULL)
745 if (is_multipart_boundary(line)) {
751 /* We are on boundary line. Start slurping the subhead. */
753 int hdr = read_one_header_line(line, sizeof(line), fin);
755 if (handle_multipart_one_part(&seen) < 0)
757 /* Reset per part headers */
758 transfer_encoding = TE_DONTCARE;
762 check_subheader_line(line);
766 fprintf(stderr, "No patch found\n");
771 /* Non multipart message */
772 static void handle_body(void)
776 handle_commit_msg(&seen);
780 fprintf(stderr, "No patch found\n");
785 int mailinfo(FILE *in, FILE *out, int ks, const char *encoding,
786 const char *msg, const char *patch)
789 metainfo_charset = encoding;
793 cmitmsg = fopen(msg, "w");
798 patchfile = fopen(patch, "w");
805 int hdr = read_one_header_line(line, sizeof(line), fin);
807 if (multipart_boundary[0])
808 handle_multipart_body();
814 check_header_line(line);
820 static const char mailinfo_usage[] =
821 "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
823 int cmd_mailinfo(int argc, const char **argv, char **envp)
825 /* NEEDSWORK: might want to do the optional .git/ directory
828 git_config(git_default_config);
830 while (1 < argc && argv[1][0] == '-') {
831 if (!strcmp(argv[1], "-k"))
833 else if (!strcmp(argv[1], "-u"))
834 metainfo_charset = git_commit_encoding;
835 else if (!strncmp(argv[1], "--encoding=", 11))
836 metainfo_charset = argv[1] + 11;
838 usage(mailinfo_usage);
843 usage(mailinfo_usage);
845 return !!mailinfo(stdin, stdout, keep_subject, metainfo_charset, argv[1], argv[2]);