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