mailinfo: simplify parsing of header values
[git/raj.git] / mailinfo.c
blobee8d05e239fca514910439774f29d88ffabc9d72
1 #include "cache.h"
2 #include "config.h"
3 #include "utf8.h"
4 #include "strbuf.h"
5 #include "mailinfo.h"
7 static void cleanup_space(struct strbuf *sb)
9 size_t pos, cnt;
10 for (pos = 0; pos < sb->len; pos++) {
11 if (isspace(sb->buf[pos])) {
12 sb->buf[pos] = ' ';
13 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
14 strbuf_remove(sb, pos + 1, cnt);
19 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
21 struct strbuf *src = name;
22 if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
23 strchr(name->buf, '<') || strchr(name->buf, '>'))
24 src = email;
25 else if (name == out)
26 return;
27 strbuf_reset(out);
28 strbuf_addbuf(out, src);
31 static void parse_bogus_from(struct mailinfo *mi, const struct strbuf *line)
33 /* John Doe <johndoe> */
35 char *bra, *ket;
36 /* This is fallback, so do not bother if we already have an
37 * e-mail address.
39 if (mi->email.len)
40 return;
42 bra = strchr(line->buf, '<');
43 if (!bra)
44 return;
45 ket = strchr(bra, '>');
46 if (!ket)
47 return;
49 strbuf_reset(&mi->email);
50 strbuf_add(&mi->email, bra + 1, ket - bra - 1);
52 strbuf_reset(&mi->name);
53 strbuf_add(&mi->name, line->buf, bra - line->buf);
54 strbuf_trim(&mi->name);
55 get_sane_name(&mi->name, &mi->name, &mi->email);
58 static const char *unquote_comment(struct strbuf *outbuf, const char *in)
60 int c;
61 int take_next_literally = 0;
63 strbuf_addch(outbuf, '(');
65 while ((c = *in++) != 0) {
66 if (take_next_literally == 1) {
67 take_next_literally = 0;
68 } else {
69 switch (c) {
70 case '\\':
71 take_next_literally = 1;
72 continue;
73 case '(':
74 in = unquote_comment(outbuf, in);
75 continue;
76 case ')':
77 strbuf_addch(outbuf, ')');
78 return in;
82 strbuf_addch(outbuf, c);
85 return in;
88 static const char *unquote_quoted_string(struct strbuf *outbuf, const char *in)
90 int c;
91 int take_next_literally = 0;
93 while ((c = *in++) != 0) {
94 if (take_next_literally == 1) {
95 take_next_literally = 0;
96 } else {
97 switch (c) {
98 case '\\':
99 take_next_literally = 1;
100 continue;
101 case '"':
102 return in;
106 strbuf_addch(outbuf, c);
109 return in;
112 static void unquote_quoted_pair(struct strbuf *line)
114 struct strbuf outbuf;
115 const char *in = line->buf;
116 int c;
118 strbuf_init(&outbuf, line->len);
120 while ((c = *in++) != 0) {
121 switch (c) {
122 case '"':
123 in = unquote_quoted_string(&outbuf, in);
124 continue;
125 case '(':
126 in = unquote_comment(&outbuf, in);
127 continue;
130 strbuf_addch(&outbuf, c);
133 strbuf_swap(&outbuf, line);
134 strbuf_release(&outbuf);
138 static void handle_from(struct mailinfo *mi, const struct strbuf *from)
140 char *at;
141 size_t el;
142 struct strbuf f;
144 strbuf_init(&f, from->len);
145 strbuf_addbuf(&f, from);
147 unquote_quoted_pair(&f);
149 at = strchr(f.buf, '@');
150 if (!at) {
151 parse_bogus_from(mi, from);
152 goto out;
156 * If we already have one email, don't take any confusing lines
158 if (mi->email.len && strchr(at + 1, '@'))
159 goto out;
161 /* Pick up the string around '@', possibly delimited with <>
162 * pair; that is the email part.
164 while (at > f.buf) {
165 char c = at[-1];
166 if (isspace(c))
167 break;
168 if (c == '<') {
169 at[-1] = ' ';
170 break;
172 at--;
174 el = strcspn(at, " \n\t\r\v\f>");
175 strbuf_reset(&mi->email);
176 strbuf_add(&mi->email, at, el);
177 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
179 /* The remainder is name. It could be
181 * - "John Doe <john.doe@xz>" (a), or
182 * - "john.doe@xz (John Doe)" (b), or
183 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
185 * but we have removed the email part, so
187 * - remove extra spaces which could stay after email (case 'c'), and
188 * - trim from both ends, possibly removing the () pair at the end
189 * (cases 'a' and 'b').
191 cleanup_space(&f);
192 strbuf_trim(&f);
193 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
194 strbuf_remove(&f, 0, 1);
195 strbuf_setlen(&f, f.len - 1);
198 get_sane_name(&mi->name, &f, &mi->email);
199 out:
200 strbuf_release(&f);
203 static void handle_header(struct strbuf **out, const struct strbuf *line)
205 if (!*out) {
206 *out = xmalloc(sizeof(struct strbuf));
207 strbuf_init(*out, line->len);
208 } else
209 strbuf_reset(*out);
211 strbuf_addbuf(*out, line);
214 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
215 * to have enough heuristics to grok MIME encoded patches often found
216 * on our mailing lists. For example, we do not even treat header lines
217 * case insensitively.
220 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
222 const char *ends, *ap = strcasestr(line, name);
223 size_t sz;
225 strbuf_setlen(attr, 0);
226 if (!ap)
227 return 0;
228 ap += strlen(name);
229 if (*ap == '"') {
230 ap++;
231 ends = "\"";
233 else
234 ends = "; \t";
235 sz = strcspn(ap, ends);
236 strbuf_add(attr, ap, sz);
237 return 1;
240 static int has_attr_value(const char *line, const char *name, const char *value)
242 struct strbuf sb = STRBUF_INIT;
243 int rc = slurp_attr(line, name, &sb) && !strcasecmp(sb.buf, value);
244 strbuf_release(&sb);
245 return rc;
248 static void handle_content_type(struct mailinfo *mi, struct strbuf *line)
250 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
251 strbuf_init(boundary, line->len);
253 mi->format_flowed = has_attr_value(line->buf, "format=", "flowed");
254 mi->delsp = has_attr_value(line->buf, "delsp=", "yes");
256 if (slurp_attr(line->buf, "boundary=", boundary)) {
257 strbuf_insertstr(boundary, 0, "--");
258 if (++mi->content_top >= &mi->content[MAX_BOUNDARIES]) {
259 error("Too many boundaries to handle");
260 mi->input_error = -1;
261 mi->content_top = &mi->content[MAX_BOUNDARIES] - 1;
262 return;
264 *(mi->content_top) = boundary;
265 boundary = NULL;
267 slurp_attr(line->buf, "charset=", &mi->charset);
269 if (boundary) {
270 strbuf_release(boundary);
271 free(boundary);
275 static void handle_content_transfer_encoding(struct mailinfo *mi,
276 const struct strbuf *line)
278 if (strcasestr(line->buf, "base64"))
279 mi->transfer_encoding = TE_BASE64;
280 else if (strcasestr(line->buf, "quoted-printable"))
281 mi->transfer_encoding = TE_QP;
282 else
283 mi->transfer_encoding = TE_DONTCARE;
286 static int is_multipart_boundary(struct mailinfo *mi, const struct strbuf *line)
288 struct strbuf *content_top = *(mi->content_top);
290 return ((content_top->len <= line->len) &&
291 !memcmp(line->buf, content_top->buf, content_top->len));
294 static void cleanup_subject(struct mailinfo *mi, struct strbuf *subject)
296 size_t at = 0;
298 while (at < subject->len) {
299 char *pos;
300 size_t remove;
302 switch (subject->buf[at]) {
303 case 'r': case 'R':
304 if (subject->len <= at + 3)
305 break;
306 if ((subject->buf[at + 1] == 'e' ||
307 subject->buf[at + 1] == 'E') &&
308 subject->buf[at + 2] == ':') {
309 strbuf_remove(subject, at, 3);
310 continue;
312 at++;
313 break;
314 case ' ': case '\t': case ':':
315 strbuf_remove(subject, at, 1);
316 continue;
317 case '[':
318 pos = strchr(subject->buf + at, ']');
319 if (!pos)
320 break;
321 remove = pos - subject->buf + at + 1;
322 if (!mi->keep_non_patch_brackets_in_subject ||
323 (7 <= remove &&
324 memmem(subject->buf + at, remove, "PATCH", 5)))
325 strbuf_remove(subject, at, remove);
326 else {
327 at += remove;
329 * If the input had a space after the ], keep
330 * it. We don't bother with finding the end of
331 * the space, since we later normalize it
332 * anyway.
334 if (isspace(subject->buf[at]))
335 at += 1;
337 continue;
339 break;
341 strbuf_trim(subject);
344 #define MAX_HDR_PARSED 10
345 static const char *header[MAX_HDR_PARSED] = {
346 "From","Subject","Date",
349 static inline int skip_header(const struct strbuf *line, const char *hdr,
350 const char **outval)
352 const char *val;
353 if (!skip_iprefix(line->buf, hdr, &val) ||
354 *val++ != ':' ||
355 !isspace(*val++))
356 return 0;
357 *outval = val;
358 return 1;
361 static int is_format_patch_separator(const char *line, int len)
363 static const char SAMPLE[] =
364 "From e6807f3efca28b30decfecb1732a56c7db1137ee Mon Sep 17 00:00:00 2001\n";
365 const char *cp;
367 if (len != strlen(SAMPLE))
368 return 0;
369 if (!skip_prefix(line, "From ", &cp))
370 return 0;
371 if (strspn(cp, "0123456789abcdef") != 40)
372 return 0;
373 cp += 40;
374 return !memcmp(SAMPLE + (cp - line), cp, strlen(SAMPLE) - (cp - line));
377 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
379 const char *in = q_seg->buf;
380 int c;
381 struct strbuf *out = xmalloc(sizeof(struct strbuf));
382 strbuf_init(out, q_seg->len);
384 while ((c = *in++) != 0) {
385 if (c == '=') {
386 int ch, d = *in;
387 if (d == '\n' || !d)
388 break; /* drop trailing newline */
389 ch = hex2chr(in);
390 if (ch >= 0) {
391 strbuf_addch(out, ch);
392 in += 2;
393 continue;
395 /* garbage -- fall through */
397 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
398 c = 0x20;
399 strbuf_addch(out, c);
401 return out;
404 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
406 /* Decode in..ep, possibly in-place to ot */
407 int c, pos = 0, acc = 0;
408 const char *in = b_seg->buf;
409 struct strbuf *out = xmalloc(sizeof(struct strbuf));
410 strbuf_init(out, b_seg->len);
412 while ((c = *in++) != 0) {
413 if (c == '+')
414 c = 62;
415 else if (c == '/')
416 c = 63;
417 else if ('A' <= c && c <= 'Z')
418 c -= 'A';
419 else if ('a' <= c && c <= 'z')
420 c -= 'a' - 26;
421 else if ('0' <= c && c <= '9')
422 c -= '0' - 52;
423 else
424 continue; /* garbage */
425 switch (pos++) {
426 case 0:
427 acc = (c << 2);
428 break;
429 case 1:
430 strbuf_addch(out, (acc | (c >> 4)));
431 acc = (c & 15) << 4;
432 break;
433 case 2:
434 strbuf_addch(out, (acc | (c >> 2)));
435 acc = (c & 3) << 6;
436 break;
437 case 3:
438 strbuf_addch(out, (acc | c));
439 acc = pos = 0;
440 break;
443 return out;
446 static int convert_to_utf8(struct mailinfo *mi,
447 struct strbuf *line, const char *charset)
449 char *out;
451 if (!mi->metainfo_charset || !charset || !*charset)
452 return 0;
454 if (same_encoding(mi->metainfo_charset, charset))
455 return 0;
456 out = reencode_string(line->buf, mi->metainfo_charset, charset);
457 if (!out) {
458 mi->input_error = -1;
459 return error("cannot convert from %s to %s",
460 charset, mi->metainfo_charset);
462 strbuf_attach(line, out, strlen(out), strlen(out));
463 return 0;
466 static void decode_header(struct mailinfo *mi, struct strbuf *it)
468 char *in, *ep, *cp;
469 struct strbuf outbuf = STRBUF_INIT, *dec;
470 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
471 int found_error = 1; /* pessimism */
473 in = it->buf;
474 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
475 int encoding;
476 strbuf_reset(&charset_q);
477 strbuf_reset(&piecebuf);
479 if (in != ep) {
481 * We are about to process an encoded-word
482 * that begins at ep, but there is something
483 * before the encoded word.
485 char *scan;
486 for (scan = in; scan < ep; scan++)
487 if (!isspace(*scan))
488 break;
490 if (scan != ep || in == it->buf) {
492 * We should not lose that "something",
493 * unless we have just processed an
494 * encoded-word, and there is only LWS
495 * before the one we are about to process.
497 strbuf_add(&outbuf, in, ep - in);
500 /* E.g.
501 * ep : "=?iso-2022-jp?B?GyR...?= foo"
502 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
504 ep += 2;
506 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
507 goto release_return;
509 if (cp + 3 - it->buf > it->len)
510 goto release_return;
511 strbuf_add(&charset_q, ep, cp - ep);
513 encoding = cp[1];
514 if (!encoding || cp[2] != '?')
515 goto release_return;
516 ep = strstr(cp + 3, "?=");
517 if (!ep)
518 goto release_return;
519 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
520 switch (tolower(encoding)) {
521 default:
522 goto release_return;
523 case 'b':
524 dec = decode_b_segment(&piecebuf);
525 break;
526 case 'q':
527 dec = decode_q_segment(&piecebuf, 1);
528 break;
530 if (convert_to_utf8(mi, dec, charset_q.buf))
531 goto release_return;
533 strbuf_addbuf(&outbuf, dec);
534 strbuf_release(dec);
535 free(dec);
536 in = ep + 2;
538 strbuf_addstr(&outbuf, in);
539 strbuf_reset(it);
540 strbuf_addbuf(it, &outbuf);
541 found_error = 0;
542 release_return:
543 strbuf_release(&outbuf);
544 strbuf_release(&charset_q);
545 strbuf_release(&piecebuf);
547 if (found_error)
548 mi->input_error = -1;
551 static int check_header(struct mailinfo *mi,
552 const struct strbuf *line,
553 struct strbuf *hdr_data[], int overwrite)
555 int i, ret = 0;
556 struct strbuf sb = STRBUF_INIT;
557 const char *val;
559 /* search for the interesting parts */
560 for (i = 0; header[i]; i++) {
561 if ((!hdr_data[i] || overwrite) &&
562 skip_header(line, header[i], &val)) {
563 /* Unwrap inline B and Q encoding, and optionally
564 * normalize the meta information to utf8.
566 strbuf_addstr(&sb, val);
567 decode_header(mi, &sb);
568 handle_header(&hdr_data[i], &sb);
569 ret = 1;
570 goto check_header_out;
574 /* Content stuff */
575 if (skip_header(line, "Content-Type", &val)) {
576 strbuf_addstr(&sb, val);
577 decode_header(mi, &sb);
578 handle_content_type(mi, &sb);
579 ret = 1;
580 goto check_header_out;
582 if (skip_header(line, "Content-Transfer-Encoding", &val)) {
583 strbuf_addstr(&sb, val);
584 decode_header(mi, &sb);
585 handle_content_transfer_encoding(mi, &sb);
586 ret = 1;
587 goto check_header_out;
589 if (skip_header(line, "Message-Id", &val)) {
590 strbuf_addstr(&sb, val);
591 decode_header(mi, &sb);
592 if (mi->add_message_id)
593 mi->message_id = strbuf_detach(&sb, NULL);
594 ret = 1;
595 goto check_header_out;
598 check_header_out:
599 strbuf_release(&sb);
600 return ret;
604 * Returns 1 if the given line or any line beginning with the given line is an
605 * in-body header (that is, check_header will succeed when passed
606 * mi->s_hdr_data).
608 static int is_inbody_header(const struct mailinfo *mi,
609 const struct strbuf *line)
611 int i;
612 const char *val;
613 for (i = 0; header[i]; i++)
614 if (!mi->s_hdr_data[i] && skip_header(line, header[i], &val))
615 return 1;
616 return 0;
619 static void decode_transfer_encoding(struct mailinfo *mi, struct strbuf *line)
621 struct strbuf *ret;
623 switch (mi->transfer_encoding) {
624 case TE_QP:
625 ret = decode_q_segment(line, 0);
626 break;
627 case TE_BASE64:
628 ret = decode_b_segment(line);
629 break;
630 case TE_DONTCARE:
631 default:
632 return;
634 strbuf_reset(line);
635 strbuf_addbuf(line, ret);
636 strbuf_release(ret);
637 free(ret);
640 static inline int patchbreak(const struct strbuf *line)
642 size_t i;
644 /* Beginning of a "diff -" header? */
645 if (starts_with(line->buf, "diff -"))
646 return 1;
648 /* CVS "Index: " line? */
649 if (starts_with(line->buf, "Index: "))
650 return 1;
653 * "--- <filename>" starts patches without headers
654 * "---<sp>*" is a manual separator
656 if (line->len < 4)
657 return 0;
659 if (starts_with(line->buf, "---")) {
660 /* space followed by a filename? */
661 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
662 return 1;
663 /* Just whitespace? */
664 for (i = 3; i < line->len; i++) {
665 unsigned char c = line->buf[i];
666 if (c == '\n')
667 return 1;
668 if (!isspace(c))
669 break;
671 return 0;
673 return 0;
676 static int is_scissors_line(const char *line)
678 const char *c;
679 int scissors = 0, gap = 0;
680 const char *first_nonblank = NULL, *last_nonblank = NULL;
681 int visible, perforation = 0, in_perforation = 0;
683 for (c = line; *c; c++) {
684 if (isspace(*c)) {
685 if (in_perforation) {
686 perforation++;
687 gap++;
689 continue;
691 last_nonblank = c;
692 if (first_nonblank == NULL)
693 first_nonblank = c;
694 if (*c == '-') {
695 in_perforation = 1;
696 perforation++;
697 continue;
699 if ((!memcmp(c, ">8", 2) || !memcmp(c, "8<", 2) ||
700 !memcmp(c, ">%", 2) || !memcmp(c, "%<", 2))) {
701 in_perforation = 1;
702 perforation += 2;
703 scissors += 2;
704 c++;
705 continue;
707 in_perforation = 0;
711 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
712 * Even though there can be arbitrary cruft on the same line
713 * (e.g. "cut here"), in order to avoid misidentification, the
714 * perforation must occupy more than a third of the visible
715 * width of the line, and dashes and scissors must occupy more
716 * than half of the perforation.
719 if (first_nonblank && last_nonblank)
720 visible = last_nonblank - first_nonblank + 1;
721 else
722 visible = 0;
723 return (scissors && 8 <= visible &&
724 visible < perforation * 3 &&
725 gap * 2 < perforation);
728 static void flush_inbody_header_accum(struct mailinfo *mi)
730 if (!mi->inbody_header_accum.len)
731 return;
732 if (!check_header(mi, &mi->inbody_header_accum, mi->s_hdr_data, 0))
733 BUG("inbody_header_accum, if not empty, must always contain a valid in-body header");
734 strbuf_reset(&mi->inbody_header_accum);
737 static int check_inbody_header(struct mailinfo *mi, const struct strbuf *line)
739 if (mi->inbody_header_accum.len &&
740 (line->buf[0] == ' ' || line->buf[0] == '\t')) {
741 if (mi->use_scissors && is_scissors_line(line->buf)) {
743 * This is a scissors line; do not consider this line
744 * as a header continuation line.
746 flush_inbody_header_accum(mi);
747 return 0;
749 strbuf_strip_suffix(&mi->inbody_header_accum, "\n");
750 strbuf_addbuf(&mi->inbody_header_accum, line);
751 return 1;
754 flush_inbody_header_accum(mi);
756 if (starts_with(line->buf, ">From") && isspace(line->buf[5]))
757 return is_format_patch_separator(line->buf + 1, line->len - 1);
758 if (starts_with(line->buf, "[PATCH]") && isspace(line->buf[7])) {
759 int i;
760 for (i = 0; header[i]; i++)
761 if (!strcmp("Subject", header[i])) {
762 handle_header(&mi->s_hdr_data[i], line);
763 return 1;
765 return 0;
767 if (is_inbody_header(mi, line)) {
768 strbuf_addbuf(&mi->inbody_header_accum, line);
769 return 1;
771 return 0;
774 static int handle_commit_msg(struct mailinfo *mi, struct strbuf *line)
776 assert(!mi->filter_stage);
778 if (mi->header_stage) {
779 if (!line->len || (line->len == 1 && line->buf[0] == '\n')) {
780 if (mi->inbody_header_accum.len) {
781 flush_inbody_header_accum(mi);
782 mi->header_stage = 0;
784 return 0;
788 if (mi->use_inbody_headers && mi->header_stage) {
789 mi->header_stage = check_inbody_header(mi, line);
790 if (mi->header_stage)
791 return 0;
792 } else
793 /* Only trim the first (blank) line of the commit message
794 * when ignoring in-body headers.
796 mi->header_stage = 0;
798 /* normalize the log message to UTF-8. */
799 if (convert_to_utf8(mi, line, mi->charset.buf))
800 return 0; /* mi->input_error already set */
802 if (mi->use_scissors && is_scissors_line(line->buf)) {
803 int i;
805 strbuf_setlen(&mi->log_message, 0);
806 mi->header_stage = 1;
809 * We may have already read "secondary headers"; purge
810 * them to give ourselves a clean restart.
812 for (i = 0; header[i]; i++) {
813 if (mi->s_hdr_data[i])
814 strbuf_release(mi->s_hdr_data[i]);
815 mi->s_hdr_data[i] = NULL;
817 return 0;
820 if (patchbreak(line)) {
821 if (mi->message_id)
822 strbuf_addf(&mi->log_message,
823 "Message-Id: %s\n", mi->message_id);
824 return 1;
827 strbuf_addbuf(&mi->log_message, line);
828 return 0;
831 static void handle_patch(struct mailinfo *mi, const struct strbuf *line)
833 fwrite(line->buf, 1, line->len, mi->patchfile);
834 mi->patch_lines++;
837 static void handle_filter(struct mailinfo *mi, struct strbuf *line)
839 switch (mi->filter_stage) {
840 case 0:
841 if (!handle_commit_msg(mi, line))
842 break;
843 mi->filter_stage++;
844 /* fallthrough */
845 case 1:
846 handle_patch(mi, line);
847 break;
851 static int is_rfc2822_header(const struct strbuf *line)
854 * The section that defines the loosest possible
855 * field name is "3.6.8 Optional fields".
857 * optional-field = field-name ":" unstructured CRLF
858 * field-name = 1*ftext
859 * ftext = %d33-57 / %59-126
861 int ch;
862 char *cp = line->buf;
864 /* Count mbox From headers as headers */
865 if (starts_with(cp, "From ") || starts_with(cp, ">From "))
866 return 1;
868 while ((ch = *cp++)) {
869 if (ch == ':')
870 return 1;
871 if ((33 <= ch && ch <= 57) ||
872 (59 <= ch && ch <= 126))
873 continue;
874 break;
876 return 0;
879 static int read_one_header_line(struct strbuf *line, FILE *in)
881 struct strbuf continuation = STRBUF_INIT;
883 /* Get the first part of the line. */
884 if (strbuf_getline_lf(line, in))
885 return 0;
888 * Is it an empty line or not a valid rfc2822 header?
889 * If so, stop here, and return false ("not a header")
891 strbuf_rtrim(line);
892 if (!line->len || !is_rfc2822_header(line)) {
893 /* Re-add the newline */
894 strbuf_addch(line, '\n');
895 return 0;
899 * Now we need to eat all the continuation lines..
900 * Yuck, 2822 header "folding"
902 for (;;) {
903 int peek;
905 peek = fgetc(in);
906 if (peek == EOF)
907 break;
908 ungetc(peek, in);
909 if (peek != ' ' && peek != '\t')
910 break;
911 if (strbuf_getline_lf(&continuation, in))
912 break;
913 continuation.buf[0] = ' ';
914 strbuf_rtrim(&continuation);
915 strbuf_addbuf(line, &continuation);
917 strbuf_release(&continuation);
919 return 1;
922 static int find_boundary(struct mailinfo *mi, struct strbuf *line)
924 while (!strbuf_getline_lf(line, mi->input)) {
925 if (*(mi->content_top) && is_multipart_boundary(mi, line))
926 return 1;
928 return 0;
931 static int handle_boundary(struct mailinfo *mi, struct strbuf *line)
933 struct strbuf newline = STRBUF_INIT;
935 strbuf_addch(&newline, '\n');
936 again:
937 if (line->len >= (*(mi->content_top))->len + 2 &&
938 !memcmp(line->buf + (*(mi->content_top))->len, "--", 2)) {
939 /* we hit an end boundary */
940 /* pop the current boundary off the stack */
941 strbuf_release(*(mi->content_top));
942 FREE_AND_NULL(*(mi->content_top));
944 /* technically won't happen as is_multipart_boundary()
945 will fail first. But just in case..
947 if (--mi->content_top < mi->content) {
948 error("Detected mismatched boundaries, can't recover");
949 mi->input_error = -1;
950 mi->content_top = mi->content;
951 strbuf_release(&newline);
952 return 0;
954 handle_filter(mi, &newline);
955 strbuf_release(&newline);
956 if (mi->input_error)
957 return 0;
959 /* skip to the next boundary */
960 if (!find_boundary(mi, line))
961 return 0;
962 goto again;
965 /* set some defaults */
966 mi->transfer_encoding = TE_DONTCARE;
967 strbuf_reset(&mi->charset);
969 /* slurp in this section's info */
970 while (read_one_header_line(line, mi->input))
971 check_header(mi, line, mi->p_hdr_data, 0);
973 strbuf_release(&newline);
974 /* replenish line */
975 if (strbuf_getline_lf(line, mi->input))
976 return 0;
977 strbuf_addch(line, '\n');
978 return 1;
981 static void handle_filter_flowed(struct mailinfo *mi, struct strbuf *line,
982 struct strbuf *prev)
984 size_t len = line->len;
985 const char *rest;
987 if (!mi->format_flowed) {
988 handle_filter(mi, line);
989 return;
992 if (line->buf[len - 1] == '\n') {
993 len--;
994 if (len && line->buf[len - 1] == '\r')
995 len--;
998 /* Keep signature separator as-is. */
999 if (skip_prefix(line->buf, "-- ", &rest) && rest - line->buf == len) {
1000 if (prev->len) {
1001 handle_filter(mi, prev);
1002 strbuf_reset(prev);
1004 handle_filter(mi, line);
1005 return;
1008 /* Unstuff space-stuffed line. */
1009 if (len && line->buf[0] == ' ') {
1010 strbuf_remove(line, 0, 1);
1011 len--;
1014 /* Save flowed line for later, but without the soft line break. */
1015 if (len && line->buf[len - 1] == ' ') {
1016 strbuf_add(prev, line->buf, len - !!mi->delsp);
1017 return;
1020 /* Prepend any previous partial lines */
1021 strbuf_insert(line, 0, prev->buf, prev->len);
1022 strbuf_reset(prev);
1024 handle_filter(mi, line);
1027 static void handle_body(struct mailinfo *mi, struct strbuf *line)
1029 struct strbuf prev = STRBUF_INIT;
1031 /* Skip up to the first boundary */
1032 if (*(mi->content_top)) {
1033 if (!find_boundary(mi, line))
1034 goto handle_body_out;
1037 do {
1038 /* process any boundary lines */
1039 if (*(mi->content_top) && is_multipart_boundary(mi, line)) {
1040 /* flush any leftover */
1041 if (prev.len) {
1042 handle_filter(mi, &prev);
1043 strbuf_reset(&prev);
1045 if (!handle_boundary(mi, line))
1046 goto handle_body_out;
1049 /* Unwrap transfer encoding */
1050 decode_transfer_encoding(mi, line);
1052 switch (mi->transfer_encoding) {
1053 case TE_BASE64:
1054 case TE_QP:
1056 struct strbuf **lines, **it, *sb;
1058 /* Prepend any previous partial lines */
1059 strbuf_insert(line, 0, prev.buf, prev.len);
1060 strbuf_reset(&prev);
1063 * This is a decoded line that may contain
1064 * multiple new lines. Pass only one chunk
1065 * at a time to handle_filter()
1067 lines = strbuf_split(line, '\n');
1068 for (it = lines; (sb = *it); it++) {
1069 if (*(it + 1) == NULL) /* The last line */
1070 if (sb->buf[sb->len - 1] != '\n') {
1071 /* Partial line, save it for later. */
1072 strbuf_addbuf(&prev, sb);
1073 break;
1075 handle_filter_flowed(mi, sb, &prev);
1078 * The partial chunk is saved in "prev" and will be
1079 * appended by the next iteration of read_line_with_nul().
1081 strbuf_list_free(lines);
1082 break;
1084 default:
1085 handle_filter_flowed(mi, line, &prev);
1088 if (mi->input_error)
1089 break;
1090 } while (!strbuf_getwholeline(line, mi->input, '\n'));
1092 if (prev.len)
1093 handle_filter(mi, &prev);
1095 flush_inbody_header_accum(mi);
1097 handle_body_out:
1098 strbuf_release(&prev);
1101 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
1103 const char *sp = data->buf;
1104 while (1) {
1105 char *ep = strchr(sp, '\n');
1106 int len;
1107 if (!ep)
1108 len = strlen(sp);
1109 else
1110 len = ep - sp;
1111 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
1112 if (!ep)
1113 break;
1114 sp = ep + 1;
1118 static void handle_info(struct mailinfo *mi)
1120 struct strbuf *hdr;
1121 int i;
1123 for (i = 0; header[i]; i++) {
1124 /* only print inbody headers if we output a patch file */
1125 if (mi->patch_lines && mi->s_hdr_data[i])
1126 hdr = mi->s_hdr_data[i];
1127 else if (mi->p_hdr_data[i])
1128 hdr = mi->p_hdr_data[i];
1129 else
1130 continue;
1132 if (!strcmp(header[i], "Subject")) {
1133 if (!mi->keep_subject) {
1134 cleanup_subject(mi, hdr);
1135 cleanup_space(hdr);
1137 output_header_lines(mi->output, "Subject", hdr);
1138 } else if (!strcmp(header[i], "From")) {
1139 cleanup_space(hdr);
1140 handle_from(mi, hdr);
1141 fprintf(mi->output, "Author: %s\n", mi->name.buf);
1142 fprintf(mi->output, "Email: %s\n", mi->email.buf);
1143 } else {
1144 cleanup_space(hdr);
1145 fprintf(mi->output, "%s: %s\n", header[i], hdr->buf);
1148 fprintf(mi->output, "\n");
1151 int mailinfo(struct mailinfo *mi, const char *msg, const char *patch)
1153 FILE *cmitmsg;
1154 int peek;
1155 struct strbuf line = STRBUF_INIT;
1157 cmitmsg = fopen(msg, "w");
1158 if (!cmitmsg) {
1159 perror(msg);
1160 return -1;
1162 mi->patchfile = fopen(patch, "w");
1163 if (!mi->patchfile) {
1164 perror(patch);
1165 fclose(cmitmsg);
1166 return -1;
1169 mi->p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*(mi->p_hdr_data)));
1170 mi->s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*(mi->s_hdr_data)));
1172 do {
1173 peek = fgetc(mi->input);
1174 if (peek == EOF) {
1175 fclose(cmitmsg);
1176 return error("empty patch: '%s'", patch);
1178 } while (isspace(peek));
1179 ungetc(peek, mi->input);
1181 /* process the email header */
1182 while (read_one_header_line(&line, mi->input))
1183 check_header(mi, &line, mi->p_hdr_data, 1);
1185 handle_body(mi, &line);
1186 fwrite(mi->log_message.buf, 1, mi->log_message.len, cmitmsg);
1187 fclose(cmitmsg);
1188 fclose(mi->patchfile);
1190 handle_info(mi);
1191 strbuf_release(&line);
1192 return mi->input_error;
1195 static int git_mailinfo_config(const char *var, const char *value, void *mi_)
1197 struct mailinfo *mi = mi_;
1199 if (!starts_with(var, "mailinfo."))
1200 return git_default_config(var, value, NULL);
1201 if (!strcmp(var, "mailinfo.scissors")) {
1202 mi->use_scissors = git_config_bool(var, value);
1203 return 0;
1205 /* perhaps others here */
1206 return 0;
1209 void setup_mailinfo(struct mailinfo *mi)
1211 memset(mi, 0, sizeof(*mi));
1212 strbuf_init(&mi->name, 0);
1213 strbuf_init(&mi->email, 0);
1214 strbuf_init(&mi->charset, 0);
1215 strbuf_init(&mi->log_message, 0);
1216 strbuf_init(&mi->inbody_header_accum, 0);
1217 mi->header_stage = 1;
1218 mi->use_inbody_headers = 1;
1219 mi->content_top = mi->content;
1220 git_config(git_mailinfo_config, mi);
1223 void clear_mailinfo(struct mailinfo *mi)
1225 int i;
1227 strbuf_release(&mi->name);
1228 strbuf_release(&mi->email);
1229 strbuf_release(&mi->charset);
1230 strbuf_release(&mi->inbody_header_accum);
1231 free(mi->message_id);
1233 if (mi->p_hdr_data)
1234 for (i = 0; mi->p_hdr_data[i]; i++)
1235 strbuf_release(mi->p_hdr_data[i]);
1236 free(mi->p_hdr_data);
1237 if (mi->s_hdr_data)
1238 for (i = 0; mi->s_hdr_data[i]; i++)
1239 strbuf_release(mi->s_hdr_data[i]);
1240 free(mi->s_hdr_data);
1242 while (mi->content < mi->content_top) {
1243 free(*(mi->content_top));
1244 mi->content_top--;
1247 strbuf_release(&mi->log_message);