mailinfo: More carefully parse header lines in read_one_header_line()
[git/gitweb.git] / mailinfo.c
blob88f9fbb198a7343715fb01c64c72044a7abaedab
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 *in_line)
77 char line[1000];
78 char *at;
79 char *dst;
81 strcpy(line, in_line);
82 at = strchr(line, '@');
83 if (!at)
84 return bogus_from(line);
87 * If we already have one email, don't take any confusing lines
89 if (*email && strchr(at+1, '@'))
90 return 0;
92 /* Pick up the string around '@', possibly delimited with <>
93 * pair; that is the email part. White them out while copying.
95 while (at > line) {
96 char c = at[-1];
97 if (isspace(c))
98 break;
99 if (c == '<') {
100 at[-1] = ' ';
101 break;
103 at--;
105 dst = email;
106 for (;;) {
107 unsigned char c = *at;
108 if (!c || c == '>' || isspace(c)) {
109 if (c == '>')
110 *at = ' ';
111 break;
113 *at++ = ' ';
114 *dst++ = c;
116 *dst++ = 0;
118 /* The remainder is name. It could be "John Doe <john.doe@xz>"
119 * or "john.doe@xz (John Doe)", but we have whited out the
120 * email part, so trim from both ends, possibly removing
121 * the () pair at the end.
123 at = line + strlen(line);
124 while (at > line) {
125 unsigned char c = *--at;
126 if (!isspace(c)) {
127 at[(c == ')') ? 0 : 1] = 0;
128 break;
132 at = line;
133 for (;;) {
134 unsigned char c = *at;
135 if (!c || !isspace(c)) {
136 if (c == '(')
137 at++;
138 break;
140 at++;
142 at = sanity_check(at, email);
143 strcpy(name, at);
144 return 1;
147 static int handle_date(char *line)
149 strcpy(date, line);
150 return 0;
153 static int handle_subject(char *line)
155 strcpy(subject, line);
156 return 0;
159 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
160 * to have enough heuristics to grok MIME encoded patches often found
161 * on our mailing lists. For example, we do not even treat header lines
162 * case insensitively.
165 static int slurp_attr(const char *line, const char *name, char *attr)
167 char *ends, *ap = strcasestr(line, name);
168 size_t sz;
170 if (!ap) {
171 *attr = 0;
172 return 0;
174 ap += strlen(name);
175 if (*ap == '"') {
176 ap++;
177 ends = "\"";
179 else
180 ends = "; \t";
181 sz = strcspn(ap, ends);
182 memcpy(attr, ap, sz);
183 attr[sz] = 0;
184 return 1;
187 static int handle_subcontent_type(char *line)
189 /* We do not want to mess with boundary. Note that we do not
190 * handle nested multipart.
192 if (strcasestr(line, "boundary=")) {
193 fprintf(stderr, "Not handling nested multipart message.\n");
194 exit(1);
196 slurp_attr(line, "charset=", charset);
197 if (*charset) {
198 int i, c;
199 for (i = 0; (c = charset[i]) != 0; i++)
200 charset[i] = tolower(c);
202 return 0;
205 static int handle_content_type(char *line)
207 *multipart_boundary = 0;
208 if (slurp_attr(line, "boundary=", multipart_boundary + 2)) {
209 memcpy(multipart_boundary, "--", 2);
210 multipart_boundary_len = strlen(multipart_boundary);
212 slurp_attr(line, "charset=", charset);
213 return 0;
216 static int handle_content_transfer_encoding(char *line)
218 if (strcasestr(line, "base64"))
219 transfer_encoding = TE_BASE64;
220 else if (strcasestr(line, "quoted-printable"))
221 transfer_encoding = TE_QP;
222 else
223 transfer_encoding = TE_DONTCARE;
224 return 0;
227 static int is_multipart_boundary(const char *line)
229 return (!memcmp(line, multipart_boundary, multipart_boundary_len));
232 static int eatspace(char *line)
234 int len = strlen(line);
235 while (len > 0 && isspace(line[len-1]))
236 line[--len] = 0;
237 return len;
240 #define SEEN_FROM 01
241 #define SEEN_DATE 02
242 #define SEEN_SUBJECT 04
243 #define SEEN_PREFIX 0x08
245 /* First lines of body can have From:, Date:, and Subject: */
246 static void handle_inbody_header(int *seen, char *line)
248 if (!memcmp("From:", line, 5) && isspace(line[5])) {
249 if (!(*seen & SEEN_FROM) && handle_from(line+6)) {
250 *seen |= SEEN_FROM;
251 return;
254 if (!memcmp("Date:", line, 5) && isspace(line[5])) {
255 if (!(*seen & SEEN_DATE)) {
256 handle_date(line+6);
257 *seen |= SEEN_DATE;
258 return;
261 if (!memcmp("Subject:", line, 8) && isspace(line[8])) {
262 if (!(*seen & SEEN_SUBJECT)) {
263 handle_subject(line+9);
264 *seen |= SEEN_SUBJECT;
265 return;
268 if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
269 if (!(*seen & SEEN_SUBJECT)) {
270 handle_subject(line);
271 *seen |= SEEN_SUBJECT;
272 return;
275 *seen |= SEEN_PREFIX;
278 static char *cleanup_subject(char *subject)
280 if (keep_subject)
281 return subject;
282 for (;;) {
283 char *p;
284 int len, remove;
285 switch (*subject) {
286 case 'r': case 'R':
287 if (!memcmp("e:", subject+1, 2)) {
288 subject +=3;
289 continue;
291 break;
292 case ' ': case '\t': case ':':
293 subject++;
294 continue;
296 case '[':
297 p = strchr(subject, ']');
298 if (!p) {
299 subject++;
300 continue;
302 len = strlen(p);
303 remove = p - subject;
304 if (remove <= len *2) {
305 subject = p+1;
306 continue;
308 break;
310 return subject;
314 static void cleanup_space(char *buf)
316 unsigned char c;
317 while ((c = *buf) != 0) {
318 buf++;
319 if (isspace(c)) {
320 buf[-1] = ' ';
321 c = *buf;
322 while (isspace(c)) {
323 int len = strlen(buf);
324 memmove(buf, buf+1, len);
325 c = *buf;
331 static void decode_header_bq(char *it);
332 typedef int (*header_fn_t)(char *);
333 struct header_def {
334 const char *name;
335 header_fn_t func;
336 int namelen;
339 static void check_header(char *line, struct header_def *header)
341 int i;
343 if (header[0].namelen <= 0) {
344 for (i = 0; header[i].name; i++)
345 header[i].namelen = strlen(header[i].name);
347 for (i = 0; header[i].name; i++) {
348 int len = header[i].namelen;
349 if (!strncasecmp(line, header[i].name, len) &&
350 line[len] == ':' && isspace(line[len + 1])) {
351 /* Unwrap inline B and Q encoding, and optionally
352 * normalize the meta information to utf8.
354 decode_header_bq(line + len + 2);
355 header[i].func(line + len + 2);
356 break;
361 static void check_subheader_line(char *line)
363 static struct header_def header[] = {
364 { "Content-Type", handle_subcontent_type },
365 { "Content-Transfer-Encoding",
366 handle_content_transfer_encoding },
367 { NULL },
369 check_header(line, header);
371 static void check_header_line(char *line)
373 static struct header_def header[] = {
374 { "From", handle_from },
375 { "Date", handle_date },
376 { "Subject", handle_subject },
377 { "Content-Type", handle_content_type },
378 { "Content-Transfer-Encoding",
379 handle_content_transfer_encoding },
380 { NULL },
382 check_header(line, header);
385 static int is_rfc2822_header(char *line)
388 * The section that defines the loosest possible
389 * field name is "3.6.8 Optional fields".
391 * optional-field = field-name ":" unstructured CRLF
392 * field-name = 1*ftext
393 * ftext = %d33-57 / %59-126
395 int ch;
396 char *cp = line;
397 while ((ch = *cp++)) {
398 if (ch == ':')
399 return cp != line;
400 if ((33 <= ch && ch <= 57) ||
401 (59 <= ch && ch <= 126))
402 continue;
403 break;
405 return 0;
408 static int read_one_header_line(char *line, int sz, FILE *in)
410 int ofs = 0;
411 while (ofs < sz) {
412 int peek, len;
413 if (fgets(line + ofs, sz - ofs, in) == NULL)
414 break;
415 len = eatspace(line + ofs);
416 if (len == 0)
417 break;
418 if (!is_rfc2822_header(line)) {
419 /* Re-add the newline */
420 line[ofs + len] = '\n';
421 line[ofs + len + 1] = '\0';
422 break;
424 ofs += len;
425 /* Yuck, 2822 header "folding" */
426 peek = fgetc(in); ungetc(peek, in);
427 if (peek != ' ' && peek != '\t')
428 break;
430 /* Count mbox From headers as headers */
431 if (!ofs && !memcmp(line, "From ", 5))
432 ofs = 1;
433 return ofs;
436 static unsigned hexval(int c)
438 if (c >= '0' && c <= '9')
439 return c - '0';
440 if (c >= 'a' && c <= 'f')
441 return c - 'a' + 10;
442 if (c >= 'A' && c <= 'F')
443 return c - 'A' + 10;
444 return ~0;
447 static int decode_q_segment(char *in, char *ot, char *ep, int rfc2047)
449 int c;
450 while ((c = *in++) != 0 && (in <= ep)) {
451 if (c == '=') {
452 int d = *in++;
453 if (d == '\n' || !d)
454 break; /* drop trailing newline */
455 *ot++ = ((hexval(d) << 4) | hexval(*in++));
456 continue;
458 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
459 c = 0x20;
460 *ot++ = c;
462 *ot = 0;
463 return 0;
466 static int decode_b_segment(char *in, char *ot, char *ep)
468 /* Decode in..ep, possibly in-place to ot */
469 int c, pos = 0, acc = 0;
471 while ((c = *in++) != 0 && (in <= ep)) {
472 if (c == '+')
473 c = 62;
474 else if (c == '/')
475 c = 63;
476 else if ('A' <= c && c <= 'Z')
477 c -= 'A';
478 else if ('a' <= c && c <= 'z')
479 c -= 'a' - 26;
480 else if ('0' <= c && c <= '9')
481 c -= '0' - 52;
482 else if (c == '=') {
483 /* padding is almost like (c == 0), except we do
484 * not output NUL resulting only from it;
485 * for now we just trust the data.
487 c = 0;
489 else
490 continue; /* garbage */
491 switch (pos++) {
492 case 0:
493 acc = (c << 2);
494 break;
495 case 1:
496 *ot++ = (acc | (c >> 4));
497 acc = (c & 15) << 4;
498 break;
499 case 2:
500 *ot++ = (acc | (c >> 2));
501 acc = (c & 3) << 6;
502 break;
503 case 3:
504 *ot++ = (acc | c);
505 acc = pos = 0;
506 break;
509 *ot = 0;
510 return 0;
513 static void convert_to_utf8(char *line, char *charset)
515 #ifndef NO_ICONV
516 char *in, *out;
517 size_t insize, outsize, nrc;
518 char outbuf[4096]; /* cheat */
519 static char latin_one[] = "latin1";
520 char *input_charset = *charset ? charset : latin_one;
521 iconv_t conv = iconv_open(metainfo_charset, input_charset);
523 if (conv == (iconv_t) -1) {
524 static int warned_latin1_once = 0;
525 if (input_charset != latin_one) {
526 fprintf(stderr, "cannot convert from %s to %s\n",
527 input_charset, metainfo_charset);
528 *charset = 0;
530 else if (!warned_latin1_once) {
531 warned_latin1_once = 1;
532 fprintf(stderr, "tried to convert from %s to %s, "
533 "but your iconv does not work with it.\n",
534 input_charset, metainfo_charset);
536 return;
538 in = line;
539 insize = strlen(in);
540 out = outbuf;
541 outsize = sizeof(outbuf);
542 nrc = iconv(conv, &in, &insize, &out, &outsize);
543 iconv_close(conv);
544 if (nrc == (size_t) -1)
545 return;
546 *out = 0;
547 strcpy(line, outbuf);
548 #endif
551 static void decode_header_bq(char *it)
553 char *in, *out, *ep, *cp, *sp;
554 char outbuf[1000];
556 in = it;
557 out = outbuf;
558 while ((ep = strstr(in, "=?")) != NULL) {
559 int sz, encoding;
560 char charset_q[256], piecebuf[256];
561 if (in != ep) {
562 sz = ep - in;
563 memcpy(out, in, sz);
564 out += sz;
565 in += sz;
567 /* E.g.
568 * ep : "=?iso-2022-jp?B?GyR...?= foo"
569 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
571 ep += 2;
572 cp = strchr(ep, '?');
573 if (!cp)
574 return; /* no munging */
575 for (sp = ep; sp < cp; sp++)
576 charset_q[sp - ep] = tolower(*sp);
577 charset_q[cp - ep] = 0;
578 encoding = cp[1];
579 if (!encoding || cp[2] != '?')
580 return; /* no munging */
581 ep = strstr(cp + 3, "?=");
582 if (!ep)
583 return; /* no munging */
584 switch (tolower(encoding)) {
585 default:
586 return; /* no munging */
587 case 'b':
588 sz = decode_b_segment(cp + 3, piecebuf, ep);
589 break;
590 case 'q':
591 sz = decode_q_segment(cp + 3, piecebuf, ep, 1);
592 break;
594 if (sz < 0)
595 return;
596 if (metainfo_charset)
597 convert_to_utf8(piecebuf, charset_q);
598 strcpy(out, piecebuf);
599 out += strlen(out);
600 in = ep + 2;
602 strcpy(out, in);
603 strcpy(it, outbuf);
606 static void decode_transfer_encoding(char *line)
608 char *ep;
610 switch (transfer_encoding) {
611 case TE_QP:
612 ep = line + strlen(line);
613 decode_q_segment(line, line, ep, 0);
614 break;
615 case TE_BASE64:
616 ep = line + strlen(line);
617 decode_b_segment(line, line, ep);
618 break;
619 case TE_DONTCARE:
620 break;
624 static void handle_info(void)
626 char *sub;
628 sub = cleanup_subject(subject);
629 cleanup_space(name);
630 cleanup_space(date);
631 cleanup_space(email);
632 cleanup_space(sub);
634 printf("Author: %s\nEmail: %s\nSubject: %s\nDate: %s\n\n",
635 name, email, sub, date);
638 /* We are inside message body and have read line[] already.
639 * Spit out the commit log.
641 static int handle_commit_msg(int *seen)
643 if (!cmitmsg)
644 return 0;
645 do {
646 if (!memcmp("diff -", line, 6) ||
647 !memcmp("---", line, 3) ||
648 !memcmp("Index: ", line, 7))
649 break;
650 if ((multipart_boundary[0] && is_multipart_boundary(line))) {
651 /* We come here when the first part had only
652 * the commit message without any patch. We
653 * pretend we have not seen this line yet, and
654 * go back to the loop.
656 return 1;
659 /* Unwrap transfer encoding and optionally
660 * normalize the log message to UTF-8.
662 decode_transfer_encoding(line);
663 if (metainfo_charset)
664 convert_to_utf8(line, charset);
666 handle_inbody_header(seen, line);
667 if (!(*seen & SEEN_PREFIX))
668 continue;
670 fputs(line, cmitmsg);
671 } while (fgets(line, sizeof(line), stdin) != NULL);
672 fclose(cmitmsg);
673 cmitmsg = NULL;
674 return 0;
677 /* We have done the commit message and have the first
678 * line of the patch in line[].
680 static void handle_patch(void)
682 do {
683 if (multipart_boundary[0] && is_multipart_boundary(line))
684 break;
685 /* Only unwrap transfer encoding but otherwise do not
686 * do anything. We do *NOT* want UTF-8 conversion
687 * here; we are dealing with the user payload.
689 decode_transfer_encoding(line);
690 fputs(line, patchfile);
691 patch_lines++;
692 } while (fgets(line, sizeof(line), stdin) != NULL);
695 /* multipart boundary and transfer encoding are set up for us, and we
696 * are at the end of the sub header. do equivalent of handle_body up
697 * to the next boundary without closing patchfile --- we will expect
698 * that the first part to contain commit message and a patch, and
699 * handle other parts as pure patches.
701 static int handle_multipart_one_part(int *seen)
703 int n = 0;
705 while (fgets(line, sizeof(line), stdin) != NULL) {
706 again:
707 n++;
708 if (is_multipart_boundary(line))
709 break;
710 if (handle_commit_msg(seen))
711 goto again;
712 handle_patch();
713 break;
715 if (n == 0)
716 return -1;
717 return 0;
720 static void handle_multipart_body(void)
722 int seen = 0;
723 int part_num = 0;
725 /* Skip up to the first boundary */
726 while (fgets(line, sizeof(line), stdin) != NULL)
727 if (is_multipart_boundary(line)) {
728 part_num = 1;
729 break;
731 if (!part_num)
732 return;
733 /* We are on boundary line. Start slurping the subhead. */
734 while (1) {
735 int hdr = read_one_header_line(line, sizeof(line), stdin);
736 if (!hdr) {
737 if (handle_multipart_one_part(&seen) < 0)
738 return;
739 /* Reset per part headers */
740 transfer_encoding = TE_DONTCARE;
741 charset[0] = 0;
743 else
744 check_subheader_line(line);
746 fclose(patchfile);
747 if (!patch_lines) {
748 fprintf(stderr, "No patch found\n");
749 exit(1);
753 /* Non multipart message */
754 static void handle_body(void)
756 int seen = 0;
758 if (line[0] || fgets(line, sizeof(line), stdin) != NULL) {
759 handle_commit_msg(&seen);
760 handle_patch();
762 fclose(patchfile);
763 if (!patch_lines) {
764 fprintf(stderr, "No patch found\n");
765 exit(1);
769 static const char mailinfo_usage[] =
770 "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
772 int main(int argc, char **argv)
774 /* NEEDSWORK: might want to do the optional .git/ directory
775 * discovery
777 git_config(git_default_config);
779 while (1 < argc && argv[1][0] == '-') {
780 if (!strcmp(argv[1], "-k"))
781 keep_subject = 1;
782 else if (!strcmp(argv[1], "-u"))
783 metainfo_charset = git_commit_encoding;
784 else if (!strncmp(argv[1], "--encoding=", 11))
785 metainfo_charset = argv[1] + 11;
786 else
787 usage(mailinfo_usage);
788 argc--; argv++;
791 if (argc != 3)
792 usage(mailinfo_usage);
793 cmitmsg = fopen(argv[1], "w");
794 if (!cmitmsg) {
795 perror(argv[1]);
796 exit(1);
798 patchfile = fopen(argv[2], "w");
799 if (!patchfile) {
800 perror(argv[2]);
801 exit(1);
803 while (1) {
804 int hdr = read_one_header_line(line, sizeof(line), stdin);
805 if (!hdr) {
806 if (multipart_boundary[0])
807 handle_multipart_body();
808 else
809 handle_body();
810 handle_info();
811 break;
813 check_header_line(line);
815 return 0;