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