Merge branch 'dj/fetch-all-tags' into maint
[git.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 /*
487  * When there is no known charset, guess.
488  *
489  * Right now we assume that if the target is UTF-8 (the default),
490  * and it already looks like UTF-8 (which includes US-ASCII as its
491  * subset, of course) then that is what it is and there is nothing
492  * to do.
493  *
494  * Otherwise, we default to assuming it is Latin1 for historical
495  * reasons.
496  */
497 static const char *guess_charset(const struct strbuf *line, const char *target_charset)
498 {
499         if (is_encoding_utf8(target_charset)) {
500                 if (is_utf8(line->buf))
501                         return NULL;
502         }
503         return "ISO8859-1";
504 }
505
506 static void convert_to_utf8(struct strbuf *line, const char *charset)
507 {
508         char *out;
509
510         if (!charset || !*charset) {
511                 charset = guess_charset(line, metainfo_charset);
512                 if (!charset)
513                         return;
514         }
515
516         if (!strcasecmp(metainfo_charset, charset))
517                 return;
518         out = reencode_string(line->buf, metainfo_charset, charset);
519         if (!out)
520                 die("cannot convert from %s to %s",
521                     charset, metainfo_charset);
522         strbuf_attach(line, out, strlen(out), strlen(out));
523 }
524
525 static int decode_header_bq(struct strbuf *it)
526 {
527         char *in, *ep, *cp;
528         struct strbuf outbuf = STRBUF_INIT, *dec;
529         struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
530         int rfc2047 = 0;
531
532         in = it->buf;
533         while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
534                 int encoding;
535                 strbuf_reset(&charset_q);
536                 strbuf_reset(&piecebuf);
537                 rfc2047 = 1;
538
539                 if (in != ep) {
540                         /*
541                          * We are about to process an encoded-word
542                          * that begins at ep, but there is something
543                          * before the encoded word.
544                          */
545                         char *scan;
546                         for (scan = in; scan < ep; scan++)
547                                 if (!isspace(*scan))
548                                         break;
549
550                         if (scan != ep || in == it->buf) {
551                                 /*
552                                  * We should not lose that "something",
553                                  * unless we have just processed an
554                                  * encoded-word, and there is only LWS
555                                  * before the one we are about to process.
556                                  */
557                                 strbuf_add(&outbuf, in, ep - in);
558                         }
559                 }
560                 /* E.g.
561                  * ep : "=?iso-2022-jp?B?GyR...?= foo"
562                  * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
563                  */
564                 ep += 2;
565
566                 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
567                         goto decode_header_bq_out;
568
569                 if (cp + 3 - it->buf > it->len)
570                         goto decode_header_bq_out;
571                 strbuf_add(&charset_q, ep, cp - ep);
572
573                 encoding = cp[1];
574                 if (!encoding || cp[2] != '?')
575                         goto decode_header_bq_out;
576                 ep = strstr(cp + 3, "?=");
577                 if (!ep)
578                         goto decode_header_bq_out;
579                 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
580                 switch (tolower(encoding)) {
581                 default:
582                         goto decode_header_bq_out;
583                 case 'b':
584                         dec = decode_b_segment(&piecebuf);
585                         break;
586                 case 'q':
587                         dec = decode_q_segment(&piecebuf, 1);
588                         break;
589                 }
590                 if (metainfo_charset)
591                         convert_to_utf8(dec, charset_q.buf);
592
593                 strbuf_addbuf(&outbuf, dec);
594                 strbuf_release(dec);
595                 free(dec);
596                 in = ep + 2;
597         }
598         strbuf_addstr(&outbuf, in);
599         strbuf_reset(it);
600         strbuf_addbuf(it, &outbuf);
601 decode_header_bq_out:
602         strbuf_release(&outbuf);
603         strbuf_release(&charset_q);
604         strbuf_release(&piecebuf);
605         return rfc2047;
606 }
607
608 static void decode_header(struct strbuf *it)
609 {
610         if (decode_header_bq(it))
611                 return;
612         /* otherwise "it" is a straight copy of the input.
613          * This can be binary guck but there is no charset specified.
614          */
615         if (metainfo_charset)
616                 convert_to_utf8(it, "");
617 }
618
619 static void decode_transfer_encoding(struct strbuf *line)
620 {
621         struct strbuf *ret;
622
623         switch (transfer_encoding) {
624         case TE_QP:
625                 ret = decode_q_segment(line, 0);
626                 break;
627         case TE_BASE64:
628                 ret = decode_b_segment(line);
629                 break;
630         case TE_DONTCARE:
631         default:
632                 return;
633         }
634         strbuf_reset(line);
635         strbuf_addbuf(line, ret);
636         strbuf_release(ret);
637         free(ret);
638 }
639
640 static void handle_filter(struct strbuf *line);
641
642 static int find_boundary(void)
643 {
644         while (!strbuf_getline(&line, fin, '\n')) {
645                 if (*content_top && is_multipart_boundary(&line))
646                         return 1;
647         }
648         return 0;
649 }
650
651 static int handle_boundary(void)
652 {
653         struct strbuf newline = STRBUF_INIT;
654
655         strbuf_addch(&newline, '\n');
656 again:
657         if (line.len >= (*content_top)->len + 2 &&
658             !memcmp(line.buf + (*content_top)->len, "--", 2)) {
659                 /* we hit an end boundary */
660                 /* pop the current boundary off the stack */
661                 strbuf_release(*content_top);
662                 free(*content_top);
663                 *content_top = NULL;
664
665                 /* technically won't happen as is_multipart_boundary()
666                    will fail first.  But just in case..
667                  */
668                 if (--content_top < content) {
669                         fprintf(stderr, "Detected mismatched boundaries, "
670                                         "can't recover\n");
671                         exit(1);
672                 }
673                 handle_filter(&newline);
674                 strbuf_release(&newline);
675
676                 /* skip to the next boundary */
677                 if (!find_boundary())
678                         return 0;
679                 goto again;
680         }
681
682         /* set some defaults */
683         transfer_encoding = TE_DONTCARE;
684         strbuf_reset(&charset);
685         message_type = TYPE_TEXT;
686
687         /* slurp in this section's info */
688         while (read_one_header_line(&line, fin))
689                 check_header(&line, p_hdr_data, 0);
690
691         strbuf_release(&newline);
692         /* replenish line */
693         if (strbuf_getline(&line, fin, '\n'))
694                 return 0;
695         strbuf_addch(&line, '\n');
696         return 1;
697 }
698
699 static inline int patchbreak(const struct strbuf *line)
700 {
701         size_t i;
702
703         /* Beginning of a "diff -" header? */
704         if (!prefixcmp(line->buf, "diff -"))
705                 return 1;
706
707         /* CVS "Index: " line? */
708         if (!prefixcmp(line->buf, "Index: "))
709                 return 1;
710
711         /*
712          * "--- <filename>" starts patches without headers
713          * "---<sp>*" is a manual separator
714          */
715         if (line->len < 4)
716                 return 0;
717
718         if (!prefixcmp(line->buf, "---")) {
719                 /* space followed by a filename? */
720                 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
721                         return 1;
722                 /* Just whitespace? */
723                 for (i = 3; i < line->len; i++) {
724                         unsigned char c = line->buf[i];
725                         if (c == '\n')
726                                 return 1;
727                         if (!isspace(c))
728                                 break;
729                 }
730                 return 0;
731         }
732         return 0;
733 }
734
735 static int is_scissors_line(const struct strbuf *line)
736 {
737         size_t i, len = line->len;
738         int scissors = 0, gap = 0;
739         int first_nonblank = -1;
740         int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
741         const char *buf = line->buf;
742
743         for (i = 0; i < len; i++) {
744                 if (isspace(buf[i])) {
745                         if (in_perforation) {
746                                 perforation++;
747                                 gap++;
748                         }
749                         continue;
750                 }
751                 last_nonblank = i;
752                 if (first_nonblank < 0)
753                         first_nonblank = i;
754                 if (buf[i] == '-') {
755                         in_perforation = 1;
756                         perforation++;
757                         continue;
758                 }
759                 if (i + 1 < len &&
760                     (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
761                      !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
762                         in_perforation = 1;
763                         perforation += 2;
764                         scissors += 2;
765                         i++;
766                         continue;
767                 }
768                 in_perforation = 0;
769         }
770
771         /*
772          * The mark must be at least 8 bytes long (e.g. "-- >8 --").
773          * Even though there can be arbitrary cruft on the same line
774          * (e.g. "cut here"), in order to avoid misidentification, the
775          * perforation must occupy more than a third of the visible
776          * width of the line, and dashes and scissors must occupy more
777          * than half of the perforation.
778          */
779
780         visible = last_nonblank - first_nonblank + 1;
781         return (scissors && 8 <= visible &&
782                 visible < perforation * 3 &&
783                 gap * 2 < perforation);
784 }
785
786 static int handle_commit_msg(struct strbuf *line)
787 {
788         static int still_looking = 1;
789
790         if (!cmitmsg)
791                 return 0;
792
793         if (still_looking) {
794                 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
795                         return 0;
796         }
797
798         if (use_inbody_headers && still_looking) {
799                 still_looking = check_header(line, s_hdr_data, 0);
800                 if (still_looking)
801                         return 0;
802         } else
803                 /* Only trim the first (blank) line of the commit message
804                  * when ignoring in-body headers.
805                  */
806                 still_looking = 0;
807
808         /* normalize the log message to UTF-8. */
809         if (metainfo_charset)
810                 convert_to_utf8(line, charset.buf);
811
812         if (use_scissors && is_scissors_line(line)) {
813                 int i;
814                 if (fseek(cmitmsg, 0L, SEEK_SET))
815                         die_errno("Could not rewind output message file");
816                 if (ftruncate(fileno(cmitmsg), 0))
817                         die_errno("Could not truncate output message file at scissors");
818                 still_looking = 1;
819
820                 /*
821                  * We may have already read "secondary headers"; purge
822                  * them to give ourselves a clean restart.
823                  */
824                 for (i = 0; header[i]; i++) {
825                         if (s_hdr_data[i])
826                                 strbuf_release(s_hdr_data[i]);
827                         s_hdr_data[i] = NULL;
828                 }
829                 return 0;
830         }
831
832         if (patchbreak(line)) {
833                 fclose(cmitmsg);
834                 cmitmsg = NULL;
835                 return 1;
836         }
837
838         fputs(line->buf, cmitmsg);
839         return 0;
840 }
841
842 static void handle_patch(const struct strbuf *line)
843 {
844         fwrite(line->buf, 1, line->len, patchfile);
845         patch_lines++;
846 }
847
848 static void handle_filter(struct strbuf *line)
849 {
850         static int filter = 0;
851
852         /* filter tells us which part we left off on */
853         switch (filter) {
854         case 0:
855                 if (!handle_commit_msg(line))
856                         break;
857                 filter++;
858         case 1:
859                 handle_patch(line);
860                 break;
861         }
862 }
863
864 static void handle_body(void)
865 {
866         struct strbuf prev = STRBUF_INIT;
867
868         /* Skip up to the first boundary */
869         if (*content_top) {
870                 if (!find_boundary())
871                         goto handle_body_out;
872         }
873
874         do {
875                 /* process any boundary lines */
876                 if (*content_top && is_multipart_boundary(&line)) {
877                         /* flush any leftover */
878                         if (prev.len) {
879                                 handle_filter(&prev);
880                                 strbuf_reset(&prev);
881                         }
882                         if (!handle_boundary())
883                                 goto handle_body_out;
884                 }
885
886                 /* Unwrap transfer encoding */
887                 decode_transfer_encoding(&line);
888
889                 switch (transfer_encoding) {
890                 case TE_BASE64:
891                 case TE_QP:
892                 {
893                         struct strbuf **lines, **it, *sb;
894
895                         /* Prepend any previous partial lines */
896                         strbuf_insert(&line, 0, prev.buf, prev.len);
897                         strbuf_reset(&prev);
898
899                         /* binary data most likely doesn't have newlines */
900                         if (message_type != TYPE_TEXT) {
901                                 handle_filter(&line);
902                                 break;
903                         }
904                         /*
905                          * This is a decoded line that may contain
906                          * multiple new lines.  Pass only one chunk
907                          * at a time to handle_filter()
908                          */
909                         lines = strbuf_split(&line, '\n');
910                         for (it = lines; (sb = *it); it++) {
911                                 if (*(it + 1) == NULL) /* The last line */
912                                         if (sb->buf[sb->len - 1] != '\n') {
913                                                 /* Partial line, save it for later. */
914                                                 strbuf_addbuf(&prev, sb);
915                                                 break;
916                                         }
917                                 handle_filter(sb);
918                         }
919                         /*
920                          * The partial chunk is saved in "prev" and will be
921                          * appended by the next iteration of read_line_with_nul().
922                          */
923                         strbuf_list_free(lines);
924                         break;
925                 }
926                 default:
927                         handle_filter(&line);
928                 }
929
930         } while (!strbuf_getwholeline(&line, fin, '\n'));
931
932 handle_body_out:
933         strbuf_release(&prev);
934 }
935
936 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
937 {
938         const char *sp = data->buf;
939         while (1) {
940                 char *ep = strchr(sp, '\n');
941                 int len;
942                 if (!ep)
943                         len = strlen(sp);
944                 else
945                         len = ep - sp;
946                 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
947                 if (!ep)
948                         break;
949                 sp = ep + 1;
950         }
951 }
952
953 static void handle_info(void)
954 {
955         struct strbuf *hdr;
956         int i;
957
958         for (i = 0; header[i]; i++) {
959                 /* only print inbody headers if we output a patch file */
960                 if (patch_lines && s_hdr_data[i])
961                         hdr = s_hdr_data[i];
962                 else if (p_hdr_data[i])
963                         hdr = p_hdr_data[i];
964                 else
965                         continue;
966
967                 if (!memcmp(header[i], "Subject", 7)) {
968                         if (!keep_subject) {
969                                 cleanup_subject(hdr);
970                                 cleanup_space(hdr);
971                         }
972                         output_header_lines(fout, "Subject", hdr);
973                 } else if (!memcmp(header[i], "From", 4)) {
974                         cleanup_space(hdr);
975                         handle_from(hdr);
976                         fprintf(fout, "Author: %s\n", name.buf);
977                         fprintf(fout, "Email: %s\n", email.buf);
978                 } else {
979                         cleanup_space(hdr);
980                         fprintf(fout, "%s: %s\n", header[i], hdr->buf);
981                 }
982         }
983         fprintf(fout, "\n");
984 }
985
986 static int mailinfo(FILE *in, FILE *out, const char *msg, const char *patch)
987 {
988         int peek;
989         fin = in;
990         fout = out;
991
992         cmitmsg = fopen(msg, "w");
993         if (!cmitmsg) {
994                 perror(msg);
995                 return -1;
996         }
997         patchfile = fopen(patch, "w");
998         if (!patchfile) {
999                 perror(patch);
1000                 fclose(cmitmsg);
1001                 return -1;
1002         }
1003
1004         p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
1005         s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
1006
1007         do {
1008                 peek = fgetc(in);
1009         } while (isspace(peek));
1010         ungetc(peek, in);
1011
1012         /* process the email header */
1013         while (read_one_header_line(&line, fin))
1014                 check_header(&line, p_hdr_data, 1);
1015
1016         handle_body();
1017         handle_info();
1018
1019         return 0;
1020 }
1021
1022 static int git_mailinfo_config(const char *var, const char *value, void *unused)
1023 {
1024         if (prefixcmp(var, "mailinfo."))
1025                 return git_default_config(var, value, unused);
1026         if (!strcmp(var, "mailinfo.scissors")) {
1027                 use_scissors = git_config_bool(var, value);
1028                 return 0;
1029         }
1030         /* perhaps others here */
1031         return 0;
1032 }
1033
1034 static const char mailinfo_usage[] =
1035         "git mailinfo [-k|-b] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] msg patch < mail >info";
1036
1037 int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1038 {
1039         const char *def_charset;
1040
1041         /* NEEDSWORK: might want to do the optional .git/ directory
1042          * discovery
1043          */
1044         git_config(git_mailinfo_config, NULL);
1045
1046         def_charset = get_commit_output_encoding();
1047         metainfo_charset = def_charset;
1048
1049         while (1 < argc && argv[1][0] == '-') {
1050                 if (!strcmp(argv[1], "-k"))
1051                         keep_subject = 1;
1052                 else if (!strcmp(argv[1], "-b"))
1053                         keep_non_patch_brackets_in_subject = 1;
1054                 else if (!strcmp(argv[1], "-u"))
1055                         metainfo_charset = def_charset;
1056                 else if (!strcmp(argv[1], "-n"))
1057                         metainfo_charset = NULL;
1058                 else if (!prefixcmp(argv[1], "--encoding="))
1059                         metainfo_charset = argv[1] + 11;
1060                 else if (!strcmp(argv[1], "--scissors"))
1061                         use_scissors = 1;
1062                 else if (!strcmp(argv[1], "--no-scissors"))
1063                         use_scissors = 0;
1064                 else if (!strcmp(argv[1], "--no-inbody-headers"))
1065                         use_inbody_headers = 0;
1066                 else
1067                         usage(mailinfo_usage);
1068                 argc--; argv++;
1069         }
1070
1071         if (argc != 3)
1072                 usage(mailinfo_usage);
1073
1074         return !!mailinfo(stdin, stdout, argv[1], argv[2]);
1075 }