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