Merge branch 'sp/maint-http-enable-gzip' into maint
[git] / builtin / mailinfo.c
1 /*
2  * Another stupid program, this one parsing the headers of an
3  * email to figure out authorship and subject
4  */
5 #include "cache.h"
6 #include "builtin.h"
7 #include "utf8.h"
8 #include "strbuf.h"
9
10 static FILE *cmitmsg, *patchfile, *fin, *fout;
11
12 static int keep_subject;
13 static int keep_non_patch_brackets_in_subject;
14 static const char *metainfo_charset;
15 static struct strbuf line = STRBUF_INIT;
16 static struct strbuf name = STRBUF_INIT;
17 static struct strbuf email = STRBUF_INIT;
18
19 static enum  {
20         TE_DONTCARE, TE_QP, TE_BASE64
21 } transfer_encoding;
22 static enum  {
23         TYPE_TEXT, TYPE_OTHER
24 } message_type;
25
26 static struct strbuf charset = STRBUF_INIT;
27 static int patch_lines;
28 static struct strbuf **p_hdr_data, **s_hdr_data;
29 static int use_scissors;
30 static int use_inbody_headers = 1;
31
32 #define MAX_HDR_PARSED 10
33 #define MAX_BOUNDARIES 5
34
35 static void cleanup_space(struct strbuf *sb);
36
37
38 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
39 {
40         struct strbuf *src = name;
41         if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
42                 strchr(name->buf, '<') || strchr(name->buf, '>'))
43                 src = email;
44         else if (name == out)
45                 return;
46         strbuf_reset(out);
47         strbuf_addbuf(out, src);
48 }
49
50 static void parse_bogus_from(const struct strbuf *line)
51 {
52         /* John Doe <johndoe> */
53
54         char *bra, *ket;
55         /* This is fallback, so do not bother if we already have an
56          * e-mail address.
57          */
58         if (email.len)
59                 return;
60
61         bra = strchr(line->buf, '<');
62         if (!bra)
63                 return;
64         ket = strchr(bra, '>');
65         if (!ket)
66                 return;
67
68         strbuf_reset(&email);
69         strbuf_add(&email, bra + 1, ket - bra - 1);
70
71         strbuf_reset(&name);
72         strbuf_add(&name, line->buf, bra - line->buf);
73         strbuf_trim(&name);
74         get_sane_name(&name, &name, &email);
75 }
76
77 static void handle_from(const struct strbuf *from)
78 {
79         char *at;
80         size_t el;
81         struct strbuf f;
82
83         strbuf_init(&f, from->len);
84         strbuf_addbuf(&f, from);
85
86         at = strchr(f.buf, '@');
87         if (!at) {
88                 parse_bogus_from(from);
89                 return;
90         }
91
92         /*
93          * If we already have one email, don't take any confusing lines
94          */
95         if (email.len && strchr(at + 1, '@')) {
96                 strbuf_release(&f);
97                 return;
98         }
99
100         /* Pick up the string around '@', possibly delimited with <>
101          * pair; that is the email part.
102          */
103         while (at > f.buf) {
104                 char c = at[-1];
105                 if (isspace(c))
106                         break;
107                 if (c == '<') {
108                         at[-1] = ' ';
109                         break;
110                 }
111                 at--;
112         }
113         el = strcspn(at, " \n\t\r\v\f>");
114         strbuf_reset(&email);
115         strbuf_add(&email, at, el);
116         strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
117
118         /* The remainder is name.  It could be
119          *
120          * - "John Doe <john.doe@xz>"                   (a), or
121          * - "john.doe@xz (John Doe)"                   (b), or
122          * - "John (zzz) Doe <john.doe@xz> (Comment)"   (c)
123          *
124          * but we have removed the email part, so
125          *
126          * - remove extra spaces which could stay after email (case 'c'), and
127          * - trim from both ends, possibly removing the () pair at the end
128          *   (cases 'a' and 'b').
129          */
130         cleanup_space(&f);
131         strbuf_trim(&f);
132         if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
133                 strbuf_remove(&f, 0, 1);
134                 strbuf_setlen(&f, f.len - 1);
135         }
136
137         get_sane_name(&name, &f, &email);
138         strbuf_release(&f);
139 }
140
141 static void handle_header(struct strbuf **out, const struct strbuf *line)
142 {
143         if (!*out) {
144                 *out = xmalloc(sizeof(struct strbuf));
145                 strbuf_init(*out, line->len);
146         } else
147                 strbuf_reset(*out);
148
149         strbuf_addbuf(*out, line);
150 }
151
152 /* NOTE NOTE NOTE.  We do not claim we do full MIME.  We just attempt
153  * to have enough heuristics to grok MIME encoded patches often found
154  * on our mailing lists.  For example, we do not even treat header lines
155  * case insensitively.
156  */
157
158 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
159 {
160         const char *ends, *ap = strcasestr(line, name);
161         size_t sz;
162
163         strbuf_setlen(attr, 0);
164         if (!ap)
165                 return 0;
166         ap += strlen(name);
167         if (*ap == '"') {
168                 ap++;
169                 ends = "\"";
170         }
171         else
172                 ends = "; \t";
173         sz = strcspn(ap, ends);
174         strbuf_add(attr, ap, sz);
175         return 1;
176 }
177
178 static struct strbuf *content[MAX_BOUNDARIES];
179
180 static struct strbuf **content_top = content;
181
182 static void handle_content_type(struct strbuf *line)
183 {
184         struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
185         strbuf_init(boundary, line->len);
186
187         if (!strcasestr(line->buf, "text/"))
188                  message_type = TYPE_OTHER;
189         if (slurp_attr(line->buf, "boundary=", boundary)) {
190                 strbuf_insert(boundary, 0, "--", 2);
191                 if (++content_top > &content[MAX_BOUNDARIES]) {
192                         fprintf(stderr, "Too many boundaries to handle\n");
193                         exit(1);
194                 }
195                 *content_top = boundary;
196                 boundary = NULL;
197         }
198         slurp_attr(line->buf, "charset=", &charset);
199
200         if (boundary) {
201                 strbuf_release(boundary);
202                 free(boundary);
203         }
204 }
205
206 static void handle_content_transfer_encoding(const struct strbuf *line)
207 {
208         if (strcasestr(line->buf, "base64"))
209                 transfer_encoding = TE_BASE64;
210         else if (strcasestr(line->buf, "quoted-printable"))
211                 transfer_encoding = TE_QP;
212         else
213                 transfer_encoding = TE_DONTCARE;
214 }
215
216 static int is_multipart_boundary(const struct strbuf *line)
217 {
218         return (((*content_top)->len <= line->len) &&
219                 !memcmp(line->buf, (*content_top)->buf, (*content_top)->len));
220 }
221
222 static void cleanup_subject(struct strbuf *subject)
223 {
224         size_t at = 0;
225
226         while (at < subject->len) {
227                 char *pos;
228                 size_t remove;
229
230                 switch (subject->buf[at]) {
231                 case 'r': case 'R':
232                         if (subject->len <= at + 3)
233                                 break;
234                         if ((subject->buf[at + 1] == 'e' ||
235                              subject->buf[at + 1] == 'E') &&
236                             subject->buf[at + 2] == ':') {
237                                 strbuf_remove(subject, at, 3);
238                                 continue;
239                         }
240                         at++;
241                         break;
242                 case ' ': case '\t': case ':':
243                         strbuf_remove(subject, at, 1);
244                         continue;
245                 case '[':
246                         pos = strchr(subject->buf + at, ']');
247                         if (!pos)
248                                 break;
249                         remove = pos - subject->buf + at + 1;
250                         if (!keep_non_patch_brackets_in_subject ||
251                             (7 <= remove &&
252                              memmem(subject->buf + at, remove, "PATCH", 5)))
253                                 strbuf_remove(subject, at, remove);
254                         else {
255                                 at += remove;
256                                 /*
257                                  * If the input had a space after the ], keep
258                                  * it.  We don't bother with finding the end of
259                                  * the space, since we later normalize it
260                                  * anyway.
261                                  */
262                                 if (isspace(subject->buf[at]))
263                                         at += 1;
264                         }
265                         continue;
266                 }
267                 break;
268         }
269         strbuf_trim(subject);
270 }
271
272 static void cleanup_space(struct strbuf *sb)
273 {
274         size_t pos, cnt;
275         for (pos = 0; pos < sb->len; pos++) {
276                 if (isspace(sb->buf[pos])) {
277                         sb->buf[pos] = ' ';
278                         for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
279                         strbuf_remove(sb, pos + 1, cnt);
280                 }
281         }
282 }
283
284 static void decode_header(struct strbuf *line);
285 static const char *header[MAX_HDR_PARSED] = {
286         "From","Subject","Date",
287 };
288
289 static inline int cmp_header(const struct strbuf *line, const char *hdr)
290 {
291         int len = strlen(hdr);
292         return !strncasecmp(line->buf, hdr, len) && line->len > len &&
293                         line->buf[len] == ':' && isspace(line->buf[len + 1]);
294 }
295
296 static int check_header(const struct strbuf *line,
297                                 struct strbuf *hdr_data[], int overwrite)
298 {
299         int i, ret = 0, len;
300         struct strbuf sb = STRBUF_INIT;
301         /* search for the interesting parts */
302         for (i = 0; header[i]; i++) {
303                 int len = strlen(header[i]);
304                 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
305                         /* Unwrap inline B and Q encoding, and optionally
306                          * normalize the meta information to utf8.
307                          */
308                         strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
309                         decode_header(&sb);
310                         handle_header(&hdr_data[i], &sb);
311                         ret = 1;
312                         goto check_header_out;
313                 }
314         }
315
316         /* Content stuff */
317         if (cmp_header(line, "Content-Type")) {
318                 len = strlen("Content-Type: ");
319                 strbuf_add(&sb, line->buf + len, line->len - len);
320                 decode_header(&sb);
321                 strbuf_insert(&sb, 0, "Content-Type: ", len);
322                 handle_content_type(&sb);
323                 ret = 1;
324                 goto check_header_out;
325         }
326         if (cmp_header(line, "Content-Transfer-Encoding")) {
327                 len = strlen("Content-Transfer-Encoding: ");
328                 strbuf_add(&sb, line->buf + len, line->len - len);
329                 decode_header(&sb);
330                 handle_content_transfer_encoding(&sb);
331                 ret = 1;
332                 goto check_header_out;
333         }
334
335         /* for inbody stuff */
336         if (!prefixcmp(line->buf, ">From") && isspace(line->buf[5])) {
337                 ret = 1; /* Should this return 0? */
338                 goto check_header_out;
339         }
340         if (!prefixcmp(line->buf, "[PATCH]") && isspace(line->buf[7])) {
341                 for (i = 0; header[i]; i++) {
342                         if (!memcmp("Subject", header[i], 7)) {
343                                 handle_header(&hdr_data[i], line);
344                                 ret = 1;
345                                 goto check_header_out;
346                         }
347                 }
348         }
349
350 check_header_out:
351         strbuf_release(&sb);
352         return ret;
353 }
354
355 static int is_rfc2822_header(const struct strbuf *line)
356 {
357         /*
358          * The section that defines the loosest possible
359          * field name is "3.6.8 Optional fields".
360          *
361          * optional-field = field-name ":" unstructured CRLF
362          * field-name = 1*ftext
363          * ftext = %d33-57 / %59-126
364          */
365         int ch;
366         char *cp = line->buf;
367
368         /* Count mbox From headers as headers */
369         if (!prefixcmp(cp, "From ") || !prefixcmp(cp, ">From "))
370                 return 1;
371
372         while ((ch = *cp++)) {
373                 if (ch == ':')
374                         return 1;
375                 if ((33 <= ch && ch <= 57) ||
376                     (59 <= ch && ch <= 126))
377                         continue;
378                 break;
379         }
380         return 0;
381 }
382
383 static int read_one_header_line(struct strbuf *line, FILE *in)
384 {
385         /* Get the first part of the line. */
386         if (strbuf_getline(line, in, '\n'))
387                 return 0;
388
389         /*
390          * Is it an empty line or not a valid rfc2822 header?
391          * If so, stop here, and return false ("not a header")
392          */
393         strbuf_rtrim(line);
394         if (!line->len || !is_rfc2822_header(line)) {
395                 /* Re-add the newline */
396                 strbuf_addch(line, '\n');
397                 return 0;
398         }
399
400         /*
401          * Now we need to eat all the continuation lines..
402          * Yuck, 2822 header "folding"
403          */
404         for (;;) {
405                 int peek;
406                 struct strbuf continuation = STRBUF_INIT;
407
408                 peek = fgetc(in); ungetc(peek, in);
409                 if (peek != ' ' && peek != '\t')
410                         break;
411                 if (strbuf_getline(&continuation, in, '\n'))
412                         break;
413                 continuation.buf[0] = ' ';
414                 strbuf_rtrim(&continuation);
415                 strbuf_addbuf(line, &continuation);
416         }
417
418         return 1;
419 }
420
421 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
422 {
423         const char *in = q_seg->buf;
424         int c;
425         struct strbuf *out = xmalloc(sizeof(struct strbuf));
426         strbuf_init(out, q_seg->len);
427
428         while ((c = *in++) != 0) {
429                 if (c == '=') {
430                         int d = *in++;
431                         if (d == '\n' || !d)
432                                 break; /* drop trailing newline */
433                         strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
434                         continue;
435                 }
436                 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
437                         c = 0x20;
438                 strbuf_addch(out, c);
439         }
440         return out;
441 }
442
443 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
444 {
445         /* Decode in..ep, possibly in-place to ot */
446         int c, pos = 0, acc = 0;
447         const char *in = b_seg->buf;
448         struct strbuf *out = xmalloc(sizeof(struct strbuf));
449         strbuf_init(out, b_seg->len);
450
451         while ((c = *in++) != 0) {
452                 if (c == '+')
453                         c = 62;
454                 else if (c == '/')
455                         c = 63;
456                 else if ('A' <= c && c <= 'Z')
457                         c -= 'A';
458                 else if ('a' <= c && c <= 'z')
459                         c -= 'a' - 26;
460                 else if ('0' <= c && c <= '9')
461                         c -= '0' - 52;
462                 else
463                         continue; /* garbage */
464                 switch (pos++) {
465                 case 0:
466                         acc = (c << 2);
467                         break;
468                 case 1:
469                         strbuf_addch(out, (acc | (c >> 4)));
470                         acc = (c & 15) << 4;
471                         break;
472                 case 2:
473                         strbuf_addch(out, (acc | (c >> 2)));
474                         acc = (c & 3) << 6;
475                         break;
476                 case 3:
477                         strbuf_addch(out, (acc | c));
478                         acc = pos = 0;
479                         break;
480                 }
481         }
482         return out;
483 }
484
485 /*
486  * When there is no known charset, guess.
487  *
488  * Right now we assume that if the target is UTF-8 (the default),
489  * and it already looks like UTF-8 (which includes US-ASCII as its
490  * subset, of course) then that is what it is and there is nothing
491  * to do.
492  *
493  * Otherwise, we default to assuming it is Latin1 for historical
494  * reasons.
495  */
496 static const char *guess_charset(const struct strbuf *line, const char *target_charset)
497 {
498         if (is_encoding_utf8(target_charset)) {
499                 if (is_utf8(line->buf))
500                         return NULL;
501         }
502         return "ISO8859-1";
503 }
504
505 static void convert_to_utf8(struct strbuf *line, const char *charset)
506 {
507         char *out;
508
509         if (!charset || !*charset) {
510                 charset = guess_charset(line, metainfo_charset);
511                 if (!charset)
512                         return;
513         }
514
515         if (!strcasecmp(metainfo_charset, charset))
516                 return;
517         out = reencode_string(line->buf, metainfo_charset, charset);
518         if (!out)
519                 die("cannot convert from %s to %s",
520                     charset, metainfo_charset);
521         strbuf_attach(line, out, strlen(out), strlen(out));
522 }
523
524 static int decode_header_bq(struct strbuf *it)
525 {
526         char *in, *ep, *cp;
527         struct strbuf outbuf = STRBUF_INIT, *dec;
528         struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
529         int rfc2047 = 0;
530
531         in = it->buf;
532         while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
533                 int encoding;
534                 strbuf_reset(&charset_q);
535                 strbuf_reset(&piecebuf);
536                 rfc2047 = 1;
537
538                 if (in != ep) {
539                         /*
540                          * We are about to process an encoded-word
541                          * that begins at ep, but there is something
542                          * before the encoded word.
543                          */
544                         char *scan;
545                         for (scan = in; scan < ep; scan++)
546                                 if (!isspace(*scan))
547                                         break;
548
549                         if (scan != ep || in == it->buf) {
550                                 /*
551                                  * We should not lose that "something",
552                                  * unless we have just processed an
553                                  * encoded-word, and there is only LWS
554                                  * before the one we are about to process.
555                                  */
556                                 strbuf_add(&outbuf, in, ep - in);
557                         }
558                 }
559                 /* E.g.
560                  * ep : "=?iso-2022-jp?B?GyR...?= foo"
561                  * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
562                  */
563                 ep += 2;
564
565                 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
566                         goto decode_header_bq_out;
567
568                 if (cp + 3 - it->buf > it->len)
569                         goto decode_header_bq_out;
570                 strbuf_add(&charset_q, ep, cp - ep);
571
572                 encoding = cp[1];
573                 if (!encoding || cp[2] != '?')
574                         goto decode_header_bq_out;
575                 ep = strstr(cp + 3, "?=");
576                 if (!ep)
577                         goto decode_header_bq_out;
578                 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
579                 switch (tolower(encoding)) {
580                 default:
581                         goto decode_header_bq_out;
582                 case 'b':
583                         dec = decode_b_segment(&piecebuf);
584                         break;
585                 case 'q':
586                         dec = decode_q_segment(&piecebuf, 1);
587                         break;
588                 }
589                 if (metainfo_charset)
590                         convert_to_utf8(dec, charset_q.buf);
591
592                 strbuf_addbuf(&outbuf, dec);
593                 strbuf_release(dec);
594                 free(dec);
595                 in = ep + 2;
596         }
597         strbuf_addstr(&outbuf, in);
598         strbuf_reset(it);
599         strbuf_addbuf(it, &outbuf);
600 decode_header_bq_out:
601         strbuf_release(&outbuf);
602         strbuf_release(&charset_q);
603         strbuf_release(&piecebuf);
604         return rfc2047;
605 }
606
607 static void decode_header(struct strbuf *it)
608 {
609         if (decode_header_bq(it))
610                 return;
611         /* otherwise "it" is a straight copy of the input.
612          * This can be binary guck but there is no charset specified.
613          */
614         if (metainfo_charset)
615                 convert_to_utf8(it, "");
616 }
617
618 static void decode_transfer_encoding(struct strbuf *line)
619 {
620         struct strbuf *ret;
621
622         switch (transfer_encoding) {
623         case TE_QP:
624                 ret = decode_q_segment(line, 0);
625                 break;
626         case TE_BASE64:
627                 ret = decode_b_segment(line);
628                 break;
629         case TE_DONTCARE:
630         default:
631                 return;
632         }
633         strbuf_reset(line);
634         strbuf_addbuf(line, ret);
635         strbuf_release(ret);
636         free(ret);
637 }
638
639 static void handle_filter(struct strbuf *line);
640
641 static int find_boundary(void)
642 {
643         while (!strbuf_getline(&line, fin, '\n')) {
644                 if (*content_top && is_multipart_boundary(&line))
645                         return 1;
646         }
647         return 0;
648 }
649
650 static int handle_boundary(void)
651 {
652         struct strbuf newline = STRBUF_INIT;
653
654         strbuf_addch(&newline, '\n');
655 again:
656         if (line.len >= (*content_top)->len + 2 &&
657             !memcmp(line.buf + (*content_top)->len, "--", 2)) {
658                 /* we hit an end boundary */
659                 /* pop the current boundary off the stack */
660                 strbuf_release(*content_top);
661                 free(*content_top);
662                 *content_top = NULL;
663
664                 /* technically won't happen as is_multipart_boundary()
665                    will fail first.  But just in case..
666                  */
667                 if (--content_top < content) {
668                         fprintf(stderr, "Detected mismatched boundaries, "
669                                         "can't recover\n");
670                         exit(1);
671                 }
672                 handle_filter(&newline);
673                 strbuf_release(&newline);
674
675                 /* skip to the next boundary */
676                 if (!find_boundary())
677                         return 0;
678                 goto again;
679         }
680
681         /* set some defaults */
682         transfer_encoding = TE_DONTCARE;
683         strbuf_reset(&charset);
684         message_type = TYPE_TEXT;
685
686         /* slurp in this section's info */
687         while (read_one_header_line(&line, fin))
688                 check_header(&line, p_hdr_data, 0);
689
690         strbuf_release(&newline);
691         /* replenish line */
692         if (strbuf_getline(&line, fin, '\n'))
693                 return 0;
694         strbuf_addch(&line, '\n');
695         return 1;
696 }
697
698 static inline int patchbreak(const struct strbuf *line)
699 {
700         size_t i;
701
702         /* Beginning of a "diff -" header? */
703         if (!prefixcmp(line->buf, "diff -"))
704                 return 1;
705
706         /* CVS "Index: " line? */
707         if (!prefixcmp(line->buf, "Index: "))
708                 return 1;
709
710         /*
711          * "--- <filename>" starts patches without headers
712          * "---<sp>*" is a manual separator
713          */
714         if (line->len < 4)
715                 return 0;
716
717         if (!prefixcmp(line->buf, "---")) {
718                 /* space followed by a filename? */
719                 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
720                         return 1;
721                 /* Just whitespace? */
722                 for (i = 3; i < line->len; i++) {
723                         unsigned char c = line->buf[i];
724                         if (c == '\n')
725                                 return 1;
726                         if (!isspace(c))
727                                 break;
728                 }
729                 return 0;
730         }
731         return 0;
732 }
733
734 static int is_scissors_line(const struct strbuf *line)
735 {
736         size_t i, len = line->len;
737         int scissors = 0, gap = 0;
738         int first_nonblank = -1;
739         int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
740         const char *buf = line->buf;
741
742         for (i = 0; i < len; i++) {
743                 if (isspace(buf[i])) {
744                         if (in_perforation) {
745                                 perforation++;
746                                 gap++;
747                         }
748                         continue;
749                 }
750                 last_nonblank = i;
751                 if (first_nonblank < 0)
752                         first_nonblank = i;
753                 if (buf[i] == '-') {
754                         in_perforation = 1;
755                         perforation++;
756                         continue;
757                 }
758                 if (i + 1 < len &&
759                     (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
760                      !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
761                         in_perforation = 1;
762                         perforation += 2;
763                         scissors += 2;
764                         i++;
765                         continue;
766                 }
767                 in_perforation = 0;
768         }
769
770         /*
771          * The mark must be at least 8 bytes long (e.g. "-- >8 --").
772          * Even though there can be arbitrary cruft on the same line
773          * (e.g. "cut here"), in order to avoid misidentification, the
774          * perforation must occupy more than a third of the visible
775          * width of the line, and dashes and scissors must occupy more
776          * than half of the perforation.
777          */
778
779         visible = last_nonblank - first_nonblank + 1;
780         return (scissors && 8 <= visible &&
781                 visible < perforation * 3 &&
782                 gap * 2 < perforation);
783 }
784
785 static int handle_commit_msg(struct strbuf *line)
786 {
787         static int still_looking = 1;
788
789         if (!cmitmsg)
790                 return 0;
791
792         if (still_looking) {
793                 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
794                         return 0;
795         }
796
797         if (use_inbody_headers && still_looking) {
798                 still_looking = check_header(line, s_hdr_data, 0);
799                 if (still_looking)
800                         return 0;
801         } else
802                 /* Only trim the first (blank) line of the commit message
803                  * when ignoring in-body headers.
804                  */
805                 still_looking = 0;
806
807         /* normalize the log message to UTF-8. */
808         if (metainfo_charset)
809                 convert_to_utf8(line, charset.buf);
810
811         if (use_scissors && is_scissors_line(line)) {
812                 int i;
813                 if (fseek(cmitmsg, 0L, SEEK_SET))
814                         die_errno("Could not rewind output message file");
815                 if (ftruncate(fileno(cmitmsg), 0))
816                         die_errno("Could not truncate output message file at scissors");
817                 still_looking = 1;
818
819                 /*
820                  * We may have already read "secondary headers"; purge
821                  * them to give ourselves a clean restart.
822                  */
823                 for (i = 0; header[i]; i++) {
824                         if (s_hdr_data[i])
825                                 strbuf_release(s_hdr_data[i]);
826                         s_hdr_data[i] = NULL;
827                 }
828                 return 0;
829         }
830
831         if (patchbreak(line)) {
832                 fclose(cmitmsg);
833                 cmitmsg = NULL;
834                 return 1;
835         }
836
837         fputs(line->buf, cmitmsg);
838         return 0;
839 }
840
841 static void handle_patch(const struct strbuf *line)
842 {
843         fwrite(line->buf, 1, line->len, patchfile);
844         patch_lines++;
845 }
846
847 static void handle_filter(struct strbuf *line)
848 {
849         static int filter = 0;
850
851         /* filter tells us which part we left off on */
852         switch (filter) {
853         case 0:
854                 if (!handle_commit_msg(line))
855                         break;
856                 filter++;
857         case 1:
858                 handle_patch(line);
859                 break;
860         }
861 }
862
863 static void handle_body(void)
864 {
865         struct strbuf prev = STRBUF_INIT;
866
867         /* Skip up to the first boundary */
868         if (*content_top) {
869                 if (!find_boundary())
870                         goto handle_body_out;
871         }
872
873         do {
874                 /* process any boundary lines */
875                 if (*content_top && is_multipart_boundary(&line)) {
876                         /* flush any leftover */
877                         if (prev.len) {
878                                 handle_filter(&prev);
879                                 strbuf_reset(&prev);
880                         }
881                         if (!handle_boundary())
882                                 goto handle_body_out;
883                 }
884
885                 /* Unwrap transfer encoding */
886                 decode_transfer_encoding(&line);
887
888                 switch (transfer_encoding) {
889                 case TE_BASE64:
890                 case TE_QP:
891                 {
892                         struct strbuf **lines, **it, *sb;
893
894                         /* Prepend any previous partial lines */
895                         strbuf_insert(&line, 0, prev.buf, prev.len);
896                         strbuf_reset(&prev);
897
898                         /* binary data most likely doesn't have newlines */
899                         if (message_type != TYPE_TEXT) {
900                                 handle_filter(&line);
901                                 break;
902                         }
903                         /*
904                          * This is a decoded line that may contain
905                          * multiple new lines.  Pass only one chunk
906                          * at a time to handle_filter()
907                          */
908                         lines = strbuf_split(&line, '\n');
909                         for (it = lines; (sb = *it); it++) {
910                                 if (*(it + 1) == NULL) /* The last line */
911                                         if (sb->buf[sb->len - 1] != '\n') {
912                                                 /* Partial line, save it for later. */
913                                                 strbuf_addbuf(&prev, sb);
914                                                 break;
915                                         }
916                                 handle_filter(sb);
917                         }
918                         /*
919                          * The partial chunk is saved in "prev" and will be
920                          * appended by the next iteration of read_line_with_nul().
921                          */
922                         strbuf_list_free(lines);
923                         break;
924                 }
925                 default:
926                         handle_filter(&line);
927                 }
928
929         } while (!strbuf_getwholeline(&line, fin, '\n'));
930
931 handle_body_out:
932         strbuf_release(&prev);
933 }
934
935 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
936 {
937         const char *sp = data->buf;
938         while (1) {
939                 char *ep = strchr(sp, '\n');
940                 int len;
941                 if (!ep)
942                         len = strlen(sp);
943                 else
944                         len = ep - sp;
945                 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
946                 if (!ep)
947                         break;
948                 sp = ep + 1;
949         }
950 }
951
952 static void handle_info(void)
953 {
954         struct strbuf *hdr;
955         int i;
956
957         for (i = 0; header[i]; i++) {
958                 /* only print inbody headers if we output a patch file */
959                 if (patch_lines && s_hdr_data[i])
960                         hdr = s_hdr_data[i];
961                 else if (p_hdr_data[i])
962                         hdr = p_hdr_data[i];
963                 else
964                         continue;
965
966                 if (!memcmp(header[i], "Subject", 7)) {
967                         if (!keep_subject) {
968                                 cleanup_subject(hdr);
969                                 cleanup_space(hdr);
970                         }
971                         output_header_lines(fout, "Subject", hdr);
972                 } else if (!memcmp(header[i], "From", 4)) {
973                         cleanup_space(hdr);
974                         handle_from(hdr);
975                         fprintf(fout, "Author: %s\n", name.buf);
976                         fprintf(fout, "Email: %s\n", email.buf);
977                 } else {
978                         cleanup_space(hdr);
979                         fprintf(fout, "%s: %s\n", header[i], hdr->buf);
980                 }
981         }
982         fprintf(fout, "\n");
983 }
984
985 static int mailinfo(FILE *in, FILE *out, const char *msg, const char *patch)
986 {
987         int peek;
988         fin = in;
989         fout = out;
990
991         cmitmsg = fopen(msg, "w");
992         if (!cmitmsg) {
993                 perror(msg);
994                 return -1;
995         }
996         patchfile = fopen(patch, "w");
997         if (!patchfile) {
998                 perror(patch);
999                 fclose(cmitmsg);
1000                 return -1;
1001         }
1002
1003         p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
1004         s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
1005
1006         do {
1007                 peek = fgetc(in);
1008         } while (isspace(peek));
1009         ungetc(peek, in);
1010
1011         /* process the email header */
1012         while (read_one_header_line(&line, fin))
1013                 check_header(&line, p_hdr_data, 1);
1014
1015         handle_body();
1016         handle_info();
1017
1018         return 0;
1019 }
1020
1021 static int git_mailinfo_config(const char *var, const char *value, void *unused)
1022 {
1023         if (prefixcmp(var, "mailinfo."))
1024                 return git_default_config(var, value, unused);
1025         if (!strcmp(var, "mailinfo.scissors")) {
1026                 use_scissors = git_config_bool(var, value);
1027                 return 0;
1028         }
1029         /* perhaps others here */
1030         return 0;
1031 }
1032
1033 static const char mailinfo_usage[] =
1034         "git mailinfo [-k|-b] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] msg patch < mail >info";
1035
1036 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1037 {
1038         const char *def_charset;
1039
1040         /* NEEDSWORK: might want to do the optional .git/ directory
1041          * discovery
1042          */
1043         git_config(git_mailinfo_config, NULL);
1044
1045         def_charset = get_commit_output_encoding();
1046         metainfo_charset = def_charset;
1047
1048         while (1 < argc && argv[1][0] == '-') {
1049                 if (!strcmp(argv[1], "-k"))
1050                         keep_subject = 1;
1051                 else if (!strcmp(argv[1], "-b"))
1052                         keep_non_patch_brackets_in_subject = 1;
1053                 else if (!strcmp(argv[1], "-u"))
1054                         metainfo_charset = def_charset;
1055                 else if (!strcmp(argv[1], "-n"))
1056                         metainfo_charset = NULL;
1057                 else if (!prefixcmp(argv[1], "--encoding="))
1058                         metainfo_charset = argv[1] + 11;
1059                 else if (!strcmp(argv[1], "--scissors"))
1060                         use_scissors = 1;
1061                 else if (!strcmp(argv[1], "--no-scissors"))
1062                         use_scissors = 0;
1063                 else if (!strcmp(argv[1], "--no-inbody-headers"))
1064                         use_inbody_headers = 0;
1065                 else
1066                         usage(mailinfo_usage);
1067                 argc--; argv++;
1068         }
1069
1070         if (argc != 3)
1071                 usage(mailinfo_usage);
1072
1073         return !!mailinfo(stdin, stdout, argv[1], argv[2]);
1074 }