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