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