Trap exit to clean up created directory if clone fails.
[git/jnareb-git.git] / mailinfo.c
blobff2d4d403826b035a7bb123dc74a50af9a76e353
1 /*
2 * Another stupid program, this one parsing the headers of an
3 * email to figure out authorship and subject
4 */
5 #define _GNU_SOURCE
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <ctype.h>
10 #include <iconv.h>
11 #include "git-compat-util.h"
12 #include "cache.h"
14 static FILE *cmitmsg, *patchfile;
16 static int keep_subject = 0;
17 static char *metainfo_charset = NULL;
18 static char line[1000];
19 static char date[1000];
20 static char name[1000];
21 static char email[1000];
22 static char subject[1000];
24 static enum {
25 TE_DONTCARE, TE_QP, TE_BASE64,
26 } transfer_encoding;
27 static char charset[256];
29 static char multipart_boundary[1000];
30 static int multipart_boundary_len;
31 static int patch_lines = 0;
33 static char *sanity_check(char *name, char *email)
35 int len = strlen(name);
36 if (len < 3 || len > 60)
37 return email;
38 if (strchr(name, '@') || strchr(name, '<') || strchr(name, '>'))
39 return email;
40 return name;
43 static int bogus_from(char *line)
45 /* John Doe <johndoe> */
46 char *bra, *ket, *dst, *cp;
48 /* This is fallback, so do not bother if we already have an
49 * e-mail address.
50 */
51 if (*email)
52 return 0;
54 bra = strchr(line, '<');
55 if (!bra)
56 return 0;
57 ket = strchr(bra, '>');
58 if (!ket)
59 return 0;
61 for (dst = email, cp = bra+1; cp < ket; )
62 *dst++ = *cp++;
63 *dst = 0;
64 for (cp = line; isspace(*cp); cp++)
66 for (bra--; isspace(*bra); bra--)
67 *bra = 0;
68 cp = sanity_check(cp, email);
69 strcpy(name, cp);
70 return 1;
73 static int handle_from(char *line)
75 char *at = strchr(line, '@');
76 char *dst;
78 if (!at)
79 return bogus_from(line);
82 * If we already have one email, don't take any confusing lines
84 if (*email && strchr(at+1, '@'))
85 return 0;
87 /* Pick up the string around '@', possibly delimited with <>
88 * pair; that is the email part. White them out while copying.
90 while (at > line) {
91 char c = at[-1];
92 if (isspace(c))
93 break;
94 if (c == '<') {
95 at[-1] = ' ';
96 break;
98 at--;
100 dst = email;
101 for (;;) {
102 unsigned char c = *at;
103 if (!c || c == '>' || isspace(c)) {
104 if (c == '>')
105 *at = ' ';
106 break;
108 *at++ = ' ';
109 *dst++ = c;
111 *dst++ = 0;
113 /* The remainder is name. It could be "John Doe <john.doe@xz>"
114 * or "john.doe@xz (John Doe)", but we have whited out the
115 * email part, so trim from both ends, possibly removing
116 * the () pair at the end.
118 at = line + strlen(line);
119 while (at > line) {
120 unsigned char c = *--at;
121 if (!isspace(c)) {
122 at[(c == ')') ? 0 : 1] = 0;
123 break;
127 at = line;
128 for (;;) {
129 unsigned char c = *at;
130 if (!c || !isspace(c)) {
131 if (c == '(')
132 at++;
133 break;
135 at++;
137 at = sanity_check(at, email);
138 strcpy(name, at);
139 return 1;
142 static int handle_date(char *line)
144 strcpy(date, line);
145 return 0;
148 static int handle_subject(char *line)
150 strcpy(subject, line);
151 return 0;
154 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
155 * to have enough heuristics to grok MIME encoded patches often found
156 * on our mailing lists. For example, we do not even treat header lines
157 * case insensitively.
160 static int slurp_attr(const char *line, const char *name, char *attr)
162 char *ends, *ap = strcasestr(line, name);
163 size_t sz;
165 if (!ap) {
166 *attr = 0;
167 return 0;
169 ap += strlen(name);
170 if (*ap == '"') {
171 ap++;
172 ends = "\"";
174 else
175 ends = "; \t";
176 sz = strcspn(ap, ends);
177 memcpy(attr, ap, sz);
178 attr[sz] = 0;
179 return 1;
182 static int handle_subcontent_type(char *line)
184 /* We do not want to mess with boundary. Note that we do not
185 * handle nested multipart.
187 if (strcasestr(line, "boundary=")) {
188 fprintf(stderr, "Not handling nested multipart message.\n");
189 exit(1);
191 slurp_attr(line, "charset=", charset);
192 if (*charset) {
193 int i, c;
194 for (i = 0; (c = charset[i]) != 0; i++)
195 charset[i] = tolower(c);
197 return 0;
200 static int handle_content_type(char *line)
202 *multipart_boundary = 0;
203 if (slurp_attr(line, "boundary=", multipart_boundary + 2)) {
204 memcpy(multipart_boundary, "--", 2);
205 multipart_boundary_len = strlen(multipart_boundary);
207 slurp_attr(line, "charset=", charset);
208 return 0;
211 static int handle_content_transfer_encoding(char *line)
213 if (strcasestr(line, "base64"))
214 transfer_encoding = TE_BASE64;
215 else if (strcasestr(line, "quoted-printable"))
216 transfer_encoding = TE_QP;
217 else
218 transfer_encoding = TE_DONTCARE;
219 return 0;
222 static int is_multipart_boundary(const char *line)
224 return (!memcmp(line, multipart_boundary, multipart_boundary_len));
227 static int eatspace(char *line)
229 int len = strlen(line);
230 while (len > 0 && isspace(line[len-1]))
231 line[--len] = 0;
232 return len;
235 #define SEEN_FROM 01
236 #define SEEN_DATE 02
237 #define SEEN_SUBJECT 04
239 /* First lines of body can have From:, Date:, and Subject: */
240 static int handle_inbody_header(int *seen, char *line)
242 if (!memcmp("From:", line, 5) && isspace(line[5])) {
243 if (!(*seen & SEEN_FROM) && handle_from(line+6)) {
244 *seen |= SEEN_FROM;
245 return 1;
248 if (!memcmp("Date:", line, 5) && isspace(line[5])) {
249 if (!(*seen & SEEN_DATE)) {
250 handle_date(line+6);
251 *seen |= SEEN_DATE;
252 return 1;
255 if (!memcmp("Subject:", line, 8) && isspace(line[8])) {
256 if (!(*seen & SEEN_SUBJECT)) {
257 handle_subject(line+9);
258 *seen |= SEEN_SUBJECT;
259 return 1;
262 if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
263 if (!(*seen & SEEN_SUBJECT)) {
264 handle_subject(line);
265 *seen |= SEEN_SUBJECT;
266 return 1;
269 return 0;
272 static char *cleanup_subject(char *subject)
274 if (keep_subject)
275 return subject;
276 for (;;) {
277 char *p;
278 int len, remove;
279 switch (*subject) {
280 case 'r': case 'R':
281 if (!memcmp("e:", subject+1, 2)) {
282 subject +=3;
283 continue;
285 break;
286 case ' ': case '\t': case ':':
287 subject++;
288 continue;
290 case '[':
291 p = strchr(subject, ']');
292 if (!p) {
293 subject++;
294 continue;
296 len = strlen(p);
297 remove = p - subject;
298 if (remove <= len *2) {
299 subject = p+1;
300 continue;
302 break;
304 return subject;
308 static void cleanup_space(char *buf)
310 unsigned char c;
311 while ((c = *buf) != 0) {
312 buf++;
313 if (isspace(c)) {
314 buf[-1] = ' ';
315 c = *buf;
316 while (isspace(c)) {
317 int len = strlen(buf);
318 memmove(buf, buf+1, len);
319 c = *buf;
325 typedef int (*header_fn_t)(char *);
326 struct header_def {
327 const char *name;
328 header_fn_t func;
329 int namelen;
332 static void check_header(char *line, int len, struct header_def *header)
334 int i;
336 if (header[0].namelen <= 0) {
337 for (i = 0; header[i].name; i++)
338 header[i].namelen = strlen(header[i].name);
340 for (i = 0; header[i].name; i++) {
341 int len = header[i].namelen;
342 if (!strncasecmp(line, header[i].name, len) &&
343 line[len] == ':' && isspace(line[len + 1])) {
344 header[i].func(line + len + 2);
345 break;
350 static void check_subheader_line(char *line, int len)
352 static struct header_def header[] = {
353 { "Content-Type", handle_subcontent_type },
354 { "Content-Transfer-Encoding",
355 handle_content_transfer_encoding },
356 { NULL },
358 check_header(line, len, header);
360 static void check_header_line(char *line, int len)
362 static struct header_def header[] = {
363 { "From", handle_from },
364 { "Date", handle_date },
365 { "Subject", handle_subject },
366 { "Content-Type", handle_content_type },
367 { "Content-Transfer-Encoding",
368 handle_content_transfer_encoding },
369 { NULL },
371 check_header(line, len, header);
374 static int read_one_header_line(char *line, int sz, FILE *in)
376 int ofs = 0;
377 while (ofs < sz) {
378 int peek, len;
379 if (fgets(line + ofs, sz - ofs, in) == NULL)
380 return ofs;
381 len = eatspace(line + ofs);
382 if (len == 0)
383 return ofs;
384 peek = fgetc(in); ungetc(peek, in);
385 if (peek == ' ' || peek == '\t') {
386 /* Yuck, 2822 header "folding" */
387 ofs += len;
388 continue;
390 return ofs + len;
392 return ofs;
395 static unsigned hexval(int c)
397 if (c >= '0' && c <= '9')
398 return c - '0';
399 if (c >= 'a' && c <= 'f')
400 return c - 'a' + 10;
401 if (c >= 'A' && c <= 'F')
402 return c - 'A' + 10;
403 return ~0;
406 static int decode_q_segment(char *in, char *ot, char *ep)
408 int c;
409 while ((c = *in++) != 0 && (in <= ep)) {
410 if (c == '=') {
411 int d = *in++;
412 if (d == '\n' || !d)
413 break; /* drop trailing newline */
414 *ot++ = ((hexval(d) << 4) | hexval(*in++));
416 else
417 *ot++ = c;
419 *ot = 0;
420 return 0;
423 static int decode_b_segment(char *in, char *ot, char *ep)
425 /* Decode in..ep, possibly in-place to ot */
426 int c, pos = 0, acc = 0;
428 while ((c = *in++) != 0 && (in <= ep)) {
429 if (c == '+')
430 c = 62;
431 else if (c == '/')
432 c = 63;
433 else if ('A' <= c && c <= 'Z')
434 c -= 'A';
435 else if ('a' <= c && c <= 'z')
436 c -= 'a' - 26;
437 else if ('0' <= c && c <= '9')
438 c -= '0' - 52;
439 else if (c == '=') {
440 /* padding is almost like (c == 0), except we do
441 * not output NUL resulting only from it;
442 * for now we just trust the data.
444 c = 0;
446 else
447 continue; /* garbage */
448 switch (pos++) {
449 case 0:
450 acc = (c << 2);
451 break;
452 case 1:
453 *ot++ = (acc | (c >> 4));
454 acc = (c & 15) << 4;
455 break;
456 case 2:
457 *ot++ = (acc | (c >> 2));
458 acc = (c & 3) << 6;
459 break;
460 case 3:
461 *ot++ = (acc | c);
462 acc = pos = 0;
463 break;
466 *ot = 0;
467 return 0;
470 static void convert_to_utf8(char *line, char *charset)
472 char *in, *out;
473 size_t insize, outsize, nrc;
474 char outbuf[4096]; /* cheat */
475 static char latin_one[] = "latin1";
476 char *input_charset = *charset ? charset : latin_one;
477 iconv_t conv = iconv_open(metainfo_charset, input_charset);
479 if (conv == (iconv_t) -1) {
480 static int warned_latin1_once = 0;
481 if (input_charset != latin_one) {
482 fprintf(stderr, "cannot convert from %s to %s\n",
483 input_charset, metainfo_charset);
484 *charset = 0;
486 else if (!warned_latin1_once) {
487 warned_latin1_once = 1;
488 fprintf(stderr, "tried to convert from %s to %s, "
489 "but your iconv does not work with it.\n",
490 input_charset, metainfo_charset);
492 return;
494 in = line;
495 insize = strlen(in);
496 out = outbuf;
497 outsize = sizeof(outbuf);
498 nrc = iconv(conv, &in, &insize, &out, &outsize);
499 iconv_close(conv);
500 if (nrc == (size_t) -1)
501 return;
502 *out = 0;
503 strcpy(line, outbuf);
506 static void decode_header_bq(char *it)
508 char *in, *out, *ep, *cp, *sp;
509 char outbuf[1000];
511 in = it;
512 out = outbuf;
513 while ((ep = strstr(in, "=?")) != NULL) {
514 int sz, encoding;
515 char charset_q[256], piecebuf[256];
516 if (in != ep) {
517 sz = ep - in;
518 memcpy(out, in, sz);
519 out += sz;
520 in += sz;
522 /* E.g.
523 * ep : "=?iso-2022-jp?B?GyR...?= foo"
524 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
526 ep += 2;
527 cp = strchr(ep, '?');
528 if (!cp)
529 return; /* no munging */
530 for (sp = ep; sp < cp; sp++)
531 charset_q[sp - ep] = tolower(*sp);
532 charset_q[cp - ep] = 0;
533 encoding = cp[1];
534 if (!encoding || cp[2] != '?')
535 return; /* no munging */
536 ep = strstr(cp + 3, "?=");
537 if (!ep)
538 return; /* no munging */
539 switch (tolower(encoding)) {
540 default:
541 return; /* no munging */
542 case 'b':
543 sz = decode_b_segment(cp + 3, piecebuf, ep);
544 break;
545 case 'q':
546 sz = decode_q_segment(cp + 3, piecebuf, ep);
547 break;
549 if (sz < 0)
550 return;
551 if (metainfo_charset)
552 convert_to_utf8(piecebuf, charset_q);
553 strcpy(out, piecebuf);
554 out += strlen(out);
555 in = ep + 2;
557 strcpy(out, in);
558 strcpy(it, outbuf);
561 static void decode_transfer_encoding(char *line)
563 char *ep;
565 switch (transfer_encoding) {
566 case TE_QP:
567 ep = line + strlen(line);
568 decode_q_segment(line, line, ep);
569 break;
570 case TE_BASE64:
571 ep = line + strlen(line);
572 decode_b_segment(line, line, ep);
573 break;
574 case TE_DONTCARE:
575 break;
579 static void handle_info(void)
581 char *sub;
582 static int done_info = 0;
584 if (done_info)
585 return;
587 done_info = 1;
588 sub = cleanup_subject(subject);
589 cleanup_space(name);
590 cleanup_space(date);
591 cleanup_space(email);
592 cleanup_space(sub);
594 /* Unwrap inline B and Q encoding, and optionally
595 * normalize the meta information to utf8.
597 decode_header_bq(name);
598 decode_header_bq(date);
599 decode_header_bq(email);
600 decode_header_bq(sub);
601 printf("Author: %s\nEmail: %s\nSubject: %s\nDate: %s\n\n",
602 name, email, sub, date);
605 /* We are inside message body and have read line[] already.
606 * Spit out the commit log.
608 static int handle_commit_msg(void)
610 if (!cmitmsg)
611 return 0;
612 do {
613 if (!memcmp("diff -", line, 6) ||
614 !memcmp("---", line, 3) ||
615 !memcmp("Index: ", line, 7))
616 break;
617 if ((multipart_boundary[0] && is_multipart_boundary(line))) {
618 /* We come here when the first part had only
619 * the commit message without any patch. We
620 * pretend we have not seen this line yet, and
621 * go back to the loop.
623 return 1;
626 /* Unwrap transfer encoding and optionally
627 * normalize the log message to UTF-8.
629 decode_transfer_encoding(line);
630 if (metainfo_charset)
631 convert_to_utf8(line, charset);
632 fputs(line, cmitmsg);
633 } while (fgets(line, sizeof(line), stdin) != NULL);
634 fclose(cmitmsg);
635 cmitmsg = NULL;
636 return 0;
639 /* We have done the commit message and have the first
640 * line of the patch in line[].
642 static void handle_patch(void)
644 do {
645 if (multipart_boundary[0] && is_multipart_boundary(line))
646 break;
647 /* Only unwrap transfer encoding but otherwise do not
648 * do anything. We do *NOT* want UTF-8 conversion
649 * here; we are dealing with the user payload.
651 decode_transfer_encoding(line);
652 fputs(line, patchfile);
653 patch_lines++;
654 } while (fgets(line, sizeof(line), stdin) != NULL);
657 /* multipart boundary and transfer encoding are set up for us, and we
658 * are at the end of the sub header. do equivalent of handle_body up
659 * to the next boundary without closing patchfile --- we will expect
660 * that the first part to contain commit message and a patch, and
661 * handle other parts as pure patches.
663 static int handle_multipart_one_part(void)
665 int seen = 0;
666 int n = 0;
667 int len;
669 while (fgets(line, sizeof(line), stdin) != NULL) {
670 again:
671 len = eatspace(line);
672 n++;
673 if (!len)
674 continue;
675 if (is_multipart_boundary(line))
676 break;
677 if (0 <= seen && handle_inbody_header(&seen, line))
678 continue;
679 seen = -1; /* no more inbody headers */
680 line[len] = '\n';
681 handle_info();
682 if (handle_commit_msg())
683 goto again;
684 handle_patch();
685 break;
687 if (n == 0)
688 return -1;
689 return 0;
692 static void handle_multipart_body(void)
694 int part_num = 0;
696 /* Skip up to the first boundary */
697 while (fgets(line, sizeof(line), stdin) != NULL)
698 if (is_multipart_boundary(line)) {
699 part_num = 1;
700 break;
702 if (!part_num)
703 return;
704 /* We are on boundary line. Start slurping the subhead. */
705 while (1) {
706 int len = read_one_header_line(line, sizeof(line), stdin);
707 if (!len) {
708 if (handle_multipart_one_part() < 0)
709 return;
710 /* Reset per part headers */
711 transfer_encoding = TE_DONTCARE;
712 charset[0] = 0;
714 else
715 check_subheader_line(line, len);
717 fclose(patchfile);
718 if (!patch_lines) {
719 fprintf(stderr, "No patch found\n");
720 exit(1);
724 /* Non multipart message */
725 static void handle_body(void)
727 int seen = 0;
729 while (fgets(line, sizeof(line), stdin) != NULL) {
730 int len = eatspace(line);
731 if (!len)
732 continue;
733 if (0 <= seen && handle_inbody_header(&seen, line))
734 continue;
735 seen = -1; /* no more inbody headers */
736 line[len] = '\n';
737 handle_info();
738 handle_commit_msg();
739 handle_patch();
740 break;
742 fclose(patchfile);
743 if (!patch_lines) {
744 fprintf(stderr, "No patch found\n");
745 exit(1);
749 static const char mailinfo_usage[] =
750 "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
752 int main(int argc, char **argv)
754 /* NEEDSWORK: might want to do the optional .git/ directory
755 * discovery
757 git_config(git_default_config);
759 while (1 < argc && argv[1][0] == '-') {
760 if (!strcmp(argv[1], "-k"))
761 keep_subject = 1;
762 else if (!strcmp(argv[1], "-u"))
763 metainfo_charset = git_commit_encoding;
764 else if (!strncmp(argv[1], "--encoding=", 11))
765 metainfo_charset = argv[1] + 11;
766 else
767 usage(mailinfo_usage);
768 argc--; argv++;
771 if (argc != 3)
772 usage(mailinfo_usage);
773 cmitmsg = fopen(argv[1], "w");
774 if (!cmitmsg) {
775 perror(argv[1]);
776 exit(1);
778 patchfile = fopen(argv[2], "w");
779 if (!patchfile) {
780 perror(argv[2]);
781 exit(1);
783 while (1) {
784 int len = read_one_header_line(line, sizeof(line), stdin);
785 if (!len) {
786 if (multipart_boundary[0])
787 handle_multipart_body();
788 else
789 handle_body();
790 break;
792 check_header_line(line, len);
794 return 0;