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