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