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