Misc doc improvements
[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 is_rfc2822_header(char *line)
393 {
394         /*
395          * The section that defines the loosest possible
396          * field name is "3.6.8 Optional fields".
397          *
398          * optional-field = field-name ":" unstructured CRLF
399          * field-name = 1*ftext
400          * ftext = %d33-57 / %59-126
401          */
402         int ch;
403         char *cp = line;
404         while ((ch = *cp++)) {
405                 if (ch == ':')
406                         return cp != line;
407                 if ((33 <= ch && ch <= 57) ||
408                     (59 <= ch && ch <= 126))
409                         continue;
410                 break;
411         }
412         return 0;
413 }
414
415 static int read_one_header_line(char *line, int sz, FILE *in)
416 {
417         int ofs = 0;
418         while (ofs < sz) {
419                 int peek, len;
420                 if (fgets(line + ofs, sz - ofs, in) == NULL)
421                         break;
422                 len = eatspace(line + ofs);
423                 if (len == 0)
424                         break;
425                 if (!is_rfc2822_header(line)) {
426                         /* Re-add the newline */
427                         line[ofs + len] = '\n';
428                         line[ofs + len + 1] = '\0';
429                         break;
430                 }
431                 ofs += len;
432                 /* Yuck, 2822 header "folding" */
433                 peek = fgetc(in); ungetc(peek, in);
434                 if (peek != ' ' && peek != '\t')
435                         break;
436         }
437         /* Count mbox From headers as headers */
438         if (!ofs && !memcmp(line, "From ", 5))
439                 ofs = 1;
440         return ofs;
441 }
442
443 static unsigned hexval(int c)
444 {
445         if (c >= '0' && c <= '9')
446                 return c - '0';
447         if (c >= 'a' && c <= 'f')
448                 return c - 'a' + 10;
449         if (c >= 'A' && c <= 'F')
450                 return c - 'A' + 10;
451         return ~0;
452 }
453
454 static int decode_q_segment(char *in, char *ot, char *ep, int rfc2047)
455 {
456         int c;
457         while ((c = *in++) != 0 && (in <= ep)) {
458                 if (c == '=') {
459                         int d = *in++;
460                         if (d == '\n' || !d)
461                                 break; /* drop trailing newline */
462                         *ot++ = ((hexval(d) << 4) | hexval(*in++));
463                         continue;
464                 }
465                 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
466                         c = 0x20;
467                 *ot++ = c;
468         }
469         *ot = 0;
470         return 0;
471 }
472
473 static int decode_b_segment(char *in, char *ot, char *ep)
474 {
475         /* Decode in..ep, possibly in-place to ot */
476         int c, pos = 0, acc = 0;
477
478         while ((c = *in++) != 0 && (in <= ep)) {
479                 if (c == '+')
480                         c = 62;
481                 else if (c == '/')
482                         c = 63;
483                 else if ('A' <= c && c <= 'Z')
484                         c -= 'A';
485                 else if ('a' <= c && c <= 'z')
486                         c -= 'a' - 26;
487                 else if ('0' <= c && c <= '9')
488                         c -= '0' - 52;
489                 else if (c == '=') {
490                         /* padding is almost like (c == 0), except we do
491                          * not output NUL resulting only from it;
492                          * for now we just trust the data.
493                          */
494                         c = 0;
495                 }
496                 else
497                         continue; /* garbage */
498                 switch (pos++) {
499                 case 0:
500                         acc = (c << 2);
501                         break;
502                 case 1:
503                         *ot++ = (acc | (c >> 4));
504                         acc = (c & 15) << 4;
505                         break;
506                 case 2:
507                         *ot++ = (acc | (c >> 2));
508                         acc = (c & 3) << 6;
509                         break;
510                 case 3:
511                         *ot++ = (acc | c);
512                         acc = pos = 0;
513                         break;
514                 }
515         }
516         *ot = 0;
517         return 0;
518 }
519
520 static void convert_to_utf8(char *line, char *charset)
521 {
522 #ifndef NO_ICONV
523         char *in, *out;
524         size_t insize, outsize, nrc;
525         char outbuf[4096]; /* cheat */
526         static char latin_one[] = "latin1";
527         char *input_charset = *charset ? charset : latin_one;
528         iconv_t conv = iconv_open(metainfo_charset, input_charset);
529
530         if (conv == (iconv_t) -1) {
531                 static int warned_latin1_once = 0;
532                 if (input_charset != latin_one) {
533                         fprintf(stderr, "cannot convert from %s to %s\n",
534                                 input_charset, metainfo_charset);
535                         *charset = 0;
536                 }
537                 else if (!warned_latin1_once) {
538                         warned_latin1_once = 1;
539                         fprintf(stderr, "tried to convert from %s to %s, "
540                                 "but your iconv does not work with it.\n",
541                                 input_charset, metainfo_charset);
542                 }
543                 return;
544         }
545         in = line;
546         insize = strlen(in);
547         out = outbuf;
548         outsize = sizeof(outbuf);
549         nrc = iconv(conv, &in, &insize, &out, &outsize);
550         iconv_close(conv);
551         if (nrc == (size_t) -1)
552                 return;
553         *out = 0;
554         strcpy(line, outbuf);
555 #endif
556 }
557
558 static void decode_header_bq(char *it)
559 {
560         char *in, *out, *ep, *cp, *sp;
561         char outbuf[1000];
562
563         in = it;
564         out = outbuf;
565         while ((ep = strstr(in, "=?")) != NULL) {
566                 int sz, encoding;
567                 char charset_q[256], piecebuf[256];
568                 if (in != ep) {
569                         sz = ep - in;
570                         memcpy(out, in, sz);
571                         out += sz;
572                         in += sz;
573                 }
574                 /* E.g.
575                  * ep : "=?iso-2022-jp?B?GyR...?= foo"
576                  * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
577                  */
578                 ep += 2;
579                 cp = strchr(ep, '?');
580                 if (!cp)
581                         return; /* no munging */
582                 for (sp = ep; sp < cp; sp++)
583                         charset_q[sp - ep] = tolower(*sp);
584                 charset_q[cp - ep] = 0;
585                 encoding = cp[1];
586                 if (!encoding || cp[2] != '?')
587                         return; /* no munging */
588                 ep = strstr(cp + 3, "?=");
589                 if (!ep)
590                         return; /* no munging */
591                 switch (tolower(encoding)) {
592                 default:
593                         return; /* no munging */
594                 case 'b':
595                         sz = decode_b_segment(cp + 3, piecebuf, ep);
596                         break;
597                 case 'q':
598                         sz = decode_q_segment(cp + 3, piecebuf, ep, 1);
599                         break;
600                 }
601                 if (sz < 0)
602                         return;
603                 if (metainfo_charset)
604                         convert_to_utf8(piecebuf, charset_q);
605                 strcpy(out, piecebuf);
606                 out += strlen(out);
607                 in = ep + 2;
608         }
609         strcpy(out, in);
610         strcpy(it, outbuf);
611 }
612
613 static void decode_transfer_encoding(char *line)
614 {
615         char *ep;
616
617         switch (transfer_encoding) {
618         case TE_QP:
619                 ep = line + strlen(line);
620                 decode_q_segment(line, line, ep, 0);
621                 break;
622         case TE_BASE64:
623                 ep = line + strlen(line);
624                 decode_b_segment(line, line, ep);
625                 break;
626         case TE_DONTCARE:
627                 break;
628         }
629 }
630
631 static void handle_info(void)
632 {
633         char *sub;
634
635         sub = cleanup_subject(subject);
636         cleanup_space(name);
637         cleanup_space(date);
638         cleanup_space(email);
639         cleanup_space(sub);
640
641         printf("Author: %s\nEmail: %s\nSubject: %s\nDate: %s\n\n",
642                name, email, sub, date);
643 }
644
645 /* We are inside message body and have read line[] already.
646  * Spit out the commit log.
647  */
648 static int handle_commit_msg(int *seen)
649 {
650         if (!cmitmsg)
651                 return 0;
652         do {
653                 if (!memcmp("diff -", line, 6) ||
654                     !memcmp("---", line, 3) ||
655                     !memcmp("Index: ", line, 7))
656                         break;
657                 if ((multipart_boundary[0] && is_multipart_boundary(line))) {
658                         /* We come here when the first part had only
659                          * the commit message without any patch.  We
660                          * pretend we have not seen this line yet, and
661                          * go back to the loop.
662                          */
663                         return 1;
664                 }
665
666                 /* Unwrap transfer encoding and optionally
667                  * normalize the log message to UTF-8.
668                  */
669                 decode_transfer_encoding(line);
670                 if (metainfo_charset)
671                         convert_to_utf8(line, charset);
672
673                 handle_inbody_header(seen, line);
674                 if (!(*seen & SEEN_PREFIX))
675                         continue;
676
677                 fputs(line, cmitmsg);
678         } while (fgets(line, sizeof(line), stdin) != NULL);
679         fclose(cmitmsg);
680         cmitmsg = NULL;
681         return 0;
682 }
683
684 /* We have done the commit message and have the first
685  * line of the patch in line[].
686  */
687 static void handle_patch(void)
688 {
689         do {
690                 if (multipart_boundary[0] && is_multipart_boundary(line))
691                         break;
692                 /* Only unwrap transfer encoding but otherwise do not
693                  * do anything.  We do *NOT* want UTF-8 conversion
694                  * here; we are dealing with the user payload.
695                  */
696                 decode_transfer_encoding(line);
697                 fputs(line, patchfile);
698                 patch_lines++;
699         } while (fgets(line, sizeof(line), stdin) != NULL);
700 }
701
702 /* multipart boundary and transfer encoding are set up for us, and we
703  * are at the end of the sub header.  do equivalent of handle_body up
704  * to the next boundary without closing patchfile --- we will expect
705  * that the first part to contain commit message and a patch, and
706  * handle other parts as pure patches.
707  */
708 static int handle_multipart_one_part(int *seen)
709 {
710         int n = 0;
711
712         while (fgets(line, sizeof(line), stdin) != NULL) {
713         again:
714                 n++;
715                 if (is_multipart_boundary(line))
716                         break;
717                 if (handle_commit_msg(seen))
718                         goto again;
719                 handle_patch();
720                 break;
721         }
722         if (n == 0)
723                 return -1;
724         return 0;
725 }
726
727 static void handle_multipart_body(void)
728 {
729         int seen = 0;
730         int part_num = 0;
731
732         /* Skip up to the first boundary */
733         while (fgets(line, sizeof(line), stdin) != NULL)
734                 if (is_multipart_boundary(line)) {
735                         part_num = 1;
736                         break;
737                 }
738         if (!part_num)
739                 return;
740         /* We are on boundary line.  Start slurping the subhead. */
741         while (1) {
742                 int hdr = read_one_header_line(line, sizeof(line), stdin);
743                 if (!hdr) {
744                         if (handle_multipart_one_part(&seen) < 0)
745                                 return;
746                         /* Reset per part headers */
747                         transfer_encoding = TE_DONTCARE;
748                         charset[0] = 0;
749                 }
750                 else
751                         check_subheader_line(line);
752         }
753         fclose(patchfile);
754         if (!patch_lines) {
755                 fprintf(stderr, "No patch found\n");
756                 exit(1);
757         }
758 }
759
760 /* Non multipart message */
761 static void handle_body(void)
762 {
763         int seen = 0;
764
765         if (line[0] || fgets(line, sizeof(line), stdin) != NULL) {
766                 handle_commit_msg(&seen);
767                 handle_patch();
768         }
769         fclose(patchfile);
770         if (!patch_lines) {
771                 fprintf(stderr, "No patch found\n");
772                 exit(1);
773         }
774 }
775
776 static const char mailinfo_usage[] =
777         "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
778
779 int main(int argc, char **argv)
780 {
781         /* NEEDSWORK: might want to do the optional .git/ directory
782          * discovery
783          */
784         git_config(git_default_config);
785
786         while (1 < argc && argv[1][0] == '-') {
787                 if (!strcmp(argv[1], "-k"))
788                         keep_subject = 1;
789                 else if (!strcmp(argv[1], "-u"))
790                         metainfo_charset = git_commit_encoding;
791                 else if (!strncmp(argv[1], "--encoding=", 11))
792                         metainfo_charset = argv[1] + 11;
793                 else
794                         usage(mailinfo_usage);
795                 argc--; argv++;
796         }
797
798         if (argc != 3)
799                 usage(mailinfo_usage);
800         cmitmsg = fopen(argv[1], "w");
801         if (!cmitmsg) {
802                 perror(argv[1]);
803                 exit(1);
804         }
805         patchfile = fopen(argv[2], "w");
806         if (!patchfile) {
807                 perror(argv[2]);
808                 exit(1);
809         }
810         while (1) {
811                 int hdr = read_one_header_line(line, sizeof(line), stdin);
812                 if (!hdr) {
813                         if (multipart_boundary[0])
814                                 handle_multipart_body();
815                         else
816                                 handle_body();
817                         handle_info();
818                         break;
819                 }
820                 check_header_line(line);
821         }
822         return 0;
823 }