builtin: fix typos
[git/gitster.git] / mailinfo.c
blobd1f42bd7e3e692aceb6806cedd71af1546c8aa4e
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "config.h"
5 #include "gettext.h"
6 #include "hex-ll.h"
7 #include "utf8.h"
8 #include "strbuf.h"
9 #include "mailinfo.h"
11 static void cleanup_space(struct strbuf *sb)
13 size_t pos, cnt;
14 for (pos = 0; pos < sb->len; pos++) {
15 if (isspace(sb->buf[pos])) {
16 sb->buf[pos] = ' ';
17 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
18 strbuf_remove(sb, pos + 1, cnt);
23 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
25 struct strbuf *src = name;
26 if (!name->len || 60 < name->len || strpbrk(name->buf, "@<>"))
27 src = email;
28 else if (name == out)
29 return;
30 strbuf_reset(out);
31 strbuf_addbuf(out, src);
34 static void parse_bogus_from(struct mailinfo *mi, const struct strbuf *line)
36 /* John Doe <johndoe> */
38 char *bra, *ket;
39 /* This is fallback, so do not bother if we already have an
40 * e-mail address.
42 if (mi->email.len)
43 return;
45 bra = strchr(line->buf, '<');
46 if (!bra)
47 return;
48 ket = strchr(bra, '>');
49 if (!ket)
50 return;
52 strbuf_reset(&mi->email);
53 strbuf_add(&mi->email, bra + 1, ket - bra - 1);
55 strbuf_reset(&mi->name);
56 strbuf_add(&mi->name, line->buf, bra - line->buf);
57 strbuf_trim(&mi->name);
58 get_sane_name(&mi->name, &mi->name, &mi->email);
61 static const char *unquote_comment(struct strbuf *outbuf, const char *in)
63 int take_next_literally = 0;
64 int depth = 1;
66 strbuf_addch(outbuf, '(');
68 while (*in) {
69 int c = *in++;
70 if (take_next_literally == 1) {
71 take_next_literally = 0;
72 } else {
73 switch (c) {
74 case '\\':
75 take_next_literally = 1;
76 continue;
77 case '(':
78 strbuf_addch(outbuf, '(');
79 depth++;
80 continue;
81 case ')':
82 strbuf_addch(outbuf, ')');
83 if (!--depth)
84 return in;
85 continue;
89 strbuf_addch(outbuf, c);
92 return in;
95 static const char *unquote_quoted_string(struct strbuf *outbuf, const char *in)
97 int take_next_literally = 0;
99 while (*in) {
100 int c = *in++;
101 if (take_next_literally == 1) {
102 take_next_literally = 0;
103 } else {
104 switch (c) {
105 case '\\':
106 take_next_literally = 1;
107 continue;
108 case '"':
109 return in;
113 strbuf_addch(outbuf, c);
116 return in;
119 static void unquote_quoted_pair(struct strbuf *line)
121 struct strbuf outbuf;
122 const char *in = line->buf;
123 int c;
125 strbuf_init(&outbuf, line->len);
127 while ((c = *in++) != 0) {
128 switch (c) {
129 case '"':
130 in = unquote_quoted_string(&outbuf, in);
131 continue;
132 case '(':
133 in = unquote_comment(&outbuf, in);
134 continue;
137 strbuf_addch(&outbuf, c);
140 strbuf_swap(&outbuf, line);
141 strbuf_release(&outbuf);
145 static void handle_from(struct mailinfo *mi, const struct strbuf *from)
147 char *at;
148 size_t el;
149 struct strbuf f;
151 strbuf_init(&f, from->len);
152 strbuf_addbuf(&f, from);
154 unquote_quoted_pair(&f);
156 at = strchr(f.buf, '@');
157 if (!at) {
158 parse_bogus_from(mi, from);
159 goto out;
163 * If we already have one email, don't take any confusing lines
165 if (mi->email.len && strchr(at + 1, '@'))
166 goto out;
168 /* Pick up the string around '@', possibly delimited with <>
169 * pair; that is the email part.
171 while (at > f.buf) {
172 char c = at[-1];
173 if (isspace(c))
174 break;
175 if (c == '<') {
176 at[-1] = ' ';
177 break;
179 at--;
181 el = strcspn(at, " \n\t\r\v\f>");
182 strbuf_reset(&mi->email);
183 strbuf_add(&mi->email, at, el);
184 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
186 /* The remainder is name. It could be
188 * - "John Doe <john.doe@xz>" (a), or
189 * - "john.doe@xz (John Doe)" (b), or
190 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
192 * but we have removed the email part, so
194 * - remove extra spaces which could stay after email (case 'c'), and
195 * - trim from both ends, possibly removing the () pair at the end
196 * (cases 'a' and 'b').
198 cleanup_space(&f);
199 strbuf_trim(&f);
200 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
201 strbuf_remove(&f, 0, 1);
202 strbuf_setlen(&f, f.len - 1);
205 get_sane_name(&mi->name, &f, &mi->email);
206 out:
207 strbuf_release(&f);
210 static void handle_header(struct strbuf **out, const struct strbuf *line)
212 if (!*out) {
213 *out = xmalloc(sizeof(struct strbuf));
214 strbuf_init(*out, line->len);
215 } else
216 strbuf_reset(*out);
218 strbuf_addbuf(*out, line);
221 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
222 * to have enough heuristics to grok MIME encoded patches often found
223 * on our mailing lists. For example, we do not even treat header lines
224 * case insensitively.
227 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
229 const char *ends, *ap = strcasestr(line, name);
230 size_t sz;
232 strbuf_setlen(attr, 0);
233 if (!ap)
234 return 0;
235 ap += strlen(name);
236 if (*ap == '"') {
237 ap++;
238 ends = "\"";
240 else
241 ends = "; \t";
242 sz = strcspn(ap, ends);
243 strbuf_add(attr, ap, sz);
244 return 1;
247 static int has_attr_value(const char *line, const char *name, const char *value)
249 struct strbuf sb = STRBUF_INIT;
250 int rc = slurp_attr(line, name, &sb) && !strcasecmp(sb.buf, value);
251 strbuf_release(&sb);
252 return rc;
255 static void handle_content_type(struct mailinfo *mi, struct strbuf *line)
257 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
258 strbuf_init(boundary, line->len);
260 mi->format_flowed = has_attr_value(line->buf, "format=", "flowed");
261 mi->delsp = has_attr_value(line->buf, "delsp=", "yes");
263 if (slurp_attr(line->buf, "boundary=", boundary)) {
264 strbuf_insertstr(boundary, 0, "--");
265 if (++mi->content_top >= &mi->content[MAX_BOUNDARIES]) {
266 error("Too many boundaries to handle");
267 mi->input_error = -1;
268 mi->content_top = &mi->content[MAX_BOUNDARIES] - 1;
269 return;
271 *(mi->content_top) = boundary;
272 boundary = NULL;
274 slurp_attr(line->buf, "charset=", &mi->charset);
276 if (boundary) {
277 strbuf_release(boundary);
278 free(boundary);
282 static void handle_content_transfer_encoding(struct mailinfo *mi,
283 const struct strbuf *line)
285 if (strcasestr(line->buf, "base64"))
286 mi->transfer_encoding = TE_BASE64;
287 else if (strcasestr(line->buf, "quoted-printable"))
288 mi->transfer_encoding = TE_QP;
289 else
290 mi->transfer_encoding = TE_DONTCARE;
293 static int is_multipart_boundary(struct mailinfo *mi, const struct strbuf *line)
295 struct strbuf *content_top = *(mi->content_top);
297 return ((content_top->len <= line->len) &&
298 !memcmp(line->buf, content_top->buf, content_top->len));
301 static void cleanup_subject(struct mailinfo *mi, struct strbuf *subject)
303 size_t at = 0;
305 while (at < subject->len) {
306 char *pos;
307 size_t remove;
309 switch (subject->buf[at]) {
310 case 'r': case 'R':
311 if (subject->len <= at + 3)
312 break;
313 if ((subject->buf[at + 1] == 'e' ||
314 subject->buf[at + 1] == 'E') &&
315 subject->buf[at + 2] == ':') {
316 strbuf_remove(subject, at, 3);
317 continue;
319 at++;
320 break;
321 case ' ': case '\t': case ':':
322 strbuf_remove(subject, at, 1);
323 continue;
324 case '[':
325 pos = strchr(subject->buf + at, ']');
326 if (!pos)
327 break;
328 remove = pos - (subject->buf + at) + 1;
329 if (!mi->keep_non_patch_brackets_in_subject ||
330 (7 <= remove &&
331 memmem(subject->buf + at, remove, "PATCH", 5)))
332 strbuf_remove(subject, at, remove);
333 else {
334 at += remove;
336 * If the input had a space after the ], keep
337 * it. We don't bother with finding the end of
338 * the space, since we later normalize it
339 * anyway.
341 if (isspace(subject->buf[at]))
342 at += 1;
344 continue;
346 break;
348 strbuf_trim(subject);
351 static const char * const header[] = {
352 "From", "Subject", "Date",
355 static inline int skip_header(const struct strbuf *line, const char *hdr,
356 const char **outval)
358 const char *val;
359 if (!skip_iprefix(line->buf, hdr, &val) ||
360 *val++ != ':')
361 return 0;
362 while (isspace(*val))
363 val++;
364 *outval = val;
365 return 1;
368 static int is_format_patch_separator(const char *line, int len)
370 static const char SAMPLE[] =
371 "From e6807f3efca28b30decfecb1732a56c7db1137ee Mon Sep 17 00:00:00 2001\n";
372 const char *cp;
374 if (len != strlen(SAMPLE))
375 return 0;
376 if (!skip_prefix(line, "From ", &cp))
377 return 0;
378 if (strspn(cp, "0123456789abcdef") != 40)
379 return 0;
380 cp += 40;
381 return !memcmp(SAMPLE + (cp - line), cp, strlen(SAMPLE) - (cp - line));
384 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
386 const char *in = q_seg->buf;
387 int c;
388 struct strbuf *out = xmalloc(sizeof(struct strbuf));
389 strbuf_init(out, q_seg->len);
391 while ((c = *in++) != 0) {
392 if (c == '=') {
393 int ch, d = *in;
394 if (d == '\n' || !d)
395 break; /* drop trailing newline */
396 ch = hex2chr(in);
397 if (ch >= 0) {
398 strbuf_addch(out, ch);
399 in += 2;
400 continue;
402 /* garbage -- fall through */
404 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
405 c = 0x20;
406 strbuf_addch(out, c);
408 return out;
411 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
413 /* Decode in..ep, possibly in-place to ot */
414 int c, pos = 0, acc = 0;
415 const char *in = b_seg->buf;
416 struct strbuf *out = xmalloc(sizeof(struct strbuf));
417 strbuf_init(out, b_seg->len);
419 while ((c = *in++) != 0) {
420 if (c == '+')
421 c = 62;
422 else if (c == '/')
423 c = 63;
424 else if ('A' <= c && c <= 'Z')
425 c -= 'A';
426 else if ('a' <= c && c <= 'z')
427 c -= 'a' - 26;
428 else if ('0' <= c && c <= '9')
429 c -= '0' - 52;
430 else
431 continue; /* garbage */
432 switch (pos++) {
433 case 0:
434 acc = (c << 2);
435 break;
436 case 1:
437 strbuf_addch(out, (acc | (c >> 4)));
438 acc = (c & 15) << 4;
439 break;
440 case 2:
441 strbuf_addch(out, (acc | (c >> 2)));
442 acc = (c & 3) << 6;
443 break;
444 case 3:
445 strbuf_addch(out, (acc | c));
446 acc = pos = 0;
447 break;
450 return out;
453 static int convert_to_utf8(struct mailinfo *mi,
454 struct strbuf *line, const char *charset)
456 char *out;
457 size_t out_len;
459 if (!mi->metainfo_charset || !charset || !*charset)
460 return 0;
462 if (same_encoding(mi->metainfo_charset, charset))
463 return 0;
464 out = reencode_string_len(line->buf, line->len,
465 mi->metainfo_charset, charset, &out_len);
466 if (!out) {
467 mi->input_error = -1;
468 return error("cannot convert from %s to %s",
469 charset, mi->metainfo_charset);
471 strbuf_attach(line, out, out_len, out_len);
472 return 0;
475 static void decode_header(struct mailinfo *mi, struct strbuf *it)
477 char *in, *ep, *cp;
478 struct strbuf outbuf = STRBUF_INIT, *dec;
479 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
480 int found_error = 1; /* pessimism */
482 in = it->buf;
483 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
484 int encoding;
485 strbuf_reset(&charset_q);
486 strbuf_reset(&piecebuf);
488 if (in != ep) {
490 * We are about to process an encoded-word
491 * that begins at ep, but there is something
492 * before the encoded word.
494 char *scan;
495 for (scan = in; scan < ep; scan++)
496 if (!isspace(*scan))
497 break;
499 if (scan != ep || in == it->buf) {
501 * We should not lose that "something",
502 * unless we have just processed an
503 * encoded-word, and there is only LWS
504 * before the one we are about to process.
506 strbuf_add(&outbuf, in, ep - in);
509 /* E.g.
510 * ep : "=?iso-2022-jp?B?GyR...?= foo"
511 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
513 ep += 2;
515 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
516 goto release_return;
518 if (cp + 3 - it->buf > it->len)
519 goto release_return;
520 strbuf_add(&charset_q, ep, cp - ep);
522 encoding = cp[1];
523 if (!encoding || cp[2] != '?')
524 goto release_return;
525 ep = strstr(cp + 3, "?=");
526 if (!ep)
527 goto release_return;
528 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
529 switch (tolower(encoding)) {
530 default:
531 goto release_return;
532 case 'b':
533 dec = decode_b_segment(&piecebuf);
534 break;
535 case 'q':
536 dec = decode_q_segment(&piecebuf, 1);
537 break;
539 if (convert_to_utf8(mi, dec, charset_q.buf))
540 goto release_return;
542 strbuf_addbuf(&outbuf, dec);
543 strbuf_release(dec);
544 free(dec);
545 in = ep + 2;
547 strbuf_addstr(&outbuf, in);
548 strbuf_reset(it);
549 strbuf_addbuf(it, &outbuf);
550 found_error = 0;
551 release_return:
552 strbuf_release(&outbuf);
553 strbuf_release(&charset_q);
554 strbuf_release(&piecebuf);
556 if (found_error)
557 mi->input_error = -1;
561 * Returns true if "line" contains a header matching "hdr", in which case "val"
562 * will contain the value of the header with any RFC2047 B and Q encoding
563 * unwrapped, and optionally normalize the meta information to utf8.
565 static int parse_header(const struct strbuf *line,
566 const char *hdr,
567 struct mailinfo *mi,
568 struct strbuf *val)
570 const char *val_str;
572 if (!skip_header(line, hdr, &val_str))
573 return 0;
574 strbuf_addstr(val, val_str);
575 decode_header(mi, val);
576 return 1;
579 static int check_header(struct mailinfo *mi,
580 const struct strbuf *line,
581 struct strbuf *hdr_data[], int overwrite)
583 int i, ret = 0;
584 struct strbuf sb = STRBUF_INIT;
586 /* search for the interesting parts */
587 for (i = 0; i < ARRAY_SIZE(header); i++) {
588 if ((!hdr_data[i] || overwrite) &&
589 parse_header(line, header[i], mi, &sb)) {
590 handle_header(&hdr_data[i], &sb);
591 ret = 1;
592 goto check_header_out;
596 /* Content stuff */
597 if (parse_header(line, "Content-Type", mi, &sb)) {
598 handle_content_type(mi, &sb);
599 ret = 1;
600 goto check_header_out;
602 if (parse_header(line, "Content-Transfer-Encoding", mi, &sb)) {
603 handle_content_transfer_encoding(mi, &sb);
604 ret = 1;
605 goto check_header_out;
607 if (parse_header(line, "Message-ID", mi, &sb)) {
608 if (mi->add_message_id)
609 mi->message_id = strbuf_detach(&sb, NULL);
610 ret = 1;
611 goto check_header_out;
614 check_header_out:
615 strbuf_release(&sb);
616 return ret;
620 * Returns 1 if the given line or any line beginning with the given line is an
621 * in-body header (that is, check_header will succeed when passed
622 * mi->s_hdr_data).
624 static int is_inbody_header(const struct mailinfo *mi,
625 const struct strbuf *line)
627 int i;
628 const char *val;
629 for (i = 0; i < ARRAY_SIZE(header); i++)
630 if (!mi->s_hdr_data[i] && skip_header(line, header[i], &val))
631 return 1;
632 return 0;
635 static void decode_transfer_encoding(struct mailinfo *mi, struct strbuf *line)
637 struct strbuf *ret;
639 switch (mi->transfer_encoding) {
640 case TE_QP:
641 ret = decode_q_segment(line, 0);
642 break;
643 case TE_BASE64:
644 ret = decode_b_segment(line);
645 break;
646 case TE_DONTCARE:
647 default:
648 return;
650 strbuf_reset(line);
651 strbuf_addbuf(line, ret);
652 strbuf_release(ret);
653 free(ret);
656 static inline int patchbreak(const struct strbuf *line)
658 size_t i;
660 /* Beginning of a "diff -" header? */
661 if (starts_with(line->buf, "diff -"))
662 return 1;
664 /* CVS "Index: " line? */
665 if (starts_with(line->buf, "Index: "))
666 return 1;
669 * "--- <filename>" starts patches without headers
670 * "---<sp>*" is a manual separator
672 if (line->len < 4)
673 return 0;
675 if (starts_with(line->buf, "---")) {
676 /* space followed by a filename? */
677 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
678 return 1;
679 /* Just whitespace? */
680 for (i = 3; i < line->len; i++) {
681 unsigned char c = line->buf[i];
682 if (c == '\n')
683 return 1;
684 if (!isspace(c))
685 break;
687 return 0;
689 return 0;
692 static int is_scissors_line(const char *line)
694 const char *c;
695 int scissors = 0, gap = 0;
696 const char *first_nonblank = NULL, *last_nonblank = NULL;
697 int visible, perforation = 0, in_perforation = 0;
699 for (c = line; *c; c++) {
700 if (isspace(*c)) {
701 if (in_perforation) {
702 perforation++;
703 gap++;
705 continue;
707 last_nonblank = c;
708 if (!first_nonblank)
709 first_nonblank = c;
710 if (*c == '-') {
711 in_perforation = 1;
712 perforation++;
713 continue;
715 if (starts_with(c, ">8") || starts_with(c, "8<") ||
716 starts_with(c, ">%") || starts_with(c, "%<")) {
717 in_perforation = 1;
718 perforation += 2;
719 scissors += 2;
720 c++;
721 continue;
723 in_perforation = 0;
727 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
728 * Even though there can be arbitrary cruft on the same line
729 * (e.g. "cut here"), in order to avoid misidentification, the
730 * perforation must occupy more than a third of the visible
731 * width of the line, and dashes and scissors must occupy more
732 * than half of the perforation.
735 if (first_nonblank && last_nonblank)
736 visible = last_nonblank - first_nonblank + 1;
737 else
738 visible = 0;
739 return (scissors && 8 <= visible &&
740 visible < perforation * 3 &&
741 gap * 2 < perforation);
744 static void flush_inbody_header_accum(struct mailinfo *mi)
746 if (!mi->inbody_header_accum.len)
747 return;
748 if (!check_header(mi, &mi->inbody_header_accum, mi->s_hdr_data, 0))
749 BUG("inbody_header_accum, if not empty, must always contain a valid in-body header");
750 strbuf_reset(&mi->inbody_header_accum);
753 static int check_inbody_header(struct mailinfo *mi, const struct strbuf *line)
755 if (mi->inbody_header_accum.len &&
756 (line->buf[0] == ' ' || line->buf[0] == '\t')) {
757 if (mi->use_scissors && is_scissors_line(line->buf)) {
759 * This is a scissors line; do not consider this line
760 * as a header continuation line.
762 flush_inbody_header_accum(mi);
763 return 0;
765 strbuf_strip_suffix(&mi->inbody_header_accum, "\n");
766 strbuf_addbuf(&mi->inbody_header_accum, line);
767 return 1;
770 flush_inbody_header_accum(mi);
772 if (starts_with(line->buf, ">From") && isspace(line->buf[5]))
773 return is_format_patch_separator(line->buf + 1, line->len - 1);
774 if (starts_with(line->buf, "[PATCH]") && isspace(line->buf[7])) {
775 int i;
776 for (i = 0; i < ARRAY_SIZE(header); i++)
777 if (!strcmp("Subject", header[i])) {
778 handle_header(&mi->s_hdr_data[i], line);
779 return 1;
781 return 0;
783 if (is_inbody_header(mi, line)) {
784 strbuf_addbuf(&mi->inbody_header_accum, line);
785 return 1;
787 return 0;
790 static int handle_commit_msg(struct mailinfo *mi, struct strbuf *line)
792 assert(!mi->filter_stage);
794 if (mi->header_stage) {
795 if (!line->len || (line->len == 1 && line->buf[0] == '\n')) {
796 if (mi->inbody_header_accum.len) {
797 flush_inbody_header_accum(mi);
798 mi->header_stage = 0;
800 return 0;
804 if (mi->use_inbody_headers && mi->header_stage) {
805 mi->header_stage = check_inbody_header(mi, line);
806 if (mi->header_stage)
807 return 0;
808 } else
809 /* Only trim the first (blank) line of the commit message
810 * when ignoring in-body headers.
812 mi->header_stage = 0;
814 /* normalize the log message to UTF-8. */
815 if (convert_to_utf8(mi, line, mi->charset.buf))
816 return 0; /* mi->input_error already set */
818 if (mi->use_scissors && is_scissors_line(line->buf)) {
819 int i;
821 strbuf_setlen(&mi->log_message, 0);
822 mi->header_stage = 1;
825 * We may have already read "secondary headers"; purge
826 * them to give ourselves a clean restart.
828 for (i = 0; i < ARRAY_SIZE(header); i++) {
829 if (mi->s_hdr_data[i])
830 strbuf_release(mi->s_hdr_data[i]);
831 FREE_AND_NULL(mi->s_hdr_data[i]);
833 return 0;
836 if (patchbreak(line)) {
837 if (mi->message_id)
838 strbuf_addf(&mi->log_message,
839 "Message-ID: %s\n", mi->message_id);
840 return 1;
843 strbuf_addbuf(&mi->log_message, line);
844 return 0;
847 static void handle_patch(struct mailinfo *mi, const struct strbuf *line)
849 fwrite(line->buf, 1, line->len, mi->patchfile);
850 mi->patch_lines++;
853 static void handle_filter(struct mailinfo *mi, struct strbuf *line)
855 switch (mi->filter_stage) {
856 case 0:
857 if (!handle_commit_msg(mi, line))
858 break;
859 mi->filter_stage++;
860 /* fallthrough */
861 case 1:
862 handle_patch(mi, line);
863 break;
867 static int is_rfc2822_header(const struct strbuf *line)
870 * The section that defines the loosest possible
871 * field name is "3.6.8 Optional fields".
873 * optional-field = field-name ":" unstructured CRLF
874 * field-name = 1*ftext
875 * ftext = %d33-57 / %59-126
877 int ch;
878 char *cp = line->buf;
880 /* Count mbox From headers as headers */
881 if (starts_with(cp, "From ") || starts_with(cp, ">From "))
882 return 1;
884 while ((ch = *cp++)) {
885 if (ch == ':')
886 return 1;
887 if ((33 <= ch && ch <= 57) ||
888 (59 <= ch && ch <= 126))
889 continue;
890 break;
892 return 0;
895 static int read_one_header_line(struct strbuf *line, FILE *in)
897 struct strbuf continuation = STRBUF_INIT;
899 /* Get the first part of the line. */
900 if (strbuf_getline_lf(line, in))
901 return 0;
904 * Is it an empty line or not a valid rfc2822 header?
905 * If so, stop here, and return false ("not a header")
907 strbuf_rtrim(line);
908 if (!line->len || !is_rfc2822_header(line)) {
909 /* Re-add the newline */
910 strbuf_addch(line, '\n');
911 return 0;
915 * Now we need to eat all the continuation lines..
916 * Yuck, 2822 header "folding"
918 for (;;) {
919 int peek;
921 peek = fgetc(in);
922 if (peek == EOF)
923 break;
924 ungetc(peek, in);
925 if (peek != ' ' && peek != '\t')
926 break;
927 if (strbuf_getline_lf(&continuation, in))
928 break;
929 continuation.buf[0] = ' ';
930 strbuf_rtrim(&continuation);
931 strbuf_addbuf(line, &continuation);
933 strbuf_release(&continuation);
935 return 1;
938 static int find_boundary(struct mailinfo *mi, struct strbuf *line)
940 while (!strbuf_getline_lf(line, mi->input)) {
941 if (*(mi->content_top) && is_multipart_boundary(mi, line))
942 return 1;
944 return 0;
947 static int handle_boundary(struct mailinfo *mi, struct strbuf *line)
949 struct strbuf newline = STRBUF_INIT;
951 strbuf_addch(&newline, '\n');
952 again:
953 if (line->len >= (*(mi->content_top))->len + 2 &&
954 !memcmp(line->buf + (*(mi->content_top))->len, "--", 2)) {
955 /* we hit an end boundary */
956 /* pop the current boundary off the stack */
957 strbuf_release(*(mi->content_top));
958 FREE_AND_NULL(*(mi->content_top));
960 /* technically won't happen as is_multipart_boundary()
961 will fail first. But just in case..
963 if (--mi->content_top < mi->content) {
964 error("Detected mismatched boundaries, can't recover");
965 mi->input_error = -1;
966 mi->content_top = mi->content;
967 strbuf_release(&newline);
968 return 0;
970 handle_filter(mi, &newline);
971 strbuf_release(&newline);
972 if (mi->input_error)
973 return 0;
975 /* skip to the next boundary */
976 if (!find_boundary(mi, line))
977 return 0;
978 goto again;
981 /* set some defaults */
982 mi->transfer_encoding = TE_DONTCARE;
983 strbuf_reset(&mi->charset);
985 /* slurp in this section's info */
986 while (read_one_header_line(line, mi->input))
987 check_header(mi, line, mi->p_hdr_data, 0);
989 strbuf_release(&newline);
990 /* replenish line */
991 if (strbuf_getline_lf(line, mi->input))
992 return 0;
993 strbuf_addch(line, '\n');
994 return 1;
997 static void handle_filter_flowed(struct mailinfo *mi, struct strbuf *line,
998 struct strbuf *prev)
1000 size_t len = line->len;
1001 const char *rest;
1003 if (!mi->format_flowed) {
1004 if (len >= 2 &&
1005 line->buf[len - 2] == '\r' &&
1006 line->buf[len - 1] == '\n') {
1007 mi->have_quoted_cr = 1;
1008 if (mi->quoted_cr == quoted_cr_strip) {
1009 strbuf_setlen(line, len - 2);
1010 strbuf_addch(line, '\n');
1011 len--;
1014 handle_filter(mi, line);
1015 return;
1018 if (line->buf[len - 1] == '\n') {
1019 len--;
1020 if (len && line->buf[len - 1] == '\r')
1021 len--;
1024 /* Keep signature separator as-is. */
1025 if (skip_prefix(line->buf, "-- ", &rest) && rest - line->buf == len) {
1026 if (prev->len) {
1027 handle_filter(mi, prev);
1028 strbuf_reset(prev);
1030 handle_filter(mi, line);
1031 return;
1034 /* Unstuff space-stuffed line. */
1035 if (len && line->buf[0] == ' ') {
1036 strbuf_remove(line, 0, 1);
1037 len--;
1040 /* Save flowed line for later, but without the soft line break. */
1041 if (len && line->buf[len - 1] == ' ') {
1042 strbuf_add(prev, line->buf, len - !!mi->delsp);
1043 return;
1046 /* Prepend any previous partial lines */
1047 strbuf_insert(line, 0, prev->buf, prev->len);
1048 strbuf_reset(prev);
1050 handle_filter(mi, line);
1053 static void summarize_quoted_cr(struct mailinfo *mi)
1055 if (mi->have_quoted_cr &&
1056 mi->quoted_cr == quoted_cr_warn)
1057 warning(_("quoted CRLF detected"));
1060 static void handle_body(struct mailinfo *mi, struct strbuf *line)
1062 struct strbuf prev = STRBUF_INIT;
1064 /* Skip up to the first boundary */
1065 if (*(mi->content_top)) {
1066 if (!find_boundary(mi, line))
1067 goto handle_body_out;
1070 do {
1071 /* process any boundary lines */
1072 if (*(mi->content_top) && is_multipart_boundary(mi, line)) {
1073 /* flush any leftover */
1074 if (prev.len) {
1075 handle_filter(mi, &prev);
1076 strbuf_reset(&prev);
1078 summarize_quoted_cr(mi);
1079 mi->have_quoted_cr = 0;
1080 if (!handle_boundary(mi, line))
1081 goto handle_body_out;
1084 /* Unwrap transfer encoding */
1085 decode_transfer_encoding(mi, line);
1087 switch (mi->transfer_encoding) {
1088 case TE_BASE64:
1089 case TE_QP:
1091 struct strbuf **lines, **it, *sb;
1093 /* Prepend any previous partial lines */
1094 strbuf_insert(line, 0, prev.buf, prev.len);
1095 strbuf_reset(&prev);
1098 * This is a decoded line that may contain
1099 * multiple new lines. Pass only one chunk
1100 * at a time to handle_filter()
1102 lines = strbuf_split(line, '\n');
1103 for (it = lines; (sb = *it); it++) {
1104 if (!*(it + 1)) /* The last line */
1105 if (sb->buf[sb->len - 1] != '\n') {
1106 /* Partial line, save it for later. */
1107 strbuf_addbuf(&prev, sb);
1108 break;
1110 handle_filter_flowed(mi, sb, &prev);
1113 * The partial chunk is saved in "prev" and will be
1114 * appended by the next iteration of read_line_with_nul().
1116 strbuf_list_free(lines);
1117 break;
1119 default:
1120 handle_filter_flowed(mi, line, &prev);
1123 if (mi->input_error)
1124 break;
1125 } while (!strbuf_getwholeline(line, mi->input, '\n'));
1127 if (prev.len)
1128 handle_filter(mi, &prev);
1129 summarize_quoted_cr(mi);
1131 flush_inbody_header_accum(mi);
1133 handle_body_out:
1134 strbuf_release(&prev);
1137 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
1139 const char *sp = data->buf;
1140 while (1) {
1141 char *ep = strchr(sp, '\n');
1142 int len;
1143 if (!ep)
1144 len = strlen(sp);
1145 else
1146 len = ep - sp;
1147 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
1148 if (!ep)
1149 break;
1150 sp = ep + 1;
1154 static void handle_info(struct mailinfo *mi)
1156 struct strbuf *hdr;
1157 int i;
1159 for (i = 0; i < ARRAY_SIZE(header); i++) {
1160 /* only print inbody headers if we output a patch file */
1161 if (mi->patch_lines && mi->s_hdr_data[i])
1162 hdr = mi->s_hdr_data[i];
1163 else if (mi->p_hdr_data[i])
1164 hdr = mi->p_hdr_data[i];
1165 else
1166 continue;
1168 if (memchr(hdr->buf, '\0', hdr->len)) {
1169 error("a NUL byte in '%s' is not allowed.", header[i]);
1170 mi->input_error = -1;
1173 if (!strcmp(header[i], "Subject")) {
1174 if (!mi->keep_subject) {
1175 cleanup_subject(mi, hdr);
1176 cleanup_space(hdr);
1178 output_header_lines(mi->output, "Subject", hdr);
1179 } else if (!strcmp(header[i], "From")) {
1180 cleanup_space(hdr);
1181 handle_from(mi, hdr);
1182 fprintf(mi->output, "Author: %s\n", mi->name.buf);
1183 fprintf(mi->output, "Email: %s\n", mi->email.buf);
1184 } else {
1185 cleanup_space(hdr);
1186 fprintf(mi->output, "%s: %s\n", header[i], hdr->buf);
1189 fprintf(mi->output, "\n");
1192 int mailinfo(struct mailinfo *mi, const char *msg, const char *patch)
1194 FILE *cmitmsg;
1195 int peek;
1196 struct strbuf line = STRBUF_INIT;
1198 cmitmsg = fopen(msg, "w");
1199 if (!cmitmsg) {
1200 perror(msg);
1201 return -1;
1203 mi->patchfile = fopen(patch, "w");
1204 if (!mi->patchfile) {
1205 perror(patch);
1206 fclose(cmitmsg);
1207 return -1;
1210 mi->p_hdr_data = xcalloc(ARRAY_SIZE(header), sizeof(*(mi->p_hdr_data)));
1211 mi->s_hdr_data = xcalloc(ARRAY_SIZE(header), sizeof(*(mi->s_hdr_data)));
1213 do {
1214 peek = fgetc(mi->input);
1215 if (peek == EOF) {
1216 fclose(cmitmsg);
1217 return error("empty patch: '%s'", patch);
1219 } while (isspace(peek));
1220 ungetc(peek, mi->input);
1222 /* process the email header */
1223 while (read_one_header_line(&line, mi->input))
1224 check_header(mi, &line, mi->p_hdr_data, 1);
1226 handle_body(mi, &line);
1227 fwrite(mi->log_message.buf, 1, mi->log_message.len, cmitmsg);
1228 fclose(cmitmsg);
1229 fclose(mi->patchfile);
1231 handle_info(mi);
1232 strbuf_release(&line);
1233 return mi->input_error;
1236 int mailinfo_parse_quoted_cr_action(const char *actionstr, int *action)
1238 if (!strcmp(actionstr, "nowarn"))
1239 *action = quoted_cr_nowarn;
1240 else if (!strcmp(actionstr, "warn"))
1241 *action = quoted_cr_warn;
1242 else if (!strcmp(actionstr, "strip"))
1243 *action = quoted_cr_strip;
1244 else
1245 return -1;
1246 return 0;
1249 static int git_mailinfo_config(const char *var, const char *value,
1250 const struct config_context *ctx, void *mi_)
1252 struct mailinfo *mi = mi_;
1254 if (!starts_with(var, "mailinfo."))
1255 return git_default_config(var, value, ctx, NULL);
1256 if (!strcmp(var, "mailinfo.scissors")) {
1257 mi->use_scissors = git_config_bool(var, value);
1258 return 0;
1260 if (!strcmp(var, "mailinfo.quotedcr")) {
1261 if (!value)
1262 return config_error_nonbool(var);
1263 if (mailinfo_parse_quoted_cr_action(value, &mi->quoted_cr) != 0)
1264 return error(_("bad action '%s' for '%s'"), value, var);
1265 return 0;
1267 /* perhaps others here */
1268 return 0;
1271 void setup_mailinfo(struct mailinfo *mi)
1273 memset(mi, 0, sizeof(*mi));
1274 strbuf_init(&mi->name, 0);
1275 strbuf_init(&mi->email, 0);
1276 strbuf_init(&mi->charset, 0);
1277 strbuf_init(&mi->log_message, 0);
1278 strbuf_init(&mi->inbody_header_accum, 0);
1279 mi->quoted_cr = quoted_cr_warn;
1280 mi->header_stage = 1;
1281 mi->use_inbody_headers = 1;
1282 mi->content_top = mi->content;
1283 git_config(git_mailinfo_config, mi);
1286 void clear_mailinfo(struct mailinfo *mi)
1288 strbuf_release(&mi->name);
1289 strbuf_release(&mi->email);
1290 strbuf_release(&mi->charset);
1291 strbuf_release(&mi->inbody_header_accum);
1292 free(mi->message_id);
1294 for (size_t i = 0; i < ARRAY_SIZE(header); i++) {
1295 if (!mi->p_hdr_data[i])
1296 continue;
1297 strbuf_release(mi->p_hdr_data[i]);
1298 free(mi->p_hdr_data[i]);
1300 free(mi->p_hdr_data);
1302 for (size_t i = 0; i < ARRAY_SIZE(header); i++) {
1303 if (!mi->s_hdr_data[i])
1304 continue;
1305 strbuf_release(mi->s_hdr_data[i]);
1306 free(mi->s_hdr_data[i]);
1308 free(mi->s_hdr_data);
1310 while (mi->content < mi->content_top) {
1311 free(*(mi->content_top));
1312 mi->content_top--;
1315 strbuf_release(&mi->log_message);