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