Merge branch 'eb/mailinfo'
[git.git] / mailinfo.c
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
16 static FILE *cmitmsg, *patchfile;
17
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];
25
26 static enum  {
27         TE_DONTCARE, TE_QP, TE_BASE64,
28 } transfer_encoding;
29 static char charset[256];
30
31 static char multipart_boundary[1000];
32 static int multipart_boundary_len;
33 static int patch_lines = 0;
34
35 static char *sanity_check(char *name, char *email)
36 {
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;
43 }
44
45 static int bogus_from(char *line)
46 {
47         /* John Doe <johndoe> */
48         char *bra, *ket, *dst, *cp;
49
50         /* This is fallback, so do not bother if we already have an
51          * e-mail address.
52          */ 
53         if (*email)
54                 return 0;
55
56         bra = strchr(line, '<');
57         if (!bra)
58                 return 0;
59         ket = strchr(bra, '>');
60         if (!ket)
61                 return 0;
62
63         for (dst = email, cp = bra+1; cp < ket; )
64                 *dst++ = *cp++;
65         *dst = 0;
66         for (cp = line; isspace(*cp); cp++)
67                 ;
68         for (bra--; isspace(*bra); bra--)
69                 *bra = 0;
70         cp = sanity_check(cp, email);
71         strcpy(name, cp);
72         return 1;
73 }
74
75 static int handle_from(char *in_line)
76 {
77         char line[1000];
78         char *at;
79         char *dst;
80
81         strcpy(line, in_line);
82         at = strchr(line, '@');
83         if (!at)
84                 return bogus_from(line);
85
86         /*
87          * If we already have one email, don't take any confusing lines
88          */
89         if (*email && strchr(at+1, '@'))
90                 return 0;
91
92         /* Pick up the string around '@', possibly delimited with <>
93          * pair; that is the email part.  White them out while copying.
94          */
95         while (at > line) {
96                 char c = at[-1];
97                 if (isspace(c))
98                         break;
99                 if (c == '<') {
100                         at[-1] = ' ';
101                         break;
102                 }
103                 at--;
104         }
105         dst = email;
106         for (;;) {
107                 unsigned char c = *at;
108                 if (!c || c == '>' || isspace(c)) {
109                         if (c == '>')
110                                 *at = ' ';
111                         break;
112                 }
113                 *at++ = ' ';
114                 *dst++ = c;
115         }
116         *dst++ = 0;
117
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.
122          */
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;
129                 }
130         }
131
132         at = line;
133         for (;;) {
134                 unsigned char c = *at;
135                 if (!c || !isspace(c)) {
136                         if (c == '(')
137                                 at++;
138                         break;
139                 }
140                 at++;
141         }
142         at = sanity_check(at, email);
143         strcpy(name, at);
144         return 1;
145 }
146
147 static int handle_date(char *line)
148 {
149         strcpy(date, line);
150         return 0;
151 }
152
153 static int handle_subject(char *line)
154 {
155         strcpy(subject, line);
156         return 0;
157 }
158
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.
163  */
164
165 static int slurp_attr(const char *line, const char *name, char *attr)
166 {
167         char *ends, *ap = strcasestr(line, name);
168         size_t sz;
169
170         if (!ap) {
171                 *attr = 0;
172                 return 0;
173         }
174         ap += strlen(name);
175         if (*ap == '"') {
176                 ap++;
177                 ends = "\"";
178         }
179         else
180                 ends = "; \t";
181         sz = strcspn(ap, ends);
182         memcpy(attr, ap, sz);
183         attr[sz] = 0;
184         return 1;
185 }
186
187 static int handle_subcontent_type(char *line)
188 {
189         /* We do not want to mess with boundary.  Note that we do not
190          * handle nested multipart.
191          */
192         if (strcasestr(line, "boundary=")) {
193                 fprintf(stderr, "Not handling nested multipart message.\n");
194                 exit(1);
195         }
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);
201         }
202         return 0;
203 }
204
205 static int handle_content_type(char *line)
206 {
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);
211         }
212         slurp_attr(line, "charset=", charset);
213         return 0;
214 }
215
216 static int handle_content_transfer_encoding(char *line)
217 {
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;
225 }
226
227 static int is_multipart_boundary(const char *line)
228 {
229         return (!memcmp(line, multipart_boundary, multipart_boundary_len));
230 }
231
232 static int eatspace(char *line)
233 {
234         int len = strlen(line);
235         while (len > 0 && isspace(line[len-1]))
236                 line[--len] = 0;
237         return len;
238 }
239
240 #define SEEN_FROM 01
241 #define SEEN_DATE 02
242 #define SEEN_SUBJECT 04
243 #define SEEN_PREFIX  0x08
244
245 /* First lines of body can have From:, Date:, and Subject: */
246 static void handle_inbody_header(int *seen, char *line)
247 {
248         if (!memcmp("From:", line, 5) && isspace(line[5])) {
249                 if (!(*seen & SEEN_FROM) && handle_from(line+6)) {
250                         *seen |= SEEN_FROM;
251                         return;
252                 }
253         }
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;
259                 }
260         }
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;
266                 }
267         }
268         if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
269                 if (!(*seen & SEEN_SUBJECT)) {
270                         handle_subject(line);
271                         *seen |= SEEN_SUBJECT;
272                         return;
273                 }
274         }
275         *seen |= SEEN_PREFIX;
276 }
277
278 static char *cleanup_subject(char *subject)
279 {
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;
290                         }
291                         break;
292                 case ' ': case '\t': case ':':
293                         subject++;
294                         continue;
295
296                 case '[':
297                         p = strchr(subject, ']');
298                         if (!p) {
299                                 subject++;
300                                 continue;
301                         }
302                         len = strlen(p);
303                         remove = p - subject;
304                         if (remove <= len *2) {
305                                 subject = p+1;
306                                 continue;
307                         }       
308                         break;
309                 }
310                 return subject;
311         }
312 }                       
313
314 static void cleanup_space(char *buf)
315 {
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;
326                         }
327                 }
328         }
329 }
330
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;
337 };
338
339 static void check_header(char *line, struct header_def *header)
340 {
341         int i;
342
343         if (header[0].namelen <= 0) {
344                 for (i = 0; header[i].name; i++)
345                         header[i].namelen = strlen(header[i].name);
346         }
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.
353                          */
354                         decode_header_bq(line + len + 2);
355                         header[i].func(line + len + 2);
356                         break;
357                 }
358         }
359 }
360
361 static void check_subheader_line(char *line)
362 {
363         static struct header_def header[] = {
364                 { "Content-Type", handle_subcontent_type },
365                 { "Content-Transfer-Encoding",
366                   handle_content_transfer_encoding },
367                 { NULL },
368         };
369         check_header(line, header);
370 }
371 static void check_header_line(char *line)
372 {
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 },
381         };
382         check_header(line, header);
383 }
384
385 static int is_rfc2822_header(char *line)
386 {
387         /*
388          * The section that defines the loosest possible
389          * field name is "3.6.8 Optional fields".
390          *
391          * optional-field = field-name ":" unstructured CRLF
392          * field-name = 1*ftext
393          * ftext = %d33-57 / %59-126
394          */
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;
404         }
405         return 0;
406 }
407
408 static int read_one_header_line(char *line, int sz, FILE *in)
409 {
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;
423                 }
424                 ofs += len;
425                 /* Yuck, 2822 header "folding" */
426                 peek = fgetc(in); ungetc(peek, in);
427                 if (peek != ' ' && peek != '\t')
428                         break;
429         }
430         /* Count mbox From headers as headers */
431         if (!ofs && !memcmp(line, "From ", 5))
432                 ofs = 1;
433         return ofs;
434 }
435
436 static unsigned hexval(int c)
437 {
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;
445 }
446
447 static int decode_q_segment(char *in, char *ot, char *ep, int rfc2047)
448 {
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;
457                 }
458                 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
459                         c = 0x20;
460                 *ot++ = c;
461         }
462         *ot = 0;
463         return 0;
464 }
465
466 static int decode_b_segment(char *in, char *ot, char *ep)
467 {
468         /* Decode in..ep, possibly in-place to ot */
469         int c, pos = 0, acc = 0;
470
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.
486                          */
487                         c = 0;
488                 }
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;
507                 }
508         }
509         *ot = 0;
510         return 0;
511 }
512
513 static void convert_to_utf8(char *line, char *charset)
514 {
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);
522
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;
529                 }
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);
535                 }
536                 return;
537         }
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
549 }
550
551 static void decode_header_bq(char *it)
552 {
553         char *in, *out, *ep, *cp, *sp;
554         char outbuf[1000];
555
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;
566                 }
567                 /* E.g.
568                  * ep : "=?iso-2022-jp?B?GyR...?= foo"
569                  * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
570                  */
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;
593                 }
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;
601         }
602         strcpy(out, in);
603         strcpy(it, outbuf);
604 }
605
606 static void decode_transfer_encoding(char *line)
607 {
608         char *ep;
609
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;
621         }
622 }
623
624 static void handle_info(void)
625 {
626         char *sub;
627
628         sub = cleanup_subject(subject);
629         cleanup_space(name);
630         cleanup_space(date);
631         cleanup_space(email);
632         cleanup_space(sub);
633
634         printf("Author: %s\nEmail: %s\nSubject: %s\nDate: %s\n\n",
635                name, email, sub, date);
636 }
637
638 /* We are inside message body and have read line[] already.
639  * Spit out the commit log.
640  */
641 static int handle_commit_msg(int *seen)
642 {
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.
655                          */
656                         return 1;
657                 }
658
659                 /* Unwrap transfer encoding and optionally
660                  * normalize the log message to UTF-8.
661                  */
662                 decode_transfer_encoding(line);
663                 if (metainfo_charset)
664                         convert_to_utf8(line, charset);
665
666                 handle_inbody_header(seen, line);
667                 if (!(*seen & SEEN_PREFIX))
668                         continue;
669
670                 fputs(line, cmitmsg);
671         } while (fgets(line, sizeof(line), stdin) != NULL);
672         fclose(cmitmsg);
673         cmitmsg = NULL;
674         return 0;
675 }
676
677 /* We have done the commit message and have the first
678  * line of the patch in line[].
679  */
680 static void handle_patch(void)
681 {
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.
688                  */
689                 decode_transfer_encoding(line);
690                 fputs(line, patchfile);
691                 patch_lines++;
692         } while (fgets(line, sizeof(line), stdin) != NULL);
693 }
694
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.
700  */
701 static int handle_multipart_one_part(int *seen)
702 {
703         int n = 0;
704
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;
714         }
715         if (n == 0)
716                 return -1;
717         return 0;
718 }
719
720 static void handle_multipart_body(void)
721 {
722         int seen = 0;
723         int part_num = 0;
724
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;
730                 }
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;
742                 }
743                 else
744                         check_subheader_line(line);
745         }
746         fclose(patchfile);
747         if (!patch_lines) {
748                 fprintf(stderr, "No patch found\n");
749                 exit(1);
750         }
751 }
752
753 /* Non multipart message */
754 static void handle_body(void)
755 {
756         int seen = 0;
757
758         if (line[0] || fgets(line, sizeof(line), stdin) != NULL) {
759                 handle_commit_msg(&seen);
760                 handle_patch();
761         }
762         fclose(patchfile);
763         if (!patch_lines) {
764                 fprintf(stderr, "No patch found\n");
765                 exit(1);
766         }
767 }
768
769 static const char mailinfo_usage[] =
770         "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
771
772 int main(int argc, char **argv)
773 {
774         /* NEEDSWORK: might want to do the optional .git/ directory
775          * discovery
776          */
777         git_config(git_default_config);
778
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++;
789         }
790
791         if (argc != 3)
792                 usage(mailinfo_usage);
793         cmitmsg = fopen(argv[1], "w");
794         if (!cmitmsg) {
795                 perror(argv[1]);
796                 exit(1);
797         }
798         patchfile = fopen(argv[2], "w");
799         if (!patchfile) {
800                 perror(argv[2]);
801                 exit(1);
802         }
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;
812                 }
813                 check_header_line(line);
814         }
815         return 0;
816 }