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