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