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