In handle_body only read a line if we don't already have one.
[git/mjg.git] / mailinfo.c
blob99989c25b28a70043b866ab21cf6d88c45bc68ed
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 #ifndef NO_ICONV
11 #include <iconv.h>
12 #endif
13 #include "git-compat-util.h"
14 #include "cache.h"
16 static FILE *cmitmsg, *patchfile;
18 static int keep_subject = 0;
19 static char *metainfo_charset = NULL;
20 static char line[1000];
21 static char date[1000];
22 static char name[1000];
23 static char email[1000];
24 static char subject[1000];
26 static enum {
27 TE_DONTCARE, TE_QP, TE_BASE64,
28 } transfer_encoding;
29 static char charset[256];
31 static char multipart_boundary[1000];
32 static int multipart_boundary_len;
33 static int patch_lines = 0;
35 static char *sanity_check(char *name, char *email)
37 int len = strlen(name);
38 if (len < 3 || len > 60)
39 return email;
40 if (strchr(name, '@') || strchr(name, '<') || strchr(name, '>'))
41 return email;
42 return name;
45 static int bogus_from(char *line)
47 /* John Doe <johndoe> */
48 char *bra, *ket, *dst, *cp;
50 /* This is fallback, so do not bother if we already have an
51 * e-mail address.
52 */
53 if (*email)
54 return 0;
56 bra = strchr(line, '<');
57 if (!bra)
58 return 0;
59 ket = strchr(bra, '>');
60 if (!ket)
61 return 0;
63 for (dst = email, cp = bra+1; cp < ket; )
64 *dst++ = *cp++;
65 *dst = 0;
66 for (cp = line; isspace(*cp); cp++)
68 for (bra--; isspace(*bra); bra--)
69 *bra = 0;
70 cp = sanity_check(cp, email);
71 strcpy(name, cp);
72 return 1;
75 static int handle_from(char *line)
77 char *at = strchr(line, '@');
78 char *dst;
80 if (!at)
81 return bogus_from(line);
84 * If we already have one email, don't take any confusing lines
86 if (*email && strchr(at+1, '@'))
87 return 0;
89 /* Pick up the string around '@', possibly delimited with <>
90 * pair; that is the email part. White them out while copying.
92 while (at > line) {
93 char c = at[-1];
94 if (isspace(c))
95 break;
96 if (c == '<') {
97 at[-1] = ' ';
98 break;
100 at--;
102 dst = email;
103 for (;;) {
104 unsigned char c = *at;
105 if (!c || c == '>' || isspace(c)) {
106 if (c == '>')
107 *at = ' ';
108 break;
110 *at++ = ' ';
111 *dst++ = c;
113 *dst++ = 0;
115 /* The remainder is name. It could be "John Doe <john.doe@xz>"
116 * or "john.doe@xz (John Doe)", but we have whited out the
117 * email part, so trim from both ends, possibly removing
118 * the () pair at the end.
120 at = line + strlen(line);
121 while (at > line) {
122 unsigned char c = *--at;
123 if (!isspace(c)) {
124 at[(c == ')') ? 0 : 1] = 0;
125 break;
129 at = line;
130 for (;;) {
131 unsigned char c = *at;
132 if (!c || !isspace(c)) {
133 if (c == '(')
134 at++;
135 break;
137 at++;
139 at = sanity_check(at, email);
140 strcpy(name, at);
141 return 1;
144 static int handle_date(char *line)
146 strcpy(date, line);
147 return 0;
150 static int handle_subject(char *line)
152 strcpy(subject, line);
153 return 0;
156 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
157 * to have enough heuristics to grok MIME encoded patches often found
158 * on our mailing lists. For example, we do not even treat header lines
159 * case insensitively.
162 static int slurp_attr(const char *line, const char *name, char *attr)
164 char *ends, *ap = strcasestr(line, name);
165 size_t sz;
167 if (!ap) {
168 *attr = 0;
169 return 0;
171 ap += strlen(name);
172 if (*ap == '"') {
173 ap++;
174 ends = "\"";
176 else
177 ends = "; \t";
178 sz = strcspn(ap, ends);
179 memcpy(attr, ap, sz);
180 attr[sz] = 0;
181 return 1;
184 static int handle_subcontent_type(char *line)
186 /* We do not want to mess with boundary. Note that we do not
187 * handle nested multipart.
189 if (strcasestr(line, "boundary=")) {
190 fprintf(stderr, "Not handling nested multipart message.\n");
191 exit(1);
193 slurp_attr(line, "charset=", charset);
194 if (*charset) {
195 int i, c;
196 for (i = 0; (c = charset[i]) != 0; i++)
197 charset[i] = tolower(c);
199 return 0;
202 static int handle_content_type(char *line)
204 *multipart_boundary = 0;
205 if (slurp_attr(line, "boundary=", multipart_boundary + 2)) {
206 memcpy(multipart_boundary, "--", 2);
207 multipart_boundary_len = strlen(multipart_boundary);
209 slurp_attr(line, "charset=", charset);
210 return 0;
213 static int handle_content_transfer_encoding(char *line)
215 if (strcasestr(line, "base64"))
216 transfer_encoding = TE_BASE64;
217 else if (strcasestr(line, "quoted-printable"))
218 transfer_encoding = TE_QP;
219 else
220 transfer_encoding = TE_DONTCARE;
221 return 0;
224 static int is_multipart_boundary(const char *line)
226 return (!memcmp(line, multipart_boundary, multipart_boundary_len));
229 static int eatspace(char *line)
231 int len = strlen(line);
232 while (len > 0 && isspace(line[len-1]))
233 line[--len] = 0;
234 return len;
237 #define SEEN_FROM 01
238 #define SEEN_DATE 02
239 #define SEEN_SUBJECT 04
240 #define SEEN_PREFIX 0x08
242 /* First lines of body can have From:, Date:, and Subject: */
243 static void handle_inbody_header(int *seen, char *line)
245 if (*seen & SEEN_PREFIX)
246 return;
247 if (!memcmp("From:", line, 5) && isspace(line[5])) {
248 if (!(*seen & SEEN_FROM) && handle_from(line+6)) {
249 *seen |= SEEN_FROM;
250 return;
253 if (!memcmp("Date:", line, 5) && isspace(line[5])) {
254 if (!(*seen & SEEN_DATE)) {
255 handle_date(line+6);
256 *seen |= SEEN_DATE;
257 return;
260 if (!memcmp("Subject:", line, 8) && isspace(line[8])) {
261 if (!(*seen & SEEN_SUBJECT)) {
262 handle_subject(line+9);
263 *seen |= SEEN_SUBJECT;
264 return;
267 if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
268 if (!(*seen & SEEN_SUBJECT)) {
269 handle_subject(line);
270 *seen |= SEEN_SUBJECT;
271 return;
274 *seen |= SEEN_PREFIX;
277 static char *cleanup_subject(char *subject)
279 if (keep_subject)
280 return subject;
281 for (;;) {
282 char *p;
283 int len, remove;
284 switch (*subject) {
285 case 'r': case 'R':
286 if (!memcmp("e:", subject+1, 2)) {
287 subject +=3;
288 continue;
290 break;
291 case ' ': case '\t': case ':':
292 subject++;
293 continue;
295 case '[':
296 p = strchr(subject, ']');
297 if (!p) {
298 subject++;
299 continue;
301 len = strlen(p);
302 remove = p - subject;
303 if (remove <= len *2) {
304 subject = p+1;
305 continue;
307 break;
309 return subject;
313 static void cleanup_space(char *buf)
315 unsigned char c;
316 while ((c = *buf) != 0) {
317 buf++;
318 if (isspace(c)) {
319 buf[-1] = ' ';
320 c = *buf;
321 while (isspace(c)) {
322 int len = strlen(buf);
323 memmove(buf, buf+1, len);
324 c = *buf;
330 static void decode_header_bq(char *it);
331 typedef int (*header_fn_t)(char *);
332 struct header_def {
333 const char *name;
334 header_fn_t func;
335 int namelen;
338 static void check_header(char *line, struct header_def *header)
340 int i;
342 if (header[0].namelen <= 0) {
343 for (i = 0; header[i].name; i++)
344 header[i].namelen = strlen(header[i].name);
346 for (i = 0; header[i].name; i++) {
347 int len = header[i].namelen;
348 if (!strncasecmp(line, header[i].name, len) &&
349 line[len] == ':' && isspace(line[len + 1])) {
350 /* Unwrap inline B and Q encoding, and optionally
351 * normalize the meta information to utf8.
353 decode_header_bq(line + len + 2);
354 header[i].func(line + len + 2);
355 break;
360 static void check_subheader_line(char *line)
362 static struct header_def header[] = {
363 { "Content-Type", handle_subcontent_type },
364 { "Content-Transfer-Encoding",
365 handle_content_transfer_encoding },
366 { NULL },
368 check_header(line, header);
370 static void check_header_line(char *line)
372 static struct header_def header[] = {
373 { "From", handle_from },
374 { "Date", handle_date },
375 { "Subject", handle_subject },
376 { "Content-Type", handle_content_type },
377 { "Content-Transfer-Encoding",
378 handle_content_transfer_encoding },
379 { NULL },
381 check_header(line, header);
384 static int read_one_header_line(char *line, int sz, FILE *in)
386 int ofs = 0;
387 while (ofs < sz) {
388 int peek, len;
389 if (fgets(line + ofs, sz - ofs, in) == NULL)
390 return ofs;
391 len = eatspace(line + ofs);
392 if (len == 0)
393 return ofs;
394 peek = fgetc(in); ungetc(peek, in);
395 if (peek == ' ' || peek == '\t') {
396 /* Yuck, 2822 header "folding" */
397 ofs += len;
398 continue;
400 return ofs + len;
402 return ofs;
405 static unsigned hexval(int c)
407 if (c >= '0' && c <= '9')
408 return c - '0';
409 if (c >= 'a' && c <= 'f')
410 return c - 'a' + 10;
411 if (c >= 'A' && c <= 'F')
412 return c - 'A' + 10;
413 return ~0;
416 static int decode_q_segment(char *in, char *ot, char *ep, int rfc2047)
418 int c;
419 while ((c = *in++) != 0 && (in <= ep)) {
420 if (c == '=') {
421 int d = *in++;
422 if (d == '\n' || !d)
423 break; /* drop trailing newline */
424 *ot++ = ((hexval(d) << 4) | hexval(*in++));
425 continue;
427 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
428 c = 0x20;
429 *ot++ = c;
431 *ot = 0;
432 return 0;
435 static int decode_b_segment(char *in, char *ot, char *ep)
437 /* Decode in..ep, possibly in-place to ot */
438 int c, pos = 0, acc = 0;
440 while ((c = *in++) != 0 && (in <= ep)) {
441 if (c == '+')
442 c = 62;
443 else if (c == '/')
444 c = 63;
445 else if ('A' <= c && c <= 'Z')
446 c -= 'A';
447 else if ('a' <= c && c <= 'z')
448 c -= 'a' - 26;
449 else if ('0' <= c && c <= '9')
450 c -= '0' - 52;
451 else if (c == '=') {
452 /* padding is almost like (c == 0), except we do
453 * not output NUL resulting only from it;
454 * for now we just trust the data.
456 c = 0;
458 else
459 continue; /* garbage */
460 switch (pos++) {
461 case 0:
462 acc = (c << 2);
463 break;
464 case 1:
465 *ot++ = (acc | (c >> 4));
466 acc = (c & 15) << 4;
467 break;
468 case 2:
469 *ot++ = (acc | (c >> 2));
470 acc = (c & 3) << 6;
471 break;
472 case 3:
473 *ot++ = (acc | c);
474 acc = pos = 0;
475 break;
478 *ot = 0;
479 return 0;
482 static void convert_to_utf8(char *line, char *charset)
484 #ifndef NO_ICONV
485 char *in, *out;
486 size_t insize, outsize, nrc;
487 char outbuf[4096]; /* cheat */
488 static char latin_one[] = "latin1";
489 char *input_charset = *charset ? charset : latin_one;
490 iconv_t conv = iconv_open(metainfo_charset, input_charset);
492 if (conv == (iconv_t) -1) {
493 static int warned_latin1_once = 0;
494 if (input_charset != latin_one) {
495 fprintf(stderr, "cannot convert from %s to %s\n",
496 input_charset, metainfo_charset);
497 *charset = 0;
499 else if (!warned_latin1_once) {
500 warned_latin1_once = 1;
501 fprintf(stderr, "tried to convert from %s to %s, "
502 "but your iconv does not work with it.\n",
503 input_charset, metainfo_charset);
505 return;
507 in = line;
508 insize = strlen(in);
509 out = outbuf;
510 outsize = sizeof(outbuf);
511 nrc = iconv(conv, &in, &insize, &out, &outsize);
512 iconv_close(conv);
513 if (nrc == (size_t) -1)
514 return;
515 *out = 0;
516 strcpy(line, outbuf);
517 #endif
520 static void decode_header_bq(char *it)
522 char *in, *out, *ep, *cp, *sp;
523 char outbuf[1000];
525 in = it;
526 out = outbuf;
527 while ((ep = strstr(in, "=?")) != NULL) {
528 int sz, encoding;
529 char charset_q[256], piecebuf[256];
530 if (in != ep) {
531 sz = ep - in;
532 memcpy(out, in, sz);
533 out += sz;
534 in += sz;
536 /* E.g.
537 * ep : "=?iso-2022-jp?B?GyR...?= foo"
538 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
540 ep += 2;
541 cp = strchr(ep, '?');
542 if (!cp)
543 return; /* no munging */
544 for (sp = ep; sp < cp; sp++)
545 charset_q[sp - ep] = tolower(*sp);
546 charset_q[cp - ep] = 0;
547 encoding = cp[1];
548 if (!encoding || cp[2] != '?')
549 return; /* no munging */
550 ep = strstr(cp + 3, "?=");
551 if (!ep)
552 return; /* no munging */
553 switch (tolower(encoding)) {
554 default:
555 return; /* no munging */
556 case 'b':
557 sz = decode_b_segment(cp + 3, piecebuf, ep);
558 break;
559 case 'q':
560 sz = decode_q_segment(cp + 3, piecebuf, ep, 1);
561 break;
563 if (sz < 0)
564 return;
565 if (metainfo_charset)
566 convert_to_utf8(piecebuf, charset_q);
567 strcpy(out, piecebuf);
568 out += strlen(out);
569 in = ep + 2;
571 strcpy(out, in);
572 strcpy(it, outbuf);
575 static void decode_transfer_encoding(char *line)
577 char *ep;
579 switch (transfer_encoding) {
580 case TE_QP:
581 ep = line + strlen(line);
582 decode_q_segment(line, line, ep, 0);
583 break;
584 case TE_BASE64:
585 ep = line + strlen(line);
586 decode_b_segment(line, line, ep);
587 break;
588 case TE_DONTCARE:
589 break;
593 static void handle_info(void)
595 char *sub;
597 sub = cleanup_subject(subject);
598 cleanup_space(name);
599 cleanup_space(date);
600 cleanup_space(email);
601 cleanup_space(sub);
603 printf("Author: %s\nEmail: %s\nSubject: %s\nDate: %s\n\n",
604 name, email, sub, date);
607 /* We are inside message body and have read line[] already.
608 * Spit out the commit log.
610 static int handle_commit_msg(int *seen)
612 if (!cmitmsg)
613 return 0;
614 do {
615 if (!memcmp("diff -", line, 6) ||
616 !memcmp("---", line, 3) ||
617 !memcmp("Index: ", line, 7))
618 break;
619 if ((multipart_boundary[0] && is_multipart_boundary(line))) {
620 /* We come here when the first part had only
621 * the commit message without any patch. We
622 * pretend we have not seen this line yet, and
623 * go back to the loop.
625 return 1;
628 /* Unwrap transfer encoding and optionally
629 * normalize the log message to UTF-8.
631 decode_transfer_encoding(line);
632 if (metainfo_charset)
633 convert_to_utf8(line, charset);
635 handle_inbody_header(seen, line);
636 if (!(*seen & SEEN_PREFIX))
637 continue;
639 fputs(line, cmitmsg);
640 } while (fgets(line, sizeof(line), stdin) != NULL);
641 fclose(cmitmsg);
642 cmitmsg = NULL;
643 return 0;
646 /* We have done the commit message and have the first
647 * line of the patch in line[].
649 static void handle_patch(void)
651 do {
652 if (multipart_boundary[0] && is_multipart_boundary(line))
653 break;
654 /* Only unwrap transfer encoding but otherwise do not
655 * do anything. We do *NOT* want UTF-8 conversion
656 * here; we are dealing with the user payload.
658 decode_transfer_encoding(line);
659 fputs(line, patchfile);
660 patch_lines++;
661 } while (fgets(line, sizeof(line), stdin) != NULL);
664 /* multipart boundary and transfer encoding are set up for us, and we
665 * are at the end of the sub header. do equivalent of handle_body up
666 * to the next boundary without closing patchfile --- we will expect
667 * that the first part to contain commit message and a patch, and
668 * handle other parts as pure patches.
670 static int handle_multipart_one_part(int *seen)
672 int n = 0;
674 while (fgets(line, sizeof(line), stdin) != NULL) {
675 again:
676 n++;
677 if (is_multipart_boundary(line))
678 break;
679 if (handle_commit_msg(seen))
680 goto again;
681 handle_patch();
682 break;
684 if (n == 0)
685 return -1;
686 return 0;
689 static void handle_multipart_body(void)
691 int seen = 0;
692 int part_num = 0;
694 /* Skip up to the first boundary */
695 while (fgets(line, sizeof(line), stdin) != NULL)
696 if (is_multipart_boundary(line)) {
697 part_num = 1;
698 break;
700 if (!part_num)
701 return;
702 /* We are on boundary line. Start slurping the subhead. */
703 while (1) {
704 int hdr = read_one_header_line(line, sizeof(line), stdin);
705 if (!hdr) {
706 if (handle_multipart_one_part(&seen) < 0)
707 return;
708 /* Reset per part headers */
709 transfer_encoding = TE_DONTCARE;
710 charset[0] = 0;
712 else
713 check_subheader_line(line);
715 fclose(patchfile);
716 if (!patch_lines) {
717 fprintf(stderr, "No patch found\n");
718 exit(1);
722 /* Non multipart message */
723 static void handle_body(void)
725 int seen = 0;
727 if (line[0] || fgets(line, sizeof(line), stdin) != NULL) {
728 handle_commit_msg(&seen);
729 handle_patch();
731 fclose(patchfile);
732 if (!patch_lines) {
733 fprintf(stderr, "No patch found\n");
734 exit(1);
738 static const char mailinfo_usage[] =
739 "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
741 int main(int argc, char **argv)
743 /* NEEDSWORK: might want to do the optional .git/ directory
744 * discovery
746 git_config(git_default_config);
748 while (1 < argc && argv[1][0] == '-') {
749 if (!strcmp(argv[1], "-k"))
750 keep_subject = 1;
751 else if (!strcmp(argv[1], "-u"))
752 metainfo_charset = git_commit_encoding;
753 else if (!strncmp(argv[1], "--encoding=", 11))
754 metainfo_charset = argv[1] + 11;
755 else
756 usage(mailinfo_usage);
757 argc--; argv++;
760 if (argc != 3)
761 usage(mailinfo_usage);
762 cmitmsg = fopen(argv[1], "w");
763 if (!cmitmsg) {
764 perror(argv[1]);
765 exit(1);
767 patchfile = fopen(argv[2], "w");
768 if (!patchfile) {
769 perror(argv[2]);
770 exit(1);
772 while (1) {
773 int hdr = read_one_header_line(line, sizeof(line), stdin);
774 if (!hdr) {
775 if (multipart_boundary[0])
776 handle_multipart_body();
777 else
778 handle_body();
779 handle_info();
780 break;
782 check_header_line(line);
784 return 0;