refs/files: fix NULL pointer deref when releasing ref store
[git/gitster.git] / mailinfo.c
blob94b9b0abf228b891bc1df5a71bcd96807ed982a8
1 #include "git-compat-util.h"
2 #include "config.h"
3 #include "gettext.h"
4 #include "hex-ll.h"
5 #include "utf8.h"
6 #include "strbuf.h"
7 #include "mailinfo.h"
9 static void cleanup_space(struct strbuf *sb)
11 size_t pos, cnt;
12 for (pos = 0; pos < sb->len; pos++) {
13 if (isspace(sb->buf[pos])) {
14 sb->buf[pos] = ' ';
15 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
16 strbuf_remove(sb, pos + 1, cnt);
21 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
23 struct strbuf *src = name;
24 if (!name->len || 60 < name->len || strpbrk(name->buf, "@<>"))
25 src = email;
26 else if (name == out)
27 return;
28 strbuf_reset(out);
29 strbuf_addbuf(out, src);
32 static void parse_bogus_from(struct mailinfo *mi, const struct strbuf *line)
34 /* John Doe <johndoe> */
36 char *bra, *ket;
37 /* This is fallback, so do not bother if we already have an
38 * e-mail address.
40 if (mi->email.len)
41 return;
43 bra = strchr(line->buf, '<');
44 if (!bra)
45 return;
46 ket = strchr(bra, '>');
47 if (!ket)
48 return;
50 strbuf_reset(&mi->email);
51 strbuf_add(&mi->email, bra + 1, ket - bra - 1);
53 strbuf_reset(&mi->name);
54 strbuf_add(&mi->name, line->buf, bra - line->buf);
55 strbuf_trim(&mi->name);
56 get_sane_name(&mi->name, &mi->name, &mi->email);
59 static const char *unquote_comment(struct strbuf *outbuf, const char *in)
61 int take_next_literally = 0;
62 int depth = 1;
64 strbuf_addch(outbuf, '(');
66 while (*in) {
67 int c = *in++;
68 if (take_next_literally == 1) {
69 take_next_literally = 0;
70 } else {
71 switch (c) {
72 case '\\':
73 take_next_literally = 1;
74 continue;
75 case '(':
76 strbuf_addch(outbuf, '(');
77 depth++;
78 continue;
79 case ')':
80 strbuf_addch(outbuf, ')');
81 if (!--depth)
82 return in;
83 continue;
87 strbuf_addch(outbuf, c);
90 return in;
93 static const char *unquote_quoted_string(struct strbuf *outbuf, const char *in)
95 int take_next_literally = 0;
97 while (*in) {
98 int c = *in++;
99 if (take_next_literally == 1) {
100 take_next_literally = 0;
101 } else {
102 switch (c) {
103 case '\\':
104 take_next_literally = 1;
105 continue;
106 case '"':
107 return in;
111 strbuf_addch(outbuf, c);
114 return in;
117 static void unquote_quoted_pair(struct strbuf *line)
119 struct strbuf outbuf;
120 const char *in = line->buf;
121 int c;
123 strbuf_init(&outbuf, line->len);
125 while ((c = *in++) != 0) {
126 switch (c) {
127 case '"':
128 in = unquote_quoted_string(&outbuf, in);
129 continue;
130 case '(':
131 in = unquote_comment(&outbuf, in);
132 continue;
135 strbuf_addch(&outbuf, c);
138 strbuf_swap(&outbuf, line);
139 strbuf_release(&outbuf);
143 static void handle_from(struct mailinfo *mi, const struct strbuf *from)
145 char *at;
146 size_t el;
147 struct strbuf f;
149 strbuf_init(&f, from->len);
150 strbuf_addbuf(&f, from);
152 unquote_quoted_pair(&f);
154 at = strchr(f.buf, '@');
155 if (!at) {
156 parse_bogus_from(mi, from);
157 goto out;
161 * If we already have one email, don't take any confusing lines
163 if (mi->email.len && strchr(at + 1, '@'))
164 goto out;
166 /* Pick up the string around '@', possibly delimited with <>
167 * pair; that is the email part.
169 while (at > f.buf) {
170 char c = at[-1];
171 if (isspace(c))
172 break;
173 if (c == '<') {
174 at[-1] = ' ';
175 break;
177 at--;
179 el = strcspn(at, " \n\t\r\v\f>");
180 strbuf_reset(&mi->email);
181 strbuf_add(&mi->email, at, el);
182 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
184 /* The remainder is name. It could be
186 * - "John Doe <john.doe@xz>" (a), or
187 * - "john.doe@xz (John Doe)" (b), or
188 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
190 * but we have removed the email part, so
192 * - remove extra spaces which could stay after email (case 'c'), and
193 * - trim from both ends, possibly removing the () pair at the end
194 * (cases 'a' and 'b').
196 cleanup_space(&f);
197 strbuf_trim(&f);
198 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
199 strbuf_remove(&f, 0, 1);
200 strbuf_setlen(&f, f.len - 1);
203 get_sane_name(&mi->name, &f, &mi->email);
204 out:
205 strbuf_release(&f);
208 static void handle_header(struct strbuf **out, const struct strbuf *line)
210 if (!*out) {
211 *out = xmalloc(sizeof(struct strbuf));
212 strbuf_init(*out, line->len);
213 } else
214 strbuf_reset(*out);
216 strbuf_addbuf(*out, line);
219 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
220 * to have enough heuristics to grok MIME encoded patches often found
221 * on our mailing lists. For example, we do not even treat header lines
222 * case insensitively.
225 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
227 const char *ends, *ap = strcasestr(line, name);
228 size_t sz;
230 strbuf_setlen(attr, 0);
231 if (!ap)
232 return 0;
233 ap += strlen(name);
234 if (*ap == '"') {
235 ap++;
236 ends = "\"";
238 else
239 ends = "; \t";
240 sz = strcspn(ap, ends);
241 strbuf_add(attr, ap, sz);
242 return 1;
245 static int has_attr_value(const char *line, const char *name, const char *value)
247 struct strbuf sb = STRBUF_INIT;
248 int rc = slurp_attr(line, name, &sb) && !strcasecmp(sb.buf, value);
249 strbuf_release(&sb);
250 return rc;
253 static void handle_content_type(struct mailinfo *mi, struct strbuf *line)
255 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
256 strbuf_init(boundary, line->len);
258 mi->format_flowed = has_attr_value(line->buf, "format=", "flowed");
259 mi->delsp = has_attr_value(line->buf, "delsp=", "yes");
261 if (slurp_attr(line->buf, "boundary=", boundary)) {
262 strbuf_insertstr(boundary, 0, "--");
263 if (++mi->content_top >= &mi->content[MAX_BOUNDARIES]) {
264 error("Too many boundaries to handle");
265 mi->input_error = -1;
266 mi->content_top = &mi->content[MAX_BOUNDARIES] - 1;
267 return;
269 *(mi->content_top) = boundary;
270 boundary = NULL;
272 slurp_attr(line->buf, "charset=", &mi->charset);
274 if (boundary) {
275 strbuf_release(boundary);
276 free(boundary);
280 static void handle_content_transfer_encoding(struct mailinfo *mi,
281 const struct strbuf *line)
283 if (strcasestr(line->buf, "base64"))
284 mi->transfer_encoding = TE_BASE64;
285 else if (strcasestr(line->buf, "quoted-printable"))
286 mi->transfer_encoding = TE_QP;
287 else
288 mi->transfer_encoding = TE_DONTCARE;
291 static int is_multipart_boundary(struct mailinfo *mi, const struct strbuf *line)
293 struct strbuf *content_top = *(mi->content_top);
295 return ((content_top->len <= line->len) &&
296 !memcmp(line->buf, content_top->buf, content_top->len));
299 static void cleanup_subject(struct mailinfo *mi, struct strbuf *subject)
301 size_t at = 0;
303 while (at < subject->len) {
304 char *pos;
305 size_t remove;
307 switch (subject->buf[at]) {
308 case 'r': case 'R':
309 if (subject->len <= at + 3)
310 break;
311 if ((subject->buf[at + 1] == 'e' ||
312 subject->buf[at + 1] == 'E') &&
313 subject->buf[at + 2] == ':') {
314 strbuf_remove(subject, at, 3);
315 continue;
317 at++;
318 break;
319 case ' ': case '\t': case ':':
320 strbuf_remove(subject, at, 1);
321 continue;
322 case '[':
323 pos = strchr(subject->buf + at, ']');
324 if (!pos)
325 break;
326 remove = pos - (subject->buf + at) + 1;
327 if (!mi->keep_non_patch_brackets_in_subject ||
328 (7 <= remove &&
329 memmem(subject->buf + at, remove, "PATCH", 5)))
330 strbuf_remove(subject, at, remove);
331 else {
332 at += remove;
334 * If the input had a space after the ], keep
335 * it. We don't bother with finding the end of
336 * the space, since we later normalize it
337 * anyway.
339 if (isspace(subject->buf[at]))
340 at += 1;
342 continue;
344 break;
346 strbuf_trim(subject);
349 #define MAX_HDR_PARSED 10
350 static const char *header[MAX_HDR_PARSED] = {
351 "From","Subject","Date",
354 static inline int skip_header(const struct strbuf *line, const char *hdr,
355 const char **outval)
357 const char *val;
358 if (!skip_iprefix(line->buf, hdr, &val) ||
359 *val++ != ':')
360 return 0;
361 while (isspace(*val))
362 val++;
363 *outval = val;
364 return 1;
367 static int is_format_patch_separator(const char *line, int len)
369 static const char SAMPLE[] =
370 "From e6807f3efca28b30decfecb1732a56c7db1137ee Mon Sep 17 00:00:00 2001\n";
371 const char *cp;
373 if (len != strlen(SAMPLE))
374 return 0;
375 if (!skip_prefix(line, "From ", &cp))
376 return 0;
377 if (strspn(cp, "0123456789abcdef") != 40)
378 return 0;
379 cp += 40;
380 return !memcmp(SAMPLE + (cp - line), cp, strlen(SAMPLE) - (cp - line));
383 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
385 const char *in = q_seg->buf;
386 int c;
387 struct strbuf *out = xmalloc(sizeof(struct strbuf));
388 strbuf_init(out, q_seg->len);
390 while ((c = *in++) != 0) {
391 if (c == '=') {
392 int ch, d = *in;
393 if (d == '\n' || !d)
394 break; /* drop trailing newline */
395 ch = hex2chr(in);
396 if (ch >= 0) {
397 strbuf_addch(out, ch);
398 in += 2;
399 continue;
401 /* garbage -- fall through */
403 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
404 c = 0x20;
405 strbuf_addch(out, c);
407 return out;
410 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
412 /* Decode in..ep, possibly in-place to ot */
413 int c, pos = 0, acc = 0;
414 const char *in = b_seg->buf;
415 struct strbuf *out = xmalloc(sizeof(struct strbuf));
416 strbuf_init(out, b_seg->len);
418 while ((c = *in++) != 0) {
419 if (c == '+')
420 c = 62;
421 else if (c == '/')
422 c = 63;
423 else if ('A' <= c && c <= 'Z')
424 c -= 'A';
425 else if ('a' <= c && c <= 'z')
426 c -= 'a' - 26;
427 else if ('0' <= c && c <= '9')
428 c -= '0' - 52;
429 else
430 continue; /* garbage */
431 switch (pos++) {
432 case 0:
433 acc = (c << 2);
434 break;
435 case 1:
436 strbuf_addch(out, (acc | (c >> 4)));
437 acc = (c & 15) << 4;
438 break;
439 case 2:
440 strbuf_addch(out, (acc | (c >> 2)));
441 acc = (c & 3) << 6;
442 break;
443 case 3:
444 strbuf_addch(out, (acc | c));
445 acc = pos = 0;
446 break;
449 return out;
452 static int convert_to_utf8(struct mailinfo *mi,
453 struct strbuf *line, const char *charset)
455 char *out;
456 size_t out_len;
458 if (!mi->metainfo_charset || !charset || !*charset)
459 return 0;
461 if (same_encoding(mi->metainfo_charset, charset))
462 return 0;
463 out = reencode_string_len(line->buf, line->len,
464 mi->metainfo_charset, charset, &out_len);
465 if (!out) {
466 mi->input_error = -1;
467 return error("cannot convert from %s to %s",
468 charset, mi->metainfo_charset);
470 strbuf_attach(line, out, out_len, out_len);
471 return 0;
474 static void decode_header(struct mailinfo *mi, struct strbuf *it)
476 char *in, *ep, *cp;
477 struct strbuf outbuf = STRBUF_INIT, *dec;
478 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
479 int found_error = 1; /* pessimism */
481 in = it->buf;
482 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
483 int encoding;
484 strbuf_reset(&charset_q);
485 strbuf_reset(&piecebuf);
487 if (in != ep) {
489 * We are about to process an encoded-word
490 * that begins at ep, but there is something
491 * before the encoded word.
493 char *scan;
494 for (scan = in; scan < ep; scan++)
495 if (!isspace(*scan))
496 break;
498 if (scan != ep || in == it->buf) {
500 * We should not lose that "something",
501 * unless we have just processed an
502 * encoded-word, and there is only LWS
503 * before the one we are about to process.
505 strbuf_add(&outbuf, in, ep - in);
508 /* E.g.
509 * ep : "=?iso-2022-jp?B?GyR...?= foo"
510 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
512 ep += 2;
514 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
515 goto release_return;
517 if (cp + 3 - it->buf > it->len)
518 goto release_return;
519 strbuf_add(&charset_q, ep, cp - ep);
521 encoding = cp[1];
522 if (!encoding || cp[2] != '?')
523 goto release_return;
524 ep = strstr(cp + 3, "?=");
525 if (!ep)
526 goto release_return;
527 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
528 switch (tolower(encoding)) {
529 default:
530 goto release_return;
531 case 'b':
532 dec = decode_b_segment(&piecebuf);
533 break;
534 case 'q':
535 dec = decode_q_segment(&piecebuf, 1);
536 break;
538 if (convert_to_utf8(mi, dec, charset_q.buf))
539 goto release_return;
541 strbuf_addbuf(&outbuf, dec);
542 strbuf_release(dec);
543 free(dec);
544 in = ep + 2;
546 strbuf_addstr(&outbuf, in);
547 strbuf_reset(it);
548 strbuf_addbuf(it, &outbuf);
549 found_error = 0;
550 release_return:
551 strbuf_release(&outbuf);
552 strbuf_release(&charset_q);
553 strbuf_release(&piecebuf);
555 if (found_error)
556 mi->input_error = -1;
560 * Returns true if "line" contains a header matching "hdr", in which case "val"
561 * will contain the value of the header with any RFC2047 B and Q encoding
562 * unwrapped, and optionally normalize the meta information to utf8.
564 static int parse_header(const struct strbuf *line,
565 const char *hdr,
566 struct mailinfo *mi,
567 struct strbuf *val)
569 const char *val_str;
571 if (!skip_header(line, hdr, &val_str))
572 return 0;
573 strbuf_addstr(val, val_str);
574 decode_header(mi, val);
575 return 1;
578 static int check_header(struct mailinfo *mi,
579 const struct strbuf *line,
580 struct strbuf *hdr_data[], int overwrite)
582 int i, ret = 0;
583 struct strbuf sb = STRBUF_INIT;
585 /* search for the interesting parts */
586 for (i = 0; header[i]; i++) {
587 if ((!hdr_data[i] || overwrite) &&
588 parse_header(line, header[i], mi, &sb)) {
589 handle_header(&hdr_data[i], &sb);
590 ret = 1;
591 goto check_header_out;
595 /* Content stuff */
596 if (parse_header(line, "Content-Type", mi, &sb)) {
597 handle_content_type(mi, &sb);
598 ret = 1;
599 goto check_header_out;
601 if (parse_header(line, "Content-Transfer-Encoding", mi, &sb)) {
602 handle_content_transfer_encoding(mi, &sb);
603 ret = 1;
604 goto check_header_out;
606 if (parse_header(line, "Message-ID", mi, &sb)) {
607 if (mi->add_message_id)
608 mi->message_id = strbuf_detach(&sb, NULL);
609 ret = 1;
610 goto check_header_out;
613 check_header_out:
614 strbuf_release(&sb);
615 return ret;
619 * Returns 1 if the given line or any line beginning with the given line is an
620 * in-body header (that is, check_header will succeed when passed
621 * mi->s_hdr_data).
623 static int is_inbody_header(const struct mailinfo *mi,
624 const struct strbuf *line)
626 int i;
627 const char *val;
628 for (i = 0; header[i]; i++)
629 if (!mi->s_hdr_data[i] && skip_header(line, header[i], &val))
630 return 1;
631 return 0;
634 static void decode_transfer_encoding(struct mailinfo *mi, struct strbuf *line)
636 struct strbuf *ret;
638 switch (mi->transfer_encoding) {
639 case TE_QP:
640 ret = decode_q_segment(line, 0);
641 break;
642 case TE_BASE64:
643 ret = decode_b_segment(line);
644 break;
645 case TE_DONTCARE:
646 default:
647 return;
649 strbuf_reset(line);
650 strbuf_addbuf(line, ret);
651 strbuf_release(ret);
652 free(ret);
655 static inline int patchbreak(const struct strbuf *line)
657 size_t i;
659 /* Beginning of a "diff -" header? */
660 if (starts_with(line->buf, "diff -"))
661 return 1;
663 /* CVS "Index: " line? */
664 if (starts_with(line->buf, "Index: "))
665 return 1;
668 * "--- <filename>" starts patches without headers
669 * "---<sp>*" is a manual separator
671 if (line->len < 4)
672 return 0;
674 if (starts_with(line->buf, "---")) {
675 /* space followed by a filename? */
676 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
677 return 1;
678 /* Just whitespace? */
679 for (i = 3; i < line->len; i++) {
680 unsigned char c = line->buf[i];
681 if (c == '\n')
682 return 1;
683 if (!isspace(c))
684 break;
686 return 0;
688 return 0;
691 static int is_scissors_line(const char *line)
693 const char *c;
694 int scissors = 0, gap = 0;
695 const char *first_nonblank = NULL, *last_nonblank = NULL;
696 int visible, perforation = 0, in_perforation = 0;
698 for (c = line; *c; c++) {
699 if (isspace(*c)) {
700 if (in_perforation) {
701 perforation++;
702 gap++;
704 continue;
706 last_nonblank = c;
707 if (!first_nonblank)
708 first_nonblank = c;
709 if (*c == '-') {
710 in_perforation = 1;
711 perforation++;
712 continue;
714 if (starts_with(c, ">8") || starts_with(c, "8<") ||
715 starts_with(c, ">%") || starts_with(c, "%<")) {
716 in_perforation = 1;
717 perforation += 2;
718 scissors += 2;
719 c++;
720 continue;
722 in_perforation = 0;
726 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
727 * Even though there can be arbitrary cruft on the same line
728 * (e.g. "cut here"), in order to avoid misidentification, the
729 * perforation must occupy more than a third of the visible
730 * width of the line, and dashes and scissors must occupy more
731 * than half of the perforation.
734 if (first_nonblank && last_nonblank)
735 visible = last_nonblank - first_nonblank + 1;
736 else
737 visible = 0;
738 return (scissors && 8 <= visible &&
739 visible < perforation * 3 &&
740 gap * 2 < perforation);
743 static void flush_inbody_header_accum(struct mailinfo *mi)
745 if (!mi->inbody_header_accum.len)
746 return;
747 if (!check_header(mi, &mi->inbody_header_accum, mi->s_hdr_data, 0))
748 BUG("inbody_header_accum, if not empty, must always contain a valid in-body header");
749 strbuf_reset(&mi->inbody_header_accum);
752 static int check_inbody_header(struct mailinfo *mi, const struct strbuf *line)
754 if (mi->inbody_header_accum.len &&
755 (line->buf[0] == ' ' || line->buf[0] == '\t')) {
756 if (mi->use_scissors && is_scissors_line(line->buf)) {
758 * This is a scissors line; do not consider this line
759 * as a header continuation line.
761 flush_inbody_header_accum(mi);
762 return 0;
764 strbuf_strip_suffix(&mi->inbody_header_accum, "\n");
765 strbuf_addbuf(&mi->inbody_header_accum, line);
766 return 1;
769 flush_inbody_header_accum(mi);
771 if (starts_with(line->buf, ">From") && isspace(line->buf[5]))
772 return is_format_patch_separator(line->buf + 1, line->len - 1);
773 if (starts_with(line->buf, "[PATCH]") && isspace(line->buf[7])) {
774 int i;
775 for (i = 0; header[i]; i++)
776 if (!strcmp("Subject", header[i])) {
777 handle_header(&mi->s_hdr_data[i], line);
778 return 1;
780 return 0;
782 if (is_inbody_header(mi, line)) {
783 strbuf_addbuf(&mi->inbody_header_accum, line);
784 return 1;
786 return 0;
789 static int handle_commit_msg(struct mailinfo *mi, struct strbuf *line)
791 assert(!mi->filter_stage);
793 if (mi->header_stage) {
794 if (!line->len || (line->len == 1 && line->buf[0] == '\n')) {
795 if (mi->inbody_header_accum.len) {
796 flush_inbody_header_accum(mi);
797 mi->header_stage = 0;
799 return 0;
803 if (mi->use_inbody_headers && mi->header_stage) {
804 mi->header_stage = check_inbody_header(mi, line);
805 if (mi->header_stage)
806 return 0;
807 } else
808 /* Only trim the first (blank) line of the commit message
809 * when ignoring in-body headers.
811 mi->header_stage = 0;
813 /* normalize the log message to UTF-8. */
814 if (convert_to_utf8(mi, line, mi->charset.buf))
815 return 0; /* mi->input_error already set */
817 if (mi->use_scissors && is_scissors_line(line->buf)) {
818 int i;
820 strbuf_setlen(&mi->log_message, 0);
821 mi->header_stage = 1;
824 * We may have already read "secondary headers"; purge
825 * them to give ourselves a clean restart.
827 for (i = 0; header[i]; i++) {
828 if (mi->s_hdr_data[i])
829 strbuf_release(mi->s_hdr_data[i]);
830 FREE_AND_NULL(mi->s_hdr_data[i]);
832 return 0;
835 if (patchbreak(line)) {
836 if (mi->message_id)
837 strbuf_addf(&mi->log_message,
838 "Message-ID: %s\n", mi->message_id);
839 return 1;
842 strbuf_addbuf(&mi->log_message, line);
843 return 0;
846 static void handle_patch(struct mailinfo *mi, const struct strbuf *line)
848 fwrite(line->buf, 1, line->len, mi->patchfile);
849 mi->patch_lines++;
852 static void handle_filter(struct mailinfo *mi, struct strbuf *line)
854 switch (mi->filter_stage) {
855 case 0:
856 if (!handle_commit_msg(mi, line))
857 break;
858 mi->filter_stage++;
859 /* fallthrough */
860 case 1:
861 handle_patch(mi, line);
862 break;
866 static int is_rfc2822_header(const struct strbuf *line)
869 * The section that defines the loosest possible
870 * field name is "3.6.8 Optional fields".
872 * optional-field = field-name ":" unstructured CRLF
873 * field-name = 1*ftext
874 * ftext = %d33-57 / %59-126
876 int ch;
877 char *cp = line->buf;
879 /* Count mbox From headers as headers */
880 if (starts_with(cp, "From ") || starts_with(cp, ">From "))
881 return 1;
883 while ((ch = *cp++)) {
884 if (ch == ':')
885 return 1;
886 if ((33 <= ch && ch <= 57) ||
887 (59 <= ch && ch <= 126))
888 continue;
889 break;
891 return 0;
894 static int read_one_header_line(struct strbuf *line, FILE *in)
896 struct strbuf continuation = STRBUF_INIT;
898 /* Get the first part of the line. */
899 if (strbuf_getline_lf(line, in))
900 return 0;
903 * Is it an empty line or not a valid rfc2822 header?
904 * If so, stop here, and return false ("not a header")
906 strbuf_rtrim(line);
907 if (!line->len || !is_rfc2822_header(line)) {
908 /* Re-add the newline */
909 strbuf_addch(line, '\n');
910 return 0;
914 * Now we need to eat all the continuation lines..
915 * Yuck, 2822 header "folding"
917 for (;;) {
918 int peek;
920 peek = fgetc(in);
921 if (peek == EOF)
922 break;
923 ungetc(peek, in);
924 if (peek != ' ' && peek != '\t')
925 break;
926 if (strbuf_getline_lf(&continuation, in))
927 break;
928 continuation.buf[0] = ' ';
929 strbuf_rtrim(&continuation);
930 strbuf_addbuf(line, &continuation);
932 strbuf_release(&continuation);
934 return 1;
937 static int find_boundary(struct mailinfo *mi, struct strbuf *line)
939 while (!strbuf_getline_lf(line, mi->input)) {
940 if (*(mi->content_top) && is_multipart_boundary(mi, line))
941 return 1;
943 return 0;
946 static int handle_boundary(struct mailinfo *mi, struct strbuf *line)
948 struct strbuf newline = STRBUF_INIT;
950 strbuf_addch(&newline, '\n');
951 again:
952 if (line->len >= (*(mi->content_top))->len + 2 &&
953 !memcmp(line->buf + (*(mi->content_top))->len, "--", 2)) {
954 /* we hit an end boundary */
955 /* pop the current boundary off the stack */
956 strbuf_release(*(mi->content_top));
957 FREE_AND_NULL(*(mi->content_top));
959 /* technically won't happen as is_multipart_boundary()
960 will fail first. But just in case..
962 if (--mi->content_top < mi->content) {
963 error("Detected mismatched boundaries, can't recover");
964 mi->input_error = -1;
965 mi->content_top = mi->content;
966 strbuf_release(&newline);
967 return 0;
969 handle_filter(mi, &newline);
970 strbuf_release(&newline);
971 if (mi->input_error)
972 return 0;
974 /* skip to the next boundary */
975 if (!find_boundary(mi, line))
976 return 0;
977 goto again;
980 /* set some defaults */
981 mi->transfer_encoding = TE_DONTCARE;
982 strbuf_reset(&mi->charset);
984 /* slurp in this section's info */
985 while (read_one_header_line(line, mi->input))
986 check_header(mi, line, mi->p_hdr_data, 0);
988 strbuf_release(&newline);
989 /* replenish line */
990 if (strbuf_getline_lf(line, mi->input))
991 return 0;
992 strbuf_addch(line, '\n');
993 return 1;
996 static void handle_filter_flowed(struct mailinfo *mi, struct strbuf *line,
997 struct strbuf *prev)
999 size_t len = line->len;
1000 const char *rest;
1002 if (!mi->format_flowed) {
1003 if (len >= 2 &&
1004 line->buf[len - 2] == '\r' &&
1005 line->buf[len - 1] == '\n') {
1006 mi->have_quoted_cr = 1;
1007 if (mi->quoted_cr == quoted_cr_strip) {
1008 strbuf_setlen(line, len - 2);
1009 strbuf_addch(line, '\n');
1010 len--;
1013 handle_filter(mi, line);
1014 return;
1017 if (line->buf[len - 1] == '\n') {
1018 len--;
1019 if (len && line->buf[len - 1] == '\r')
1020 len--;
1023 /* Keep signature separator as-is. */
1024 if (skip_prefix(line->buf, "-- ", &rest) && rest - line->buf == len) {
1025 if (prev->len) {
1026 handle_filter(mi, prev);
1027 strbuf_reset(prev);
1029 handle_filter(mi, line);
1030 return;
1033 /* Unstuff space-stuffed line. */
1034 if (len && line->buf[0] == ' ') {
1035 strbuf_remove(line, 0, 1);
1036 len--;
1039 /* Save flowed line for later, but without the soft line break. */
1040 if (len && line->buf[len - 1] == ' ') {
1041 strbuf_add(prev, line->buf, len - !!mi->delsp);
1042 return;
1045 /* Prepend any previous partial lines */
1046 strbuf_insert(line, 0, prev->buf, prev->len);
1047 strbuf_reset(prev);
1049 handle_filter(mi, line);
1052 static void summarize_quoted_cr(struct mailinfo *mi)
1054 if (mi->have_quoted_cr &&
1055 mi->quoted_cr == quoted_cr_warn)
1056 warning(_("quoted CRLF detected"));
1059 static void handle_body(struct mailinfo *mi, struct strbuf *line)
1061 struct strbuf prev = STRBUF_INIT;
1063 /* Skip up to the first boundary */
1064 if (*(mi->content_top)) {
1065 if (!find_boundary(mi, line))
1066 goto handle_body_out;
1069 do {
1070 /* process any boundary lines */
1071 if (*(mi->content_top) && is_multipart_boundary(mi, line)) {
1072 /* flush any leftover */
1073 if (prev.len) {
1074 handle_filter(mi, &prev);
1075 strbuf_reset(&prev);
1077 summarize_quoted_cr(mi);
1078 mi->have_quoted_cr = 0;
1079 if (!handle_boundary(mi, line))
1080 goto handle_body_out;
1083 /* Unwrap transfer encoding */
1084 decode_transfer_encoding(mi, line);
1086 switch (mi->transfer_encoding) {
1087 case TE_BASE64:
1088 case TE_QP:
1090 struct strbuf **lines, **it, *sb;
1092 /* Prepend any previous partial lines */
1093 strbuf_insert(line, 0, prev.buf, prev.len);
1094 strbuf_reset(&prev);
1097 * This is a decoded line that may contain
1098 * multiple new lines. Pass only one chunk
1099 * at a time to handle_filter()
1101 lines = strbuf_split(line, '\n');
1102 for (it = lines; (sb = *it); it++) {
1103 if (!*(it + 1)) /* The last line */
1104 if (sb->buf[sb->len - 1] != '\n') {
1105 /* Partial line, save it for later. */
1106 strbuf_addbuf(&prev, sb);
1107 break;
1109 handle_filter_flowed(mi, sb, &prev);
1112 * The partial chunk is saved in "prev" and will be
1113 * appended by the next iteration of read_line_with_nul().
1115 strbuf_list_free(lines);
1116 break;
1118 default:
1119 handle_filter_flowed(mi, line, &prev);
1122 if (mi->input_error)
1123 break;
1124 } while (!strbuf_getwholeline(line, mi->input, '\n'));
1126 if (prev.len)
1127 handle_filter(mi, &prev);
1128 summarize_quoted_cr(mi);
1130 flush_inbody_header_accum(mi);
1132 handle_body_out:
1133 strbuf_release(&prev);
1136 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
1138 const char *sp = data->buf;
1139 while (1) {
1140 char *ep = strchr(sp, '\n');
1141 int len;
1142 if (!ep)
1143 len = strlen(sp);
1144 else
1145 len = ep - sp;
1146 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
1147 if (!ep)
1148 break;
1149 sp = ep + 1;
1153 static void handle_info(struct mailinfo *mi)
1155 struct strbuf *hdr;
1156 int i;
1158 for (i = 0; header[i]; i++) {
1159 /* only print inbody headers if we output a patch file */
1160 if (mi->patch_lines && mi->s_hdr_data[i])
1161 hdr = mi->s_hdr_data[i];
1162 else if (mi->p_hdr_data[i])
1163 hdr = mi->p_hdr_data[i];
1164 else
1165 continue;
1167 if (memchr(hdr->buf, '\0', hdr->len)) {
1168 error("a NUL byte in '%s' is not allowed.", header[i]);
1169 mi->input_error = -1;
1172 if (!strcmp(header[i], "Subject")) {
1173 if (!mi->keep_subject) {
1174 cleanup_subject(mi, hdr);
1175 cleanup_space(hdr);
1177 output_header_lines(mi->output, "Subject", hdr);
1178 } else if (!strcmp(header[i], "From")) {
1179 cleanup_space(hdr);
1180 handle_from(mi, hdr);
1181 fprintf(mi->output, "Author: %s\n", mi->name.buf);
1182 fprintf(mi->output, "Email: %s\n", mi->email.buf);
1183 } else {
1184 cleanup_space(hdr);
1185 fprintf(mi->output, "%s: %s\n", header[i], hdr->buf);
1188 fprintf(mi->output, "\n");
1191 int mailinfo(struct mailinfo *mi, const char *msg, const char *patch)
1193 FILE *cmitmsg;
1194 int peek;
1195 struct strbuf line = STRBUF_INIT;
1197 cmitmsg = fopen(msg, "w");
1198 if (!cmitmsg) {
1199 perror(msg);
1200 return -1;
1202 mi->patchfile = fopen(patch, "w");
1203 if (!mi->patchfile) {
1204 perror(patch);
1205 fclose(cmitmsg);
1206 return -1;
1209 mi->p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*(mi->p_hdr_data)));
1210 mi->s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*(mi->s_hdr_data)));
1212 do {
1213 peek = fgetc(mi->input);
1214 if (peek == EOF) {
1215 fclose(cmitmsg);
1216 return error("empty patch: '%s'", patch);
1218 } while (isspace(peek));
1219 ungetc(peek, mi->input);
1221 /* process the email header */
1222 while (read_one_header_line(&line, mi->input))
1223 check_header(mi, &line, mi->p_hdr_data, 1);
1225 handle_body(mi, &line);
1226 fwrite(mi->log_message.buf, 1, mi->log_message.len, cmitmsg);
1227 fclose(cmitmsg);
1228 fclose(mi->patchfile);
1230 handle_info(mi);
1231 strbuf_release(&line);
1232 return mi->input_error;
1235 int mailinfo_parse_quoted_cr_action(const char *actionstr, int *action)
1237 if (!strcmp(actionstr, "nowarn"))
1238 *action = quoted_cr_nowarn;
1239 else if (!strcmp(actionstr, "warn"))
1240 *action = quoted_cr_warn;
1241 else if (!strcmp(actionstr, "strip"))
1242 *action = quoted_cr_strip;
1243 else
1244 return -1;
1245 return 0;
1248 static int git_mailinfo_config(const char *var, const char *value,
1249 const struct config_context *ctx, void *mi_)
1251 struct mailinfo *mi = mi_;
1253 if (!starts_with(var, "mailinfo."))
1254 return git_default_config(var, value, ctx, NULL);
1255 if (!strcmp(var, "mailinfo.scissors")) {
1256 mi->use_scissors = git_config_bool(var, value);
1257 return 0;
1259 if (!strcmp(var, "mailinfo.quotedcr")) {
1260 if (!value)
1261 return config_error_nonbool(var);
1262 if (mailinfo_parse_quoted_cr_action(value, &mi->quoted_cr) != 0)
1263 return error(_("bad action '%s' for '%s'"), value, var);
1264 return 0;
1266 /* perhaps others here */
1267 return 0;
1270 void setup_mailinfo(struct mailinfo *mi)
1272 memset(mi, 0, sizeof(*mi));
1273 strbuf_init(&mi->name, 0);
1274 strbuf_init(&mi->email, 0);
1275 strbuf_init(&mi->charset, 0);
1276 strbuf_init(&mi->log_message, 0);
1277 strbuf_init(&mi->inbody_header_accum, 0);
1278 mi->quoted_cr = quoted_cr_warn;
1279 mi->header_stage = 1;
1280 mi->use_inbody_headers = 1;
1281 mi->content_top = mi->content;
1282 git_config(git_mailinfo_config, mi);
1285 void clear_mailinfo(struct mailinfo *mi)
1287 strbuf_release(&mi->name);
1288 strbuf_release(&mi->email);
1289 strbuf_release(&mi->charset);
1290 strbuf_release(&mi->inbody_header_accum);
1291 free(mi->message_id);
1293 strbuf_list_free(mi->p_hdr_data);
1294 strbuf_list_free(mi->s_hdr_data);
1296 while (mi->content < mi->content_top) {
1297 free(*(mi->content_top));
1298 mi->content_top--;
1301 strbuf_release(&mi->log_message);