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