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