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