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