string_list: add a function string_list_longest_prefix()
[git] / builtin / mailinfo.c
1 /*
2  * Another stupid program, this one parsing the headers of an
3  * email to figure out authorship and subject
4  */
5 #include "cache.h"
6 #include "builtin.h"
7 #include "utf8.h"
8 #include "strbuf.h"
9
10 static FILE *cmitmsg, *patchfile, *fin, *fout;
11
12 static int keep_subject;
13 static int keep_non_patch_brackets_in_subject;
14 static const char *metainfo_charset;
15 static struct strbuf line = STRBUF_INIT;
16 static struct strbuf name = STRBUF_INIT;
17 static struct strbuf email = STRBUF_INIT;
18
19 static enum  {
20         TE_DONTCARE, TE_QP, TE_BASE64
21 } transfer_encoding;
22 static enum  {
23         TYPE_TEXT, TYPE_OTHER
24 } message_type;
25
26 static struct strbuf charset = STRBUF_INIT;
27 static int patch_lines;
28 static struct strbuf **p_hdr_data, **s_hdr_data;
29 static int use_scissors;
30 static int use_inbody_headers = 1;
31
32 #define MAX_HDR_PARSED 10
33 #define MAX_BOUNDARIES 5
34
35 static void cleanup_space(struct strbuf *sb);
36
37
38 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
39 {
40         struct strbuf *src = name;
41         if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
42                 strchr(name->buf, '<') || strchr(name->buf, '>'))
43                 src = email;
44         else if (name == out)
45                 return;
46         strbuf_reset(out);
47         strbuf_addbuf(out, src);
48 }
49
50 static void parse_bogus_from(const struct strbuf *line)
51 {
52         /* John Doe <johndoe> */
53
54         char *bra, *ket;
55         /* This is fallback, so do not bother if we already have an
56          * e-mail address.
57          */
58         if (email.len)
59                 return;
60
61         bra = strchr(line->buf, '<');
62         if (!bra)
63                 return;
64         ket = strchr(bra, '>');
65         if (!ket)
66                 return;
67
68         strbuf_reset(&email);
69         strbuf_add(&email, bra + 1, ket - bra - 1);
70
71         strbuf_reset(&name);
72         strbuf_add(&name, line->buf, bra - line->buf);
73         strbuf_trim(&name);
74         get_sane_name(&name, &name, &email);
75 }
76
77 static void handle_from(const struct strbuf *from)
78 {
79         char *at;
80         size_t el;
81         struct strbuf f;
82
83         strbuf_init(&f, from->len);
84         strbuf_addbuf(&f, from);
85
86         at = strchr(f.buf, '@');
87         if (!at) {
88                 parse_bogus_from(from);
89                 return;
90         }
91
92         /*
93          * If we already have one email, don't take any confusing lines
94          */
95         if (email.len && strchr(at + 1, '@')) {
96                 strbuf_release(&f);
97                 return;
98         }
99
100         /* Pick up the string around '@', possibly delimited with <>
101          * pair; that is the email part.
102          */
103         while (at > f.buf) {
104                 char c = at[-1];
105                 if (isspace(c))
106                         break;
107                 if (c == '<') {
108                         at[-1] = ' ';
109                         break;
110                 }
111                 at--;
112         }
113         el = strcspn(at, " \n\t\r\v\f>");
114         strbuf_reset(&email);
115         strbuf_add(&email, at, el);
116         strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
117
118         /* The remainder is name.  It could be
119          *
120          * - "John Doe <john.doe@xz>"                   (a), or
121          * - "john.doe@xz (John Doe)"                   (b), or
122          * - "John (zzz) Doe <john.doe@xz> (Comment)"   (c)
123          *
124          * but we have removed the email part, so
125          *
126          * - remove extra spaces which could stay after email (case 'c'), and
127          * - trim from both ends, possibly removing the () pair at the end
128          *   (cases 'a' and 'b').
129          */
130         cleanup_space(&f);
131         strbuf_trim(&f);
132         if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
133                 strbuf_remove(&f, 0, 1);
134                 strbuf_setlen(&f, f.len - 1);
135         }
136
137         get_sane_name(&name, &f, &email);
138         strbuf_release(&f);
139 }
140
141 static void handle_header(struct strbuf **out, const struct strbuf *line)
142 {
143         if (!*out) {
144                 *out = xmalloc(sizeof(struct strbuf));
145                 strbuf_init(*out, line->len);
146         } else
147                 strbuf_reset(*out);
148
149         strbuf_addbuf(*out, line);
150 }
151
152 /* NOTE NOTE NOTE.  We do not claim we do full MIME.  We just attempt
153  * to have enough heuristics to grok MIME encoded patches often found
154  * on our mailing lists.  For example, we do not even treat header lines
155  * case insensitively.
156  */
157
158 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
159 {
160         const char *ends, *ap = strcasestr(line, name);
161         size_t sz;
162
163         if (!ap) {
164                 strbuf_setlen(attr, 0);
165                 return 0;
166         }
167         ap += strlen(name);
168         if (*ap == '"') {
169                 ap++;
170                 ends = "\"";
171         }
172         else
173                 ends = "; \t";
174         sz = strcspn(ap, ends);
175         strbuf_add(attr, ap, sz);
176         return 1;
177 }
178
179 static struct strbuf *content[MAX_BOUNDARIES];
180
181 static struct strbuf **content_top = content;
182
183 static void handle_content_type(struct strbuf *line)
184 {
185         struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
186         strbuf_init(boundary, line->len);
187
188         if (!strcasestr(line->buf, "text/"))
189                  message_type = TYPE_OTHER;
190         if (slurp_attr(line->buf, "boundary=", boundary)) {
191                 strbuf_insert(boundary, 0, "--", 2);
192                 if (++content_top > &content[MAX_BOUNDARIES]) {
193                         fprintf(stderr, "Too many boundaries to handle\n");
194                         exit(1);
195                 }
196                 *content_top = boundary;
197                 boundary = NULL;
198         }
199         slurp_attr(line->buf, "charset=", &charset);
200
201         if (boundary) {
202                 strbuf_release(boundary);
203                 free(boundary);
204         }
205 }
206
207 static void handle_content_transfer_encoding(const struct strbuf *line)
208 {
209         if (strcasestr(line->buf, "base64"))
210                 transfer_encoding = TE_BASE64;
211         else if (strcasestr(line->buf, "quoted-printable"))
212                 transfer_encoding = TE_QP;
213         else
214                 transfer_encoding = TE_DONTCARE;
215 }
216
217 static int is_multipart_boundary(const struct strbuf *line)
218 {
219         return (((*content_top)->len <= line->len) &&
220                 !memcmp(line->buf, (*content_top)->buf, (*content_top)->len));
221 }
222
223 static void cleanup_subject(struct strbuf *subject)
224 {
225         size_t at = 0;
226
227         while (at < subject->len) {
228                 char *pos;
229                 size_t remove;
230
231                 switch (subject->buf[at]) {
232                 case 'r': case 'R':
233                         if (subject->len <= at + 3)
234                                 break;
235                         if (!memcmp(subject->buf + at + 1, "e:", 2)) {
236                                 strbuf_remove(subject, at, 3);
237                                 continue;
238                         }
239                         at++;
240                         break;
241                 case ' ': case '\t': case ':':
242                         strbuf_remove(subject, at, 1);
243                         continue;
244                 case '[':
245                         pos = strchr(subject->buf + at, ']');
246                         if (!pos)
247                                 break;
248                         remove = pos - subject->buf + at + 1;
249                         if (!keep_non_patch_brackets_in_subject ||
250                             (7 <= remove &&
251                              memmem(subject->buf + at, remove, "PATCH", 5)))
252                                 strbuf_remove(subject, at, remove);
253                         else {
254                                 at += remove;
255                                 /*
256                                  * If the input had a space after the ], keep
257                                  * it.  We don't bother with finding the end of
258                                  * the space, since we later normalize it
259                                  * anyway.
260                                  */
261                                 if (isspace(subject->buf[at]))
262                                         at += 1;
263                         }
264                         continue;
265                 }
266                 break;
267         }
268         strbuf_trim(subject);
269 }
270
271 static void cleanup_space(struct strbuf *sb)
272 {
273         size_t pos, cnt;
274         for (pos = 0; pos < sb->len; pos++) {
275                 if (isspace(sb->buf[pos])) {
276                         sb->buf[pos] = ' ';
277                         for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
278                         strbuf_remove(sb, pos + 1, cnt);
279                 }
280         }
281 }
282
283 static void decode_header(struct strbuf *line);
284 static const char *header[MAX_HDR_PARSED] = {
285         "From","Subject","Date",
286 };
287
288 static inline int cmp_header(const struct strbuf *line, const char *hdr)
289 {
290         int len = strlen(hdr);
291         return !strncasecmp(line->buf, hdr, len) && line->len > len &&
292                         line->buf[len] == ':' && isspace(line->buf[len + 1]);
293 }
294
295 static int check_header(const struct strbuf *line,
296                                 struct strbuf *hdr_data[], int overwrite)
297 {
298         int i, ret = 0, len;
299         struct strbuf sb = STRBUF_INIT;
300         /* search for the interesting parts */
301         for (i = 0; header[i]; i++) {
302                 int len = strlen(header[i]);
303                 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
304                         /* Unwrap inline B and Q encoding, and optionally
305                          * normalize the meta information to utf8.
306                          */
307                         strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
308                         decode_header(&sb);
309                         handle_header(&hdr_data[i], &sb);
310                         ret = 1;
311                         goto check_header_out;
312                 }
313         }
314
315         /* Content stuff */
316         if (cmp_header(line, "Content-Type")) {
317                 len = strlen("Content-Type: ");
318                 strbuf_add(&sb, line->buf + len, line->len - len);
319                 decode_header(&sb);
320                 strbuf_insert(&sb, 0, "Content-Type: ", len);
321                 handle_content_type(&sb);
322                 ret = 1;
323                 goto check_header_out;
324         }
325         if (cmp_header(line, "Content-Transfer-Encoding")) {
326                 len = strlen("Content-Transfer-Encoding: ");
327                 strbuf_add(&sb, line->buf + len, line->len - len);
328                 decode_header(&sb);
329                 handle_content_transfer_encoding(&sb);
330                 ret = 1;
331                 goto check_header_out;
332         }
333
334         /* for inbody stuff */
335         if (!prefixcmp(line->buf, ">From") && isspace(line->buf[5])) {
336                 ret = 1; /* Should this return 0? */
337                 goto check_header_out;
338         }
339         if (!prefixcmp(line->buf, "[PATCH]") && isspace(line->buf[7])) {
340                 for (i = 0; header[i]; i++) {
341                         if (!memcmp("Subject", header[i], 7)) {
342                                 handle_header(&hdr_data[i], line);
343                                 ret = 1;
344                                 goto check_header_out;
345                         }
346                 }
347         }
348
349 check_header_out:
350         strbuf_release(&sb);
351         return ret;
352 }
353
354 static int is_rfc2822_header(const struct strbuf *line)
355 {
356         /*
357          * The section that defines the loosest possible
358          * field name is "3.6.8 Optional fields".
359          *
360          * optional-field = field-name ":" unstructured CRLF
361          * field-name = 1*ftext
362          * ftext = %d33-57 / %59-126
363          */
364         int ch;
365         char *cp = line->buf;
366
367         /* Count mbox From headers as headers */
368         if (!prefixcmp(cp, "From ") || !prefixcmp(cp, ">From "))
369                 return 1;
370
371         while ((ch = *cp++)) {
372                 if (ch == ':')
373                         return 1;
374                 if ((33 <= ch && ch <= 57) ||
375                     (59 <= ch && ch <= 126))
376                         continue;
377                 break;
378         }
379         return 0;
380 }
381
382 static int read_one_header_line(struct strbuf *line, FILE *in)
383 {
384         /* Get the first part of the line. */
385         if (strbuf_getline(line, in, '\n'))
386                 return 0;
387
388         /*
389          * Is it an empty line or not a valid rfc2822 header?
390          * If so, stop here, and return false ("not a header")
391          */
392         strbuf_rtrim(line);
393         if (!line->len || !is_rfc2822_header(line)) {
394                 /* Re-add the newline */
395                 strbuf_addch(line, '\n');
396                 return 0;
397         }
398
399         /*
400          * Now we need to eat all the continuation lines..
401          * Yuck, 2822 header "folding"
402          */
403         for (;;) {
404                 int peek;
405                 struct strbuf continuation = STRBUF_INIT;
406
407                 peek = fgetc(in); ungetc(peek, in);
408                 if (peek != ' ' && peek != '\t')
409                         break;
410                 if (strbuf_getline(&continuation, in, '\n'))
411                         break;
412                 continuation.buf[0] = ' ';
413                 strbuf_rtrim(&continuation);
414                 strbuf_addbuf(line, &continuation);
415         }
416
417         return 1;
418 }
419
420 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
421 {
422         const char *in = q_seg->buf;
423         int c;
424         struct strbuf *out = xmalloc(sizeof(struct strbuf));
425         strbuf_init(out, q_seg->len);
426
427         while ((c = *in++) != 0) {
428                 if (c == '=') {
429                         int d = *in++;
430                         if (d == '\n' || !d)
431                                 break; /* drop trailing newline */
432                         strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
433                         continue;
434                 }
435                 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
436                         c = 0x20;
437                 strbuf_addch(out, c);
438         }
439         return out;
440 }
441
442 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
443 {
444         /* Decode in..ep, possibly in-place to ot */
445         int c, pos = 0, acc = 0;
446         const char *in = b_seg->buf;
447         struct strbuf *out = xmalloc(sizeof(struct strbuf));
448         strbuf_init(out, b_seg->len);
449
450         while ((c = *in++) != 0) {
451                 if (c == '+')
452                         c = 62;
453                 else if (c == '/')
454                         c = 63;
455                 else if ('A' <= c && c <= 'Z')
456                         c -= 'A';
457                 else if ('a' <= c && c <= 'z')
458                         c -= 'a' - 26;
459                 else if ('0' <= c && c <= '9')
460                         c -= '0' - 52;
461                 else
462                         continue; /* garbage */
463                 switch (pos++) {
464                 case 0:
465                         acc = (c << 2);
466                         break;
467                 case 1:
468                         strbuf_addch(out, (acc | (c >> 4)));
469                         acc = (c & 15) << 4;
470                         break;
471                 case 2:
472                         strbuf_addch(out, (acc | (c >> 2)));
473                         acc = (c & 3) << 6;
474                         break;
475                 case 3:
476                         strbuf_addch(out, (acc | c));
477                         acc = pos = 0;
478                         break;
479                 }
480         }
481         return out;
482 }
483
484 static void convert_to_utf8(struct strbuf *line, const char *charset)
485 {
486         char *out;
487
488         if (!charset || !*charset)
489                 return;
490         if (!strcasecmp(metainfo_charset, charset))
491                 return;
492         out = reencode_string(line->buf, metainfo_charset, charset);
493         if (!out)
494                 die("cannot convert from %s to %s",
495                     charset, metainfo_charset);
496         strbuf_attach(line, out, strlen(out), strlen(out));
497 }
498
499 static int decode_header_bq(struct strbuf *it)
500 {
501         char *in, *ep, *cp;
502         struct strbuf outbuf = STRBUF_INIT, *dec;
503         struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
504         int rfc2047 = 0;
505
506         in = it->buf;
507         while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
508                 int encoding;
509                 strbuf_reset(&charset_q);
510                 strbuf_reset(&piecebuf);
511                 rfc2047 = 1;
512
513                 if (in != ep) {
514                         /*
515                          * We are about to process an encoded-word
516                          * that begins at ep, but there is something
517                          * before the encoded word.
518                          */
519                         char *scan;
520                         for (scan = in; scan < ep; scan++)
521                                 if (!isspace(*scan))
522                                         break;
523
524                         if (scan != ep || in == it->buf) {
525                                 /*
526                                  * We should not lose that "something",
527                                  * unless we have just processed an
528                                  * encoded-word, and there is only LWS
529                                  * before the one we are about to process.
530                                  */
531                                 strbuf_add(&outbuf, in, ep - in);
532                         }
533                 }
534                 /* E.g.
535                  * ep : "=?iso-2022-jp?B?GyR...?= foo"
536                  * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
537                  */
538                 ep += 2;
539
540                 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
541                         goto decode_header_bq_out;
542
543                 if (cp + 3 - it->buf > it->len)
544                         goto decode_header_bq_out;
545                 strbuf_add(&charset_q, ep, cp - ep);
546
547                 encoding = cp[1];
548                 if (!encoding || cp[2] != '?')
549                         goto decode_header_bq_out;
550                 ep = strstr(cp + 3, "?=");
551                 if (!ep)
552                         goto decode_header_bq_out;
553                 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
554                 switch (tolower(encoding)) {
555                 default:
556                         goto decode_header_bq_out;
557                 case 'b':
558                         dec = decode_b_segment(&piecebuf);
559                         break;
560                 case 'q':
561                         dec = decode_q_segment(&piecebuf, 1);
562                         break;
563                 }
564                 if (metainfo_charset)
565                         convert_to_utf8(dec, charset_q.buf);
566
567                 strbuf_addbuf(&outbuf, dec);
568                 strbuf_release(dec);
569                 free(dec);
570                 in = ep + 2;
571         }
572         strbuf_addstr(&outbuf, in);
573         strbuf_reset(it);
574         strbuf_addbuf(it, &outbuf);
575 decode_header_bq_out:
576         strbuf_release(&outbuf);
577         strbuf_release(&charset_q);
578         strbuf_release(&piecebuf);
579         return rfc2047;
580 }
581
582 static void decode_header(struct strbuf *it)
583 {
584         if (decode_header_bq(it))
585                 return;
586         /* otherwise "it" is a straight copy of the input.
587          * This can be binary guck but there is no charset specified.
588          */
589         if (metainfo_charset)
590                 convert_to_utf8(it, "");
591 }
592
593 static void decode_transfer_encoding(struct strbuf *line)
594 {
595         struct strbuf *ret;
596
597         switch (transfer_encoding) {
598         case TE_QP:
599                 ret = decode_q_segment(line, 0);
600                 break;
601         case TE_BASE64:
602                 ret = decode_b_segment(line);
603                 break;
604         case TE_DONTCARE:
605         default:
606                 return;
607         }
608         strbuf_reset(line);
609         strbuf_addbuf(line, ret);
610         strbuf_release(ret);
611         free(ret);
612 }
613
614 static void handle_filter(struct strbuf *line);
615
616 static int find_boundary(void)
617 {
618         while (!strbuf_getline(&line, fin, '\n')) {
619                 if (*content_top && is_multipart_boundary(&line))
620                         return 1;
621         }
622         return 0;
623 }
624
625 static int handle_boundary(void)
626 {
627         struct strbuf newline = STRBUF_INIT;
628
629         strbuf_addch(&newline, '\n');
630 again:
631         if (line.len >= (*content_top)->len + 2 &&
632             !memcmp(line.buf + (*content_top)->len, "--", 2)) {
633                 /* we hit an end boundary */
634                 /* pop the current boundary off the stack */
635                 strbuf_release(*content_top);
636                 free(*content_top);
637                 *content_top = NULL;
638
639                 /* technically won't happen as is_multipart_boundary()
640                    will fail first.  But just in case..
641                  */
642                 if (--content_top < content) {
643                         fprintf(stderr, "Detected mismatched boundaries, "
644                                         "can't recover\n");
645                         exit(1);
646                 }
647                 handle_filter(&newline);
648                 strbuf_release(&newline);
649
650                 /* skip to the next boundary */
651                 if (!find_boundary())
652                         return 0;
653                 goto again;
654         }
655
656         /* set some defaults */
657         transfer_encoding = TE_DONTCARE;
658         strbuf_reset(&charset);
659         message_type = TYPE_TEXT;
660
661         /* slurp in this section's info */
662         while (read_one_header_line(&line, fin))
663                 check_header(&line, p_hdr_data, 0);
664
665         strbuf_release(&newline);
666         /* replenish line */
667         if (strbuf_getline(&line, fin, '\n'))
668                 return 0;
669         strbuf_addch(&line, '\n');
670         return 1;
671 }
672
673 static inline int patchbreak(const struct strbuf *line)
674 {
675         size_t i;
676
677         /* Beginning of a "diff -" header? */
678         if (!prefixcmp(line->buf, "diff -"))
679                 return 1;
680
681         /* CVS "Index: " line? */
682         if (!prefixcmp(line->buf, "Index: "))
683                 return 1;
684
685         /*
686          * "--- <filename>" starts patches without headers
687          * "---<sp>*" is a manual separator
688          */
689         if (line->len < 4)
690                 return 0;
691
692         if (!prefixcmp(line->buf, "---")) {
693                 /* space followed by a filename? */
694                 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
695                         return 1;
696                 /* Just whitespace? */
697                 for (i = 3; i < line->len; i++) {
698                         unsigned char c = line->buf[i];
699                         if (c == '\n')
700                                 return 1;
701                         if (!isspace(c))
702                                 break;
703                 }
704                 return 0;
705         }
706         return 0;
707 }
708
709 static int is_scissors_line(const struct strbuf *line)
710 {
711         size_t i, len = line->len;
712         int scissors = 0, gap = 0;
713         int first_nonblank = -1;
714         int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
715         const char *buf = line->buf;
716
717         for (i = 0; i < len; i++) {
718                 if (isspace(buf[i])) {
719                         if (in_perforation) {
720                                 perforation++;
721                                 gap++;
722                         }
723                         continue;
724                 }
725                 last_nonblank = i;
726                 if (first_nonblank < 0)
727                         first_nonblank = i;
728                 if (buf[i] == '-') {
729                         in_perforation = 1;
730                         perforation++;
731                         continue;
732                 }
733                 if (i + 1 < len &&
734                     (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
735                      !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
736                         in_perforation = 1;
737                         perforation += 2;
738                         scissors += 2;
739                         i++;
740                         continue;
741                 }
742                 in_perforation = 0;
743         }
744
745         /*
746          * The mark must be at least 8 bytes long (e.g. "-- >8 --").
747          * Even though there can be arbitrary cruft on the same line
748          * (e.g. "cut here"), in order to avoid misidentification, the
749          * perforation must occupy more than a third of the visible
750          * width of the line, and dashes and scissors must occupy more
751          * than half of the perforation.
752          */
753
754         visible = last_nonblank - first_nonblank + 1;
755         return (scissors && 8 <= visible &&
756                 visible < perforation * 3 &&
757                 gap * 2 < perforation);
758 }
759
760 static int handle_commit_msg(struct strbuf *line)
761 {
762         static int still_looking = 1;
763
764         if (!cmitmsg)
765                 return 0;
766
767         if (still_looking) {
768                 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
769                         return 0;
770         }
771
772         if (use_inbody_headers && still_looking) {
773                 still_looking = check_header(line, s_hdr_data, 0);
774                 if (still_looking)
775                         return 0;
776         } else
777                 /* Only trim the first (blank) line of the commit message
778                  * when ignoring in-body headers.
779                  */
780                 still_looking = 0;
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|-b] [-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 = get_commit_output_encoding();
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], "-b"))
1027                         keep_non_patch_brackets_in_subject = 1;
1028                 else if (!strcmp(argv[1], "-u"))
1029                         metainfo_charset = def_charset;
1030                 else if (!strcmp(argv[1], "-n"))
1031                         metainfo_charset = NULL;
1032                 else if (!prefixcmp(argv[1], "--encoding="))
1033                         metainfo_charset = argv[1] + 11;
1034                 else if (!strcmp(argv[1], "--scissors"))
1035                         use_scissors = 1;
1036                 else if (!strcmp(argv[1], "--no-scissors"))
1037                         use_scissors = 0;
1038                 else if (!strcmp(argv[1], "--no-inbody-headers"))
1039                         use_inbody_headers = 0;
1040                 else
1041                         usage(mailinfo_usage);
1042                 argc--; argv++;
1043         }
1044
1045         if (argc != 3)
1046                 usage(mailinfo_usage);
1047
1048         return !!mailinfo(stdin, stdout, argv[1], argv[2]);
1049 }