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