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