e2979e0c7661ebb938b6cd14a870bef023c5fdd5
1/*
2 * Another stupid program, this one parsing the headers of an
3 * email to figure out authorship and subject
4 */
5#include "cache.h"
6#include "builtin.h"
7#include "utf8.h"
8#include "strbuf.h"
9
10static FILE *cmitmsg, *patchfile;
11
12static const char *metainfo_charset;
13
14struct mailinfo {
15 FILE *input;
16 FILE *output;
17
18 struct strbuf name;
19 struct strbuf email;
20 int keep_subject;
21 int keep_non_patch_brackets_in_subject;
22};
23static char *message_id;
24
25static enum {
26 TE_DONTCARE, TE_QP, TE_BASE64
27} transfer_encoding;
28
29static struct strbuf charset = STRBUF_INIT;
30static int patch_lines;
31static struct strbuf **p_hdr_data, **s_hdr_data;
32static int use_scissors;
33static int add_message_id;
34static int use_inbody_headers = 1;
35
36#define MAX_BOUNDARIES 5
37
38static void cleanup_space(struct strbuf *sb)
39{
40 size_t pos, cnt;
41 for (pos = 0; pos < sb->len; pos++) {
42 if (isspace(sb->buf[pos])) {
43 sb->buf[pos] = ' ';
44 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
45 strbuf_remove(sb, pos + 1, cnt);
46 }
47 }
48}
49
50static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
51{
52 struct strbuf *src = name;
53 if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
54 strchr(name->buf, '<') || strchr(name->buf, '>'))
55 src = email;
56 else if (name == out)
57 return;
58 strbuf_reset(out);
59 strbuf_addbuf(out, src);
60}
61
62static void parse_bogus_from(struct mailinfo *mi, const struct strbuf *line)
63{
64 /* John Doe <johndoe> */
65
66 char *bra, *ket;
67 /* This is fallback, so do not bother if we already have an
68 * e-mail address.
69 */
70 if (mi->email.len)
71 return;
72
73 bra = strchr(line->buf, '<');
74 if (!bra)
75 return;
76 ket = strchr(bra, '>');
77 if (!ket)
78 return;
79
80 strbuf_reset(&mi->email);
81 strbuf_add(&mi->email, bra + 1, ket - bra - 1);
82
83 strbuf_reset(&mi->name);
84 strbuf_add(&mi->name, line->buf, bra - line->buf);
85 strbuf_trim(&mi->name);
86 get_sane_name(&mi->name, &mi->name, &mi->email);
87}
88
89static void handle_from(struct mailinfo *mi, const struct strbuf *from)
90{
91 char *at;
92 size_t el;
93 struct strbuf f;
94
95 strbuf_init(&f, from->len);
96 strbuf_addbuf(&f, from);
97
98 at = strchr(f.buf, '@');
99 if (!at) {
100 parse_bogus_from(mi, from);
101 return;
102 }
103
104 /*
105 * If we already have one email, don't take any confusing lines
106 */
107 if (mi->email.len && strchr(at + 1, '@')) {
108 strbuf_release(&f);
109 return;
110 }
111
112 /* Pick up the string around '@', possibly delimited with <>
113 * pair; that is the email part.
114 */
115 while (at > f.buf) {
116 char c = at[-1];
117 if (isspace(c))
118 break;
119 if (c == '<') {
120 at[-1] = ' ';
121 break;
122 }
123 at--;
124 }
125 el = strcspn(at, " \n\t\r\v\f>");
126 strbuf_reset(&mi->email);
127 strbuf_add(&mi->email, at, el);
128 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
129
130 /* The remainder is name. It could be
131 *
132 * - "John Doe <john.doe@xz>" (a), or
133 * - "john.doe@xz (John Doe)" (b), or
134 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
135 *
136 * but we have removed the email part, so
137 *
138 * - remove extra spaces which could stay after email (case 'c'), and
139 * - trim from both ends, possibly removing the () pair at the end
140 * (cases 'a' and 'b').
141 */
142 cleanup_space(&f);
143 strbuf_trim(&f);
144 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
145 strbuf_remove(&f, 0, 1);
146 strbuf_setlen(&f, f.len - 1);
147 }
148
149 get_sane_name(&mi->name, &f, &mi->email);
150 strbuf_release(&f);
151}
152
153static void handle_header(struct strbuf **out, const struct strbuf *line)
154{
155 if (!*out) {
156 *out = xmalloc(sizeof(struct strbuf));
157 strbuf_init(*out, line->len);
158 } else
159 strbuf_reset(*out);
160
161 strbuf_addbuf(*out, line);
162}
163
164/* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
165 * to have enough heuristics to grok MIME encoded patches often found
166 * on our mailing lists. For example, we do not even treat header lines
167 * case insensitively.
168 */
169
170static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
171{
172 const char *ends, *ap = strcasestr(line, name);
173 size_t sz;
174
175 strbuf_setlen(attr, 0);
176 if (!ap)
177 return 0;
178 ap += strlen(name);
179 if (*ap == '"') {
180 ap++;
181 ends = "\"";
182 }
183 else
184 ends = "; \t";
185 sz = strcspn(ap, ends);
186 strbuf_add(attr, ap, sz);
187 return 1;
188}
189
190static struct strbuf *content[MAX_BOUNDARIES];
191
192static struct strbuf **content_top = content;
193
194static void handle_content_type(struct strbuf *line)
195{
196 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
197 strbuf_init(boundary, line->len);
198
199 if (slurp_attr(line->buf, "boundary=", boundary)) {
200 strbuf_insert(boundary, 0, "--", 2);
201 if (++content_top >= &content[MAX_BOUNDARIES]) {
202 fprintf(stderr, "Too many boundaries to handle\n");
203 exit(1);
204 }
205 *content_top = boundary;
206 boundary = NULL;
207 }
208 slurp_attr(line->buf, "charset=", &charset);
209
210 if (boundary) {
211 strbuf_release(boundary);
212 free(boundary);
213 }
214}
215
216static void handle_message_id(const struct strbuf *line)
217{
218 if (add_message_id)
219 message_id = strdup(line->buf);
220}
221
222static void handle_content_transfer_encoding(const struct strbuf *line)
223{
224 if (strcasestr(line->buf, "base64"))
225 transfer_encoding = TE_BASE64;
226 else if (strcasestr(line->buf, "quoted-printable"))
227 transfer_encoding = TE_QP;
228 else
229 transfer_encoding = TE_DONTCARE;
230}
231
232static int is_multipart_boundary(const struct strbuf *line)
233{
234 return (((*content_top)->len <= line->len) &&
235 !memcmp(line->buf, (*content_top)->buf, (*content_top)->len));
236}
237
238static void cleanup_subject(struct mailinfo *mi, struct strbuf *subject)
239{
240 size_t at = 0;
241
242 while (at < subject->len) {
243 char *pos;
244 size_t remove;
245
246 switch (subject->buf[at]) {
247 case 'r': case 'R':
248 if (subject->len <= at + 3)
249 break;
250 if ((subject->buf[at + 1] == 'e' ||
251 subject->buf[at + 1] == 'E') &&
252 subject->buf[at + 2] == ':') {
253 strbuf_remove(subject, at, 3);
254 continue;
255 }
256 at++;
257 break;
258 case ' ': case '\t': case ':':
259 strbuf_remove(subject, at, 1);
260 continue;
261 case '[':
262 pos = strchr(subject->buf + at, ']');
263 if (!pos)
264 break;
265 remove = pos - subject->buf + at + 1;
266 if (!mi->keep_non_patch_brackets_in_subject ||
267 (7 <= remove &&
268 memmem(subject->buf + at, remove, "PATCH", 5)))
269 strbuf_remove(subject, at, remove);
270 else {
271 at += remove;
272 /*
273 * If the input had a space after the ], keep
274 * it. We don't bother with finding the end of
275 * the space, since we later normalize it
276 * anyway.
277 */
278 if (isspace(subject->buf[at]))
279 at += 1;
280 }
281 continue;
282 }
283 break;
284 }
285 strbuf_trim(subject);
286}
287
288#define MAX_HDR_PARSED 10
289static const char *header[MAX_HDR_PARSED] = {
290 "From","Subject","Date",
291};
292
293static inline int cmp_header(const struct strbuf *line, const char *hdr)
294{
295 int len = strlen(hdr);
296 return !strncasecmp(line->buf, hdr, len) && line->len > len &&
297 line->buf[len] == ':' && isspace(line->buf[len + 1]);
298}
299
300static int is_format_patch_separator(const char *line, int len)
301{
302 static const char SAMPLE[] =
303 "From e6807f3efca28b30decfecb1732a56c7db1137ee Mon Sep 17 00:00:00 2001\n";
304 const char *cp;
305
306 if (len != strlen(SAMPLE))
307 return 0;
308 if (!skip_prefix(line, "From ", &cp))
309 return 0;
310 if (strspn(cp, "0123456789abcdef") != 40)
311 return 0;
312 cp += 40;
313 return !memcmp(SAMPLE + (cp - line), cp, strlen(SAMPLE) - (cp - line));
314}
315
316static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
317{
318 const char *in = q_seg->buf;
319 int c;
320 struct strbuf *out = xmalloc(sizeof(struct strbuf));
321 strbuf_init(out, q_seg->len);
322
323 while ((c = *in++) != 0) {
324 if (c == '=') {
325 int d = *in++;
326 if (d == '\n' || !d)
327 break; /* drop trailing newline */
328 strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
329 continue;
330 }
331 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
332 c = 0x20;
333 strbuf_addch(out, c);
334 }
335 return out;
336}
337
338static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
339{
340 /* Decode in..ep, possibly in-place to ot */
341 int c, pos = 0, acc = 0;
342 const char *in = b_seg->buf;
343 struct strbuf *out = xmalloc(sizeof(struct strbuf));
344 strbuf_init(out, b_seg->len);
345
346 while ((c = *in++) != 0) {
347 if (c == '+')
348 c = 62;
349 else if (c == '/')
350 c = 63;
351 else if ('A' <= c && c <= 'Z')
352 c -= 'A';
353 else if ('a' <= c && c <= 'z')
354 c -= 'a' - 26;
355 else if ('0' <= c && c <= '9')
356 c -= '0' - 52;
357 else
358 continue; /* garbage */
359 switch (pos++) {
360 case 0:
361 acc = (c << 2);
362 break;
363 case 1:
364 strbuf_addch(out, (acc | (c >> 4)));
365 acc = (c & 15) << 4;
366 break;
367 case 2:
368 strbuf_addch(out, (acc | (c >> 2)));
369 acc = (c & 3) << 6;
370 break;
371 case 3:
372 strbuf_addch(out, (acc | c));
373 acc = pos = 0;
374 break;
375 }
376 }
377 return out;
378}
379
380static void convert_to_utf8(struct strbuf *line, const char *charset)
381{
382 char *out;
383
384 if (!charset || !*charset)
385 return;
386
387 if (same_encoding(metainfo_charset, charset))
388 return;
389 out = reencode_string(line->buf, metainfo_charset, charset);
390 if (!out)
391 die("cannot convert from %s to %s",
392 charset, metainfo_charset);
393 strbuf_attach(line, out, strlen(out), strlen(out));
394}
395
396static void decode_header(struct strbuf *it)
397{
398 char *in, *ep, *cp;
399 struct strbuf outbuf = STRBUF_INIT, *dec;
400 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
401
402 in = it->buf;
403 while (in - it->buf <= it->len && (ep = strstr(in, "=?")) != NULL) {
404 int encoding;
405 strbuf_reset(&charset_q);
406 strbuf_reset(&piecebuf);
407
408 if (in != ep) {
409 /*
410 * We are about to process an encoded-word
411 * that begins at ep, but there is something
412 * before the encoded word.
413 */
414 char *scan;
415 for (scan = in; scan < ep; scan++)
416 if (!isspace(*scan))
417 break;
418
419 if (scan != ep || in == it->buf) {
420 /*
421 * We should not lose that "something",
422 * unless we have just processed an
423 * encoded-word, and there is only LWS
424 * before the one we are about to process.
425 */
426 strbuf_add(&outbuf, in, ep - in);
427 }
428 }
429 /* E.g.
430 * ep : "=?iso-2022-jp?B?GyR...?= foo"
431 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
432 */
433 ep += 2;
434
435 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
436 goto release_return;
437
438 if (cp + 3 - it->buf > it->len)
439 goto release_return;
440 strbuf_add(&charset_q, ep, cp - ep);
441
442 encoding = cp[1];
443 if (!encoding || cp[2] != '?')
444 goto release_return;
445 ep = strstr(cp + 3, "?=");
446 if (!ep)
447 goto release_return;
448 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
449 switch (tolower(encoding)) {
450 default:
451 goto release_return;
452 case 'b':
453 dec = decode_b_segment(&piecebuf);
454 break;
455 case 'q':
456 dec = decode_q_segment(&piecebuf, 1);
457 break;
458 }
459 if (metainfo_charset)
460 convert_to_utf8(dec, charset_q.buf);
461
462 strbuf_addbuf(&outbuf, dec);
463 strbuf_release(dec);
464 free(dec);
465 in = ep + 2;
466 }
467 strbuf_addstr(&outbuf, in);
468 strbuf_reset(it);
469 strbuf_addbuf(it, &outbuf);
470release_return:
471 strbuf_release(&outbuf);
472 strbuf_release(&charset_q);
473 strbuf_release(&piecebuf);
474}
475
476static int check_header(const struct strbuf *line,
477 struct strbuf *hdr_data[], int overwrite)
478{
479 int i, ret = 0, len;
480 struct strbuf sb = STRBUF_INIT;
481 /* search for the interesting parts */
482 for (i = 0; header[i]; i++) {
483 int len = strlen(header[i]);
484 if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
485 /* Unwrap inline B and Q encoding, and optionally
486 * normalize the meta information to utf8.
487 */
488 strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
489 decode_header(&sb);
490 handle_header(&hdr_data[i], &sb);
491 ret = 1;
492 goto check_header_out;
493 }
494 }
495
496 /* Content stuff */
497 if (cmp_header(line, "Content-Type")) {
498 len = strlen("Content-Type: ");
499 strbuf_add(&sb, line->buf + len, line->len - len);
500 decode_header(&sb);
501 strbuf_insert(&sb, 0, "Content-Type: ", len);
502 handle_content_type(&sb);
503 ret = 1;
504 goto check_header_out;
505 }
506 if (cmp_header(line, "Content-Transfer-Encoding")) {
507 len = strlen("Content-Transfer-Encoding: ");
508 strbuf_add(&sb, line->buf + len, line->len - len);
509 decode_header(&sb);
510 handle_content_transfer_encoding(&sb);
511 ret = 1;
512 goto check_header_out;
513 }
514 if (cmp_header(line, "Message-Id")) {
515 len = strlen("Message-Id: ");
516 strbuf_add(&sb, line->buf + len, line->len - len);
517 decode_header(&sb);
518 handle_message_id(&sb);
519 ret = 1;
520 goto check_header_out;
521 }
522
523 /* for inbody stuff */
524 if (starts_with(line->buf, ">From") && isspace(line->buf[5])) {
525 ret = is_format_patch_separator(line->buf + 1, line->len - 1);
526 goto check_header_out;
527 }
528 if (starts_with(line->buf, "[PATCH]") && isspace(line->buf[7])) {
529 for (i = 0; header[i]; i++) {
530 if (!strcmp("Subject", header[i])) {
531 handle_header(&hdr_data[i], line);
532 ret = 1;
533 goto check_header_out;
534 }
535 }
536 }
537
538check_header_out:
539 strbuf_release(&sb);
540 return ret;
541}
542
543static void decode_transfer_encoding(struct strbuf *line)
544{
545 struct strbuf *ret;
546
547 switch (transfer_encoding) {
548 case TE_QP:
549 ret = decode_q_segment(line, 0);
550 break;
551 case TE_BASE64:
552 ret = decode_b_segment(line);
553 break;
554 case TE_DONTCARE:
555 default:
556 return;
557 }
558 strbuf_reset(line);
559 strbuf_addbuf(line, ret);
560 strbuf_release(ret);
561 free(ret);
562}
563
564static inline int patchbreak(const struct strbuf *line)
565{
566 size_t i;
567
568 /* Beginning of a "diff -" header? */
569 if (starts_with(line->buf, "diff -"))
570 return 1;
571
572 /* CVS "Index: " line? */
573 if (starts_with(line->buf, "Index: "))
574 return 1;
575
576 /*
577 * "--- <filename>" starts patches without headers
578 * "---<sp>*" is a manual separator
579 */
580 if (line->len < 4)
581 return 0;
582
583 if (starts_with(line->buf, "---")) {
584 /* space followed by a filename? */
585 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
586 return 1;
587 /* Just whitespace? */
588 for (i = 3; i < line->len; i++) {
589 unsigned char c = line->buf[i];
590 if (c == '\n')
591 return 1;
592 if (!isspace(c))
593 break;
594 }
595 return 0;
596 }
597 return 0;
598}
599
600static int is_scissors_line(const struct strbuf *line)
601{
602 size_t i, len = line->len;
603 int scissors = 0, gap = 0;
604 int first_nonblank = -1;
605 int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
606 const char *buf = line->buf;
607
608 for (i = 0; i < len; i++) {
609 if (isspace(buf[i])) {
610 if (in_perforation) {
611 perforation++;
612 gap++;
613 }
614 continue;
615 }
616 last_nonblank = i;
617 if (first_nonblank < 0)
618 first_nonblank = i;
619 if (buf[i] == '-') {
620 in_perforation = 1;
621 perforation++;
622 continue;
623 }
624 if (i + 1 < len &&
625 (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
626 !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
627 in_perforation = 1;
628 perforation += 2;
629 scissors += 2;
630 i++;
631 continue;
632 }
633 in_perforation = 0;
634 }
635
636 /*
637 * The mark must be at least 8 bytes long (e.g. "-- >8 --").
638 * Even though there can be arbitrary cruft on the same line
639 * (e.g. "cut here"), in order to avoid misidentification, the
640 * perforation must occupy more than a third of the visible
641 * width of the line, and dashes and scissors must occupy more
642 * than half of the perforation.
643 */
644
645 visible = last_nonblank - first_nonblank + 1;
646 return (scissors && 8 <= visible &&
647 visible < perforation * 3 &&
648 gap * 2 < perforation);
649}
650
651static int handle_commit_msg(struct strbuf *line, int *still_looking)
652{
653 if (!cmitmsg)
654 return 0;
655
656 if (*still_looking) {
657 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
658 return 0;
659 }
660
661 if (use_inbody_headers && *still_looking) {
662 *still_looking = check_header(line, s_hdr_data, 0);
663 if (*still_looking)
664 return 0;
665 } else
666 /* Only trim the first (blank) line of the commit message
667 * when ignoring in-body headers.
668 */
669 *still_looking = 0;
670
671 /* normalize the log message to UTF-8. */
672 if (metainfo_charset)
673 convert_to_utf8(line, charset.buf);
674
675 if (use_scissors && is_scissors_line(line)) {
676 int i;
677 if (fseek(cmitmsg, 0L, SEEK_SET))
678 die_errno("Could not rewind output message file");
679 if (ftruncate(fileno(cmitmsg), 0))
680 die_errno("Could not truncate output message file at scissors");
681 *still_looking = 1;
682
683 /*
684 * We may have already read "secondary headers"; purge
685 * them to give ourselves a clean restart.
686 */
687 for (i = 0; header[i]; i++) {
688 if (s_hdr_data[i])
689 strbuf_release(s_hdr_data[i]);
690 s_hdr_data[i] = NULL;
691 }
692 return 0;
693 }
694
695 if (patchbreak(line)) {
696 if (message_id)
697 fprintf(cmitmsg, "Message-Id: %s\n", message_id);
698 fclose(cmitmsg);
699 cmitmsg = NULL;
700 return 1;
701 }
702
703 fputs(line->buf, cmitmsg);
704 return 0;
705}
706
707static void handle_patch(const struct strbuf *line)
708{
709 fwrite(line->buf, 1, line->len, patchfile);
710 patch_lines++;
711}
712
713static void handle_filter(struct strbuf *line, int *filter_stage, int *header_stage)
714{
715 switch (*filter_stage) {
716 case 0:
717 if (!handle_commit_msg(line, header_stage))
718 break;
719 (*filter_stage)++;
720 case 1:
721 handle_patch(line);
722 break;
723 }
724}
725
726static int is_rfc2822_header(const struct strbuf *line)
727{
728 /*
729 * The section that defines the loosest possible
730 * field name is "3.6.8 Optional fields".
731 *
732 * optional-field = field-name ":" unstructured CRLF
733 * field-name = 1*ftext
734 * ftext = %d33-57 / %59-126
735 */
736 int ch;
737 char *cp = line->buf;
738
739 /* Count mbox From headers as headers */
740 if (starts_with(cp, "From ") || starts_with(cp, ">From "))
741 return 1;
742
743 while ((ch = *cp++)) {
744 if (ch == ':')
745 return 1;
746 if ((33 <= ch && ch <= 57) ||
747 (59 <= ch && ch <= 126))
748 continue;
749 break;
750 }
751 return 0;
752}
753
754static int read_one_header_line(struct strbuf *line, FILE *in)
755{
756 struct strbuf continuation = STRBUF_INIT;
757
758 /* Get the first part of the line. */
759 if (strbuf_getline(line, in, '\n'))
760 return 0;
761
762 /*
763 * Is it an empty line or not a valid rfc2822 header?
764 * If so, stop here, and return false ("not a header")
765 */
766 strbuf_rtrim(line);
767 if (!line->len || !is_rfc2822_header(line)) {
768 /* Re-add the newline */
769 strbuf_addch(line, '\n');
770 return 0;
771 }
772
773 /*
774 * Now we need to eat all the continuation lines..
775 * Yuck, 2822 header "folding"
776 */
777 for (;;) {
778 int peek;
779
780 peek = fgetc(in); ungetc(peek, in);
781 if (peek != ' ' && peek != '\t')
782 break;
783 if (strbuf_getline(&continuation, in, '\n'))
784 break;
785 continuation.buf[0] = ' ';
786 strbuf_rtrim(&continuation);
787 strbuf_addbuf(line, &continuation);
788 }
789 strbuf_release(&continuation);
790
791 return 1;
792}
793
794static int find_boundary(struct mailinfo *mi, struct strbuf *line)
795{
796 while (!strbuf_getline(line, mi->input, '\n')) {
797 if (*content_top && is_multipart_boundary(line))
798 return 1;
799 }
800 return 0;
801}
802
803static int handle_boundary(struct mailinfo *mi, struct strbuf *line,
804 int *filter_stage, int *header_stage)
805{
806 struct strbuf newline = STRBUF_INIT;
807
808 strbuf_addch(&newline, '\n');
809again:
810 if (line->len >= (*content_top)->len + 2 &&
811 !memcmp(line->buf + (*content_top)->len, "--", 2)) {
812 /* we hit an end boundary */
813 /* pop the current boundary off the stack */
814 strbuf_release(*content_top);
815 free(*content_top);
816 *content_top = NULL;
817
818 /* technically won't happen as is_multipart_boundary()
819 will fail first. But just in case..
820 */
821 if (--content_top < content) {
822 fprintf(stderr, "Detected mismatched boundaries, "
823 "can't recover\n");
824 exit(1);
825 }
826 handle_filter(&newline, filter_stage, header_stage);
827 strbuf_release(&newline);
828
829 /* skip to the next boundary */
830 if (!find_boundary(mi, line))
831 return 0;
832 goto again;
833 }
834
835 /* set some defaults */
836 transfer_encoding = TE_DONTCARE;
837 strbuf_reset(&charset);
838
839 /* slurp in this section's info */
840 while (read_one_header_line(line, mi->input))
841 check_header(line, p_hdr_data, 0);
842
843 strbuf_release(&newline);
844 /* replenish line */
845 if (strbuf_getline(line, mi->input, '\n'))
846 return 0;
847 strbuf_addch(line, '\n');
848 return 1;
849}
850
851static void handle_body(struct mailinfo *mi, struct strbuf *line)
852{
853 struct strbuf prev = STRBUF_INIT;
854 int filter_stage = 0;
855 int header_stage = 1;
856
857 /* Skip up to the first boundary */
858 if (*content_top) {
859 if (!find_boundary(mi, line))
860 goto handle_body_out;
861 }
862
863 do {
864 /* process any boundary lines */
865 if (*content_top && is_multipart_boundary(line)) {
866 /* flush any leftover */
867 if (prev.len) {
868 handle_filter(&prev, &filter_stage, &header_stage);
869 strbuf_reset(&prev);
870 }
871 if (!handle_boundary(mi, line, &filter_stage, &header_stage))
872 goto handle_body_out;
873 }
874
875 /* Unwrap transfer encoding */
876 decode_transfer_encoding(line);
877
878 switch (transfer_encoding) {
879 case TE_BASE64:
880 case TE_QP:
881 {
882 struct strbuf **lines, **it, *sb;
883
884 /* Prepend any previous partial lines */
885 strbuf_insert(line, 0, prev.buf, prev.len);
886 strbuf_reset(&prev);
887
888 /*
889 * This is a decoded line that may contain
890 * multiple new lines. Pass only one chunk
891 * at a time to handle_filter()
892 */
893 lines = strbuf_split(line, '\n');
894 for (it = lines; (sb = *it); it++) {
895 if (*(it + 1) == NULL) /* The last line */
896 if (sb->buf[sb->len - 1] != '\n') {
897 /* Partial line, save it for later. */
898 strbuf_addbuf(&prev, sb);
899 break;
900 }
901 handle_filter(sb, &filter_stage, &header_stage);
902 }
903 /*
904 * The partial chunk is saved in "prev" and will be
905 * appended by the next iteration of read_line_with_nul().
906 */
907 strbuf_list_free(lines);
908 break;
909 }
910 default:
911 handle_filter(line, &filter_stage, &header_stage);
912 }
913
914 } while (!strbuf_getwholeline(line, mi->input, '\n'));
915
916handle_body_out:
917 strbuf_release(&prev);
918}
919
920static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
921{
922 const char *sp = data->buf;
923 while (1) {
924 char *ep = strchr(sp, '\n');
925 int len;
926 if (!ep)
927 len = strlen(sp);
928 else
929 len = ep - sp;
930 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
931 if (!ep)
932 break;
933 sp = ep + 1;
934 }
935}
936
937static void handle_info(struct mailinfo *mi)
938{
939 struct strbuf *hdr;
940 int i;
941
942 for (i = 0; header[i]; i++) {
943 /* only print inbody headers if we output a patch file */
944 if (patch_lines && s_hdr_data[i])
945 hdr = s_hdr_data[i];
946 else if (p_hdr_data[i])
947 hdr = p_hdr_data[i];
948 else
949 continue;
950
951 if (!strcmp(header[i], "Subject")) {
952 if (!mi->keep_subject) {
953 cleanup_subject(mi, hdr);
954 cleanup_space(hdr);
955 }
956 output_header_lines(mi->output, "Subject", hdr);
957 } else if (!strcmp(header[i], "From")) {
958 cleanup_space(hdr);
959 handle_from(mi, hdr);
960 fprintf(mi->output, "Author: %s\n", mi->name.buf);
961 fprintf(mi->output, "Email: %s\n", mi->email.buf);
962 } else {
963 cleanup_space(hdr);
964 fprintf(mi->output, "%s: %s\n", header[i], hdr->buf);
965 }
966 }
967 fprintf(mi->output, "\n");
968}
969
970static int mailinfo(struct mailinfo *mi, const char *msg, const char *patch)
971{
972 int peek;
973 struct strbuf line = STRBUF_INIT;
974
975 cmitmsg = fopen(msg, "w");
976 if (!cmitmsg) {
977 perror(msg);
978 return -1;
979 }
980 patchfile = fopen(patch, "w");
981 if (!patchfile) {
982 perror(patch);
983 fclose(cmitmsg);
984 return -1;
985 }
986
987 p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*p_hdr_data));
988 s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*s_hdr_data));
989
990 do {
991 peek = fgetc(mi->input);
992 } while (isspace(peek));
993 ungetc(peek, mi->input);
994
995 /* process the email header */
996 while (read_one_header_line(&line, mi->input))
997 check_header(&line, p_hdr_data, 1);
998
999 handle_body(mi, &line);
1000 fclose(patchfile);
1001
1002 handle_info(mi);
1003 strbuf_release(&line);
1004 return 0;
1005}
1006
1007static int git_mailinfo_config(const char *var, const char *value, void *unused)
1008{
1009 if (!starts_with(var, "mailinfo."))
1010 return git_default_config(var, value, unused);
1011 if (!strcmp(var, "mailinfo.scissors")) {
1012 use_scissors = git_config_bool(var, value);
1013 return 0;
1014 }
1015 /* perhaps others here */
1016 return 0;
1017}
1018
1019static void setup_mailinfo(struct mailinfo *mi)
1020{
1021 memset(mi, 0, sizeof(*mi));
1022 strbuf_init(&mi->name, 0);
1023 strbuf_init(&mi->email, 0);
1024 git_config(git_mailinfo_config, &mi);
1025}
1026
1027static void clear_mailinfo(struct mailinfo *mi)
1028{
1029 strbuf_release(&mi->name);
1030 strbuf_release(&mi->email);
1031}
1032
1033static const char mailinfo_usage[] =
1034 "git mailinfo [-k | -b] [-m | --message-id] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] <msg> <patch> < mail >info";
1035
1036int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1037{
1038 const char *def_charset;
1039 struct mailinfo mi;
1040 int status;
1041
1042 /* NEEDSWORK: might want to do the optional .git/ directory
1043 * discovery
1044 */
1045 setup_mailinfo(&mi);
1046
1047 def_charset = get_commit_output_encoding();
1048 metainfo_charset = def_charset;
1049
1050 while (1 < argc && argv[1][0] == '-') {
1051 if (!strcmp(argv[1], "-k"))
1052 mi.keep_subject = 1;
1053 else if (!strcmp(argv[1], "-b"))
1054 mi.keep_non_patch_brackets_in_subject = 1;
1055 else if (!strcmp(argv[1], "-m") || !strcmp(argv[1], "--message-id"))
1056 add_message_id = 1;
1057 else if (!strcmp(argv[1], "-u"))
1058 metainfo_charset = def_charset;
1059 else if (!strcmp(argv[1], "-n"))
1060 metainfo_charset = NULL;
1061 else if (starts_with(argv[1], "--encoding="))
1062 metainfo_charset = argv[1] + 11;
1063 else if (!strcmp(argv[1], "--scissors"))
1064 use_scissors = 1;
1065 else if (!strcmp(argv[1], "--no-scissors"))
1066 use_scissors = 0;
1067 else if (!strcmp(argv[1], "--no-inbody-headers"))
1068 use_inbody_headers = 0;
1069 else
1070 usage(mailinfo_usage);
1071 argc--; argv++;
1072 }
1073
1074 if (argc != 3)
1075 usage(mailinfo_usage);
1076
1077 mi.input = stdin;
1078 mi.output = stdout;
1079 status = !!mailinfo(&mi, argv[1], argv[2]);
1080 clear_mailinfo(&mi);
1081
1082 return status;
1083}