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