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