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