Merge branch 'jk/reflog-date' into next
[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 static int use_scissors;
29
30 #define MAX_HDR_PARSED 10
31 #define MAX_BOUNDARIES 5
32
33 static void cleanup_space(struct strbuf *sb);
34
35
36 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
37 {
38         struct strbuf *src = name;
39         if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
40                 strchr(name->buf, '<') || strchr(name->buf, '>'))
41                 src = email;
42         else if (name == out)
43                 return;
44         strbuf_reset(out);
45         strbuf_addbuf(out, src);
46 }
47
48 static void parse_bogus_from(const struct strbuf *line)
49 {
50         /* John Doe <johndoe> */
51
52         char *bra, *ket;
53         /* This is fallback, so do not bother if we already have an
54          * e-mail address.
55          */
56         if (email.len)
57                 return;
58
59         bra = strchr(line->buf, '<');
60         if (!bra)
61                 return;
62         ket = strchr(bra, '>');
63         if (!ket)
64                 return;
65
66         strbuf_reset(&email);
67         strbuf_add(&email, bra + 1, ket - bra - 1);
68
69         strbuf_reset(&name);
70         strbuf_add(&name, line->buf, bra - line->buf);
71         strbuf_trim(&name);
72         get_sane_name(&name, &name, &email);
73 }
74
75 static void handle_from(const struct strbuf *from)
76 {
77         char *at;
78         size_t el;
79         struct strbuf f;
80
81         strbuf_init(&f, from->len);
82         strbuf_addbuf(&f, from);
83
84         at = strchr(f.buf, '@');
85         if (!at) {
86                 parse_bogus_from(from);
87                 return;
88         }
89
90         /*
91          * If we already have one email, don't take any confusing lines
92          */
93         if (email.len && strchr(at + 1, '@')) {
94                 strbuf_release(&f);
95                 return;
96         }
97
98         /* Pick up the string around '@', possibly delimited with <>
99          * pair; that is the email part.
100          */
101         while (at > f.buf) {
102                 char c = at[-1];
103                 if (isspace(c))
104                         break;
105                 if (c == '<') {
106                         at[-1] = ' ';
107                         break;
108                 }
109                 at--;
110         }
111         el = strcspn(at, " \n\t\r\v\f>");
112         strbuf_reset(&email);
113         strbuf_add(&email, at, el);
114         strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
115
116         /* The remainder is name.  It could be
117          *
118          * - "John Doe <john.doe@xz>"                   (a), or
119          * - "john.doe@xz (John Doe)"                   (b), or
120          * - "John (zzz) Doe <john.doe@xz> (Comment)"   (c)
121          *
122          * but we have removed the email part, so
123          *
124          * - remove extra spaces which could stay after email (case 'c'), and
125          * - trim from both ends, possibly removing the () pair at the end
126          *   (cases 'a' and 'b').
127          */
128         cleanup_space(&f);
129         strbuf_trim(&f);
130         if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
131                 strbuf_remove(&f, 0, 1);
132                 strbuf_setlen(&f, f.len - 1);
133         }
134
135         get_sane_name(&name, &f, &email);
136         strbuf_release(&f);
137 }
138
139 static void handle_header(struct strbuf **out, const struct strbuf *line)
140 {
141         if (!*out) {
142                 *out = xmalloc(sizeof(struct strbuf));
143                 strbuf_init(*out, line->len);
144         } else
145                 strbuf_reset(*out);
146
147         strbuf_addbuf(*out, line);
148 }
149
150 /* NOTE NOTE NOTE.  We do not claim we do full MIME.  We just attempt
151  * to have enough heuristics to grok MIME encoded patches often found
152  * on our mailing lists.  For example, we do not even treat header lines
153  * case insensitively.
154  */
155
156 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
157 {
158         const char *ends, *ap = strcasestr(line, name);
159         size_t sz;
160
161         if (!ap) {
162                 strbuf_setlen(attr, 0);
163                 return 0;
164         }
165         ap += strlen(name);
166         if (*ap == '"') {
167                 ap++;
168                 ends = "\"";
169         }
170         else
171                 ends = "; \t";
172         sz = strcspn(ap, ends);
173         strbuf_add(attr, ap, sz);
174         return 1;
175 }
176
177 static struct strbuf *content[MAX_BOUNDARIES];
178
179 static struct strbuf **content_top = content;
180
181 static void handle_content_type(struct strbuf *line)
182 {
183         struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
184         strbuf_init(boundary, line->len);
185
186         if (!strcasestr(line->buf, "text/"))
187                  message_type = TYPE_OTHER;
188         if (slurp_attr(line->buf, "boundary=", boundary)) {
189                 strbuf_insert(boundary, 0, "--", 2);
190                 if (++content_top > &content[MAX_BOUNDARIES]) {
191                         fprintf(stderr, "Too many boundaries to handle\n");
192                         exit(1);
193                 }
194                 *content_top = boundary;
195                 boundary = NULL;
196         }
197         slurp_attr(line->buf, "charset=", &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 "ISO8859-1";
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 (!strcasecmp(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
554                 encoding = cp[1];
555                 if (!encoding || cp[2] != '?')
556                         goto decode_header_bq_out;
557                 ep = strstr(cp + 3, "?=");
558                 if (!ep)
559                         goto decode_header_bq_out;
560                 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
561                 switch (tolower(encoding)) {
562                 default:
563                         goto decode_header_bq_out;
564                 case 'b':
565                         dec = decode_b_segment(&piecebuf);
566                         break;
567                 case 'q':
568                         dec = decode_q_segment(&piecebuf, 1);
569                         break;
570                 }
571                 if (metainfo_charset)
572                         convert_to_utf8(dec, charset_q.buf);
573
574                 strbuf_addbuf(&outbuf, dec);
575                 strbuf_release(dec);
576                 free(dec);
577                 in = ep + 2;
578         }
579         strbuf_addstr(&outbuf, in);
580         strbuf_reset(it);
581         strbuf_addbuf(it, &outbuf);
582 decode_header_bq_out:
583         strbuf_release(&outbuf);
584         strbuf_release(&charset_q);
585         strbuf_release(&piecebuf);
586         return rfc2047;
587 }
588
589 static void decode_header(struct strbuf *it)
590 {
591         if (decode_header_bq(it))
592                 return;
593         /* otherwise "it" is a straight copy of the input.
594          * This can be binary guck but there is no charset specified.
595          */
596         if (metainfo_charset)
597                 convert_to_utf8(it, "");
598 }
599
600 static void decode_transfer_encoding(struct strbuf *line)
601 {
602         struct strbuf *ret;
603
604         switch (transfer_encoding) {
605         case TE_QP:
606                 ret = decode_q_segment(line, 0);
607                 break;
608         case TE_BASE64:
609                 ret = decode_b_segment(line);
610                 break;
611         case TE_DONTCARE:
612         default:
613                 return;
614         }
615         strbuf_reset(line);
616         strbuf_addbuf(line, ret);
617         strbuf_release(ret);
618         free(ret);
619 }
620
621 static void handle_filter(struct strbuf *line);
622
623 static int find_boundary(void)
624 {
625         while (!strbuf_getline(&line, fin, '\n')) {
626                 if (*content_top && is_multipart_boundary(&line))
627                         return 1;
628         }
629         return 0;
630 }
631
632 static int handle_boundary(void)
633 {
634         struct strbuf newline = STRBUF_INIT;
635
636         strbuf_addch(&newline, '\n');
637 again:
638         if (line.len >= (*content_top)->len + 2 &&
639             !memcmp(line.buf + (*content_top)->len, "--", 2)) {
640                 /* we hit an end boundary */
641                 /* pop the current boundary off the stack */
642                 strbuf_release(*content_top);
643                 free(*content_top);
644                 *content_top = NULL;
645
646                 /* technically won't happen as is_multipart_boundary()
647                    will fail first.  But just in case..
648                  */
649                 if (--content_top < content) {
650                         fprintf(stderr, "Detected mismatched boundaries, "
651                                         "can't recover\n");
652                         exit(1);
653                 }
654                 handle_filter(&newline);
655                 strbuf_release(&newline);
656
657                 /* skip to the next boundary */
658                 if (!find_boundary())
659                         return 0;
660                 goto again;
661         }
662
663         /* set some defaults */
664         transfer_encoding = TE_DONTCARE;
665         strbuf_reset(&charset);
666         message_type = TYPE_TEXT;
667
668         /* slurp in this section's info */
669         while (read_one_header_line(&line, fin))
670                 check_header(&line, p_hdr_data, 0);
671
672         strbuf_release(&newline);
673         /* replenish line */
674         if (strbuf_getline(&line, fin, '\n'))
675                 return 0;
676         strbuf_addch(&line, '\n');
677         return 1;
678 }
679
680 static inline int patchbreak(const struct strbuf *line)
681 {
682         size_t i;
683
684         /* Beginning of a "diff -" header? */
685         if (!prefixcmp(line->buf, "diff -"))
686                 return 1;
687
688         /* CVS "Index: " line? */
689         if (!prefixcmp(line->buf, "Index: "))
690                 return 1;
691
692         /*
693          * "--- <filename>" starts patches without headers
694          * "---<sp>*" is a manual separator
695          */
696         if (line->len < 4)
697                 return 0;
698
699         if (!prefixcmp(line->buf, "---")) {
700                 /* space followed by a filename? */
701                 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
702                         return 1;
703                 /* Just whitespace? */
704                 for (i = 3; i < line->len; i++) {
705                         unsigned char c = line->buf[i];
706                         if (c == '\n')
707                                 return 1;
708                         if (!isspace(c))
709                                 break;
710                 }
711                 return 0;
712         }
713         return 0;
714 }
715
716 static int is_scissors_line(const struct strbuf *line)
717 {
718         size_t i, len = line->len;
719         int scissors = 0, gap = 0;
720         int first_nonblank = -1;
721         int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
722         const char *buf = line->buf;
723
724         for (i = 0; i < len; i++) {
725                 if (isspace(buf[i])) {
726                         if (in_perforation) {
727                                 perforation++;
728                                 gap++;
729                         }
730                         continue;
731                 }
732                 last_nonblank = i;
733                 if (first_nonblank < 0)
734                         first_nonblank = i;
735                 if (buf[i] == '-') {
736                         in_perforation = 1;
737                         perforation++;
738                         continue;
739                 }
740                 if (i + 1 < len &&
741                     (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2))) {
742                         in_perforation = 1;
743                         perforation += 2;
744                         scissors += 2;
745                         i++;
746                         continue;
747                 }
748                 in_perforation = 0;
749         }
750
751         /*
752          * The mark must be at least 8 bytes long (e.g. "-- >8 --").
753          * Even though there can be arbitrary cruft on the same line
754          * (e.g. "cut here"), in order to avoid misidentification, the
755          * perforation must occupy more than a third of the visible
756          * width of the line, and dashes and scissors must occupy more
757          * than half of the perforation.
758          */
759
760         visible = last_nonblank - first_nonblank + 1;
761         return (scissors && 8 <= visible &&
762                 visible < perforation * 3 &&
763                 gap * 2 < perforation);
764 }
765
766 static int handle_commit_msg(struct strbuf *line)
767 {
768         static int still_looking = 1;
769
770         if (!cmitmsg)
771                 return 0;
772
773         if (still_looking) {
774                 strbuf_ltrim(line);
775                 if (!line->len)
776                         return 0;
777                 still_looking = check_header(line, s_hdr_data, 0);
778                 if (still_looking)
779                         return 0;
780         }
781
782         /* normalize the log message to UTF-8. */
783         if (metainfo_charset)
784                 convert_to_utf8(line, charset.buf);
785
786         if (use_scissors && is_scissors_line(line)) {
787                 int i;
788                 if (fseek(cmitmsg, 0L, SEEK_SET))
789                         die_errno("Could not rewind output message file");
790                 if (ftruncate(fileno(cmitmsg), 0))
791                         die_errno("Could not truncate output message file at scissors");
792                 still_looking = 1;
793
794                 /*
795                  * We may have already read "secondary headers"; purge
796                  * them to give ourselves a clean restart.
797                  */
798                 for (i = 0; header[i]; i++) {
799                         if (s_hdr_data[i])
800                                 strbuf_release(s_hdr_data[i]);
801                         s_hdr_data[i] = NULL;
802                 }
803                 return 0;
804         }
805
806         if (patchbreak(line)) {
807                 fclose(cmitmsg);
808                 cmitmsg = NULL;
809                 return 1;
810         }
811
812         fputs(line->buf, cmitmsg);
813         return 0;
814 }
815
816 static void handle_patch(const struct strbuf *line)
817 {
818         fwrite(line->buf, 1, line->len, patchfile);
819         patch_lines++;
820 }
821
822 static void handle_filter(struct strbuf *line)
823 {
824         static int filter = 0;
825
826         /* filter tells us which part we left off on */
827         switch (filter) {
828         case 0:
829                 if (!handle_commit_msg(line))
830                         break;
831                 filter++;
832         case 1:
833                 handle_patch(line);
834                 break;
835         }
836 }
837
838 static void handle_body(void)
839 {
840         struct strbuf prev = STRBUF_INIT;
841
842         /* Skip up to the first boundary */
843         if (*content_top) {
844                 if (!find_boundary())
845                         goto handle_body_out;
846         }
847
848         do {
849                 /* process any boundary lines */
850                 if (*content_top && is_multipart_boundary(&line)) {
851                         /* flush any leftover */
852                         if (prev.len) {
853                                 handle_filter(&prev);
854                                 strbuf_reset(&prev);
855                         }
856                         if (!handle_boundary())
857                                 goto handle_body_out;
858                 }
859
860                 /* Unwrap transfer encoding */
861                 decode_transfer_encoding(&line);
862
863                 switch (transfer_encoding) {
864                 case TE_BASE64:
865                 case TE_QP:
866                 {
867                         struct strbuf **lines, **it, *sb;
868
869                         /* Prepend any previous partial lines */
870                         strbuf_insert(&line, 0, prev.buf, prev.len);
871                         strbuf_reset(&prev);
872
873                         /* binary data most likely doesn't have newlines */
874                         if (message_type != TYPE_TEXT) {
875                                 handle_filter(&line);
876                                 break;
877                         }
878                         /*
879                          * This is a decoded line that may contain
880                          * multiple new lines.  Pass only one chunk
881                          * at a time to handle_filter()
882                          */
883                         lines = strbuf_split(&line, '\n');
884                         for (it = lines; (sb = *it); it++) {
885                                 if (*(it + 1) == NULL) /* The last line */
886                                         if (sb->buf[sb->len - 1] != '\n') {
887                                                 /* Partial line, save it for later. */
888                                                 strbuf_addbuf(&prev, sb);
889                                                 break;
890                                         }
891                                 handle_filter(sb);
892                         }
893                         /*
894                          * The partial chunk is saved in "prev" and will be
895                          * appended by the next iteration of read_line_with_nul().
896                          */
897                         strbuf_list_free(lines);
898                         break;
899                 }
900                 default:
901                         handle_filter(&line);
902                 }
903
904         } while (!strbuf_getwholeline(&line, fin, '\n'));
905
906 handle_body_out:
907         strbuf_release(&prev);
908 }
909
910 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
911 {
912         const char *sp = data->buf;
913         while (1) {
914                 char *ep = strchr(sp, '\n');
915                 int len;
916                 if (!ep)
917                         len = strlen(sp);
918                 else
919                         len = ep - sp;
920                 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
921                 if (!ep)
922                         break;
923                 sp = ep + 1;
924         }
925 }
926
927 static void handle_info(void)
928 {
929         struct strbuf *hdr;
930         int i;
931
932         for (i = 0; header[i]; i++) {
933                 /* only print inbody headers if we output a patch file */
934                 if (patch_lines && s_hdr_data[i])
935                         hdr = s_hdr_data[i];
936                 else if (p_hdr_data[i])
937                         hdr = p_hdr_data[i];
938                 else
939                         continue;
940
941                 if (!memcmp(header[i], "Subject", 7)) {
942                         if (!keep_subject) {
943                                 cleanup_subject(hdr);
944                                 cleanup_space(hdr);
945                         }
946                         output_header_lines(fout, "Subject", hdr);
947                 } else if (!memcmp(header[i], "From", 4)) {
948                         cleanup_space(hdr);
949                         handle_from(hdr);
950                         fprintf(fout, "Author: %s\n", name.buf);
951                         fprintf(fout, "Email: %s\n", email.buf);
952                 } else {
953                         cleanup_space(hdr);
954                         fprintf(fout, "%s: %s\n", header[i], hdr->buf);
955                 }
956         }
957         fprintf(fout, "\n");
958 }
959
960 static int mailinfo(FILE *in, FILE *out, const char *msg, const char *patch)
961 {
962         int peek;
963         fin = in;
964         fout = out;
965
966         cmitmsg = fopen(msg, "w");
967         if (!cmitmsg) {
968                 perror(msg);
969                 return -1;
970         }
971         patchfile = fopen(patch, "w");
972         if (!patchfile) {
973                 perror(patch);
974                 fclose(cmitmsg);
975                 return -1;
976         }
977
978         p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
979         s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
980
981         do {
982                 peek = fgetc(in);
983         } while (isspace(peek));
984         ungetc(peek, in);
985
986         /* process the email header */
987         while (read_one_header_line(&line, fin))
988                 check_header(&line, p_hdr_data, 1);
989
990         handle_body();
991         handle_info();
992
993         return 0;
994 }
995
996 static int git_mailinfo_config(const char *var, const char *value, void *unused)
997 {
998         if (prefixcmp(var, "mailinfo."))
999                 return git_default_config(var, value, unused);
1000         if (!strcmp(var, "mailinfo.scissors")) {
1001                 use_scissors = git_config_bool(var, value);
1002                 return 0;
1003         }
1004         /* perhaps others here */
1005         return 0;
1006 }
1007
1008 static const char mailinfo_usage[] =
1009         "git mailinfo [-k] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] msg patch < mail >info";
1010
1011 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1012 {
1013         const char *def_charset;
1014
1015         /* NEEDSWORK: might want to do the optional .git/ directory
1016          * discovery
1017          */
1018         git_config(git_mailinfo_config, NULL);
1019
1020         def_charset = (git_commit_encoding ? git_commit_encoding : "UTF-8");
1021         metainfo_charset = def_charset;
1022
1023         while (1 < argc && argv[1][0] == '-') {
1024                 if (!strcmp(argv[1], "-k"))
1025                         keep_subject = 1;
1026                 else if (!strcmp(argv[1], "-u"))
1027                         metainfo_charset = def_charset;
1028                 else if (!strcmp(argv[1], "-n"))
1029                         metainfo_charset = NULL;
1030                 else if (!prefixcmp(argv[1], "--encoding="))
1031                         metainfo_charset = argv[1] + 11;
1032                 else if (!strcmp(argv[1], "--scissors"))
1033                         use_scissors = 1;
1034                 else if (!strcmp(argv[1], "--no-scissors"))
1035                         use_scissors = 0;
1036                 else
1037                         usage(mailinfo_usage);
1038                 argc--; argv++;
1039         }
1040
1041         if (argc != 3)
1042                 usage(mailinfo_usage);
1043
1044         return !!mailinfo(stdin, stdout, argv[1], argv[2]);
1045 }