Merge branch 'jc/parse-options-show-branch'
[alt-git.git] / mailinfo.c
blob931505363cde08b0475f200e9c60fd3c034413b7
1 #include "git-compat-util.h"
2 #include "config.h"
3 #include "gettext.h"
4 #include "hex.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 c;
62 int take_next_literally = 0;
64 strbuf_addch(outbuf, '(');
66 while ((c = *in++) != 0) {
67 if (take_next_literally == 1) {
68 take_next_literally = 0;
69 } else {
70 switch (c) {
71 case '\\':
72 take_next_literally = 1;
73 continue;
74 case '(':
75 in = unquote_comment(outbuf, in);
76 continue;
77 case ')':
78 strbuf_addch(outbuf, ')');
79 return in;
83 strbuf_addch(outbuf, c);
86 return in;
89 static const char *unquote_quoted_string(struct strbuf *outbuf, const char *in)
91 int c;
92 int take_next_literally = 0;
94 while ((c = *in++) != 0) {
95 if (take_next_literally == 1) {
96 take_next_literally = 0;
97 } else {
98 switch (c) {
99 case '\\':
100 take_next_literally = 1;
101 continue;
102 case '"':
103 return in;
107 strbuf_addch(outbuf, c);
110 return in;
113 static void unquote_quoted_pair(struct strbuf *line)
115 struct strbuf outbuf;
116 const char *in = line->buf;
117 int c;
119 strbuf_init(&outbuf, line->len);
121 while ((c = *in++) != 0) {
122 switch (c) {
123 case '"':
124 in = unquote_quoted_string(&outbuf, in);
125 continue;
126 case '(':
127 in = unquote_comment(&outbuf, in);
128 continue;
131 strbuf_addch(&outbuf, c);
134 strbuf_swap(&outbuf, line);
135 strbuf_release(&outbuf);
139 static void handle_from(struct mailinfo *mi, const struct strbuf *from)
141 char *at;
142 size_t el;
143 struct strbuf f;
145 strbuf_init(&f, from->len);
146 strbuf_addbuf(&f, from);
148 unquote_quoted_pair(&f);
150 at = strchr(f.buf, '@');
151 if (!at) {
152 parse_bogus_from(mi, from);
153 goto out;
157 * If we already have one email, don't take any confusing lines
159 if (mi->email.len && strchr(at + 1, '@'))
160 goto out;
162 /* Pick up the string around '@', possibly delimited with <>
163 * pair; that is the email part.
165 while (at > f.buf) {
166 char c = at[-1];
167 if (isspace(c))
168 break;
169 if (c == '<') {
170 at[-1] = ' ';
171 break;
173 at--;
175 el = strcspn(at, " \n\t\r\v\f>");
176 strbuf_reset(&mi->email);
177 strbuf_add(&mi->email, at, el);
178 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
180 /* The remainder is name. It could be
182 * - "John Doe <john.doe@xz>" (a), or
183 * - "john.doe@xz (John Doe)" (b), or
184 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
186 * but we have removed the email part, so
188 * - remove extra spaces which could stay after email (case 'c'), and
189 * - trim from both ends, possibly removing the () pair at the end
190 * (cases 'a' and 'b').
192 cleanup_space(&f);
193 strbuf_trim(&f);
194 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
195 strbuf_remove(&f, 0, 1);
196 strbuf_setlen(&f, f.len - 1);
199 get_sane_name(&mi->name, &f, &mi->email);
200 out:
201 strbuf_release(&f);
204 static void handle_header(struct strbuf **out, const struct strbuf *line)
206 if (!*out) {
207 *out = xmalloc(sizeof(struct strbuf));
208 strbuf_init(*out, line->len);
209 } else
210 strbuf_reset(*out);
212 strbuf_addbuf(*out, line);
215 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
216 * to have enough heuristics to grok MIME encoded patches often found
217 * on our mailing lists. For example, we do not even treat header lines
218 * case insensitively.
221 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
223 const char *ends, *ap = strcasestr(line, name);
224 size_t sz;
226 strbuf_setlen(attr, 0);
227 if (!ap)
228 return 0;
229 ap += strlen(name);
230 if (*ap == '"') {
231 ap++;
232 ends = "\"";
234 else
235 ends = "; \t";
236 sz = strcspn(ap, ends);
237 strbuf_add(attr, ap, sz);
238 return 1;
241 static int has_attr_value(const char *line, const char *name, const char *value)
243 struct strbuf sb = STRBUF_INIT;
244 int rc = slurp_attr(line, name, &sb) && !strcasecmp(sb.buf, value);
245 strbuf_release(&sb);
246 return rc;
249 static void handle_content_type(struct mailinfo *mi, struct strbuf *line)
251 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
252 strbuf_init(boundary, line->len);
254 mi->format_flowed = has_attr_value(line->buf, "format=", "flowed");
255 mi->delsp = has_attr_value(line->buf, "delsp=", "yes");
257 if (slurp_attr(line->buf, "boundary=", boundary)) {
258 strbuf_insertstr(boundary, 0, "--");
259 if (++mi->content_top >= &mi->content[MAX_BOUNDARIES]) {
260 error("Too many boundaries to handle");
261 mi->input_error = -1;
262 mi->content_top = &mi->content[MAX_BOUNDARIES] - 1;
263 return;
265 *(mi->content_top) = boundary;
266 boundary = NULL;
268 slurp_attr(line->buf, "charset=", &mi->charset);
270 if (boundary) {
271 strbuf_release(boundary);
272 free(boundary);
276 static void handle_content_transfer_encoding(struct mailinfo *mi,
277 const struct strbuf *line)
279 if (strcasestr(line->buf, "base64"))
280 mi->transfer_encoding = TE_BASE64;
281 else if (strcasestr(line->buf, "quoted-printable"))
282 mi->transfer_encoding = TE_QP;
283 else
284 mi->transfer_encoding = TE_DONTCARE;
287 static int is_multipart_boundary(struct mailinfo *mi, const struct strbuf *line)
289 struct strbuf *content_top = *(mi->content_top);
291 return ((content_top->len <= line->len) &&
292 !memcmp(line->buf, content_top->buf, content_top->len));
295 static void cleanup_subject(struct mailinfo *mi, struct strbuf *subject)
297 size_t at = 0;
299 while (at < subject->len) {
300 char *pos;
301 size_t remove;
303 switch (subject->buf[at]) {
304 case 'r': case 'R':
305 if (subject->len <= at + 3)
306 break;
307 if ((subject->buf[at + 1] == 'e' ||
308 subject->buf[at + 1] == 'E') &&
309 subject->buf[at + 2] == ':') {
310 strbuf_remove(subject, at, 3);
311 continue;
313 at++;
314 break;
315 case ' ': case '\t': case ':':
316 strbuf_remove(subject, at, 1);
317 continue;
318 case '[':
319 pos = strchr(subject->buf + at, ']');
320 if (!pos)
321 break;
322 remove = pos - (subject->buf + at) + 1;
323 if (!mi->keep_non_patch_brackets_in_subject ||
324 (7 <= remove &&
325 memmem(subject->buf + at, remove, "PATCH", 5)))
326 strbuf_remove(subject, at, remove);
327 else {
328 at += remove;
330 * If the input had a space after the ], keep
331 * it. We don't bother with finding the end of
332 * the space, since we later normalize it
333 * anyway.
335 if (isspace(subject->buf[at]))
336 at += 1;
338 continue;
340 break;
342 strbuf_trim(subject);
345 #define MAX_HDR_PARSED 10
346 static const char *header[MAX_HDR_PARSED] = {
347 "From","Subject","Date",
350 static inline int skip_header(const struct strbuf *line, const char *hdr,
351 const char **outval)
353 const char *val;
354 if (!skip_iprefix(line->buf, hdr, &val) ||
355 *val++ != ':')
356 return 0;
357 while (isspace(*val))
358 val++;
359 *outval = val;
360 return 1;
363 static int is_format_patch_separator(const char *line, int len)
365 static const char SAMPLE[] =
366 "From e6807f3efca28b30decfecb1732a56c7db1137ee Mon Sep 17 00:00:00 2001\n";
367 const char *cp;
369 if (len != strlen(SAMPLE))
370 return 0;
371 if (!skip_prefix(line, "From ", &cp))
372 return 0;
373 if (strspn(cp, "0123456789abcdef") != 40)
374 return 0;
375 cp += 40;
376 return !memcmp(SAMPLE + (cp - line), cp, strlen(SAMPLE) - (cp - line));
379 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
381 const char *in = q_seg->buf;
382 int c;
383 struct strbuf *out = xmalloc(sizeof(struct strbuf));
384 strbuf_init(out, q_seg->len);
386 while ((c = *in++) != 0) {
387 if (c == '=') {
388 int ch, d = *in;
389 if (d == '\n' || !d)
390 break; /* drop trailing newline */
391 ch = hex2chr(in);
392 if (ch >= 0) {
393 strbuf_addch(out, ch);
394 in += 2;
395 continue;
397 /* garbage -- fall through */
399 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
400 c = 0x20;
401 strbuf_addch(out, c);
403 return out;
406 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
408 /* Decode in..ep, possibly in-place to ot */
409 int c, pos = 0, acc = 0;
410 const char *in = b_seg->buf;
411 struct strbuf *out = xmalloc(sizeof(struct strbuf));
412 strbuf_init(out, b_seg->len);
414 while ((c = *in++) != 0) {
415 if (c == '+')
416 c = 62;
417 else if (c == '/')
418 c = 63;
419 else if ('A' <= c && c <= 'Z')
420 c -= 'A';
421 else if ('a' <= c && c <= 'z')
422 c -= 'a' - 26;
423 else if ('0' <= c && c <= '9')
424 c -= '0' - 52;
425 else
426 continue; /* garbage */
427 switch (pos++) {
428 case 0:
429 acc = (c << 2);
430 break;
431 case 1:
432 strbuf_addch(out, (acc | (c >> 4)));
433 acc = (c & 15) << 4;
434 break;
435 case 2:
436 strbuf_addch(out, (acc | (c >> 2)));
437 acc = (c & 3) << 6;
438 break;
439 case 3:
440 strbuf_addch(out, (acc | c));
441 acc = pos = 0;
442 break;
445 return out;
448 static int convert_to_utf8(struct mailinfo *mi,
449 struct strbuf *line, const char *charset)
451 char *out;
452 size_t out_len;
454 if (!mi->metainfo_charset || !charset || !*charset)
455 return 0;
457 if (same_encoding(mi->metainfo_charset, charset))
458 return 0;
459 out = reencode_string_len(line->buf, line->len,
460 mi->metainfo_charset, charset, &out_len);
461 if (!out) {
462 mi->input_error = -1;
463 return error("cannot convert from %s to %s",
464 charset, mi->metainfo_charset);
466 strbuf_attach(line, out, out_len, out_len);
467 return 0;
470 static void decode_header(struct mailinfo *mi, struct strbuf *it)
472 char *in, *ep, *cp;
473 struct strbuf outbuf = STRBUF_INIT, *dec;
474 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
475 int found_error = 1; /* pessimism */
477 in = it->buf;
478 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
479 int encoding;
480 strbuf_reset(&charset_q);
481 strbuf_reset(&piecebuf);
483 if (in != ep) {
485 * We are about to process an encoded-word
486 * that begins at ep, but there is something
487 * before the encoded word.
489 char *scan;
490 for (scan = in; scan < ep; scan++)
491 if (!isspace(*scan))
492 break;
494 if (scan != ep || in == it->buf) {
496 * We should not lose that "something",
497 * unless we have just processed an
498 * encoded-word, and there is only LWS
499 * before the one we are about to process.
501 strbuf_add(&outbuf, in, ep - in);
504 /* E.g.
505 * ep : "=?iso-2022-jp?B?GyR...?= foo"
506 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
508 ep += 2;
510 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
511 goto release_return;
513 if (cp + 3 - it->buf > it->len)
514 goto release_return;
515 strbuf_add(&charset_q, ep, cp - ep);
517 encoding = cp[1];
518 if (!encoding || cp[2] != '?')
519 goto release_return;
520 ep = strstr(cp + 3, "?=");
521 if (!ep)
522 goto release_return;
523 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
524 switch (tolower(encoding)) {
525 default:
526 goto release_return;
527 case 'b':
528 dec = decode_b_segment(&piecebuf);
529 break;
530 case 'q':
531 dec = decode_q_segment(&piecebuf, 1);
532 break;
534 if (convert_to_utf8(mi, dec, charset_q.buf))
535 goto release_return;
537 strbuf_addbuf(&outbuf, dec);
538 strbuf_release(dec);
539 free(dec);
540 in = ep + 2;
542 strbuf_addstr(&outbuf, in);
543 strbuf_reset(it);
544 strbuf_addbuf(it, &outbuf);
545 found_error = 0;
546 release_return:
547 strbuf_release(&outbuf);
548 strbuf_release(&charset_q);
549 strbuf_release(&piecebuf);
551 if (found_error)
552 mi->input_error = -1;
556 * Returns true if "line" contains a header matching "hdr", in which case "val"
557 * will contain the value of the header with any RFC2047 B and Q encoding
558 * unwrapped, and optionally normalize the meta information to utf8.
560 static int parse_header(const struct strbuf *line,
561 const char *hdr,
562 struct mailinfo *mi,
563 struct strbuf *val)
565 const char *val_str;
567 if (!skip_header(line, hdr, &val_str))
568 return 0;
569 strbuf_addstr(val, val_str);
570 decode_header(mi, val);
571 return 1;
574 static int check_header(struct mailinfo *mi,
575 const struct strbuf *line,
576 struct strbuf *hdr_data[], int overwrite)
578 int i, ret = 0;
579 struct strbuf sb = STRBUF_INIT;
581 /* search for the interesting parts */
582 for (i = 0; header[i]; i++) {
583 if ((!hdr_data[i] || overwrite) &&
584 parse_header(line, header[i], mi, &sb)) {
585 handle_header(&hdr_data[i], &sb);
586 ret = 1;
587 goto check_header_out;
591 /* Content stuff */
592 if (parse_header(line, "Content-Type", mi, &sb)) {
593 handle_content_type(mi, &sb);
594 ret = 1;
595 goto check_header_out;
597 if (parse_header(line, "Content-Transfer-Encoding", mi, &sb)) {
598 handle_content_transfer_encoding(mi, &sb);
599 ret = 1;
600 goto check_header_out;
602 if (parse_header(line, "Message-ID", mi, &sb)) {
603 if (mi->add_message_id)
604 mi->message_id = strbuf_detach(&sb, NULL);
605 ret = 1;
606 goto check_header_out;
609 check_header_out:
610 strbuf_release(&sb);
611 return ret;
615 * Returns 1 if the given line or any line beginning with the given line is an
616 * in-body header (that is, check_header will succeed when passed
617 * mi->s_hdr_data).
619 static int is_inbody_header(const struct mailinfo *mi,
620 const struct strbuf *line)
622 int i;
623 const char *val;
624 for (i = 0; header[i]; i++)
625 if (!mi->s_hdr_data[i] && skip_header(line, header[i], &val))
626 return 1;
627 return 0;
630 static void decode_transfer_encoding(struct mailinfo *mi, struct strbuf *line)
632 struct strbuf *ret;
634 switch (mi->transfer_encoding) {
635 case TE_QP:
636 ret = decode_q_segment(line, 0);
637 break;
638 case TE_BASE64:
639 ret = decode_b_segment(line);
640 break;
641 case TE_DONTCARE:
642 default:
643 return;
645 strbuf_reset(line);
646 strbuf_addbuf(line, ret);
647 strbuf_release(ret);
648 free(ret);
651 static inline int patchbreak(const struct strbuf *line)
653 size_t i;
655 /* Beginning of a "diff -" header? */
656 if (starts_with(line->buf, "diff -"))
657 return 1;
659 /* CVS "Index: " line? */
660 if (starts_with(line->buf, "Index: "))
661 return 1;
664 * "--- <filename>" starts patches without headers
665 * "---<sp>*" is a manual separator
667 if (line->len < 4)
668 return 0;
670 if (starts_with(line->buf, "---")) {
671 /* space followed by a filename? */
672 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
673 return 1;
674 /* Just whitespace? */
675 for (i = 3; i < line->len; i++) {
676 unsigned char c = line->buf[i];
677 if (c == '\n')
678 return 1;
679 if (!isspace(c))
680 break;
682 return 0;
684 return 0;
687 static int is_scissors_line(const char *line)
689 const char *c;
690 int scissors = 0, gap = 0;
691 const char *first_nonblank = NULL, *last_nonblank = NULL;
692 int visible, perforation = 0, in_perforation = 0;
694 for (c = line; *c; c++) {
695 if (isspace(*c)) {
696 if (in_perforation) {
697 perforation++;
698 gap++;
700 continue;
702 last_nonblank = c;
703 if (!first_nonblank)
704 first_nonblank = c;
705 if (*c == '-') {
706 in_perforation = 1;
707 perforation++;
708 continue;
710 if (starts_with(c, ">8") || starts_with(c, "8<") ||
711 starts_with(c, ">%") || starts_with(c, "%<")) {
712 in_perforation = 1;
713 perforation += 2;
714 scissors += 2;
715 c++;
716 continue;
718 in_perforation = 0;
722 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
723 * Even though there can be arbitrary cruft on the same line
724 * (e.g. "cut here"), in order to avoid misidentification, the
725 * perforation must occupy more than a third of the visible
726 * width of the line, and dashes and scissors must occupy more
727 * than half of the perforation.
730 if (first_nonblank && last_nonblank)
731 visible = last_nonblank - first_nonblank + 1;
732 else
733 visible = 0;
734 return (scissors && 8 <= visible &&
735 visible < perforation * 3 &&
736 gap * 2 < perforation);
739 static void flush_inbody_header_accum(struct mailinfo *mi)
741 if (!mi->inbody_header_accum.len)
742 return;
743 if (!check_header(mi, &mi->inbody_header_accum, mi->s_hdr_data, 0))
744 BUG("inbody_header_accum, if not empty, must always contain a valid in-body header");
745 strbuf_reset(&mi->inbody_header_accum);
748 static int check_inbody_header(struct mailinfo *mi, const struct strbuf *line)
750 if (mi->inbody_header_accum.len &&
751 (line->buf[0] == ' ' || line->buf[0] == '\t')) {
752 if (mi->use_scissors && is_scissors_line(line->buf)) {
754 * This is a scissors line; do not consider this line
755 * as a header continuation line.
757 flush_inbody_header_accum(mi);
758 return 0;
760 strbuf_strip_suffix(&mi->inbody_header_accum, "\n");
761 strbuf_addbuf(&mi->inbody_header_accum, line);
762 return 1;
765 flush_inbody_header_accum(mi);
767 if (starts_with(line->buf, ">From") && isspace(line->buf[5]))
768 return is_format_patch_separator(line->buf + 1, line->len - 1);
769 if (starts_with(line->buf, "[PATCH]") && isspace(line->buf[7])) {
770 int i;
771 for (i = 0; header[i]; i++)
772 if (!strcmp("Subject", header[i])) {
773 handle_header(&mi->s_hdr_data[i], line);
774 return 1;
776 return 0;
778 if (is_inbody_header(mi, line)) {
779 strbuf_addbuf(&mi->inbody_header_accum, line);
780 return 1;
782 return 0;
785 static int handle_commit_msg(struct mailinfo *mi, struct strbuf *line)
787 assert(!mi->filter_stage);
789 if (mi->header_stage) {
790 if (!line->len || (line->len == 1 && line->buf[0] == '\n')) {
791 if (mi->inbody_header_accum.len) {
792 flush_inbody_header_accum(mi);
793 mi->header_stage = 0;
795 return 0;
799 if (mi->use_inbody_headers && mi->header_stage) {
800 mi->header_stage = check_inbody_header(mi, line);
801 if (mi->header_stage)
802 return 0;
803 } else
804 /* Only trim the first (blank) line of the commit message
805 * when ignoring in-body headers.
807 mi->header_stage = 0;
809 /* normalize the log message to UTF-8. */
810 if (convert_to_utf8(mi, line, mi->charset.buf))
811 return 0; /* mi->input_error already set */
813 if (mi->use_scissors && is_scissors_line(line->buf)) {
814 int i;
816 strbuf_setlen(&mi->log_message, 0);
817 mi->header_stage = 1;
820 * We may have already read "secondary headers"; purge
821 * them to give ourselves a clean restart.
823 for (i = 0; header[i]; i++) {
824 if (mi->s_hdr_data[i])
825 strbuf_release(mi->s_hdr_data[i]);
826 FREE_AND_NULL(mi->s_hdr_data[i]);
828 return 0;
831 if (patchbreak(line)) {
832 if (mi->message_id)
833 strbuf_addf(&mi->log_message,
834 "Message-ID: %s\n", mi->message_id);
835 return 1;
838 strbuf_addbuf(&mi->log_message, line);
839 return 0;
842 static void handle_patch(struct mailinfo *mi, const struct strbuf *line)
844 fwrite(line->buf, 1, line->len, mi->patchfile);
845 mi->patch_lines++;
848 static void handle_filter(struct mailinfo *mi, struct strbuf *line)
850 switch (mi->filter_stage) {
851 case 0:
852 if (!handle_commit_msg(mi, line))
853 break;
854 mi->filter_stage++;
855 /* fallthrough */
856 case 1:
857 handle_patch(mi, line);
858 break;
862 static int is_rfc2822_header(const struct strbuf *line)
865 * The section that defines the loosest possible
866 * field name is "3.6.8 Optional fields".
868 * optional-field = field-name ":" unstructured CRLF
869 * field-name = 1*ftext
870 * ftext = %d33-57 / %59-126
872 int ch;
873 char *cp = line->buf;
875 /* Count mbox From headers as headers */
876 if (starts_with(cp, "From ") || starts_with(cp, ">From "))
877 return 1;
879 while ((ch = *cp++)) {
880 if (ch == ':')
881 return 1;
882 if ((33 <= ch && ch <= 57) ||
883 (59 <= ch && ch <= 126))
884 continue;
885 break;
887 return 0;
890 static int read_one_header_line(struct strbuf *line, FILE *in)
892 struct strbuf continuation = STRBUF_INIT;
894 /* Get the first part of the line. */
895 if (strbuf_getline_lf(line, in))
896 return 0;
899 * Is it an empty line or not a valid rfc2822 header?
900 * If so, stop here, and return false ("not a header")
902 strbuf_rtrim(line);
903 if (!line->len || !is_rfc2822_header(line)) {
904 /* Re-add the newline */
905 strbuf_addch(line, '\n');
906 return 0;
910 * Now we need to eat all the continuation lines..
911 * Yuck, 2822 header "folding"
913 for (;;) {
914 int peek;
916 peek = fgetc(in);
917 if (peek == EOF)
918 break;
919 ungetc(peek, in);
920 if (peek != ' ' && peek != '\t')
921 break;
922 if (strbuf_getline_lf(&continuation, in))
923 break;
924 continuation.buf[0] = ' ';
925 strbuf_rtrim(&continuation);
926 strbuf_addbuf(line, &continuation);
928 strbuf_release(&continuation);
930 return 1;
933 static int find_boundary(struct mailinfo *mi, struct strbuf *line)
935 while (!strbuf_getline_lf(line, mi->input)) {
936 if (*(mi->content_top) && is_multipart_boundary(mi, line))
937 return 1;
939 return 0;
942 static int handle_boundary(struct mailinfo *mi, struct strbuf *line)
944 struct strbuf newline = STRBUF_INIT;
946 strbuf_addch(&newline, '\n');
947 again:
948 if (line->len >= (*(mi->content_top))->len + 2 &&
949 !memcmp(line->buf + (*(mi->content_top))->len, "--", 2)) {
950 /* we hit an end boundary */
951 /* pop the current boundary off the stack */
952 strbuf_release(*(mi->content_top));
953 FREE_AND_NULL(*(mi->content_top));
955 /* technically won't happen as is_multipart_boundary()
956 will fail first. But just in case..
958 if (--mi->content_top < mi->content) {
959 error("Detected mismatched boundaries, can't recover");
960 mi->input_error = -1;
961 mi->content_top = mi->content;
962 strbuf_release(&newline);
963 return 0;
965 handle_filter(mi, &newline);
966 strbuf_release(&newline);
967 if (mi->input_error)
968 return 0;
970 /* skip to the next boundary */
971 if (!find_boundary(mi, line))
972 return 0;
973 goto again;
976 /* set some defaults */
977 mi->transfer_encoding = TE_DONTCARE;
978 strbuf_reset(&mi->charset);
980 /* slurp in this section's info */
981 while (read_one_header_line(line, mi->input))
982 check_header(mi, line, mi->p_hdr_data, 0);
984 strbuf_release(&newline);
985 /* replenish line */
986 if (strbuf_getline_lf(line, mi->input))
987 return 0;
988 strbuf_addch(line, '\n');
989 return 1;
992 static void handle_filter_flowed(struct mailinfo *mi, struct strbuf *line,
993 struct strbuf *prev)
995 size_t len = line->len;
996 const char *rest;
998 if (!mi->format_flowed) {
999 if (len >= 2 &&
1000 line->buf[len - 2] == '\r' &&
1001 line->buf[len - 1] == '\n') {
1002 mi->have_quoted_cr = 1;
1003 if (mi->quoted_cr == quoted_cr_strip) {
1004 strbuf_setlen(line, len - 2);
1005 strbuf_addch(line, '\n');
1006 len--;
1009 handle_filter(mi, line);
1010 return;
1013 if (line->buf[len - 1] == '\n') {
1014 len--;
1015 if (len && line->buf[len - 1] == '\r')
1016 len--;
1019 /* Keep signature separator as-is. */
1020 if (skip_prefix(line->buf, "-- ", &rest) && rest - line->buf == len) {
1021 if (prev->len) {
1022 handle_filter(mi, prev);
1023 strbuf_reset(prev);
1025 handle_filter(mi, line);
1026 return;
1029 /* Unstuff space-stuffed line. */
1030 if (len && line->buf[0] == ' ') {
1031 strbuf_remove(line, 0, 1);
1032 len--;
1035 /* Save flowed line for later, but without the soft line break. */
1036 if (len && line->buf[len - 1] == ' ') {
1037 strbuf_add(prev, line->buf, len - !!mi->delsp);
1038 return;
1041 /* Prepend any previous partial lines */
1042 strbuf_insert(line, 0, prev->buf, prev->len);
1043 strbuf_reset(prev);
1045 handle_filter(mi, line);
1048 static void summarize_quoted_cr(struct mailinfo *mi)
1050 if (mi->have_quoted_cr &&
1051 mi->quoted_cr == quoted_cr_warn)
1052 warning(_("quoted CRLF detected"));
1055 static void handle_body(struct mailinfo *mi, struct strbuf *line)
1057 struct strbuf prev = STRBUF_INIT;
1059 /* Skip up to the first boundary */
1060 if (*(mi->content_top)) {
1061 if (!find_boundary(mi, line))
1062 goto handle_body_out;
1065 do {
1066 /* process any boundary lines */
1067 if (*(mi->content_top) && is_multipart_boundary(mi, line)) {
1068 /* flush any leftover */
1069 if (prev.len) {
1070 handle_filter(mi, &prev);
1071 strbuf_reset(&prev);
1073 summarize_quoted_cr(mi);
1074 mi->have_quoted_cr = 0;
1075 if (!handle_boundary(mi, line))
1076 goto handle_body_out;
1079 /* Unwrap transfer encoding */
1080 decode_transfer_encoding(mi, line);
1082 switch (mi->transfer_encoding) {
1083 case TE_BASE64:
1084 case TE_QP:
1086 struct strbuf **lines, **it, *sb;
1088 /* Prepend any previous partial lines */
1089 strbuf_insert(line, 0, prev.buf, prev.len);
1090 strbuf_reset(&prev);
1093 * This is a decoded line that may contain
1094 * multiple new lines. Pass only one chunk
1095 * at a time to handle_filter()
1097 lines = strbuf_split(line, '\n');
1098 for (it = lines; (sb = *it); it++) {
1099 if (!*(it + 1)) /* The last line */
1100 if (sb->buf[sb->len - 1] != '\n') {
1101 /* Partial line, save it for later. */
1102 strbuf_addbuf(&prev, sb);
1103 break;
1105 handle_filter_flowed(mi, sb, &prev);
1108 * The partial chunk is saved in "prev" and will be
1109 * appended by the next iteration of read_line_with_nul().
1111 strbuf_list_free(lines);
1112 break;
1114 default:
1115 handle_filter_flowed(mi, line, &prev);
1118 if (mi->input_error)
1119 break;
1120 } while (!strbuf_getwholeline(line, mi->input, '\n'));
1122 if (prev.len)
1123 handle_filter(mi, &prev);
1124 summarize_quoted_cr(mi);
1126 flush_inbody_header_accum(mi);
1128 handle_body_out:
1129 strbuf_release(&prev);
1132 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
1134 const char *sp = data->buf;
1135 while (1) {
1136 char *ep = strchr(sp, '\n');
1137 int len;
1138 if (!ep)
1139 len = strlen(sp);
1140 else
1141 len = ep - sp;
1142 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
1143 if (!ep)
1144 break;
1145 sp = ep + 1;
1149 static void handle_info(struct mailinfo *mi)
1151 struct strbuf *hdr;
1152 int i;
1154 for (i = 0; header[i]; i++) {
1155 /* only print inbody headers if we output a patch file */
1156 if (mi->patch_lines && mi->s_hdr_data[i])
1157 hdr = mi->s_hdr_data[i];
1158 else if (mi->p_hdr_data[i])
1159 hdr = mi->p_hdr_data[i];
1160 else
1161 continue;
1163 if (memchr(hdr->buf, '\0', hdr->len)) {
1164 error("a NUL byte in '%s' is not allowed.", header[i]);
1165 mi->input_error = -1;
1168 if (!strcmp(header[i], "Subject")) {
1169 if (!mi->keep_subject) {
1170 cleanup_subject(mi, hdr);
1171 cleanup_space(hdr);
1173 output_header_lines(mi->output, "Subject", hdr);
1174 } else if (!strcmp(header[i], "From")) {
1175 cleanup_space(hdr);
1176 handle_from(mi, hdr);
1177 fprintf(mi->output, "Author: %s\n", mi->name.buf);
1178 fprintf(mi->output, "Email: %s\n", mi->email.buf);
1179 } else {
1180 cleanup_space(hdr);
1181 fprintf(mi->output, "%s: %s\n", header[i], hdr->buf);
1184 fprintf(mi->output, "\n");
1187 int mailinfo(struct mailinfo *mi, const char *msg, const char *patch)
1189 FILE *cmitmsg;
1190 int peek;
1191 struct strbuf line = STRBUF_INIT;
1193 cmitmsg = fopen(msg, "w");
1194 if (!cmitmsg) {
1195 perror(msg);
1196 return -1;
1198 mi->patchfile = fopen(patch, "w");
1199 if (!mi->patchfile) {
1200 perror(patch);
1201 fclose(cmitmsg);
1202 return -1;
1205 mi->p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*(mi->p_hdr_data)));
1206 mi->s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*(mi->s_hdr_data)));
1208 do {
1209 peek = fgetc(mi->input);
1210 if (peek == EOF) {
1211 fclose(cmitmsg);
1212 return error("empty patch: '%s'", patch);
1214 } while (isspace(peek));
1215 ungetc(peek, mi->input);
1217 /* process the email header */
1218 while (read_one_header_line(&line, mi->input))
1219 check_header(mi, &line, mi->p_hdr_data, 1);
1221 handle_body(mi, &line);
1222 fwrite(mi->log_message.buf, 1, mi->log_message.len, cmitmsg);
1223 fclose(cmitmsg);
1224 fclose(mi->patchfile);
1226 handle_info(mi);
1227 strbuf_release(&line);
1228 return mi->input_error;
1231 int mailinfo_parse_quoted_cr_action(const char *actionstr, int *action)
1233 if (!strcmp(actionstr, "nowarn"))
1234 *action = quoted_cr_nowarn;
1235 else if (!strcmp(actionstr, "warn"))
1236 *action = quoted_cr_warn;
1237 else if (!strcmp(actionstr, "strip"))
1238 *action = quoted_cr_strip;
1239 else
1240 return -1;
1241 return 0;
1244 static int git_mailinfo_config(const char *var, const char *value,
1245 const struct config_context *ctx, void *mi_)
1247 struct mailinfo *mi = mi_;
1249 if (!starts_with(var, "mailinfo."))
1250 return git_default_config(var, value, ctx, NULL);
1251 if (!strcmp(var, "mailinfo.scissors")) {
1252 mi->use_scissors = git_config_bool(var, value);
1253 return 0;
1255 if (!strcmp(var, "mailinfo.quotedcr")) {
1256 if (mailinfo_parse_quoted_cr_action(value, &mi->quoted_cr) != 0)
1257 return error(_("bad action '%s' for '%s'"), value, var);
1258 return 0;
1260 /* perhaps others here */
1261 return 0;
1264 void setup_mailinfo(struct mailinfo *mi)
1266 memset(mi, 0, sizeof(*mi));
1267 strbuf_init(&mi->name, 0);
1268 strbuf_init(&mi->email, 0);
1269 strbuf_init(&mi->charset, 0);
1270 strbuf_init(&mi->log_message, 0);
1271 strbuf_init(&mi->inbody_header_accum, 0);
1272 mi->quoted_cr = quoted_cr_warn;
1273 mi->header_stage = 1;
1274 mi->use_inbody_headers = 1;
1275 mi->content_top = mi->content;
1276 git_config(git_mailinfo_config, mi);
1279 void clear_mailinfo(struct mailinfo *mi)
1281 strbuf_release(&mi->name);
1282 strbuf_release(&mi->email);
1283 strbuf_release(&mi->charset);
1284 strbuf_release(&mi->inbody_header_accum);
1285 free(mi->message_id);
1287 strbuf_list_free(mi->p_hdr_data);
1288 strbuf_list_free(mi->s_hdr_data);
1290 while (mi->content < mi->content_top) {
1291 free(*(mi->content_top));
1292 mi->content_top--;
1295 strbuf_release(&mi->log_message);