6 static void cleanup_space(struct strbuf *sb)
9 for (pos = 0; pos < sb->len; pos++) {
10 if (isspace(sb->buf[pos])) {
12 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
13 strbuf_remove(sb, pos + 1, cnt);
18 static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
20 struct strbuf *src = name;
21 if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
22 strchr(name->buf, '<') || strchr(name->buf, '>'))
27 strbuf_addbuf(out, src);
30 static void parse_bogus_from(struct mailinfo *mi, const struct strbuf *line)
32 /* John Doe <johndoe> */
35 /* This is fallback, so do not bother if we already have an
41 bra = strchr(line->buf, '<');
44 ket = strchr(bra, '>');
48 strbuf_reset(&mi->email);
49 strbuf_add(&mi->email, bra + 1, ket - bra - 1);
51 strbuf_reset(&mi->name);
52 strbuf_add(&mi->name, line->buf, bra - line->buf);
53 strbuf_trim(&mi->name);
54 get_sane_name(&mi->name, &mi->name, &mi->email);
57 static void handle_from(struct mailinfo *mi, const struct strbuf *from)
63 strbuf_init(&f, from->len);
64 strbuf_addbuf(&f, from);
66 at = strchr(f.buf, '@');
68 parse_bogus_from(mi, from);
73 * If we already have one email, don't take any confusing lines
75 if (mi->email.len && strchr(at + 1, '@')) {
80 /* Pick up the string around '@', possibly delimited with <>
81 * pair; that is the email part.
93 el = strcspn(at, " \n\t\r\v\f>");
94 strbuf_reset(&mi->email);
95 strbuf_add(&mi->email, at, el);
96 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
98 /* The remainder is name. It could be
100 * - "John Doe <john.doe@xz>" (a), or
101 * - "john.doe@xz (John Doe)" (b), or
102 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
104 * but we have removed the email part, so
106 * - remove extra spaces which could stay after email (case 'c'), and
107 * - trim from both ends, possibly removing the () pair at the end
108 * (cases 'a' and 'b').
112 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
113 strbuf_remove(&f, 0, 1);
114 strbuf_setlen(&f, f.len - 1);
117 get_sane_name(&mi->name, &f, &mi->email);
121 static void handle_header(struct strbuf **out, const struct strbuf *line)
124 *out = xmalloc(sizeof(struct strbuf));
125 strbuf_init(*out, line->len);
129 strbuf_addbuf(*out, line);
132 /* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
133 * to have enough heuristics to grok MIME encoded patches often found
134 * on our mailing lists. For example, we do not even treat header lines
135 * case insensitively.
138 static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
140 const char *ends, *ap = strcasestr(line, name);
143 strbuf_setlen(attr, 0);
153 sz = strcspn(ap, ends);
154 strbuf_add(attr, ap, sz);
158 static void handle_content_type(struct mailinfo *mi, struct strbuf *line)
160 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
161 strbuf_init(boundary, line->len);
163 if (slurp_attr(line->buf, "boundary=", boundary)) {
164 strbuf_insert(boundary, 0, "--", 2);
165 if (++mi->content_top >= &mi->content[MAX_BOUNDARIES]) {
166 fprintf(stderr, "Too many boundaries to handle\n");
169 *(mi->content_top) = boundary;
172 slurp_attr(line->buf, "charset=", &mi->charset);
175 strbuf_release(boundary);
180 static void handle_message_id(struct mailinfo *mi, const struct strbuf *line)
182 if (mi->add_message_id)
183 mi->message_id = strdup(line->buf);
186 static void handle_content_transfer_encoding(struct mailinfo *mi,
187 const struct strbuf *line)
189 if (strcasestr(line->buf, "base64"))
190 mi->transfer_encoding = TE_BASE64;
191 else if (strcasestr(line->buf, "quoted-printable"))
192 mi->transfer_encoding = TE_QP;
194 mi->transfer_encoding = TE_DONTCARE;
197 static int is_multipart_boundary(struct mailinfo *mi, const struct strbuf *line)
199 struct strbuf *content_top = *(mi->content_top);
201 return ((content_top->len <= line->len) &&
202 !memcmp(line->buf, content_top->buf, content_top->len));
205 static void cleanup_subject(struct mailinfo *mi, struct strbuf *subject)
209 while (at < subject->len) {
213 switch (subject->buf[at]) {
215 if (subject->len <= at + 3)
217 if ((subject->buf[at + 1] == 'e' ||
218 subject->buf[at + 1] == 'E') &&
219 subject->buf[at + 2] == ':') {
220 strbuf_remove(subject, at, 3);
225 case ' ': case '\t': case ':':
226 strbuf_remove(subject, at, 1);
229 pos = strchr(subject->buf + at, ']');
232 remove = pos - subject->buf + at + 1;
233 if (!mi->keep_non_patch_brackets_in_subject ||
235 memmem(subject->buf + at, remove, "PATCH", 5)))
236 strbuf_remove(subject, at, remove);
240 * If the input had a space after the ], keep
241 * it. We don't bother with finding the end of
242 * the space, since we later normalize it
245 if (isspace(subject->buf[at]))
252 strbuf_trim(subject);
255 #define MAX_HDR_PARSED 10
256 static const char *header[MAX_HDR_PARSED] = {
257 "From","Subject","Date",
260 static inline int cmp_header(const struct strbuf *line, const char *hdr)
262 int len = strlen(hdr);
263 return !strncasecmp(line->buf, hdr, len) && line->len > len &&
264 line->buf[len] == ':' && isspace(line->buf[len + 1]);
267 static int is_format_patch_separator(const char *line, int len)
269 static const char SAMPLE[] =
270 "From e6807f3efca28b30decfecb1732a56c7db1137ee Mon Sep 17 00:00:00 2001\n";
273 if (len != strlen(SAMPLE))
275 if (!skip_prefix(line, "From ", &cp))
277 if (strspn(cp, "0123456789abcdef") != 40)
280 return !memcmp(SAMPLE + (cp - line), cp, strlen(SAMPLE) - (cp - line));
283 static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
285 const char *in = q_seg->buf;
287 struct strbuf *out = xmalloc(sizeof(struct strbuf));
288 strbuf_init(out, q_seg->len);
290 while ((c = *in++) != 0) {
294 break; /* drop trailing newline */
295 strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
298 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
300 strbuf_addch(out, c);
305 static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
307 /* Decode in..ep, possibly in-place to ot */
308 int c, pos = 0, acc = 0;
309 const char *in = b_seg->buf;
310 struct strbuf *out = xmalloc(sizeof(struct strbuf));
311 strbuf_init(out, b_seg->len);
313 while ((c = *in++) != 0) {
318 else if ('A' <= c && c <= 'Z')
320 else if ('a' <= c && c <= 'z')
322 else if ('0' <= c && c <= '9')
325 continue; /* garbage */
331 strbuf_addch(out, (acc | (c >> 4)));
335 strbuf_addch(out, (acc | (c >> 2)));
339 strbuf_addch(out, (acc | c));
347 static void convert_to_utf8(struct mailinfo *mi,
348 struct strbuf *line, const char *charset)
352 if (!mi->metainfo_charset || !charset || !*charset)
355 if (same_encoding(mi->metainfo_charset, charset))
357 out = reencode_string(line->buf, mi->metainfo_charset, charset);
359 die("cannot convert from %s to %s",
360 charset, mi->metainfo_charset);
361 strbuf_attach(line, out, strlen(out), strlen(out));
364 static void decode_header(struct mailinfo *mi, struct strbuf *it)
367 struct strbuf outbuf = STRBUF_INIT, *dec;
368 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
371 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
373 strbuf_reset(&charset_q);
374 strbuf_reset(&piecebuf);
378 * We are about to process an encoded-word
379 * that begins at ep, but there is something
380 * before the encoded word.
383 for (scan = in; scan < ep; scan++)
387 if (scan != ep || in == it->buf) {
389 * We should not lose that "something",
390 * unless we have just processed an
391 * encoded-word, and there is only LWS
392 * before the one we are about to process.
394 strbuf_add(&outbuf, in, ep - in);
398 * ep : "=?iso-2022-jp?B?GyR...?= foo"
399 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
403 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
406 if (cp + 3 - it->buf > it->len)
408 strbuf_add(&charset_q, ep, cp - ep);
411 if (!encoding || cp[2] != '?')
413 ep = strstr(cp + 3, "?=");
416 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
417 switch (tolower(encoding)) {
421 dec = decode_b_segment(&piecebuf);
424 dec = decode_q_segment(&piecebuf, 1);
427 convert_to_utf8(mi, dec, charset_q.buf);
429 strbuf_addbuf(&outbuf, dec);
434 strbuf_addstr(&outbuf, in);
436 strbuf_addbuf(it, &outbuf);
438 strbuf_release(&outbuf);
439 strbuf_release(&charset_q);
440 strbuf_release(&piecebuf);
443 static int check_header(struct mailinfo *mi,
444 const struct strbuf *line,
445 struct strbuf *hdr_data[], int overwrite)
448 struct strbuf sb = STRBUF_INIT;
450 /* search for the interesting parts */
451 for (i = 0; header[i]; i++) {
452 int len = strlen(header[i]);
453 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
454 /* Unwrap inline B and Q encoding, and optionally
455 * normalize the meta information to utf8.
457 strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
458 decode_header(mi, &sb);
459 handle_header(&hdr_data[i], &sb);
461 goto check_header_out;
466 if (cmp_header(line, "Content-Type")) {
467 len = strlen("Content-Type: ");
468 strbuf_add(&sb, line->buf + len, line->len - len);
469 decode_header(mi, &sb);
470 strbuf_insert(&sb, 0, "Content-Type: ", len);
471 handle_content_type(mi, &sb);
473 goto check_header_out;
475 if (cmp_header(line, "Content-Transfer-Encoding")) {
476 len = strlen("Content-Transfer-Encoding: ");
477 strbuf_add(&sb, line->buf + len, line->len - len);
478 decode_header(mi, &sb);
479 handle_content_transfer_encoding(mi, &sb);
481 goto check_header_out;
483 if (cmp_header(line, "Message-Id")) {
484 len = strlen("Message-Id: ");
485 strbuf_add(&sb, line->buf + len, line->len - len);
486 decode_header(mi, &sb);
487 handle_message_id(mi, &sb);
489 goto check_header_out;
492 /* for inbody stuff */
493 if (starts_with(line->buf, ">From") && isspace(line->buf[5])) {
494 ret = is_format_patch_separator(line->buf + 1, line->len - 1);
495 goto check_header_out;
497 if (starts_with(line->buf, "[PATCH]") && isspace(line->buf[7])) {
498 for (i = 0; header[i]; i++) {
499 if (!strcmp("Subject", header[i])) {
500 handle_header(&hdr_data[i], line);
502 goto check_header_out;
512 static void decode_transfer_encoding(struct mailinfo *mi, struct strbuf *line)
516 switch (mi->transfer_encoding) {
518 ret = decode_q_segment(line, 0);
521 ret = decode_b_segment(line);
528 strbuf_addbuf(line, ret);
533 static inline int patchbreak(const struct strbuf *line)
537 /* Beginning of a "diff -" header? */
538 if (starts_with(line->buf, "diff -"))
541 /* CVS "Index: " line? */
542 if (starts_with(line->buf, "Index: "))
546 * "--- <filename>" starts patches without headers
547 * "---<sp>*" is a manual separator
552 if (starts_with(line->buf, "---")) {
553 /* space followed by a filename? */
554 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
556 /* Just whitespace? */
557 for (i = 3; i < line->len; i++) {
558 unsigned char c = line->buf[i];
569 static int is_scissors_line(const struct strbuf *line)
571 size_t i, len = line->len;
572 int scissors = 0, gap = 0;
573 int first_nonblank = -1;
574 int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
575 const char *buf = line->buf;
577 for (i = 0; i < len; i++) {
578 if (isspace(buf[i])) {
579 if (in_perforation) {
586 if (first_nonblank < 0)
594 (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
595 !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
606 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
607 * Even though there can be arbitrary cruft on the same line
608 * (e.g. "cut here"), in order to avoid misidentification, the
609 * perforation must occupy more than a third of the visible
610 * width of the line, and dashes and scissors must occupy more
611 * than half of the perforation.
614 visible = last_nonblank - first_nonblank + 1;
615 return (scissors && 8 <= visible &&
616 visible < perforation * 3 &&
617 gap * 2 < perforation);
620 static int handle_commit_msg(struct mailinfo *mi, struct strbuf *line)
622 assert(!mi->filter_stage);
624 if (mi->header_stage) {
625 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
629 if (mi->use_inbody_headers && mi->header_stage) {
630 mi->header_stage = check_header(mi, line, mi->s_hdr_data, 0);
631 if (mi->header_stage)
634 /* Only trim the first (blank) line of the commit message
635 * when ignoring in-body headers.
637 mi->header_stage = 0;
639 /* normalize the log message to UTF-8. */
640 convert_to_utf8(mi, line, mi->charset.buf);
642 if (mi->use_scissors && is_scissors_line(line)) {
645 strbuf_setlen(&mi->log_message, 0);
646 mi->header_stage = 1;
649 * We may have already read "secondary headers"; purge
650 * them to give ourselves a clean restart.
652 for (i = 0; header[i]; i++) {
653 if (mi->s_hdr_data[i])
654 strbuf_release(mi->s_hdr_data[i]);
655 mi->s_hdr_data[i] = NULL;
660 if (patchbreak(line)) {
662 strbuf_addf(&mi->log_message,
663 "Message-Id: %s\n", mi->message_id);
667 strbuf_addbuf(&mi->log_message, line);
671 static void handle_patch(struct mailinfo *mi, const struct strbuf *line)
673 fwrite(line->buf, 1, line->len, mi->patchfile);
677 static void handle_filter(struct mailinfo *mi, struct strbuf *line)
679 switch (mi->filter_stage) {
681 if (!handle_commit_msg(mi, line))
685 handle_patch(mi, line);
690 static int is_rfc2822_header(const struct strbuf *line)
693 * The section that defines the loosest possible
694 * field name is "3.6.8 Optional fields".
696 * optional-field = field-name ":" unstructured CRLF
697 * field-name = 1*ftext
698 * ftext = %d33-57 / %59-126
701 char *cp = line->buf;
703 /* Count mbox From headers as headers */
704 if (starts_with(cp, "From ") || starts_with(cp, ">From "))
707 while ((ch = *cp++)) {
710 if ((33 <= ch && ch <= 57) ||
711 (59 <= ch && ch <= 126))
718 static int read_one_header_line(struct strbuf *line, FILE *in)
720 struct strbuf continuation = STRBUF_INIT;
722 /* Get the first part of the line. */
723 if (strbuf_getline(line, in, '\n'))
727 * Is it an empty line or not a valid rfc2822 header?
728 * If so, stop here, and return false ("not a header")
731 if (!line->len || !is_rfc2822_header(line)) {
732 /* Re-add the newline */
733 strbuf_addch(line, '\n');
738 * Now we need to eat all the continuation lines..
739 * Yuck, 2822 header "folding"
744 peek = fgetc(in); ungetc(peek, in);
745 if (peek != ' ' && peek != '\t')
747 if (strbuf_getline(&continuation, in, '\n'))
749 continuation.buf[0] = ' ';
750 strbuf_rtrim(&continuation);
751 strbuf_addbuf(line, &continuation);
753 strbuf_release(&continuation);
758 static int find_boundary(struct mailinfo *mi, struct strbuf *line)
760 while (!strbuf_getline(line, mi->input, '\n')) {
761 if (*(mi->content_top) && is_multipart_boundary(mi, line))
767 static int handle_boundary(struct mailinfo *mi, struct strbuf *line)
769 struct strbuf newline = STRBUF_INIT;
771 strbuf_addch(&newline, '\n');
773 if (line->len >= (*(mi->content_top))->len + 2 &&
774 !memcmp(line->buf + (*(mi->content_top))->len, "--", 2)) {
775 /* we hit an end boundary */
776 /* pop the current boundary off the stack */
777 strbuf_release(*(mi->content_top));
778 free(*(mi->content_top));
779 *(mi->content_top) = NULL;
781 /* technically won't happen as is_multipart_boundary()
782 will fail first. But just in case..
784 if (--mi->content_top < mi->content) {
785 fprintf(stderr, "Detected mismatched boundaries, "
789 handle_filter(mi, &newline);
790 strbuf_release(&newline);
792 /* skip to the next boundary */
793 if (!find_boundary(mi, line))
798 /* set some defaults */
799 mi->transfer_encoding = TE_DONTCARE;
800 strbuf_reset(&mi->charset);
802 /* slurp in this section's info */
803 while (read_one_header_line(line, mi->input))
804 check_header(mi, line, mi->p_hdr_data, 0);
806 strbuf_release(&newline);
808 if (strbuf_getline(line, mi->input, '\n'))
810 strbuf_addch(line, '\n');
814 static void handle_body(struct mailinfo *mi, struct strbuf *line)
816 struct strbuf prev = STRBUF_INIT;
818 /* Skip up to the first boundary */
819 if (*(mi->content_top)) {
820 if (!find_boundary(mi, line))
821 goto handle_body_out;
825 /* process any boundary lines */
826 if (*(mi->content_top) && is_multipart_boundary(mi, line)) {
827 /* flush any leftover */
829 handle_filter(mi, &prev);
832 if (!handle_boundary(mi, line))
833 goto handle_body_out;
836 /* Unwrap transfer encoding */
837 decode_transfer_encoding(mi, line);
839 switch (mi->transfer_encoding) {
843 struct strbuf **lines, **it, *sb;
845 /* Prepend any previous partial lines */
846 strbuf_insert(line, 0, prev.buf, prev.len);
850 * This is a decoded line that may contain
851 * multiple new lines. Pass only one chunk
852 * at a time to handle_filter()
854 lines = strbuf_split(line, '\n');
855 for (it = lines; (sb = *it); it++) {
856 if (*(it + 1) == NULL) /* The last line */
857 if (sb->buf[sb->len - 1] != '\n') {
858 /* Partial line, save it for later. */
859 strbuf_addbuf(&prev, sb);
862 handle_filter(mi, sb);
865 * The partial chunk is saved in "prev" and will be
866 * appended by the next iteration of read_line_with_nul().
868 strbuf_list_free(lines);
872 handle_filter(mi, line);
875 } while (!strbuf_getwholeline(line, mi->input, '\n'));
878 strbuf_release(&prev);
881 static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
883 const char *sp = data->buf;
885 char *ep = strchr(sp, '\n');
891 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
898 static void handle_info(struct mailinfo *mi)
903 for (i = 0; header[i]; i++) {
904 /* only print inbody headers if we output a patch file */
905 if (mi->patch_lines && mi->s_hdr_data[i])
906 hdr = mi->s_hdr_data[i];
907 else if (mi->p_hdr_data[i])
908 hdr = mi->p_hdr_data[i];
912 if (!strcmp(header[i], "Subject")) {
913 if (!mi->keep_subject) {
914 cleanup_subject(mi, hdr);
917 output_header_lines(mi->output, "Subject", hdr);
918 } else if (!strcmp(header[i], "From")) {
920 handle_from(mi, hdr);
921 fprintf(mi->output, "Author: %s\n", mi->name.buf);
922 fprintf(mi->output, "Email: %s\n", mi->email.buf);
925 fprintf(mi->output, "%s: %s\n", header[i], hdr->buf);
928 fprintf(mi->output, "\n");
931 int mailinfo(struct mailinfo *mi, const char *msg, const char *patch)
935 struct strbuf line = STRBUF_INIT;
937 cmitmsg = fopen(msg, "w");
942 mi->patchfile = fopen(patch, "w");
943 if (!mi->patchfile) {
949 mi->p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*(mi->p_hdr_data)));
950 mi->s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*(mi->s_hdr_data)));
953 peek = fgetc(mi->input);
954 } while (isspace(peek));
955 ungetc(peek, mi->input);
957 /* process the email header */
958 while (read_one_header_line(&line, mi->input))
959 check_header(mi, &line, mi->p_hdr_data, 1);
961 handle_body(mi, &line);
962 fwrite(mi->log_message.buf, 1, mi->log_message.len, cmitmsg);
964 fclose(mi->patchfile);
967 strbuf_release(&line);
971 static int git_mailinfo_config(const char *var, const char *value, void *mi_)
973 struct mailinfo *mi = mi_;
975 if (!starts_with(var, "mailinfo."))
976 return git_default_config(var, value, NULL);
977 if (!strcmp(var, "mailinfo.scissors")) {
978 mi->use_scissors = git_config_bool(var, value);
981 /* perhaps others here */
985 void setup_mailinfo(struct mailinfo *mi)
987 memset(mi, 0, sizeof(*mi));
988 strbuf_init(&mi->name, 0);
989 strbuf_init(&mi->email, 0);
990 strbuf_init(&mi->charset, 0);
991 strbuf_init(&mi->log_message, 0);
992 mi->header_stage = 1;
993 mi->use_inbody_headers = 1;
994 mi->content_top = mi->content;
995 git_config(git_mailinfo_config, &mi);
998 void clear_mailinfo(struct mailinfo *mi)
1002 strbuf_release(&mi->name);
1003 strbuf_release(&mi->email);
1004 strbuf_release(&mi->charset);
1005 free(mi->message_id);
1007 for (i = 0; mi->p_hdr_data[i]; i++)
1008 strbuf_release(mi->p_hdr_data[i]);
1009 free(mi->p_hdr_data);
1010 for (i = 0; mi->s_hdr_data[i]; i++)
1011 strbuf_release(mi->s_hdr_data[i]);
1012 free(mi->s_hdr_data);
1014 while (mi->content < mi->content_top) {
1015 free(*(mi->content_top));
1019 strbuf_release(&mi->log_message);