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