Merge branch 'sp/reflog' into next
[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_BOGUS_UNIX_FROM 010
244 #define SEEN_PREFIX  020
245
246 /* First lines of body can have From:, Date:, and Subject: */
247 static void handle_inbody_header(int *seen, char *line)
248 {
249         if (!memcmp(">From", line, 5) && isspace(line[5])) {
250                 if (!(*seen & SEEN_BOGUS_UNIX_FROM)) {
251                         *seen |= SEEN_BOGUS_UNIX_FROM;
252                         return;
253                 }
254         }
255         if (!memcmp("From:", line, 5) && isspace(line[5])) {
256                 if (!(*seen & SEEN_FROM) && handle_from(line+6)) {
257                         *seen |= SEEN_FROM;
258                         return;
259                 }
260         }
261         if (!memcmp("Date:", line, 5) && isspace(line[5])) {
262                 if (!(*seen & SEEN_DATE)) {
263                         handle_date(line+6);
264                         *seen |= SEEN_DATE;
265                         return;
266                 }
267         }
268         if (!memcmp("Subject:", line, 8) && isspace(line[8])) {
269                 if (!(*seen & SEEN_SUBJECT)) {
270                         handle_subject(line+9);
271                         *seen |= SEEN_SUBJECT;
272                         return;
273                 }
274         }
275         if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
276                 if (!(*seen & SEEN_SUBJECT)) {
277                         handle_subject(line);
278                         *seen |= SEEN_SUBJECT;
279                         return;
280                 }
281         }
282         *seen |= SEEN_PREFIX;
283 }
284
285 static char *cleanup_subject(char *subject)
286 {
287         if (keep_subject)
288                 return subject;
289         for (;;) {
290                 char *p;
291                 int len, remove;
292                 switch (*subject) {
293                 case 'r': case 'R':
294                         if (!memcmp("e:", subject+1, 2)) {
295                                 subject +=3;
296                                 continue;
297                         }
298                         break;
299                 case ' ': case '\t': case ':':
300                         subject++;
301                         continue;
302
303                 case '[':
304                         p = strchr(subject, ']');
305                         if (!p) {
306                                 subject++;
307                                 continue;
308                         }
309                         len = strlen(p);
310                         remove = p - subject;
311                         if (remove <= len *2) {
312                                 subject = p+1;
313                                 continue;
314                         }       
315                         break;
316                 }
317                 return subject;
318         }
319 }                       
320
321 static void cleanup_space(char *buf)
322 {
323         unsigned char c;
324         while ((c = *buf) != 0) {
325                 buf++;
326                 if (isspace(c)) {
327                         buf[-1] = ' ';
328                         c = *buf;
329                         while (isspace(c)) {
330                                 int len = strlen(buf);
331                                 memmove(buf, buf+1, len);
332                                 c = *buf;
333                         }
334                 }
335         }
336 }
337
338 static void decode_header_bq(char *it);
339 typedef int (*header_fn_t)(char *);
340 struct header_def {
341         const char *name;
342         header_fn_t func;
343         int namelen;
344 };
345
346 static void check_header(char *line, struct header_def *header)
347 {
348         int i;
349
350         if (header[0].namelen <= 0) {
351                 for (i = 0; header[i].name; i++)
352                         header[i].namelen = strlen(header[i].name);
353         }
354         for (i = 0; header[i].name; i++) {
355                 int len = header[i].namelen;
356                 if (!strncasecmp(line, header[i].name, len) &&
357                     line[len] == ':' && isspace(line[len + 1])) {
358                         /* Unwrap inline B and Q encoding, and optionally
359                          * normalize the meta information to utf8.
360                          */
361                         decode_header_bq(line + len + 2);
362                         header[i].func(line + len + 2);
363                         break;
364                 }
365         }
366 }
367
368 static void check_subheader_line(char *line)
369 {
370         static struct header_def header[] = {
371                 { "Content-Type", handle_subcontent_type },
372                 { "Content-Transfer-Encoding",
373                   handle_content_transfer_encoding },
374                 { NULL },
375         };
376         check_header(line, header);
377 }
378 static void check_header_line(char *line)
379 {
380         static struct header_def header[] = {
381                 { "From", handle_from },
382                 { "Date", handle_date },
383                 { "Subject", handle_subject },
384                 { "Content-Type", handle_content_type },
385                 { "Content-Transfer-Encoding",
386                   handle_content_transfer_encoding },
387                 { NULL },
388         };
389         check_header(line, header);
390 }
391
392 static int read_one_header_line(char *line, int sz, FILE *in)
393 {
394         int ofs = 0;
395         while (ofs < sz) {
396                 const char *colon;
397                 int peek, len;
398                 if (fgets(line + ofs, sz - ofs, in) == NULL)
399                         break;
400                 len = eatspace(line + ofs);
401                 if (len == 0)
402                         break;
403                 colon = strchr(line, ':');
404                 if (!colon || !isspace(colon[1])) {
405                         /* Re-add the newline */
406                         line[ofs + len] = '\n';
407                         line[ofs + len + 1] = '\0';
408                         break;
409                 }
410                 ofs += len;
411                 /* Yuck, 2822 header "folding" */
412                 peek = fgetc(in); ungetc(peek, in);
413                 if (peek != ' ' && peek != '\t')
414                         break;
415         }
416         /* Count mbox From headers as headers */
417         if (!ofs && !memcmp(line, "From ", 5))
418                 ofs = 1;
419         return ofs;
420 }
421
422 static unsigned hexval(int c)
423 {
424         if (c >= '0' && c <= '9')
425                 return c - '0';
426         if (c >= 'a' && c <= 'f')
427                 return c - 'a' + 10;
428         if (c >= 'A' && c <= 'F')
429                 return c - 'A' + 10;
430         return ~0;
431 }
432
433 static int decode_q_segment(char *in, char *ot, char *ep, int rfc2047)
434 {
435         int c;
436         while ((c = *in++) != 0 && (in <= ep)) {
437                 if (c == '=') {
438                         int d = *in++;
439                         if (d == '\n' || !d)
440                                 break; /* drop trailing newline */
441                         *ot++ = ((hexval(d) << 4) | hexval(*in++));
442                         continue;
443                 }
444                 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
445                         c = 0x20;
446                 *ot++ = c;
447         }
448         *ot = 0;
449         return 0;
450 }
451
452 static int decode_b_segment(char *in, char *ot, char *ep)
453 {
454         /* Decode in..ep, possibly in-place to ot */
455         int c, pos = 0, acc = 0;
456
457         while ((c = *in++) != 0 && (in <= ep)) {
458                 if (c == '+')
459                         c = 62;
460                 else if (c == '/')
461                         c = 63;
462                 else if ('A' <= c && c <= 'Z')
463                         c -= 'A';
464                 else if ('a' <= c && c <= 'z')
465                         c -= 'a' - 26;
466                 else if ('0' <= c && c <= '9')
467                         c -= '0' - 52;
468                 else if (c == '=') {
469                         /* padding is almost like (c == 0), except we do
470                          * not output NUL resulting only from it;
471                          * for now we just trust the data.
472                          */
473                         c = 0;
474                 }
475                 else
476                         continue; /* garbage */
477                 switch (pos++) {
478                 case 0:
479                         acc = (c << 2);
480                         break;
481                 case 1:
482                         *ot++ = (acc | (c >> 4));
483                         acc = (c & 15) << 4;
484                         break;
485                 case 2:
486                         *ot++ = (acc | (c >> 2));
487                         acc = (c & 3) << 6;
488                         break;
489                 case 3:
490                         *ot++ = (acc | c);
491                         acc = pos = 0;
492                         break;
493                 }
494         }
495         *ot = 0;
496         return 0;
497 }
498
499 static void convert_to_utf8(char *line, char *charset)
500 {
501 #ifndef NO_ICONV
502         char *in, *out;
503         size_t insize, outsize, nrc;
504         char outbuf[4096]; /* cheat */
505         static char latin_one[] = "latin1";
506         char *input_charset = *charset ? charset : latin_one;
507         iconv_t conv = iconv_open(metainfo_charset, input_charset);
508
509         if (conv == (iconv_t) -1) {
510                 static int warned_latin1_once = 0;
511                 if (input_charset != latin_one) {
512                         fprintf(stderr, "cannot convert from %s to %s\n",
513                                 input_charset, metainfo_charset);
514                         *charset = 0;
515                 }
516                 else if (!warned_latin1_once) {
517                         warned_latin1_once = 1;
518                         fprintf(stderr, "tried to convert from %s to %s, "
519                                 "but your iconv does not work with it.\n",
520                                 input_charset, metainfo_charset);
521                 }
522                 return;
523         }
524         in = line;
525         insize = strlen(in);
526         out = outbuf;
527         outsize = sizeof(outbuf);
528         nrc = iconv(conv, &in, &insize, &out, &outsize);
529         iconv_close(conv);
530         if (nrc == (size_t) -1)
531                 return;
532         *out = 0;
533         strcpy(line, outbuf);
534 #endif
535 }
536
537 static void decode_header_bq(char *it)
538 {
539         char *in, *out, *ep, *cp, *sp;
540         char outbuf[1000];
541
542         in = it;
543         out = outbuf;
544         while ((ep = strstr(in, "=?")) != NULL) {
545                 int sz, encoding;
546                 char charset_q[256], piecebuf[256];
547                 if (in != ep) {
548                         sz = ep - in;
549                         memcpy(out, in, sz);
550                         out += sz;
551                         in += sz;
552                 }
553                 /* E.g.
554                  * ep : "=?iso-2022-jp?B?GyR...?= foo"
555                  * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
556                  */
557                 ep += 2;
558                 cp = strchr(ep, '?');
559                 if (!cp)
560                         return; /* no munging */
561                 for (sp = ep; sp < cp; sp++)
562                         charset_q[sp - ep] = tolower(*sp);
563                 charset_q[cp - ep] = 0;
564                 encoding = cp[1];
565                 if (!encoding || cp[2] != '?')
566                         return; /* no munging */
567                 ep = strstr(cp + 3, "?=");
568                 if (!ep)
569                         return; /* no munging */
570                 switch (tolower(encoding)) {
571                 default:
572                         return; /* no munging */
573                 case 'b':
574                         sz = decode_b_segment(cp + 3, piecebuf, ep);
575                         break;
576                 case 'q':
577                         sz = decode_q_segment(cp + 3, piecebuf, ep, 1);
578                         break;
579                 }
580                 if (sz < 0)
581                         return;
582                 if (metainfo_charset)
583                         convert_to_utf8(piecebuf, charset_q);
584                 strcpy(out, piecebuf);
585                 out += strlen(out);
586                 in = ep + 2;
587         }
588         strcpy(out, in);
589         strcpy(it, outbuf);
590 }
591
592 static void decode_transfer_encoding(char *line)
593 {
594         char *ep;
595
596         switch (transfer_encoding) {
597         case TE_QP:
598                 ep = line + strlen(line);
599                 decode_q_segment(line, line, ep, 0);
600                 break;
601         case TE_BASE64:
602                 ep = line + strlen(line);
603                 decode_b_segment(line, line, ep);
604                 break;
605         case TE_DONTCARE:
606                 break;
607         }
608 }
609
610 static void handle_info(void)
611 {
612         char *sub;
613
614         sub = cleanup_subject(subject);
615         cleanup_space(name);
616         cleanup_space(date);
617         cleanup_space(email);
618         cleanup_space(sub);
619
620         printf("Author: %s\nEmail: %s\nSubject: %s\nDate: %s\n\n",
621                name, email, sub, date);
622 }
623
624 /* We are inside message body and have read line[] already.
625  * Spit out the commit log.
626  */
627 static int handle_commit_msg(int *seen)
628 {
629         if (!cmitmsg)
630                 return 0;
631         do {
632                 if (!memcmp("diff -", line, 6) ||
633                     !memcmp("---", line, 3) ||
634                     !memcmp("Index: ", line, 7))
635                         break;
636                 if ((multipart_boundary[0] && is_multipart_boundary(line))) {
637                         /* We come here when the first part had only
638                          * the commit message without any patch.  We
639                          * pretend we have not seen this line yet, and
640                          * go back to the loop.
641                          */
642                         return 1;
643                 }
644
645                 /* Unwrap transfer encoding and optionally
646                  * normalize the log message to UTF-8.
647                  */
648                 decode_transfer_encoding(line);
649                 if (metainfo_charset)
650                         convert_to_utf8(line, charset);
651
652                 handle_inbody_header(seen, line);
653                 if (!(*seen & SEEN_PREFIX))
654                         continue;
655
656                 fputs(line, cmitmsg);
657         } while (fgets(line, sizeof(line), stdin) != NULL);
658         fclose(cmitmsg);
659         cmitmsg = NULL;
660         return 0;
661 }
662
663 /* We have done the commit message and have the first
664  * line of the patch in line[].
665  */
666 static void handle_patch(void)
667 {
668         do {
669                 if (multipart_boundary[0] && is_multipart_boundary(line))
670                         break;
671                 /* Only unwrap transfer encoding but otherwise do not
672                  * do anything.  We do *NOT* want UTF-8 conversion
673                  * here; we are dealing with the user payload.
674                  */
675                 decode_transfer_encoding(line);
676                 fputs(line, patchfile);
677                 patch_lines++;
678         } while (fgets(line, sizeof(line), stdin) != NULL);
679 }
680
681 /* multipart boundary and transfer encoding are set up for us, and we
682  * are at the end of the sub header.  do equivalent of handle_body up
683  * to the next boundary without closing patchfile --- we will expect
684  * that the first part to contain commit message and a patch, and
685  * handle other parts as pure patches.
686  */
687 static int handle_multipart_one_part(int *seen)
688 {
689         int n = 0;
690
691         while (fgets(line, sizeof(line), stdin) != NULL) {
692         again:
693                 n++;
694                 if (is_multipart_boundary(line))
695                         break;
696                 if (handle_commit_msg(seen))
697                         goto again;
698                 handle_patch();
699                 break;
700         }
701         if (n == 0)
702                 return -1;
703         return 0;
704 }
705
706 static void handle_multipart_body(void)
707 {
708         int seen = 0;
709         int part_num = 0;
710
711         /* Skip up to the first boundary */
712         while (fgets(line, sizeof(line), stdin) != NULL)
713                 if (is_multipart_boundary(line)) {
714                         part_num = 1;
715                         break;
716                 }
717         if (!part_num)
718                 return;
719         /* We are on boundary line.  Start slurping the subhead. */
720         while (1) {
721                 int hdr = read_one_header_line(line, sizeof(line), stdin);
722                 if (!hdr) {
723                         if (handle_multipart_one_part(&seen) < 0)
724                                 return;
725                         /* Reset per part headers */
726                         transfer_encoding = TE_DONTCARE;
727                         charset[0] = 0;
728                 }
729                 else
730                         check_subheader_line(line);
731         }
732         fclose(patchfile);
733         if (!patch_lines) {
734                 fprintf(stderr, "No patch found\n");
735                 exit(1);
736         }
737 }
738
739 /* Non multipart message */
740 static void handle_body(void)
741 {
742         int seen = 0;
743
744         if (line[0] || fgets(line, sizeof(line), stdin) != NULL) {
745                 handle_commit_msg(&seen);
746                 handle_patch();
747         }
748         fclose(patchfile);
749         if (!patch_lines) {
750                 fprintf(stderr, "No patch found\n");
751                 exit(1);
752         }
753 }
754
755 static const char mailinfo_usage[] =
756         "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
757
758 int main(int argc, char **argv)
759 {
760         /* NEEDSWORK: might want to do the optional .git/ directory
761          * discovery
762          */
763         git_config(git_default_config);
764
765         while (1 < argc && argv[1][0] == '-') {
766                 if (!strcmp(argv[1], "-k"))
767                         keep_subject = 1;
768                 else if (!strcmp(argv[1], "-u"))
769                         metainfo_charset = git_commit_encoding;
770                 else if (!strncmp(argv[1], "--encoding=", 11))
771                         metainfo_charset = argv[1] + 11;
772                 else
773                         usage(mailinfo_usage);
774                 argc--; argv++;
775         }
776
777         if (argc != 3)
778                 usage(mailinfo_usage);
779         cmitmsg = fopen(argv[1], "w");
780         if (!cmitmsg) {
781                 perror(argv[1]);
782                 exit(1);
783         }
784         patchfile = fopen(argv[2], "w");
785         if (!patchfile) {
786                 perror(argv[2]);
787                 exit(1);
788         }
789         while (1) {
790                 int hdr = read_one_header_line(line, sizeof(line), stdin);
791                 if (!hdr) {
792                         if (multipart_boundary[0])
793                                 handle_multipart_body();
794                         else
795                                 handle_body();
796                         handle_info();
797                         break;
798                 }
799                 check_header_line(line);
800         }
801         return 0;
802 }