]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/mailinfo.c
mailinfo: keep the parsed log message in a strbuf
[thirdparty/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
8e919277
JH
10#define MAX_BOUNDARIES 5
11
c69f2395 12struct mailinfo {
173aef7c
JH
13 FILE *input;
14 FILE *output;
8f63588a 15 FILE *patchfile;
173aef7c 16
c69f2395
JH
17 struct strbuf name;
18 struct strbuf email;
849106d5
JH
19 int keep_subject;
20 int keep_non_patch_brackets_in_subject;
6200b751 21 int add_message_id;
ad57ef9d
JH
22 int use_scissors;
23 int use_inbody_headers;
28be2d08 24 const char *metainfo_charset;
13c6df26 25
8e919277
JH
26 struct strbuf *content[MAX_BOUNDARIES];
27 struct strbuf **content_top;
f1e037b9 28 struct strbuf charset;
6200b751 29 char *message_id;
ab50e38b
JH
30 enum {
31 TE_DONTCARE, TE_QP, TE_BASE64
32 } transfer_encoding;
43550efa 33 int patch_lines;
13c6df26
JH
34 int filter_stage; /* still reading log or are we copying patch? */
35 int header_stage; /* still checking in-body headers? */
d895bf0f
JH
36 struct strbuf **p_hdr_data;
37 struct strbuf **s_hdr_data;
05e625e5
JH
38
39 struct strbuf log_message;
c69f2395 40};
2744b234 41
30f50c34
JH
42static void cleanup_space(struct strbuf *sb)
43{
44 size_t pos, cnt;
45 for (pos = 0; pos < sb->len; pos++) {
46 if (isspace(sb->buf[pos])) {
47 sb->buf[pos] = ' ';
48 for (cnt = 0; isspace(sb->buf[pos + cnt + 1]); cnt++);
49 strbuf_remove(sb, pos + 1, cnt);
50 }
51 }
52}
08e6710f 53
3b6121f6 54static void get_sane_name(struct strbuf *out, struct strbuf *name, struct strbuf *email)
2744b234 55{
3b6121f6
LS
56 struct strbuf *src = name;
57 if (name->len < 3 || 60 < name->len || strchr(name->buf, '@') ||
58 strchr(name->buf, '<') || strchr(name->buf, '>'))
59 src = email;
60 else if (name == out)
61 return;
62 strbuf_reset(out);
63 strbuf_addbuf(out, src);
2744b234
LT
64}
65
c69f2395 66static void parse_bogus_from(struct mailinfo *mi, const struct strbuf *line)
e0e3ba20
JH
67{
68 /* John Doe <johndoe> */
e0e3ba20 69
3b6121f6 70 char *bra, *ket;
e0e3ba20
JH
71 /* This is fallback, so do not bother if we already have an
72 * e-mail address.
34488e3c 73 */
c69f2395 74 if (mi->email.len)
3b6121f6 75 return;
e0e3ba20 76
3b6121f6 77 bra = strchr(line->buf, '<');
e0e3ba20 78 if (!bra)
3b6121f6 79 return;
e0e3ba20
JH
80 ket = strchr(bra, '>');
81 if (!ket)
3b6121f6 82 return;
e0e3ba20 83
c69f2395
JH
84 strbuf_reset(&mi->email);
85 strbuf_add(&mi->email, bra + 1, ket - bra - 1);
3b6121f6 86
c69f2395
JH
87 strbuf_reset(&mi->name);
88 strbuf_add(&mi->name, line->buf, bra - line->buf);
89 strbuf_trim(&mi->name);
90 get_sane_name(&mi->name, &mi->name, &mi->email);
e0e3ba20
JH
91}
92
c69f2395 93static void handle_from(struct mailinfo *mi, const struct strbuf *from)
2744b234 94{
2dec02b1 95 char *at;
3b6121f6
LS
96 size_t el;
97 struct strbuf f;
2744b234 98
3b6121f6
LS
99 strbuf_init(&f, from->len);
100 strbuf_addbuf(&f, from);
101
102 at = strchr(f.buf, '@');
103 if (!at) {
c69f2395 104 parse_bogus_from(mi, from);
3b6121f6
LS
105 return;
106 }
2744b234
LT
107
108 /*
109 * If we already have one email, don't take any confusing lines
110 */
c69f2395 111 if (mi->email.len && strchr(at + 1, '@')) {
3b6121f6
LS
112 strbuf_release(&f);
113 return;
114 }
2744b234 115
d4a9ce78 116 /* Pick up the string around '@', possibly delimited with <>
3b6121f6 117 * pair; that is the email part.
d4a9ce78 118 */
3b6121f6 119 while (at > f.buf) {
2744b234 120 char c = at[-1];
d4a9ce78
JH
121 if (isspace(c))
122 break;
123 if (c == '<') {
124 at[-1] = ' ';
2744b234 125 break;
d4a9ce78 126 }
2744b234
LT
127 at--;
128 }
3b6121f6 129 el = strcspn(at, " \n\t\r\v\f>");
c69f2395
JH
130 strbuf_reset(&mi->email);
131 strbuf_add(&mi->email, at, el);
e9d7d10a 132 strbuf_remove(&f, at - f.buf, el + (at[el] ? 1 : 0));
2744b234 133
08e6710f
KS
134 /* The remainder is name. It could be
135 *
136 * - "John Doe <john.doe@xz>" (a), or
137 * - "john.doe@xz (John Doe)" (b), or
138 * - "John (zzz) Doe <john.doe@xz> (Comment)" (c)
139 *
140 * but we have removed the email part, so
141 *
142 * - remove extra spaces which could stay after email (case 'c'), and
143 * - trim from both ends, possibly removing the () pair at the end
144 * (cases 'a' and 'b').
d4a9ce78 145 */
08e6710f 146 cleanup_space(&f);
3b6121f6 147 strbuf_trim(&f);
0d4ede9f
PB
148 if (f.buf[0] == '(' && f.len && f.buf[f.len - 1] == ')') {
149 strbuf_remove(&f, 0, 1);
3b6121f6 150 strbuf_setlen(&f, f.len - 1);
0d4ede9f 151 }
2744b234 152
c69f2395 153 get_sane_name(&mi->name, &f, &mi->email);
3b6121f6 154 strbuf_release(&f);
2744b234
LT
155}
156
3b6121f6 157static void handle_header(struct strbuf **out, const struct strbuf *line)
62c1f6b4 158{
3b6121f6
LS
159 if (!*out) {
160 *out = xmalloc(sizeof(struct strbuf));
161 strbuf_init(*out, line->len);
162 } else
163 strbuf_reset(*out);
87ab7992 164
3b6121f6 165 strbuf_addbuf(*out, line);
d4a9ce78
JH
166}
167
168/* NOTE NOTE NOTE. We do not claim we do full MIME. We just attempt
169 * to have enough heuristics to grok MIME encoded patches often found
170 * on our mailing lists. For example, we do not even treat header lines
171 * case insensitively.
172 */
173
3b6121f6 174static int slurp_attr(const char *line, const char *name, struct strbuf *attr)
d4a9ce78 175{
554fe20d 176 const char *ends, *ap = strcasestr(line, name);
d4a9ce78
JH
177 size_t sz;
178
176943b9
JH
179 strbuf_setlen(attr, 0);
180 if (!ap)
d4a9ce78 181 return 0;
d4a9ce78
JH
182 ap += strlen(name);
183 if (*ap == '"') {
184 ap++;
185 ends = "\"";
186 }
187 else
188 ends = "; \t";
189 sz = strcspn(ap, ends);
3b6121f6 190 strbuf_add(attr, ap, sz);
d4a9ce78
JH
191 return 1;
192}
193
f1e037b9 194static void handle_content_type(struct mailinfo *mi, struct strbuf *line)
d4a9ce78 195{
3b6121f6
LS
196 struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
197 strbuf_init(boundary, line->len);
87ab7992 198
3b6121f6
LS
199 if (slurp_attr(line->buf, "boundary=", boundary)) {
200 strbuf_insert(boundary, 0, "--", 2);
8e919277 201 if (++mi->content_top >= &mi->content[MAX_BOUNDARIES]) {
87ab7992
DZ
202 fprintf(stderr, "Too many boundaries to handle\n");
203 exit(1);
204 }
8e919277 205 *(mi->content_top) = boundary;
3b6121f6 206 boundary = NULL;
b893f091 207 }
f1e037b9 208 slurp_attr(line->buf, "charset=", &mi->charset);
3b6121f6
LS
209
210 if (boundary) {
211 strbuf_release(boundary);
212 free(boundary);
d4a9ce78 213 }
d4a9ce78
JH
214}
215
6200b751 216static void handle_message_id(struct mailinfo *mi, const struct strbuf *line)
452dfbed 217{
6200b751
JH
218 if (mi->add_message_id)
219 mi->message_id = strdup(line->buf);
452dfbed
PB
220}
221
ab50e38b
JH
222static void handle_content_transfer_encoding(struct mailinfo *mi,
223 const struct strbuf *line)
d4a9ce78 224{
3b6121f6 225 if (strcasestr(line->buf, "base64"))
ab50e38b 226 mi->transfer_encoding = TE_BASE64;
3b6121f6 227 else if (strcasestr(line->buf, "quoted-printable"))
ab50e38b 228 mi->transfer_encoding = TE_QP;
d4a9ce78 229 else
ab50e38b 230 mi->transfer_encoding = TE_DONTCARE;
2744b234
LT
231}
232
8e919277 233static int is_multipart_boundary(struct mailinfo *mi, const struct strbuf *line)
d4a9ce78 234{
8e919277
JH
235 struct strbuf *content_top = *(mi->content_top);
236
237 return ((content_top->len <= line->len) &&
238 !memcmp(line->buf, content_top->buf, content_top->len));
d4a9ce78
JH
239}
240
849106d5 241static void cleanup_subject(struct mailinfo *mi, struct strbuf *subject)
2744b234 242{
17635fc9
JH
243 size_t at = 0;
244
245 while (at < subject->len) {
246 char *pos;
247 size_t remove;
248
249 switch (subject->buf[at]) {
2744b234 250 case 'r': case 'R':
17635fc9 251 if (subject->len <= at + 3)
3b6121f6 252 break;
d5b4d80d
JH
253 if ((subject->buf[at + 1] == 'e' ||
254 subject->buf[at + 1] == 'E') &&
255 subject->buf[at + 2] == ':') {
17635fc9 256 strbuf_remove(subject, at, 3);
2744b234
LT
257 continue;
258 }
17635fc9 259 at++;
2744b234
LT
260 break;
261 case ' ': case '\t': case ':':
17635fc9 262 strbuf_remove(subject, at, 1);
2744b234 263 continue;
2744b234 264 case '[':
17635fc9
JH
265 pos = strchr(subject->buf + at, ']');
266 if (!pos)
267 break;
268 remove = pos - subject->buf + at + 1;
849106d5 269 if (!mi->keep_non_patch_brackets_in_subject ||
17635fc9
JH
270 (7 <= remove &&
271 memmem(subject->buf + at, remove, "PATCH", 5)))
272 strbuf_remove(subject, at, remove);
ee2d1cb4 273 else {
17635fc9 274 at += remove;
ee2d1cb4
TR
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 }
17635fc9 284 continue;
2744b234 285 }
17635fc9 286 break;
2744b234 287 }
17635fc9 288 strbuf_trim(subject);
34488e3c 289}
2744b234 290
c1b40bd7 291#define MAX_HDR_PARSED 10
538dfe73 292static const char *header[MAX_HDR_PARSED] = {
87ab7992 293 "From","Subject","Date",
d4a9ce78
JH
294};
295
3b6121f6 296static inline int cmp_header(const struct strbuf *line, const char *hdr)
d4a9ce78 297{
3b6121f6
LS
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}
d4a9ce78 302
2da1f366
JK
303static int is_format_patch_separator(const char *line, int len)
304{
85de86a1
ES
305 static const char SAMPLE[] =
306 "From e6807f3efca28b30decfecb1732a56c7db1137ee Mon Sep 17 00:00:00 2001\n";
2da1f366
JK
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
3b6121f6 319static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
d4a9ce78 320{
3b6121f6 321 const char *in = q_seg->buf;
d4a9ce78 322 int c;
3b6121f6
LS
323 struct strbuf *out = xmalloc(sizeof(struct strbuf));
324 strbuf_init(out, q_seg->len);
325
326 while ((c = *in++) != 0) {
d4a9ce78
JH
327 if (c == '=') {
328 int d = *in++;
329 if (d == '\n' || !d)
330 break; /* drop trailing newline */
3b6121f6 331 strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
75731930 332 continue;
d4a9ce78 333 }
75731930
JH
334 if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
335 c = 0x20;
3b6121f6 336 strbuf_addch(out, c);
d4a9ce78 337 }
3b6121f6 338 return out;
d4a9ce78
JH
339}
340
3b6121f6 341static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
d4a9ce78
JH
342{
343 /* Decode in..ep, possibly in-place to ot */
344 int c, pos = 0, acc = 0;
3b6121f6
LS
345 const char *in = b_seg->buf;
346 struct strbuf *out = xmalloc(sizeof(struct strbuf));
347 strbuf_init(out, b_seg->len);
d4a9ce78 348
3b6121f6 349 while ((c = *in++) != 0) {
d4a9ce78
JH
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;
d4a9ce78
JH
360 else
361 continue; /* garbage */
362 switch (pos++) {
363 case 0:
364 acc = (c << 2);
365 break;
366 case 1:
3b6121f6 367 strbuf_addch(out, (acc | (c >> 4)));
d4a9ce78
JH
368 acc = (c & 15) << 4;
369 break;
370 case 2:
3b6121f6 371 strbuf_addch(out, (acc | (c >> 2)));
d4a9ce78
JH
372 acc = (c & 3) << 6;
373 break;
374 case 3:
3b6121f6 375 strbuf_addch(out, (acc | c));
d4a9ce78
JH
376 acc = pos = 0;
377 break;
378 }
379 }
3b6121f6 380 return out;
d4a9ce78
JH
381}
382
28be2d08
JH
383static void convert_to_utf8(struct mailinfo *mi,
384 struct strbuf *line, const char *charset)
d4a9ce78 385{
b59d398b
LT
386 char *out;
387
28c6bfe9 388 if (!mi->metainfo_charset || !charset || !*charset)
08a94a14 389 return;
b45974a6 390
28be2d08 391 if (same_encoding(mi->metainfo_charset, charset))
7296096c 392 return;
28be2d08 393 out = reencode_string(line->buf, mi->metainfo_charset, charset);
bb1091a4 394 if (!out)
d7530708 395 die("cannot convert from %s to %s",
28be2d08 396 charset, mi->metainfo_charset);
3b6121f6 397 strbuf_attach(line, out, strlen(out), strlen(out));
d4a9ce78
JH
398}
399
28be2d08 400static void decode_header(struct mailinfo *mi, struct strbuf *it)
d4a9ce78 401{
3b6121f6
LS
402 char *in, *ep, *cp;
403 struct strbuf outbuf = STRBUF_INIT, *dec;
404 struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
d4a9ce78 405
3b6121f6
LS
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);
b75bf2c3 411
d4a9ce78 412 if (in != ep) {
353aaf2f
KS
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 }
d4a9ce78
JH
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;
3b6121f6
LS
438
439 if (ep - it->buf >= it->len || !(cp = strchr(ep, '?')))
3a8fcdaf 440 goto release_return;
3b6121f6
LS
441
442 if (cp + 3 - it->buf > it->len)
3a8fcdaf 443 goto release_return;
3b6121f6 444 strbuf_add(&charset_q, ep, cp - ep);
3b6121f6 445
d4a9ce78
JH
446 encoding = cp[1];
447 if (!encoding || cp[2] != '?')
3a8fcdaf 448 goto release_return;
d4a9ce78
JH
449 ep = strstr(cp + 3, "?=");
450 if (!ep)
3a8fcdaf 451 goto release_return;
3b6121f6 452 strbuf_add(&piecebuf, cp + 3, ep - cp - 3);
d4a9ce78
JH
453 switch (tolower(encoding)) {
454 default:
3a8fcdaf 455 goto release_return;
d4a9ce78 456 case 'b':
3b6121f6 457 dec = decode_b_segment(&piecebuf);
d4a9ce78
JH
458 break;
459 case 'q':
3b6121f6 460 dec = decode_q_segment(&piecebuf, 1);
d4a9ce78
JH
461 break;
462 }
28c6bfe9 463 convert_to_utf8(mi, dec, charset_q.buf);
8dabdfcc 464
3b6121f6
LS
465 strbuf_addbuf(&outbuf, dec);
466 strbuf_release(dec);
467 free(dec);
d4a9ce78
JH
468 in = ep + 2;
469 }
3b6121f6
LS
470 strbuf_addstr(&outbuf, in);
471 strbuf_reset(it);
472 strbuf_addbuf(it, &outbuf);
3a8fcdaf 473release_return:
3b6121f6
LS
474 strbuf_release(&outbuf);
475 strbuf_release(&charset_q);
476 strbuf_release(&piecebuf);
d4a9ce78
JH
477}
478
6200b751
JH
479static int check_header(struct mailinfo *mi,
480 const struct strbuf *line,
481 struct strbuf *hdr_data[], int overwrite)
4f0f9d46
JH
482{
483 int i, ret = 0, len;
484 struct strbuf sb = STRBUF_INIT;
6200b751 485
4f0f9d46
JH
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);
28be2d08 494 decode_header(mi, &sb);
4f0f9d46
JH
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);
28be2d08 505 decode_header(mi, &sb);
4f0f9d46 506 strbuf_insert(&sb, 0, "Content-Type: ", len);
f1e037b9 507 handle_content_type(mi, &sb);
4f0f9d46
JH
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);
28be2d08 514 decode_header(mi, &sb);
ab50e38b 515 handle_content_transfer_encoding(mi, &sb);
4f0f9d46
JH
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);
28be2d08 522 decode_header(mi, &sb);
6200b751 523 handle_message_id(mi, &sb);
4f0f9d46
JH
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
ab50e38b 548static void decode_transfer_encoding(struct mailinfo *mi, struct strbuf *line)
d4a9ce78 549{
3b6121f6 550 struct strbuf *ret;
d4a9ce78 551
ab50e38b 552 switch (mi->transfer_encoding) {
d4a9ce78 553 case TE_QP:
3b6121f6
LS
554 ret = decode_q_segment(line, 0);
555 break;
d4a9ce78 556 case TE_BASE64:
3b6121f6
LS
557 ret = decode_b_segment(line);
558 break;
d4a9ce78 559 case TE_DONTCARE:
9aa23094 560 default:
3b6121f6 561 return;
d4a9ce78 562 }
3b6121f6
LS
563 strbuf_reset(line);
564 strbuf_addbuf(line, ret);
565 strbuf_release(ret);
566 free(ret);
d4a9ce78
JH
567}
568
3b6121f6 569static inline int patchbreak(const struct strbuf *line)
f0658cf2 570{
3b6121f6
LS
571 size_t i;
572
f0658cf2 573 /* Beginning of a "diff -" header? */
59556548 574 if (starts_with(line->buf, "diff -"))
f0658cf2
DZ
575 return 1;
576
577 /* CVS "Index: " line? */
59556548 578 if (starts_with(line->buf, "Index: "))
f0658cf2
DZ
579 return 1;
580
581 /*
582 * "--- <filename>" starts patches without headers
583 * "---<sp>*" is a manual separator
584 */
3b6121f6
LS
585 if (line->len < 4)
586 return 0;
587
59556548 588 if (starts_with(line->buf, "---")) {
f0658cf2 589 /* space followed by a filename? */
3b6121f6 590 if (line->buf[3] == ' ' && !isspace(line->buf[4]))
f0658cf2
DZ
591 return 1;
592 /* Just whitespace? */
3b6121f6
LS
593 for (i = 3; i < line->len; i++) {
594 unsigned char c = line->buf[i];
f0658cf2
DZ
595 if (c == '\n')
596 return 1;
597 if (!isspace(c))
598 break;
599 }
600 return 0;
601 }
602 return 0;
603}
604
200c75f0
JH
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 &&
9974e290
JN
630 (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
631 !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
200c75f0
JH
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
13c6df26 656static int handle_commit_msg(struct mailinfo *mi, struct strbuf *line)
d4a9ce78 657{
4933910a 658 assert(!mi->filter_stage);
2744b234 659
13c6df26 660 if (mi->header_stage) {
470b4526 661 if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
3b6121f6 662 return 0;
d25e5159
LS
663 }
664
ad57ef9d 665 if (mi->use_inbody_headers && mi->header_stage) {
d895bf0f 666 mi->header_stage = check_header(mi, line, mi->s_hdr_data, 0);
13c6df26 667 if (mi->header_stage)
87ab7992 668 return 0;
d25e5159
LS
669 } else
670 /* Only trim the first (blank) line of the commit message
671 * when ignoring in-body headers.
672 */
13c6df26 673 mi->header_stage = 0;
8b4525fb 674
86747c13 675 /* normalize the log message to UTF-8. */
f1e037b9 676 convert_to_utf8(mi, line, mi->charset.buf);
86747c13 677
ad57ef9d 678 if (mi->use_scissors && is_scissors_line(line)) {
200c75f0 679 int i;
05e625e5
JH
680
681 strbuf_setlen(&mi->log_message, 0);
13c6df26 682 mi->header_stage = 1;
200c75f0
JH
683
684 /*
685 * We may have already read "secondary headers"; purge
686 * them to give ourselves a clean restart.
687 */
688 for (i = 0; header[i]; i++) {
d895bf0f
JH
689 if (mi->s_hdr_data[i])
690 strbuf_release(mi->s_hdr_data[i]);
691 mi->s_hdr_data[i] = NULL;
200c75f0
JH
692 }
693 return 0;
694 }
695
f0658cf2 696 if (patchbreak(line)) {
6200b751 697 if (mi->message_id)
05e625e5
JH
698 strbuf_addf(&mi->log_message,
699 "Message-Id: %s\n", mi->message_id);
87ab7992
DZ
700 return 1;
701 }
8b4525fb 702
05e625e5 703 strbuf_addbuf(&mi->log_message, line);
d4a9ce78 704 return 0;
2744b234
LT
705}
706
43550efa 707static void handle_patch(struct mailinfo *mi, const struct strbuf *line)
2744b234 708{
8f63588a 709 fwrite(line->buf, 1, line->len, mi->patchfile);
43550efa 710 mi->patch_lines++;
2744b234
LT
711}
712
13c6df26 713static void handle_filter(struct mailinfo *mi, struct strbuf *line)
2744b234 714{
13c6df26 715 switch (mi->filter_stage) {
87ab7992 716 case 0:
13c6df26 717 if (!handle_commit_msg(mi, line))
d4a9ce78 718 break;
13c6df26 719 mi->filter_stage++;
87ab7992 720 case 1:
43550efa 721 handle_patch(mi, line);
3b6121f6 722 break;
2744b234
LT
723 }
724}
725
9cc243f7
JH
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
173aef7c 794static int find_boundary(struct mailinfo *mi, struct strbuf *line)
39afcd38 795{
173aef7c 796 while (!strbuf_getline(line, mi->input, '\n')) {
8e919277 797 if (*(mi->content_top) && is_multipart_boundary(mi, line))
39afcd38
JH
798 return 1;
799 }
800 return 0;
801}
802
13c6df26 803static int handle_boundary(struct mailinfo *mi, struct strbuf *line)
39afcd38
JH
804{
805 struct strbuf newline = STRBUF_INIT;
806
807 strbuf_addch(&newline, '\n');
808again:
8e919277
JH
809 if (line->len >= (*(mi->content_top))->len + 2 &&
810 !memcmp(line->buf + (*(mi->content_top))->len, "--", 2)) {
39afcd38
JH
811 /* we hit an end boundary */
812 /* pop the current boundary off the stack */
8e919277
JH
813 strbuf_release(*(mi->content_top));
814 free(*(mi->content_top));
815 *(mi->content_top) = NULL;
39afcd38
JH
816
817 /* technically won't happen as is_multipart_boundary()
818 will fail first. But just in case..
819 */
8e919277 820 if (--mi->content_top < mi->content) {
39afcd38
JH
821 fprintf(stderr, "Detected mismatched boundaries, "
822 "can't recover\n");
823 exit(1);
824 }
13c6df26 825 handle_filter(mi, &newline);
39afcd38
JH
826 strbuf_release(&newline);
827
828 /* skip to the next boundary */
173aef7c 829 if (!find_boundary(mi, line))
39afcd38
JH
830 return 0;
831 goto again;
832 }
833
834 /* set some defaults */
ab50e38b 835 mi->transfer_encoding = TE_DONTCARE;
f1e037b9 836 strbuf_reset(&mi->charset);
39afcd38
JH
837
838 /* slurp in this section's info */
173aef7c 839 while (read_one_header_line(line, mi->input))
d895bf0f 840 check_header(mi, line, mi->p_hdr_data, 0);
39afcd38
JH
841
842 strbuf_release(&newline);
843 /* replenish line */
173aef7c 844 if (strbuf_getline(line, mi->input, '\n'))
39afcd38 845 return 0;
69e24def 846 strbuf_addch(line, '\n');
39afcd38
JH
847 return 1;
848}
849
173aef7c 850static void handle_body(struct mailinfo *mi, struct strbuf *line)
1d8fa411 851{
3b6121f6 852 struct strbuf prev = STRBUF_INIT;
d4a9ce78
JH
853
854 /* Skip up to the first boundary */
8e919277 855 if (*(mi->content_top)) {
173aef7c 856 if (!find_boundary(mi, line))
3b6121f6 857 goto handle_body_out;
87ab7992
DZ
858 }
859
860 do {
861 /* process any boundary lines */
8e919277 862 if (*(mi->content_top) && is_multipart_boundary(mi, line)) {
87ab7992 863 /* flush any leftover */
a9fd1383 864 if (prev.len) {
13c6df26 865 handle_filter(mi, &prev);
a9fd1383
JH
866 strbuf_reset(&prev);
867 }
13c6df26 868 if (!handle_boundary(mi, line))
3b6121f6 869 goto handle_body_out;
87ab7992
DZ
870 }
871
86747c13 872 /* Unwrap transfer encoding */
ab50e38b 873 decode_transfer_encoding(mi, line);
87ab7992 874
ab50e38b 875 switch (mi->transfer_encoding) {
87ab7992 876 case TE_BASE64:
87f1b884 877 case TE_QP:
87ab7992 878 {
3b6121f6
LS
879 struct strbuf **lines, **it, *sb;
880
881 /* Prepend any previous partial lines */
fde00d50 882 strbuf_insert(line, 0, prev.buf, prev.len);
3b6121f6 883 strbuf_reset(&prev);
87ab7992 884
9aa23094
JH
885 /*
886 * This is a decoded line that may contain
87ab7992
DZ
887 * multiple new lines. Pass only one chunk
888 * at a time to handle_filter()
889 */
fde00d50 890 lines = strbuf_split(line, '\n');
3b6121f6
LS
891 for (it = lines; (sb = *it); it++) {
892 if (*(it + 1) == NULL) /* The last line */
893 if (sb->buf[sb->len - 1] != '\n') {
894 /* Partial line, save it for later. */
895 strbuf_addbuf(&prev, sb);
896 break;
897 }
13c6df26 898 handle_filter(mi, sb);
3b6121f6 899 }
9aa23094 900 /*
3b6121f6 901 * The partial chunk is saved in "prev" and will be
9aa23094 902 * appended by the next iteration of read_line_with_nul().
87ab7992 903 */
3b6121f6 904 strbuf_list_free(lines);
d4a9ce78 905 break;
1d8fa411 906 }
87ab7992 907 default:
13c6df26 908 handle_filter(mi, line);
d4a9ce78 909 }
87ab7992 910
173aef7c 911 } while (!strbuf_getwholeline(line, mi->input, '\n'));
3b6121f6
LS
912
913handle_body_out:
914 strbuf_release(&prev);
1d8fa411
JH
915}
916
3b6121f6 917static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
d7f6bae2 918{
3b6121f6 919 const char *sp = data->buf;
d7f6bae2 920 while (1) {
3b6121f6 921 char *ep = strchr(sp, '\n');
d7f6bae2
JH
922 int len;
923 if (!ep)
3b6121f6 924 len = strlen(sp);
d7f6bae2 925 else
3b6121f6
LS
926 len = ep - sp;
927 fprintf(fout, "%s: %.*s\n", hdr, len, sp);
d7f6bae2
JH
928 if (!ep)
929 break;
3b6121f6 930 sp = ep + 1;
d7f6bae2
JH
931 }
932}
933
c69f2395 934static void handle_info(struct mailinfo *mi)
2744b234 935{
3b6121f6 936 struct strbuf *hdr;
87ab7992
DZ
937 int i;
938
939 for (i = 0; header[i]; i++) {
87ab7992 940 /* only print inbody headers if we output a patch file */
d895bf0f
JH
941 if (mi->patch_lines && mi->s_hdr_data[i])
942 hdr = mi->s_hdr_data[i];
943 else if (mi->p_hdr_data[i])
944 hdr = mi->p_hdr_data[i];
87ab7992
DZ
945 else
946 continue;
947
b1a013dd 948 if (!strcmp(header[i], "Subject")) {
849106d5
JH
949 if (!mi->keep_subject) {
950 cleanup_subject(mi, hdr);
3b6121f6 951 cleanup_space(hdr);
d7f6bae2 952 }
173aef7c 953 output_header_lines(mi->output, "Subject", hdr);
b1a013dd 954 } else if (!strcmp(header[i], "From")) {
ddfb3696 955 cleanup_space(hdr);
c69f2395 956 handle_from(mi, hdr);
173aef7c
JH
957 fprintf(mi->output, "Author: %s\n", mi->name.buf);
958 fprintf(mi->output, "Email: %s\n", mi->email.buf);
87ab7992
DZ
959 } else {
960 cleanup_space(hdr);
173aef7c 961 fprintf(mi->output, "%s: %s\n", header[i], hdr->buf);
87ab7992 962 }
d4a9ce78 963 }
173aef7c 964 fprintf(mi->output, "\n");
2744b234
LT
965}
966
173aef7c 967static int mailinfo(struct mailinfo *mi, const char *msg, const char *patch)
34488e3c 968{
05e625e5 969 FILE *cmitmsg;
f88a545a 970 int peek;
6e21b508
JH
971 struct strbuf line = STRBUF_INIT;
972
05e625e5
JH
973 cmitmsg = fopen(msg, "w");
974 if (!cmitmsg) {
34488e3c
LS
975 perror(msg);
976 return -1;
977 }
8f63588a
JH
978 mi->patchfile = fopen(patch, "w");
979 if (!mi->patchfile) {
34488e3c 980 perror(patch);
05e625e5 981 fclose(cmitmsg);
34488e3c
LS
982 return -1;
983 }
87ab7992 984
d895bf0f
JH
985 mi->p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*(mi->p_hdr_data)));
986 mi->s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*(mi->s_hdr_data)));
87ab7992 987
f88a545a 988 do {
173aef7c 989 peek = fgetc(mi->input);
f88a545a 990 } while (isspace(peek));
173aef7c 991 ungetc(peek, mi->input);
f88a545a 992
87ab7992 993 /* process the email header */
173aef7c 994 while (read_one_header_line(&line, mi->input))
d895bf0f 995 check_header(mi, &line, mi->p_hdr_data, 1);
87ab7992 996
173aef7c 997 handle_body(mi, &line);
05e625e5
JH
998 fwrite(mi->log_message.buf, 1, mi->log_message.len, cmitmsg);
999 fclose(cmitmsg);
8f63588a 1000 fclose(mi->patchfile);
e38ee06e 1001
c69f2395 1002 handle_info(mi);
6e21b508 1003 strbuf_release(&line);
34488e3c
LS
1004 return 0;
1005}
1006
ad57ef9d 1007static int git_mailinfo_config(const char *var, const char *value, void *mi_)
43485d3d 1008{
ad57ef9d
JH
1009 struct mailinfo *mi = mi_;
1010
59556548 1011 if (!starts_with(var, "mailinfo."))
ad57ef9d 1012 return git_default_config(var, value, NULL);
43485d3d 1013 if (!strcmp(var, "mailinfo.scissors")) {
ad57ef9d 1014 mi->use_scissors = git_config_bool(var, value);
43485d3d
JH
1015 return 0;
1016 }
1017 /* perhaps others here */
1018 return 0;
1019}
1020
c69f2395
JH
1021static void setup_mailinfo(struct mailinfo *mi)
1022{
1023 memset(mi, 0, sizeof(*mi));
1024 strbuf_init(&mi->name, 0);
1025 strbuf_init(&mi->email, 0);
f1e037b9 1026 strbuf_init(&mi->charset, 0);
05e625e5 1027 strbuf_init(&mi->log_message, 0);
13c6df26 1028 mi->header_stage = 1;
ad57ef9d 1029 mi->use_inbody_headers = 1;
8e919277 1030 mi->content_top = mi->content;
c69f2395
JH
1031 git_config(git_mailinfo_config, &mi);
1032}
1033
1034static void clear_mailinfo(struct mailinfo *mi)
1035{
d895bf0f
JH
1036 int i;
1037
c69f2395
JH
1038 strbuf_release(&mi->name);
1039 strbuf_release(&mi->email);
f1e037b9 1040 strbuf_release(&mi->charset);
6200b751 1041 free(mi->message_id);
d895bf0f
JH
1042
1043 for (i = 0; mi->p_hdr_data[i]; i++)
1044 strbuf_release(mi->p_hdr_data[i]);
1045 free(mi->p_hdr_data);
1046 for (i = 0; mi->s_hdr_data[i]; i++)
1047 strbuf_release(mi->s_hdr_data[i]);
1048 free(mi->s_hdr_data);
8e919277
JH
1049
1050 while (mi->content < mi->content_top) {
1051 free(*(mi->content_top));
1052 mi->content_top--;
1053 }
05e625e5
JH
1054
1055 strbuf_release(&mi->log_message);
c69f2395
JH
1056}
1057
6bff6a60 1058static const char mailinfo_usage[] =
9c9b4f2f 1059 "git mailinfo [-k | -b] [-m | --message-id] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] <msg> <patch> < mail >info";
d4a9ce78 1060
a633fca0 1061int cmd_mailinfo(int argc, const char **argv, const char *prefix)
2744b234 1062{
bb1091a4 1063 const char *def_charset;
c69f2395
JH
1064 struct mailinfo mi;
1065 int status;
bb1091a4 1066
f1f909e3
JH
1067 /* NEEDSWORK: might want to do the optional .git/ directory
1068 * discovery
1069 */
c69f2395 1070 setup_mailinfo(&mi);
f1f909e3 1071
a6fa5992 1072 def_charset = get_commit_output_encoding();
28be2d08 1073 mi.metainfo_charset = def_charset;
bb1091a4 1074
6bff6a60
JH
1075 while (1 < argc && argv[1][0] == '-') {
1076 if (!strcmp(argv[1], "-k"))
849106d5 1077 mi.keep_subject = 1;
17635fc9 1078 else if (!strcmp(argv[1], "-b"))
849106d5 1079 mi.keep_non_patch_brackets_in_subject = 1;
452dfbed 1080 else if (!strcmp(argv[1], "-m") || !strcmp(argv[1], "--message-id"))
6200b751 1081 mi.add_message_id = 1;
d4a9ce78 1082 else if (!strcmp(argv[1], "-u"))
28be2d08 1083 mi.metainfo_charset = def_charset;
bb1091a4 1084 else if (!strcmp(argv[1], "-n"))
28be2d08 1085 mi.metainfo_charset = NULL;
59556548 1086 else if (starts_with(argv[1], "--encoding="))
28be2d08 1087 mi.metainfo_charset = argv[1] + 11;
017678b4 1088 else if (!strcmp(argv[1], "--scissors"))
ad57ef9d 1089 mi.use_scissors = 1;
017678b4 1090 else if (!strcmp(argv[1], "--no-scissors"))
ad57ef9d 1091 mi.use_scissors = 0;
d25e5159 1092 else if (!strcmp(argv[1], "--no-inbody-headers"))
ad57ef9d 1093 mi.use_inbody_headers = 0;
d4a9ce78 1094 else
f1f909e3 1095 usage(mailinfo_usage);
6bff6a60
JH
1096 argc--; argv++;
1097 }
1098
a196d8d4 1099 if (argc != 3)
f1f909e3 1100 usage(mailinfo_usage);
34488e3c 1101
173aef7c
JH
1102 mi.input = stdin;
1103 mi.output = stdout;
1104 status = !!mailinfo(&mi, argv[1], argv[2]);
c69f2395
JH
1105 clear_mailinfo(&mi);
1106
1107 return status;
2744b234 1108}