git-blame.el: Autoupdate while editing
[tgit.git] / builtin-mailinfo.c
blob583da38b6750185eb38f04d91555aa75ee4a77b0
1 /*
2 * Another stupid program, this one parsing the headers of an
3 * email to figure out authorship and subject
4 */
5 #include "cache.h"
6 #include "builtin.h"
7 #include "utf8.h"
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 date[1000];
15 static char name[1000];
16 static char email[1000];
17 static char subject[1000];
19 static enum {
20 TE_DONTCARE, TE_QP, TE_BASE64,
21 } transfer_encoding;
22 static char charset[256];
24 static char multipart_boundary[1000];
25 static int multipart_boundary_len;
26 static int patch_lines;
28 static char *sanity_check(char *name, char *email)
30 int len = strlen(name);
31 if (len < 3 || len > 60)
32 return email;
33 if (strchr(name, '@') || strchr(name, '<') || strchr(name, '>'))
34 return email;
35 return name;
38 static int bogus_from(char *line)
40 /* John Doe <johndoe> */
41 char *bra, *ket, *dst, *cp;
43 /* This is fallback, so do not bother if we already have an
44 * e-mail address.
46 if (*email)
47 return 0;
49 bra = strchr(line, '<');
50 if (!bra)
51 return 0;
52 ket = strchr(bra, '>');
53 if (!ket)
54 return 0;
56 for (dst = email, cp = bra+1; cp < ket; )
57 *dst++ = *cp++;
58 *dst = 0;
59 for (cp = line; isspace(*cp); cp++)
61 for (bra--; isspace(*bra); bra--)
62 *bra = 0;
63 cp = sanity_check(cp, email);
64 strcpy(name, cp);
65 return 1;
68 static int handle_from(char *in_line)
70 char line[1000];
71 char *at;
72 char *dst;
74 strcpy(line, in_line);
75 at = strchr(line, '@');
76 if (!at)
77 return bogus_from(line);
80 * If we already have one email, don't take any confusing lines
82 if (*email && strchr(at+1, '@'))
83 return 0;
85 /* Pick up the string around '@', possibly delimited with <>
86 * pair; that is the email part. White them out while copying.
88 while (at > line) {
89 char c = at[-1];
90 if (isspace(c))
91 break;
92 if (c == '<') {
93 at[-1] = ' ';
94 break;
96 at--;
98 dst = email;
99 for (;;) {
100 unsigned char c = *at;
101 if (!c || c == '>' || isspace(c)) {
102 if (c == '>')
103 *at = ' ';
104 break;
106 *at++ = ' ';
107 *dst++ = c;
109 *dst++ = 0;
111 /* The remainder is name. It could be "John Doe <john.doe@xz>"
112 * or "john.doe@xz (John Doe)", but we have whited out the
113 * email part, so trim from both ends, possibly removing
114 * the () pair at the end.
116 at = line + strlen(line);
117 while (at > line) {
118 unsigned char c = *--at;
119 if (!isspace(c)) {
120 at[(c == ')') ? 0 : 1] = 0;
121 break;
125 at = line;
126 for (;;) {
127 unsigned char c = *at;
128 if (!c || !isspace(c)) {
129 if (c == '(')
130 at++;
131 break;
133 at++;
135 at = sanity_check(at, email);
136 strcpy(name, at);
137 return 1;
140 static int handle_date(char *line)
142 strcpy(date, line);
143 return 0;
146 static int handle_subject(char *line)
148 strcpy(subject, line);
149 return 0;
152 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
153 * to have enough heuristics to grok MIME encoded patches often found
154 * on our mailing lists. For example, we do not even treat header lines
155 * case insensitively.
158 static int slurp_attr(const char *line, const char *name, char *attr)
160 const char *ends, *ap = strcasestr(line, name);
161 size_t sz;
163 if (!ap) {
164 *attr = 0;
165 return 0;
167 ap += strlen(name);
168 if (*ap == '"') {
169 ap++;
170 ends = "\"";
172 else
173 ends = "; \t";
174 sz = strcspn(ap, ends);
175 memcpy(attr, ap, sz);
176 attr[sz] = 0;
177 return 1;
180 static int handle_subcontent_type(char *line)
182 /* We do not want to mess with boundary. Note that we do not
183 * handle nested multipart.
185 if (strcasestr(line, "boundary=")) {
186 fprintf(stderr, "Not handling nested multipart message.\n");
187 exit(1);
189 slurp_attr(line, "charset=", charset);
190 if (*charset) {
191 int i, c;
192 for (i = 0; (c = charset[i]) != 0; i++)
193 charset[i] = tolower(c);
195 return 0;
198 static int handle_content_type(char *line)
200 *multipart_boundary = 0;
201 if (slurp_attr(line, "boundary=", multipart_boundary + 2)) {
202 memcpy(multipart_boundary, "--", 2);
203 multipart_boundary_len = strlen(multipart_boundary);
205 slurp_attr(line, "charset=", charset);
206 return 0;
209 static int handle_content_transfer_encoding(char *line)
211 if (strcasestr(line, "base64"))
212 transfer_encoding = TE_BASE64;
213 else if (strcasestr(line, "quoted-printable"))
214 transfer_encoding = TE_QP;
215 else
216 transfer_encoding = TE_DONTCARE;
217 return 0;
220 static int is_multipart_boundary(const char *line)
222 return (!memcmp(line, multipart_boundary, multipart_boundary_len));
225 static int eatspace(char *line)
227 int len = strlen(line);
228 while (len > 0 && isspace(line[len-1]))
229 line[--len] = 0;
230 return len;
233 #define SEEN_FROM 01
234 #define SEEN_DATE 02
235 #define SEEN_SUBJECT 04
236 #define SEEN_BOGUS_UNIX_FROM 010
237 #define SEEN_PREFIX 020
239 /* First lines of body can have From:, Date:, and Subject: or empty */
240 static void handle_inbody_header(int *seen, char *line)
242 if (*seen & SEEN_PREFIX)
243 return;
244 if (isspace(*line)) {
245 char *cp;
246 for (cp = line + 1; *cp; cp++) {
247 if (!isspace(*cp))
248 break;
250 if (!*cp)
251 return;
253 if (!memcmp(">From", line, 5) && isspace(line[5])) {
254 if (!(*seen & SEEN_BOGUS_UNIX_FROM)) {
255 *seen |= SEEN_BOGUS_UNIX_FROM;
256 return;
259 if (!memcmp("From:", line, 5) && isspace(line[5])) {
260 if (!(*seen & SEEN_FROM) && handle_from(line+6)) {
261 *seen |= SEEN_FROM;
262 return;
265 if (!memcmp("Date:", line, 5) && isspace(line[5])) {
266 if (!(*seen & SEEN_DATE)) {
267 handle_date(line+6);
268 *seen |= SEEN_DATE;
269 return;
272 if (!memcmp("Subject:", line, 8) && isspace(line[8])) {
273 if (!(*seen & SEEN_SUBJECT)) {
274 handle_subject(line+9);
275 *seen |= SEEN_SUBJECT;
276 return;
279 if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
280 if (!(*seen & SEEN_SUBJECT)) {
281 handle_subject(line);
282 *seen |= SEEN_SUBJECT;
283 return;
286 *seen |= SEEN_PREFIX;
289 static char *cleanup_subject(char *subject)
291 if (keep_subject)
292 return subject;
293 for (;;) {
294 char *p;
295 int len, remove;
296 switch (*subject) {
297 case 'r': case 'R':
298 if (!memcmp("e:", subject+1, 2)) {
299 subject +=3;
300 continue;
302 break;
303 case ' ': case '\t': case ':':
304 subject++;
305 continue;
307 case '[':
308 p = strchr(subject, ']');
309 if (!p) {
310 subject++;
311 continue;
313 len = strlen(p);
314 remove = p - subject;
315 if (remove <= len *2) {
316 subject = p+1;
317 continue;
319 break;
321 eatspace(subject);
322 return subject;
326 static void cleanup_space(char *buf)
328 unsigned char c;
329 while ((c = *buf) != 0) {
330 buf++;
331 if (isspace(c)) {
332 buf[-1] = ' ';
333 c = *buf;
334 while (isspace(c)) {
335 int len = strlen(buf);
336 memmove(buf, buf+1, len);
337 c = *buf;
343 static void decode_header(char *it);
344 typedef int (*header_fn_t)(char *);
345 struct header_def {
346 const char *name;
347 header_fn_t func;
348 int namelen;
351 static void check_header(char *line, struct header_def *header)
353 int i;
355 if (header[0].namelen <= 0) {
356 for (i = 0; header[i].name; i++)
357 header[i].namelen = strlen(header[i].name);
359 for (i = 0; header[i].name; i++) {
360 int len = header[i].namelen;
361 if (!strncasecmp(line, header[i].name, len) &&
362 line[len] == ':' && isspace(line[len + 1])) {
363 /* Unwrap inline B and Q encoding, and optionally
364 * normalize the meta information to utf8.
366 decode_header(line + len + 2);
367 header[i].func(line + len + 2);
368 break;
373 static void check_subheader_line(char *line)
375 static struct header_def header[] = {
376 { "Content-Type", handle_subcontent_type },
377 { "Content-Transfer-Encoding",
378 handle_content_transfer_encoding },
379 { NULL },
381 check_header(line, header);
383 static void check_header_line(char *line)
385 static struct header_def header[] = {
386 { "From", handle_from },
387 { "Date", handle_date },
388 { "Subject", handle_subject },
389 { "Content-Type", handle_content_type },
390 { "Content-Transfer-Encoding",
391 handle_content_transfer_encoding },
392 { NULL },
394 check_header(line, header);
397 static int is_rfc2822_header(char *line)
400 * The section that defines the loosest possible
401 * field name is "3.6.8 Optional fields".
403 * optional-field = field-name ":" unstructured CRLF
404 * field-name = 1*ftext
405 * ftext = %d33-57 / %59-126
407 int ch;
408 char *cp = line;
409 while ((ch = *cp++)) {
410 if (ch == ':')
411 return cp != line;
412 if ((33 <= ch && ch <= 57) ||
413 (59 <= ch && ch <= 126))
414 continue;
415 break;
417 return 0;
420 static int read_one_header_line(char *line, int sz, FILE *in)
422 int ofs = 0;
423 while (ofs < sz) {
424 int peek, len;
425 if (fgets(line + ofs, sz - ofs, in) == NULL)
426 break;
427 len = eatspace(line + ofs);
428 if ((len == 0) || !is_rfc2822_header(line)) {
429 /* Re-add the newline */
430 line[ofs + len] = '\n';
431 line[ofs + len + 1] = '\0';
432 break;
434 ofs += len;
435 /* Yuck, 2822 header "folding" */
436 peek = fgetc(in); ungetc(peek, in);
437 if (peek != ' ' && peek != '\t')
438 break;
440 /* Count mbox From headers as headers */
441 if (!ofs && (!memcmp(line, "From ", 5) || !memcmp(line, ">From ", 6)))
442 ofs = 1;
443 return ofs;
446 static int decode_q_segment(char *in, char *ot, char *ep, int rfc2047)
448 int c;
449 while ((c = *in++) != 0 && (in <= ep)) {
450 if (c == '=') {
451 int d = *in++;
452 if (d == '\n' || !d)
453 break; /* drop trailing newline */
454 *ot++ = ((hexval(d) << 4) | hexval(*in++));
455 continue;
457 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
458 c = 0x20;
459 *ot++ = c;
461 *ot = 0;
462 return 0;
465 static int decode_b_segment(char *in, char *ot, char *ep)
467 /* Decode in..ep, possibly in-place to ot */
468 int c, pos = 0, acc = 0;
470 while ((c = *in++) != 0 && (in <= ep)) {
471 if (c == '+')
472 c = 62;
473 else if (c == '/')
474 c = 63;
475 else if ('A' <= c && c <= 'Z')
476 c -= 'A';
477 else if ('a' <= c && c <= 'z')
478 c -= 'a' - 26;
479 else if ('0' <= c && c <= '9')
480 c -= '0' - 52;
481 else if (c == '=') {
482 /* padding is almost like (c == 0), except we do
483 * not output NUL resulting only from it;
484 * for now we just trust the data.
486 c = 0;
488 else
489 continue; /* garbage */
490 switch (pos++) {
491 case 0:
492 acc = (c << 2);
493 break;
494 case 1:
495 *ot++ = (acc | (c >> 4));
496 acc = (c & 15) << 4;
497 break;
498 case 2:
499 *ot++ = (acc | (c >> 2));
500 acc = (c & 3) << 6;
501 break;
502 case 3:
503 *ot++ = (acc | c);
504 acc = pos = 0;
505 break;
508 *ot = 0;
509 return 0;
512 static void convert_to_utf8(char *line, char *charset)
514 static char latin_one[] = "latin1";
515 char *input_charset = *charset ? charset : latin_one;
516 char *out = reencode_string(line, metainfo_charset, input_charset);
518 if (!out)
519 die("cannot convert from %s to %s\n",
520 input_charset, metainfo_charset);
521 strcpy(line, out);
522 free(out);
525 static int decode_header_bq(char *it)
527 char *in, *out, *ep, *cp, *sp;
528 char outbuf[1000];
529 int rfc2047 = 0;
531 in = it;
532 out = outbuf;
533 while ((ep = strstr(in, "=?")) != NULL) {
534 int sz, encoding;
535 char charset_q[256], piecebuf[256];
536 rfc2047 = 1;
538 if (in != ep) {
539 sz = ep - in;
540 memcpy(out, in, sz);
541 out += sz;
542 in += sz;
544 /* E.g.
545 * ep : "=?iso-2022-jp?B?GyR...?= foo"
546 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
548 ep += 2;
549 cp = strchr(ep, '?');
550 if (!cp)
551 return rfc2047; /* no munging */
552 for (sp = ep; sp < cp; sp++)
553 charset_q[sp - ep] = tolower(*sp);
554 charset_q[cp - ep] = 0;
555 encoding = cp[1];
556 if (!encoding || cp[2] != '?')
557 return rfc2047; /* no munging */
558 ep = strstr(cp + 3, "?=");
559 if (!ep)
560 return rfc2047; /* no munging */
561 switch (tolower(encoding)) {
562 default:
563 return rfc2047; /* no munging */
564 case 'b':
565 sz = decode_b_segment(cp + 3, piecebuf, ep);
566 break;
567 case 'q':
568 sz = decode_q_segment(cp + 3, piecebuf, ep, 1);
569 break;
571 if (sz < 0)
572 return rfc2047;
573 if (metainfo_charset)
574 convert_to_utf8(piecebuf, charset_q);
575 strcpy(out, piecebuf);
576 out += strlen(out);
577 in = ep + 2;
579 strcpy(out, in);
580 strcpy(it, outbuf);
581 return rfc2047;
584 static void decode_header(char *it)
587 if (decode_header_bq(it))
588 return;
589 /* otherwise "it" is a straight copy of the input.
590 * This can be binary guck but there is no charset specified.
592 if (metainfo_charset)
593 convert_to_utf8(it, "");
596 static void decode_transfer_encoding(char *line)
598 char *ep;
600 switch (transfer_encoding) {
601 case TE_QP:
602 ep = line + strlen(line);
603 decode_q_segment(line, line, ep, 0);
604 break;
605 case TE_BASE64:
606 ep = line + strlen(line);
607 decode_b_segment(line, line, ep);
608 break;
609 case TE_DONTCARE:
610 break;
614 static void handle_info(void)
616 char *sub;
618 sub = cleanup_subject(subject);
619 cleanup_space(name);
620 cleanup_space(date);
621 cleanup_space(email);
622 cleanup_space(sub);
624 fprintf(fout, "Author: %s\nEmail: %s\nSubject: %s\nDate: %s\n\n",
625 name, email, sub, date);
628 /* We are inside message body and have read line[] already.
629 * Spit out the commit log.
631 static int handle_commit_msg(int *seen)
633 if (!cmitmsg)
634 return 0;
635 do {
636 if (!memcmp("diff -", line, 6) ||
637 !memcmp("---", line, 3) ||
638 !memcmp("Index: ", line, 7))
639 break;
640 if ((multipart_boundary[0] && is_multipart_boundary(line))) {
641 /* We come here when the first part had only
642 * the commit message without any patch. We
643 * pretend we have not seen this line yet, and
644 * go back to the loop.
646 return 1;
649 /* Unwrap transfer encoding and optionally
650 * normalize the log message to UTF-8.
652 decode_transfer_encoding(line);
653 if (metainfo_charset)
654 convert_to_utf8(line, charset);
656 handle_inbody_header(seen, line);
657 if (!(*seen & SEEN_PREFIX))
658 continue;
660 fputs(line, cmitmsg);
661 } while (fgets(line, sizeof(line), fin) != NULL);
662 fclose(cmitmsg);
663 cmitmsg = NULL;
664 return 0;
667 /* We have done the commit message and have the first
668 * line of the patch in line[].
670 static void handle_patch(void)
672 do {
673 if (multipart_boundary[0] && is_multipart_boundary(line))
674 break;
675 /* Only unwrap transfer encoding but otherwise do not
676 * do anything. We do *NOT* want UTF-8 conversion
677 * here; we are dealing with the user payload.
679 decode_transfer_encoding(line);
680 fputs(line, patchfile);
681 patch_lines++;
682 } while (fgets(line, sizeof(line), fin) != NULL);
685 /* multipart boundary and transfer encoding are set up for us, and we
686 * are at the end of the sub header. do equivalent of handle_body up
687 * to the next boundary without closing patchfile --- we will expect
688 * that the first part to contain commit message and a patch, and
689 * handle other parts as pure patches.
691 static int handle_multipart_one_part(int *seen)
693 int n = 0;
695 while (fgets(line, sizeof(line), fin) != NULL) {
696 again:
697 n++;
698 if (is_multipart_boundary(line))
699 break;
700 if (handle_commit_msg(seen))
701 goto again;
702 handle_patch();
703 break;
705 if (n == 0)
706 return -1;
707 return 0;
710 static void handle_multipart_body(void)
712 int seen = 0;
713 int part_num = 0;
715 /* Skip up to the first boundary */
716 while (fgets(line, sizeof(line), fin) != NULL)
717 if (is_multipart_boundary(line)) {
718 part_num = 1;
719 break;
721 if (!part_num)
722 return;
723 /* We are on boundary line. Start slurping the subhead. */
724 while (1) {
725 int hdr = read_one_header_line(line, sizeof(line), fin);
726 if (!hdr) {
727 if (handle_multipart_one_part(&seen) < 0)
728 return;
729 /* Reset per part headers */
730 transfer_encoding = TE_DONTCARE;
731 charset[0] = 0;
733 else
734 check_subheader_line(line);
736 fclose(patchfile);
737 if (!patch_lines) {
738 fprintf(stderr, "No patch found\n");
739 exit(1);
743 /* Non multipart message */
744 static void handle_body(void)
746 int seen = 0;
748 handle_commit_msg(&seen);
749 handle_patch();
750 fclose(patchfile);
751 if (!patch_lines) {
752 fprintf(stderr, "No patch found\n");
753 exit(1);
757 int mailinfo(FILE *in, FILE *out, int ks, const char *encoding,
758 const char *msg, const char *patch)
760 keep_subject = ks;
761 metainfo_charset = encoding;
762 fin = in;
763 fout = out;
765 cmitmsg = fopen(msg, "w");
766 if (!cmitmsg) {
767 perror(msg);
768 return -1;
770 patchfile = fopen(patch, "w");
771 if (!patchfile) {
772 perror(patch);
773 fclose(cmitmsg);
774 return -1;
776 while (1) {
777 int hdr = read_one_header_line(line, sizeof(line), fin);
778 if (!hdr) {
779 if (multipart_boundary[0])
780 handle_multipart_body();
781 else
782 handle_body();
783 handle_info();
784 break;
786 check_header_line(line);
789 return 0;
792 static const char mailinfo_usage[] =
793 "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
795 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
797 const char *def_charset;
799 /* NEEDSWORK: might want to do the optional .git/ directory
800 * discovery
802 git_config(git_default_config);
804 def_charset = (git_commit_encoding ? git_commit_encoding : "utf-8");
805 metainfo_charset = def_charset;
807 while (1 < argc && argv[1][0] == '-') {
808 if (!strcmp(argv[1], "-k"))
809 keep_subject = 1;
810 else if (!strcmp(argv[1], "-u"))
811 metainfo_charset = def_charset;
812 else if (!strcmp(argv[1], "-n"))
813 metainfo_charset = NULL;
814 else if (!strncmp(argv[1], "--encoding=", 11))
815 metainfo_charset = argv[1] + 11;
816 else
817 usage(mailinfo_usage);
818 argc--; argv++;
821 if (argc != 3)
822 usage(mailinfo_usage);
824 return !!mailinfo(stdin, stdout, keep_subject, metainfo_charset, argv[1], argv[2]);