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