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