Merge branch 'js/shallow'
[tgit.git] / builtin-mailinfo.c
blobe6472293d47611d415276f6057227d9c93788f63
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"
8 static FILE *cmitmsg, *patchfile, *fin, *fout;
10 static int keep_subject;
11 static const char *metainfo_charset;
12 static char line[1000];
13 static char date[1000];
14 static char name[1000];
15 static char email[1000];
16 static char subject[1000];
18 static enum {
19 TE_DONTCARE, TE_QP, TE_BASE64,
20 } transfer_encoding;
21 static char charset[256];
23 static char multipart_boundary[1000];
24 static int multipart_boundary_len;
25 static int patch_lines;
27 static char *sanity_check(char *name, char *email)
29 int len = strlen(name);
30 if (len < 3 || len > 60)
31 return email;
32 if (strchr(name, '@') || strchr(name, '<') || strchr(name, '>'))
33 return email;
34 return name;
37 static int bogus_from(char *line)
39 /* John Doe <johndoe> */
40 char *bra, *ket, *dst, *cp;
42 /* This is fallback, so do not bother if we already have an
43 * e-mail address.
45 if (*email)
46 return 0;
48 bra = strchr(line, '<');
49 if (!bra)
50 return 0;
51 ket = strchr(bra, '>');
52 if (!ket)
53 return 0;
55 for (dst = email, cp = bra+1; cp < ket; )
56 *dst++ = *cp++;
57 *dst = 0;
58 for (cp = line; isspace(*cp); cp++)
60 for (bra--; isspace(*bra); bra--)
61 *bra = 0;
62 cp = sanity_check(cp, email);
63 strcpy(name, cp);
64 return 1;
67 static int handle_from(char *in_line)
69 char line[1000];
70 char *at;
71 char *dst;
73 strcpy(line, in_line);
74 at = strchr(line, '@');
75 if (!at)
76 return bogus_from(line);
79 * If we already have one email, don't take any confusing lines
81 if (*email && strchr(at+1, '@'))
82 return 0;
84 /* Pick up the string around '@', possibly delimited with <>
85 * pair; that is the email part. White them out while copying.
87 while (at > line) {
88 char c = at[-1];
89 if (isspace(c))
90 break;
91 if (c == '<') {
92 at[-1] = ' ';
93 break;
95 at--;
97 dst = email;
98 for (;;) {
99 unsigned char c = *at;
100 if (!c || c == '>' || isspace(c)) {
101 if (c == '>')
102 *at = ' ';
103 break;
105 *at++ = ' ';
106 *dst++ = c;
108 *dst++ = 0;
110 /* The remainder is name. It could be "John Doe <john.doe@xz>"
111 * or "john.doe@xz (John Doe)", but we have whited out the
112 * email part, so trim from both ends, possibly removing
113 * the () pair at the end.
115 at = line + strlen(line);
116 while (at > line) {
117 unsigned char c = *--at;
118 if (!isspace(c)) {
119 at[(c == ')') ? 0 : 1] = 0;
120 break;
124 at = line;
125 for (;;) {
126 unsigned char c = *at;
127 if (!c || !isspace(c)) {
128 if (c == '(')
129 at++;
130 break;
132 at++;
134 at = sanity_check(at, email);
135 strcpy(name, at);
136 return 1;
139 static int handle_date(char *line)
141 strcpy(date, line);
142 return 0;
145 static int handle_subject(char *line)
147 strcpy(subject, line);
148 return 0;
151 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
152 * to have enough heuristics to grok MIME encoded patches often found
153 * on our mailing lists. For example, we do not even treat header lines
154 * case insensitively.
157 static int slurp_attr(const char *line, const char *name, char *attr)
159 const char *ends, *ap = strcasestr(line, name);
160 size_t sz;
162 if (!ap) {
163 *attr = 0;
164 return 0;
166 ap += strlen(name);
167 if (*ap == '"') {
168 ap++;
169 ends = "\"";
171 else
172 ends = "; \t";
173 sz = strcspn(ap, ends);
174 memcpy(attr, ap, sz);
175 attr[sz] = 0;
176 return 1;
179 static int handle_subcontent_type(char *line)
181 /* We do not want to mess with boundary. Note that we do not
182 * handle nested multipart.
184 if (strcasestr(line, "boundary=")) {
185 fprintf(stderr, "Not handling nested multipart message.\n");
186 exit(1);
188 slurp_attr(line, "charset=", charset);
189 if (*charset) {
190 int i, c;
191 for (i = 0; (c = charset[i]) != 0; i++)
192 charset[i] = tolower(c);
194 return 0;
197 static int handle_content_type(char *line)
199 *multipart_boundary = 0;
200 if (slurp_attr(line, "boundary=", multipart_boundary + 2)) {
201 memcpy(multipart_boundary, "--", 2);
202 multipart_boundary_len = strlen(multipart_boundary);
204 slurp_attr(line, "charset=", charset);
205 return 0;
208 static int handle_content_transfer_encoding(char *line)
210 if (strcasestr(line, "base64"))
211 transfer_encoding = TE_BASE64;
212 else if (strcasestr(line, "quoted-printable"))
213 transfer_encoding = TE_QP;
214 else
215 transfer_encoding = TE_DONTCARE;
216 return 0;
219 static int is_multipart_boundary(const char *line)
221 return (!memcmp(line, multipart_boundary, multipart_boundary_len));
224 static int eatspace(char *line)
226 int len = strlen(line);
227 while (len > 0 && isspace(line[len-1]))
228 line[--len] = 0;
229 return len;
232 #define SEEN_FROM 01
233 #define SEEN_DATE 02
234 #define SEEN_SUBJECT 04
235 #define SEEN_BOGUS_UNIX_FROM 010
236 #define SEEN_PREFIX 020
238 /* First lines of body can have From:, Date:, and Subject: or empty */
239 static void handle_inbody_header(int *seen, char *line)
241 if (*seen & SEEN_PREFIX)
242 return;
243 if (isspace(*line)) {
244 char *cp;
245 for (cp = line + 1; *cp; cp++) {
246 if (!isspace(*cp))
247 break;
249 if (!*cp)
250 return;
252 if (!memcmp(">From", line, 5) && isspace(line[5])) {
253 if (!(*seen & SEEN_BOGUS_UNIX_FROM)) {
254 *seen |= SEEN_BOGUS_UNIX_FROM;
255 return;
258 if (!memcmp("From:", line, 5) && isspace(line[5])) {
259 if (!(*seen & SEEN_FROM) && handle_from(line+6)) {
260 *seen |= SEEN_FROM;
261 return;
264 if (!memcmp("Date:", line, 5) && isspace(line[5])) {
265 if (!(*seen & SEEN_DATE)) {
266 handle_date(line+6);
267 *seen |= SEEN_DATE;
268 return;
271 if (!memcmp("Subject:", line, 8) && isspace(line[8])) {
272 if (!(*seen & SEEN_SUBJECT)) {
273 handle_subject(line+9);
274 *seen |= SEEN_SUBJECT;
275 return;
278 if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
279 if (!(*seen & SEEN_SUBJECT)) {
280 handle_subject(line);
281 *seen |= SEEN_SUBJECT;
282 return;
285 *seen |= SEEN_PREFIX;
288 static char *cleanup_subject(char *subject)
290 if (keep_subject)
291 return subject;
292 for (;;) {
293 char *p;
294 int len, remove;
295 switch (*subject) {
296 case 'r': case 'R':
297 if (!memcmp("e:", subject+1, 2)) {
298 subject +=3;
299 continue;
301 break;
302 case ' ': case '\t': case ':':
303 subject++;
304 continue;
306 case '[':
307 p = strchr(subject, ']');
308 if (!p) {
309 subject++;
310 continue;
312 len = strlen(p);
313 remove = p - subject;
314 if (remove <= len *2) {
315 subject = p+1;
316 continue;
318 break;
320 eatspace(subject);
321 return subject;
325 static void cleanup_space(char *buf)
327 unsigned char c;
328 while ((c = *buf) != 0) {
329 buf++;
330 if (isspace(c)) {
331 buf[-1] = ' ';
332 c = *buf;
333 while (isspace(c)) {
334 int len = strlen(buf);
335 memmove(buf, buf+1, len);
336 c = *buf;
342 static void decode_header(char *it);
343 typedef int (*header_fn_t)(char *);
344 struct header_def {
345 const char *name;
346 header_fn_t func;
347 int namelen;
350 static void check_header(char *line, struct header_def *header)
352 int i;
354 if (header[0].namelen <= 0) {
355 for (i = 0; header[i].name; i++)
356 header[i].namelen = strlen(header[i].name);
358 for (i = 0; header[i].name; i++) {
359 int len = header[i].namelen;
360 if (!strncasecmp(line, header[i].name, len) &&
361 line[len] == ':' && isspace(line[len + 1])) {
362 /* Unwrap inline B and Q encoding, and optionally
363 * normalize the meta information to utf8.
365 decode_header(line + len + 2);
366 header[i].func(line + len + 2);
367 break;
372 static void check_subheader_line(char *line)
374 static struct header_def header[] = {
375 { "Content-Type", handle_subcontent_type },
376 { "Content-Transfer-Encoding",
377 handle_content_transfer_encoding },
378 { NULL },
380 check_header(line, header);
382 static void check_header_line(char *line)
384 static struct header_def header[] = {
385 { "From", handle_from },
386 { "Date", handle_date },
387 { "Subject", handle_subject },
388 { "Content-Type", handle_content_type },
389 { "Content-Transfer-Encoding",
390 handle_content_transfer_encoding },
391 { NULL },
393 check_header(line, header);
396 static int is_rfc2822_header(char *line)
399 * The section that defines the loosest possible
400 * field name is "3.6.8 Optional fields".
402 * optional-field = field-name ":" unstructured CRLF
403 * field-name = 1*ftext
404 * ftext = %d33-57 / %59-126
406 int ch;
407 char *cp = line;
408 while ((ch = *cp++)) {
409 if (ch == ':')
410 return cp != line;
411 if ((33 <= ch && ch <= 57) ||
412 (59 <= ch && ch <= 126))
413 continue;
414 break;
416 return 0;
419 static int read_one_header_line(char *line, int sz, FILE *in)
421 int ofs = 0;
422 while (ofs < sz) {
423 int peek, len;
424 if (fgets(line + ofs, sz - ofs, in) == NULL)
425 break;
426 len = eatspace(line + ofs);
427 if ((len == 0) || !is_rfc2822_header(line)) {
428 /* Re-add the newline */
429 line[ofs + len] = '\n';
430 line[ofs + len + 1] = '\0';
431 break;
433 ofs += len;
434 /* Yuck, 2822 header "folding" */
435 peek = fgetc(in); ungetc(peek, in);
436 if (peek != ' ' && peek != '\t')
437 break;
439 /* Count mbox From headers as headers */
440 if (!ofs && (!memcmp(line, "From ", 5) || !memcmp(line, ">From ", 6)))
441 ofs = 1;
442 return ofs;
445 static int decode_q_segment(char *in, char *ot, char *ep, int rfc2047)
447 int c;
448 while ((c = *in++) != 0 && (in <= ep)) {
449 if (c == '=') {
450 int d = *in++;
451 if (d == '\n' || !d)
452 break; /* drop trailing newline */
453 *ot++ = ((hexval(d) << 4) | hexval(*in++));
454 continue;
456 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
457 c = 0x20;
458 *ot++ = c;
460 *ot = 0;
461 return 0;
464 static int decode_b_segment(char *in, char *ot, char *ep)
466 /* Decode in..ep, possibly in-place to ot */
467 int c, pos = 0, acc = 0;
469 while ((c = *in++) != 0 && (in <= ep)) {
470 if (c == '+')
471 c = 62;
472 else if (c == '/')
473 c = 63;
474 else if ('A' <= c && c <= 'Z')
475 c -= 'A';
476 else if ('a' <= c && c <= 'z')
477 c -= 'a' - 26;
478 else if ('0' <= c && c <= '9')
479 c -= '0' - 52;
480 else if (c == '=') {
481 /* padding is almost like (c == 0), except we do
482 * not output NUL resulting only from it;
483 * for now we just trust the data.
485 c = 0;
487 else
488 continue; /* garbage */
489 switch (pos++) {
490 case 0:
491 acc = (c << 2);
492 break;
493 case 1:
494 *ot++ = (acc | (c >> 4));
495 acc = (c & 15) << 4;
496 break;
497 case 2:
498 *ot++ = (acc | (c >> 2));
499 acc = (c & 3) << 6;
500 break;
501 case 3:
502 *ot++ = (acc | c);
503 acc = pos = 0;
504 break;
507 *ot = 0;
508 return 0;
511 static void convert_to_utf8(char *line, char *charset)
513 #ifndef NO_ICONV
514 char *in, *out;
515 size_t insize, outsize, nrc;
516 char outbuf[4096]; /* cheat */
517 static char latin_one[] = "latin1";
518 char *input_charset = *charset ? charset : latin_one;
519 iconv_t conv = iconv_open(metainfo_charset, input_charset);
521 if (conv == (iconv_t) -1) {
522 static int warned_latin1_once = 0;
523 if (input_charset != latin_one) {
524 fprintf(stderr, "cannot convert from %s to %s\n",
525 input_charset, metainfo_charset);
526 *charset = 0;
528 else if (!warned_latin1_once) {
529 warned_latin1_once = 1;
530 fprintf(stderr, "tried to convert from %s to %s, "
531 "but your iconv does not work with it.\n",
532 input_charset, metainfo_charset);
534 return;
536 in = line;
537 insize = strlen(in);
538 out = outbuf;
539 outsize = sizeof(outbuf);
540 nrc = iconv(conv, &in, &insize, &out, &outsize);
541 iconv_close(conv);
542 if (nrc == (size_t) -1)
543 return;
544 *out = 0;
545 strcpy(line, outbuf);
546 #endif
549 static int decode_header_bq(char *it)
551 char *in, *out, *ep, *cp, *sp;
552 char outbuf[1000];
553 int rfc2047 = 0;
555 in = it;
556 out = outbuf;
557 while ((ep = strstr(in, "=?")) != NULL) {
558 int sz, encoding;
559 char charset_q[256], piecebuf[256];
560 rfc2047 = 1;
562 if (in != ep) {
563 sz = ep - in;
564 memcpy(out, in, sz);
565 out += sz;
566 in += sz;
568 /* E.g.
569 * ep : "=?iso-2022-jp?B?GyR...?= foo"
570 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
572 ep += 2;
573 cp = strchr(ep, '?');
574 if (!cp)
575 return rfc2047; /* no munging */
576 for (sp = ep; sp < cp; sp++)
577 charset_q[sp - ep] = tolower(*sp);
578 charset_q[cp - ep] = 0;
579 encoding = cp[1];
580 if (!encoding || cp[2] != '?')
581 return rfc2047; /* no munging */
582 ep = strstr(cp + 3, "?=");
583 if (!ep)
584 return rfc2047; /* no munging */
585 switch (tolower(encoding)) {
586 default:
587 return rfc2047; /* no munging */
588 case 'b':
589 sz = decode_b_segment(cp + 3, piecebuf, ep);
590 break;
591 case 'q':
592 sz = decode_q_segment(cp + 3, piecebuf, ep, 1);
593 break;
595 if (sz < 0)
596 return rfc2047;
597 if (metainfo_charset)
598 convert_to_utf8(piecebuf, charset_q);
599 strcpy(out, piecebuf);
600 out += strlen(out);
601 in = ep + 2;
603 strcpy(out, in);
604 strcpy(it, outbuf);
605 return rfc2047;
608 static void decode_header(char *it)
611 if (decode_header_bq(it))
612 return;
613 /* otherwise "it" is a straight copy of the input.
614 * This can be binary guck but there is no charset specified.
616 if (metainfo_charset)
617 convert_to_utf8(it, "");
620 static void decode_transfer_encoding(char *line)
622 char *ep;
624 switch (transfer_encoding) {
625 case TE_QP:
626 ep = line + strlen(line);
627 decode_q_segment(line, line, ep, 0);
628 break;
629 case TE_BASE64:
630 ep = line + strlen(line);
631 decode_b_segment(line, line, ep);
632 break;
633 case TE_DONTCARE:
634 break;
638 static void handle_info(void)
640 char *sub;
642 sub = cleanup_subject(subject);
643 cleanup_space(name);
644 cleanup_space(date);
645 cleanup_space(email);
646 cleanup_space(sub);
648 fprintf(fout, "Author: %s\nEmail: %s\nSubject: %s\nDate: %s\n\n",
649 name, email, sub, date);
652 /* We are inside message body and have read line[] already.
653 * Spit out the commit log.
655 static int handle_commit_msg(int *seen)
657 if (!cmitmsg)
658 return 0;
659 do {
660 if (!memcmp("diff -", line, 6) ||
661 !memcmp("---", line, 3) ||
662 !memcmp("Index: ", line, 7))
663 break;
664 if ((multipart_boundary[0] && is_multipart_boundary(line))) {
665 /* We come here when the first part had only
666 * the commit message without any patch. We
667 * pretend we have not seen this line yet, and
668 * go back to the loop.
670 return 1;
673 /* Unwrap transfer encoding and optionally
674 * normalize the log message to UTF-8.
676 decode_transfer_encoding(line);
677 if (metainfo_charset)
678 convert_to_utf8(line, charset);
680 handle_inbody_header(seen, line);
681 if (!(*seen & SEEN_PREFIX))
682 continue;
684 fputs(line, cmitmsg);
685 } while (fgets(line, sizeof(line), fin) != NULL);
686 fclose(cmitmsg);
687 cmitmsg = NULL;
688 return 0;
691 /* We have done the commit message and have the first
692 * line of the patch in line[].
694 static void handle_patch(void)
696 do {
697 if (multipart_boundary[0] && is_multipart_boundary(line))
698 break;
699 /* Only unwrap transfer encoding but otherwise do not
700 * do anything. We do *NOT* want UTF-8 conversion
701 * here; we are dealing with the user payload.
703 decode_transfer_encoding(line);
704 fputs(line, patchfile);
705 patch_lines++;
706 } while (fgets(line, sizeof(line), fin) != NULL);
709 /* multipart boundary and transfer encoding are set up for us, and we
710 * are at the end of the sub header. do equivalent of handle_body up
711 * to the next boundary without closing patchfile --- we will expect
712 * that the first part to contain commit message and a patch, and
713 * handle other parts as pure patches.
715 static int handle_multipart_one_part(int *seen)
717 int n = 0;
719 while (fgets(line, sizeof(line), fin) != NULL) {
720 again:
721 n++;
722 if (is_multipart_boundary(line))
723 break;
724 if (handle_commit_msg(seen))
725 goto again;
726 handle_patch();
727 break;
729 if (n == 0)
730 return -1;
731 return 0;
734 static void handle_multipart_body(void)
736 int seen = 0;
737 int part_num = 0;
739 /* Skip up to the first boundary */
740 while (fgets(line, sizeof(line), fin) != NULL)
741 if (is_multipart_boundary(line)) {
742 part_num = 1;
743 break;
745 if (!part_num)
746 return;
747 /* We are on boundary line. Start slurping the subhead. */
748 while (1) {
749 int hdr = read_one_header_line(line, sizeof(line), fin);
750 if (!hdr) {
751 if (handle_multipart_one_part(&seen) < 0)
752 return;
753 /* Reset per part headers */
754 transfer_encoding = TE_DONTCARE;
755 charset[0] = 0;
757 else
758 check_subheader_line(line);
760 fclose(patchfile);
761 if (!patch_lines) {
762 fprintf(stderr, "No patch found\n");
763 exit(1);
767 /* Non multipart message */
768 static void handle_body(void)
770 int seen = 0;
772 handle_commit_msg(&seen);
773 handle_patch();
774 fclose(patchfile);
775 if (!patch_lines) {
776 fprintf(stderr, "No patch found\n");
777 exit(1);
781 int mailinfo(FILE *in, FILE *out, int ks, const char *encoding,
782 const char *msg, const char *patch)
784 keep_subject = ks;
785 metainfo_charset = encoding;
786 fin = in;
787 fout = out;
789 cmitmsg = fopen(msg, "w");
790 if (!cmitmsg) {
791 perror(msg);
792 return -1;
794 patchfile = fopen(patch, "w");
795 if (!patchfile) {
796 perror(patch);
797 fclose(cmitmsg);
798 return -1;
800 while (1) {
801 int hdr = read_one_header_line(line, sizeof(line), fin);
802 if (!hdr) {
803 if (multipart_boundary[0])
804 handle_multipart_body();
805 else
806 handle_body();
807 handle_info();
808 break;
810 check_header_line(line);
813 return 0;
816 static const char mailinfo_usage[] =
817 "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
819 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
821 /* NEEDSWORK: might want to do the optional .git/ directory
822 * discovery
824 git_config(git_default_config);
826 while (1 < argc && argv[1][0] == '-') {
827 if (!strcmp(argv[1], "-k"))
828 keep_subject = 1;
829 else if (!strcmp(argv[1], "-u"))
830 metainfo_charset = git_commit_encoding;
831 else if (!strncmp(argv[1], "--encoding=", 11))
832 metainfo_charset = argv[1] + 11;
833 else
834 usage(mailinfo_usage);
835 argc--; argv++;
838 if (argc != 3)
839 usage(mailinfo_usage);
841 return !!mailinfo(stdin, stdout, keep_subject, metainfo_charset, argv[1], argv[2]);