4a8c704c8a255ae5e1828cb7cb61364eadaf20a1
   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
  10#define MAX_BOUNDARIES 5
  11
  12struct mailinfo {
  13        FILE *input;
  14        FILE *output;
  15        FILE *cmitmsg;
  16        FILE *patchfile;
  17
  18        struct strbuf name;
  19        struct strbuf email;
  20        int keep_subject;
  21        int keep_non_patch_brackets_in_subject;
  22        int add_message_id;
  23        int use_scissors;
  24        int use_inbody_headers;
  25        const char *metainfo_charset;
  26
  27        struct strbuf *content[MAX_BOUNDARIES];
  28        struct strbuf **content_top;
  29        struct strbuf charset;
  30        char *message_id;
  31        enum  {
  32                TE_DONTCARE, TE_QP, TE_BASE64
  33        } transfer_encoding;
  34        int patch_lines;
  35        int filter_stage; /* still reading log or are we copying patch? */
  36        int header_stage; /* still checking in-body headers? */
  37        struct strbuf **p_hdr_data;
  38        struct strbuf **s_hdr_data;
  39};
  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 void handle_content_type(struct mailinfo *mi, struct strbuf *line)
 194{
 195        struct strbuf *boundary = xmalloc(sizeof(struct strbuf));
 196        strbuf_init(boundary, line->len);
 197
 198        if (slurp_attr(line->buf, "boundary=", boundary)) {
 199                strbuf_insert(boundary, 0, "--", 2);
 200                if (++mi->content_top >= &mi->content[MAX_BOUNDARIES]) {
 201                        fprintf(stderr, "Too many boundaries to handle\n");
 202                        exit(1);
 203                }
 204                *(mi->content_top) = boundary;
 205                boundary = NULL;
 206        }
 207        slurp_attr(line->buf, "charset=", &mi->charset);
 208
 209        if (boundary) {
 210                strbuf_release(boundary);
 211                free(boundary);
 212        }
 213}
 214
 215static void handle_message_id(struct mailinfo *mi, const struct strbuf *line)
 216{
 217        if (mi->add_message_id)
 218                mi->message_id = strdup(line->buf);
 219}
 220
 221static void handle_content_transfer_encoding(struct mailinfo *mi,
 222                                             const struct strbuf *line)
 223{
 224        if (strcasestr(line->buf, "base64"))
 225                mi->transfer_encoding = TE_BASE64;
 226        else if (strcasestr(line->buf, "quoted-printable"))
 227                mi->transfer_encoding = TE_QP;
 228        else
 229                mi->transfer_encoding = TE_DONTCARE;
 230}
 231
 232static int is_multipart_boundary(struct mailinfo *mi, const struct strbuf *line)
 233{
 234        struct strbuf *content_top = *(mi->content_top);
 235
 236        return ((content_top->len <= line->len) &&
 237                !memcmp(line->buf, content_top->buf, content_top->len));
 238}
 239
 240static void cleanup_subject(struct mailinfo *mi, struct strbuf *subject)
 241{
 242        size_t at = 0;
 243
 244        while (at < subject->len) {
 245                char *pos;
 246                size_t remove;
 247
 248                switch (subject->buf[at]) {
 249                case 'r': case 'R':
 250                        if (subject->len <= at + 3)
 251                                break;
 252                        if ((subject->buf[at + 1] == 'e' ||
 253                             subject->buf[at + 1] == 'E') &&
 254                            subject->buf[at + 2] == ':') {
 255                                strbuf_remove(subject, at, 3);
 256                                continue;
 257                        }
 258                        at++;
 259                        break;
 260                case ' ': case '\t': case ':':
 261                        strbuf_remove(subject, at, 1);
 262                        continue;
 263                case '[':
 264                        pos = strchr(subject->buf + at, ']');
 265                        if (!pos)
 266                                break;
 267                        remove = pos - subject->buf + at + 1;
 268                        if (!mi->keep_non_patch_brackets_in_subject ||
 269                            (7 <= remove &&
 270                             memmem(subject->buf + at, remove, "PATCH", 5)))
 271                                strbuf_remove(subject, at, remove);
 272                        else {
 273                                at += remove;
 274                                /*
 275                                 * If the input had a space after the ], keep
 276                                 * it.  We don't bother with finding the end of
 277                                 * the space, since we later normalize it
 278                                 * anyway.
 279                                 */
 280                                if (isspace(subject->buf[at]))
 281                                        at += 1;
 282                        }
 283                        continue;
 284                }
 285                break;
 286        }
 287        strbuf_trim(subject);
 288}
 289
 290#define MAX_HDR_PARSED 10
 291static const char *header[MAX_HDR_PARSED] = {
 292        "From","Subject","Date",
 293};
 294
 295static inline int cmp_header(const struct strbuf *line, const char *hdr)
 296{
 297        int len = strlen(hdr);
 298        return !strncasecmp(line->buf, hdr, len) && line->len > len &&
 299                        line->buf[len] == ':' && isspace(line->buf[len + 1]);
 300}
 301
 302static int is_format_patch_separator(const char *line, int len)
 303{
 304        static const char SAMPLE[] =
 305                "From e6807f3efca28b30decfecb1732a56c7db1137ee Mon Sep 17 00:00:00 2001\n";
 306        const char *cp;
 307
 308        if (len != strlen(SAMPLE))
 309                return 0;
 310        if (!skip_prefix(line, "From ", &cp))
 311                return 0;
 312        if (strspn(cp, "0123456789abcdef") != 40)
 313                return 0;
 314        cp += 40;
 315        return !memcmp(SAMPLE + (cp - line), cp, strlen(SAMPLE) - (cp - line));
 316}
 317
 318static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
 319{
 320        const char *in = q_seg->buf;
 321        int c;
 322        struct strbuf *out = xmalloc(sizeof(struct strbuf));
 323        strbuf_init(out, q_seg->len);
 324
 325        while ((c = *in++) != 0) {
 326                if (c == '=') {
 327                        int d = *in++;
 328                        if (d == '\n' || !d)
 329                                break; /* drop trailing newline */
 330                        strbuf_addch(out, (hexval(d) << 4) | hexval(*in++));
 331                        continue;
 332                }
 333                if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
 334                        c = 0x20;
 335                strbuf_addch(out, c);
 336        }
 337        return out;
 338}
 339
 340static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
 341{
 342        /* Decode in..ep, possibly in-place to ot */
 343        int c, pos = 0, acc = 0;
 344        const char *in = b_seg->buf;
 345        struct strbuf *out = xmalloc(sizeof(struct strbuf));
 346        strbuf_init(out, b_seg->len);
 347
 348        while ((c = *in++) != 0) {
 349                if (c == '+')
 350                        c = 62;
 351                else if (c == '/')
 352                        c = 63;
 353                else if ('A' <= c && c <= 'Z')
 354                        c -= 'A';
 355                else if ('a' <= c && c <= 'z')
 356                        c -= 'a' - 26;
 357                else if ('0' <= c && c <= '9')
 358                        c -= '0' - 52;
 359                else
 360                        continue; /* garbage */
 361                switch (pos++) {
 362                case 0:
 363                        acc = (c << 2);
 364                        break;
 365                case 1:
 366                        strbuf_addch(out, (acc | (c >> 4)));
 367                        acc = (c & 15) << 4;
 368                        break;
 369                case 2:
 370                        strbuf_addch(out, (acc | (c >> 2)));
 371                        acc = (c & 3) << 6;
 372                        break;
 373                case 3:
 374                        strbuf_addch(out, (acc | c));
 375                        acc = pos = 0;
 376                        break;
 377                }
 378        }
 379        return out;
 380}
 381
 382static void convert_to_utf8(struct mailinfo *mi,
 383                            struct strbuf *line, const char *charset)
 384{
 385        char *out;
 386
 387        if (!mi->metainfo_charset || !charset || !*charset)
 388                return;
 389
 390        if (same_encoding(mi->metainfo_charset, charset))
 391                return;
 392        out = reencode_string(line->buf, mi->metainfo_charset, charset);
 393        if (!out)
 394                die("cannot convert from %s to %s",
 395                    charset, mi->metainfo_charset);
 396        strbuf_attach(line, out, strlen(out), strlen(out));
 397}
 398
 399static void decode_header(struct mailinfo *mi, 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                convert_to_utf8(mi, dec, charset_q.buf);
 463
 464                strbuf_addbuf(&outbuf, dec);
 465                strbuf_release(dec);
 466                free(dec);
 467                in = ep + 2;
 468        }
 469        strbuf_addstr(&outbuf, in);
 470        strbuf_reset(it);
 471        strbuf_addbuf(it, &outbuf);
 472release_return:
 473        strbuf_release(&outbuf);
 474        strbuf_release(&charset_q);
 475        strbuf_release(&piecebuf);
 476}
 477
 478static int check_header(struct mailinfo *mi,
 479                        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
 485        /* search for the interesting parts */
 486        for (i = 0; header[i]; i++) {
 487                int len = strlen(header[i]);
 488                if ((!hdr_data[i] || overwrite) && cmp_header(line, header[i])) {
 489                        /* Unwrap inline B and Q encoding, and optionally
 490                         * normalize the meta information to utf8.
 491                         */
 492                        strbuf_add(&sb, line->buf + len + 2, line->len - len - 2);
 493                        decode_header(mi, &sb);
 494                        handle_header(&hdr_data[i], &sb);
 495                        ret = 1;
 496                        goto check_header_out;
 497                }
 498        }
 499
 500        /* Content stuff */
 501        if (cmp_header(line, "Content-Type")) {
 502                len = strlen("Content-Type: ");
 503                strbuf_add(&sb, line->buf + len, line->len - len);
 504                decode_header(mi, &sb);
 505                strbuf_insert(&sb, 0, "Content-Type: ", len);
 506                handle_content_type(mi, &sb);
 507                ret = 1;
 508                goto check_header_out;
 509        }
 510        if (cmp_header(line, "Content-Transfer-Encoding")) {
 511                len = strlen("Content-Transfer-Encoding: ");
 512                strbuf_add(&sb, line->buf + len, line->len - len);
 513                decode_header(mi, &sb);
 514                handle_content_transfer_encoding(mi, &sb);
 515                ret = 1;
 516                goto check_header_out;
 517        }
 518        if (cmp_header(line, "Message-Id")) {
 519                len = strlen("Message-Id: ");
 520                strbuf_add(&sb, line->buf + len, line->len - len);
 521                decode_header(mi, &sb);
 522                handle_message_id(mi, &sb);
 523                ret = 1;
 524                goto check_header_out;
 525        }
 526
 527        /* for inbody stuff */
 528        if (starts_with(line->buf, ">From") && isspace(line->buf[5])) {
 529                ret = is_format_patch_separator(line->buf + 1, line->len - 1);
 530                goto check_header_out;
 531        }
 532        if (starts_with(line->buf, "[PATCH]") && isspace(line->buf[7])) {
 533                for (i = 0; header[i]; i++) {
 534                        if (!strcmp("Subject", header[i])) {
 535                                handle_header(&hdr_data[i], line);
 536                                ret = 1;
 537                                goto check_header_out;
 538                        }
 539                }
 540        }
 541
 542check_header_out:
 543        strbuf_release(&sb);
 544        return ret;
 545}
 546
 547static void decode_transfer_encoding(struct mailinfo *mi, struct strbuf *line)
 548{
 549        struct strbuf *ret;
 550
 551        switch (mi->transfer_encoding) {
 552        case TE_QP:
 553                ret = decode_q_segment(line, 0);
 554                break;
 555        case TE_BASE64:
 556                ret = decode_b_segment(line);
 557                break;
 558        case TE_DONTCARE:
 559        default:
 560                return;
 561        }
 562        strbuf_reset(line);
 563        strbuf_addbuf(line, ret);
 564        strbuf_release(ret);
 565        free(ret);
 566}
 567
 568static inline int patchbreak(const struct strbuf *line)
 569{
 570        size_t i;
 571
 572        /* Beginning of a "diff -" header? */
 573        if (starts_with(line->buf, "diff -"))
 574                return 1;
 575
 576        /* CVS "Index: " line? */
 577        if (starts_with(line->buf, "Index: "))
 578                return 1;
 579
 580        /*
 581         * "--- <filename>" starts patches without headers
 582         * "---<sp>*" is a manual separator
 583         */
 584        if (line->len < 4)
 585                return 0;
 586
 587        if (starts_with(line->buf, "---")) {
 588                /* space followed by a filename? */
 589                if (line->buf[3] == ' ' && !isspace(line->buf[4]))
 590                        return 1;
 591                /* Just whitespace? */
 592                for (i = 3; i < line->len; i++) {
 593                        unsigned char c = line->buf[i];
 594                        if (c == '\n')
 595                                return 1;
 596                        if (!isspace(c))
 597                                break;
 598                }
 599                return 0;
 600        }
 601        return 0;
 602}
 603
 604static int is_scissors_line(const struct strbuf *line)
 605{
 606        size_t i, len = line->len;
 607        int scissors = 0, gap = 0;
 608        int first_nonblank = -1;
 609        int last_nonblank = 0, visible, perforation = 0, in_perforation = 0;
 610        const char *buf = line->buf;
 611
 612        for (i = 0; i < len; i++) {
 613                if (isspace(buf[i])) {
 614                        if (in_perforation) {
 615                                perforation++;
 616                                gap++;
 617                        }
 618                        continue;
 619                }
 620                last_nonblank = i;
 621                if (first_nonblank < 0)
 622                        first_nonblank = i;
 623                if (buf[i] == '-') {
 624                        in_perforation = 1;
 625                        perforation++;
 626                        continue;
 627                }
 628                if (i + 1 < len &&
 629                    (!memcmp(buf + i, ">8", 2) || !memcmp(buf + i, "8<", 2) ||
 630                     !memcmp(buf + i, ">%", 2) || !memcmp(buf + i, "%<", 2))) {
 631                        in_perforation = 1;
 632                        perforation += 2;
 633                        scissors += 2;
 634                        i++;
 635                        continue;
 636                }
 637                in_perforation = 0;
 638        }
 639
 640        /*
 641         * The mark must be at least 8 bytes long (e.g. "-- >8 --").
 642         * Even though there can be arbitrary cruft on the same line
 643         * (e.g. "cut here"), in order to avoid misidentification, the
 644         * perforation must occupy more than a third of the visible
 645         * width of the line, and dashes and scissors must occupy more
 646         * than half of the perforation.
 647         */
 648
 649        visible = last_nonblank - first_nonblank + 1;
 650        return (scissors && 8 <= visible &&
 651                visible < perforation * 3 &&
 652                gap * 2 < perforation);
 653}
 654
 655static int handle_commit_msg(struct mailinfo *mi, struct strbuf *line)
 656{
 657        assert(!mi->filter_stage);
 658
 659        if (mi->header_stage) {
 660                if (!line->len || (line->len == 1 && line->buf[0] == '\n'))
 661                        return 0;
 662        }
 663
 664        if (mi->use_inbody_headers && mi->header_stage) {
 665                mi->header_stage = check_header(mi, line, mi->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        convert_to_utf8(mi, line, mi->charset.buf);
 676
 677        if (mi->use_scissors && is_scissors_line(line)) {
 678                int i;
 679                if (fseek(mi->cmitmsg, 0L, SEEK_SET))
 680                        die_errno("Could not rewind output message file");
 681                if (ftruncate(fileno(mi->cmitmsg), 0))
 682                        die_errno("Could not truncate output message file at scissors");
 683                mi->header_stage = 1;
 684
 685                /*
 686                 * We may have already read "secondary headers"; purge
 687                 * them to give ourselves a clean restart.
 688                 */
 689                for (i = 0; header[i]; i++) {
 690                        if (mi->s_hdr_data[i])
 691                                strbuf_release(mi->s_hdr_data[i]);
 692                        mi->s_hdr_data[i] = NULL;
 693                }
 694                return 0;
 695        }
 696
 697        if (patchbreak(line)) {
 698                if (mi->message_id)
 699                        fprintf(mi->cmitmsg, "Message-Id: %s\n", mi->message_id);
 700                fclose(mi->cmitmsg);
 701                mi->cmitmsg = NULL;
 702                return 1;
 703        }
 704
 705        fputs(line->buf, mi->cmitmsg);
 706        return 0;
 707}
 708
 709static void handle_patch(struct mailinfo *mi, const struct strbuf *line)
 710{
 711        fwrite(line->buf, 1, line->len, mi->patchfile);
 712        mi->patch_lines++;
 713}
 714
 715static void handle_filter(struct mailinfo *mi, struct strbuf *line)
 716{
 717        switch (mi->filter_stage) {
 718        case 0:
 719                if (!handle_commit_msg(mi, line))
 720                        break;
 721                mi->filter_stage++;
 722        case 1:
 723                handle_patch(mi, line);
 724                break;
 725        }
 726}
 727
 728static int is_rfc2822_header(const struct strbuf *line)
 729{
 730        /*
 731         * The section that defines the loosest possible
 732         * field name is "3.6.8 Optional fields".
 733         *
 734         * optional-field = field-name ":" unstructured CRLF
 735         * field-name = 1*ftext
 736         * ftext = %d33-57 / %59-126
 737         */
 738        int ch;
 739        char *cp = line->buf;
 740
 741        /* Count mbox From headers as headers */
 742        if (starts_with(cp, "From ") || starts_with(cp, ">From "))
 743                return 1;
 744
 745        while ((ch = *cp++)) {
 746                if (ch == ':')
 747                        return 1;
 748                if ((33 <= ch && ch <= 57) ||
 749                    (59 <= ch && ch <= 126))
 750                        continue;
 751                break;
 752        }
 753        return 0;
 754}
 755
 756static int read_one_header_line(struct strbuf *line, FILE *in)
 757{
 758        struct strbuf continuation = STRBUF_INIT;
 759
 760        /* Get the first part of the line. */
 761        if (strbuf_getline(line, in, '\n'))
 762                return 0;
 763
 764        /*
 765         * Is it an empty line or not a valid rfc2822 header?
 766         * If so, stop here, and return false ("not a header")
 767         */
 768        strbuf_rtrim(line);
 769        if (!line->len || !is_rfc2822_header(line)) {
 770                /* Re-add the newline */
 771                strbuf_addch(line, '\n');
 772                return 0;
 773        }
 774
 775        /*
 776         * Now we need to eat all the continuation lines..
 777         * Yuck, 2822 header "folding"
 778         */
 779        for (;;) {
 780                int peek;
 781
 782                peek = fgetc(in); ungetc(peek, in);
 783                if (peek != ' ' && peek != '\t')
 784                        break;
 785                if (strbuf_getline(&continuation, in, '\n'))
 786                        break;
 787                continuation.buf[0] = ' ';
 788                strbuf_rtrim(&continuation);
 789                strbuf_addbuf(line, &continuation);
 790        }
 791        strbuf_release(&continuation);
 792
 793        return 1;
 794}
 795
 796static int find_boundary(struct mailinfo *mi, struct strbuf *line)
 797{
 798        while (!strbuf_getline(line, mi->input, '\n')) {
 799                if (*(mi->content_top) && is_multipart_boundary(mi, line))
 800                        return 1;
 801        }
 802        return 0;
 803}
 804
 805static int handle_boundary(struct mailinfo *mi, struct strbuf *line)
 806{
 807        struct strbuf newline = STRBUF_INIT;
 808
 809        strbuf_addch(&newline, '\n');
 810again:
 811        if (line->len >= (*(mi->content_top))->len + 2 &&
 812            !memcmp(line->buf + (*(mi->content_top))->len, "--", 2)) {
 813                /* we hit an end boundary */
 814                /* pop the current boundary off the stack */
 815                strbuf_release(*(mi->content_top));
 816                free(*(mi->content_top));
 817                *(mi->content_top) = NULL;
 818
 819                /* technically won't happen as is_multipart_boundary()
 820                   will fail first.  But just in case..
 821                 */
 822                if (--mi->content_top < mi->content) {
 823                        fprintf(stderr, "Detected mismatched boundaries, "
 824                                        "can't recover\n");
 825                        exit(1);
 826                }
 827                handle_filter(mi, &newline);
 828                strbuf_release(&newline);
 829
 830                /* skip to the next boundary */
 831                if (!find_boundary(mi, line))
 832                        return 0;
 833                goto again;
 834        }
 835
 836        /* set some defaults */
 837        mi->transfer_encoding = TE_DONTCARE;
 838        strbuf_reset(&mi->charset);
 839
 840        /* slurp in this section's info */
 841        while (read_one_header_line(line, mi->input))
 842                check_header(mi, line, mi->p_hdr_data, 0);
 843
 844        strbuf_release(&newline);
 845        /* replenish line */
 846        if (strbuf_getline(line, mi->input, '\n'))
 847                return 0;
 848        strbuf_addch(line, '\n');
 849        return 1;
 850}
 851
 852static void handle_body(struct mailinfo *mi, struct strbuf *line)
 853{
 854        struct strbuf prev = STRBUF_INIT;
 855
 856        /* Skip up to the first boundary */
 857        if (*(mi->content_top)) {
 858                if (!find_boundary(mi, line))
 859                        goto handle_body_out;
 860        }
 861
 862        do {
 863                /* process any boundary lines */
 864                if (*(mi->content_top) && is_multipart_boundary(mi, line)) {
 865                        /* flush any leftover */
 866                        if (prev.len) {
 867                                handle_filter(mi, &prev);
 868                                strbuf_reset(&prev);
 869                        }
 870                        if (!handle_boundary(mi, line))
 871                                goto handle_body_out;
 872                }
 873
 874                /* Unwrap transfer encoding */
 875                decode_transfer_encoding(mi, line);
 876
 877                switch (mi->transfer_encoding) {
 878                case TE_BASE64:
 879                case TE_QP:
 880                {
 881                        struct strbuf **lines, **it, *sb;
 882
 883                        /* Prepend any previous partial lines */
 884                        strbuf_insert(line, 0, prev.buf, prev.len);
 885                        strbuf_reset(&prev);
 886
 887                        /*
 888                         * This is a decoded line that may contain
 889                         * multiple new lines.  Pass only one chunk
 890                         * at a time to handle_filter()
 891                         */
 892                        lines = strbuf_split(line, '\n');
 893                        for (it = lines; (sb = *it); it++) {
 894                                if (*(it + 1) == NULL) /* The last line */
 895                                        if (sb->buf[sb->len - 1] != '\n') {
 896                                                /* Partial line, save it for later. */
 897                                                strbuf_addbuf(&prev, sb);
 898                                                break;
 899                                        }
 900                                handle_filter(mi, sb);
 901                        }
 902                        /*
 903                         * The partial chunk is saved in "prev" and will be
 904                         * appended by the next iteration of read_line_with_nul().
 905                         */
 906                        strbuf_list_free(lines);
 907                        break;
 908                }
 909                default:
 910                        handle_filter(mi, line);
 911                }
 912
 913        } while (!strbuf_getwholeline(line, mi->input, '\n'));
 914
 915handle_body_out:
 916        strbuf_release(&prev);
 917}
 918
 919static void output_header_lines(FILE *fout, const char *hdr, const struct strbuf *data)
 920{
 921        const char *sp = data->buf;
 922        while (1) {
 923                char *ep = strchr(sp, '\n');
 924                int len;
 925                if (!ep)
 926                        len = strlen(sp);
 927                else
 928                        len = ep - sp;
 929                fprintf(fout, "%s: %.*s\n", hdr, len, sp);
 930                if (!ep)
 931                        break;
 932                sp = ep + 1;
 933        }
 934}
 935
 936static void handle_info(struct mailinfo *mi)
 937{
 938        struct strbuf *hdr;
 939        int i;
 940
 941        for (i = 0; header[i]; i++) {
 942                /* only print inbody headers if we output a patch file */
 943                if (mi->patch_lines && mi->s_hdr_data[i])
 944                        hdr = mi->s_hdr_data[i];
 945                else if (mi->p_hdr_data[i])
 946                        hdr = mi->p_hdr_data[i];
 947                else
 948                        continue;
 949
 950                if (!strcmp(header[i], "Subject")) {
 951                        if (!mi->keep_subject) {
 952                                cleanup_subject(mi, hdr);
 953                                cleanup_space(hdr);
 954                        }
 955                        output_header_lines(mi->output, "Subject", hdr);
 956                } else if (!strcmp(header[i], "From")) {
 957                        cleanup_space(hdr);
 958                        handle_from(mi, hdr);
 959                        fprintf(mi->output, "Author: %s\n", mi->name.buf);
 960                        fprintf(mi->output, "Email: %s\n", mi->email.buf);
 961                } else {
 962                        cleanup_space(hdr);
 963                        fprintf(mi->output, "%s: %s\n", header[i], hdr->buf);
 964                }
 965        }
 966        fprintf(mi->output, "\n");
 967}
 968
 969static int mailinfo(struct mailinfo *mi, const char *msg, const char *patch)
 970{
 971        int peek;
 972        struct strbuf line = STRBUF_INIT;
 973
 974        mi->cmitmsg = fopen(msg, "w");
 975        if (!mi->cmitmsg) {
 976                perror(msg);
 977                return -1;
 978        }
 979        mi->patchfile = fopen(patch, "w");
 980        if (!mi->patchfile) {
 981                perror(patch);
 982                fclose(mi->cmitmsg);
 983                return -1;
 984        }
 985
 986        mi->p_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*(mi->p_hdr_data)));
 987        mi->s_hdr_data = xcalloc(MAX_HDR_PARSED, sizeof(*(mi->s_hdr_data)));
 988
 989        do {
 990                peek = fgetc(mi->input);
 991        } while (isspace(peek));
 992        ungetc(peek, mi->input);
 993
 994        /* process the email header */
 995        while (read_one_header_line(&line, mi->input))
 996                check_header(mi, &line, mi->p_hdr_data, 1);
 997
 998        handle_body(mi, &line);
 999        fclose(mi->patchfile);
1000
1001        handle_info(mi);
1002        strbuf_release(&line);
1003        return 0;
1004}
1005
1006static int git_mailinfo_config(const char *var, const char *value, void *mi_)
1007{
1008        struct mailinfo *mi = mi_;
1009
1010        if (!starts_with(var, "mailinfo."))
1011                return git_default_config(var, value, NULL);
1012        if (!strcmp(var, "mailinfo.scissors")) {
1013                mi->use_scissors = git_config_bool(var, value);
1014                return 0;
1015        }
1016        /* perhaps others here */
1017        return 0;
1018}
1019
1020static void setup_mailinfo(struct mailinfo *mi)
1021{
1022        memset(mi, 0, sizeof(*mi));
1023        strbuf_init(&mi->name, 0);
1024        strbuf_init(&mi->email, 0);
1025        strbuf_init(&mi->charset, 0);
1026        mi->header_stage = 1;
1027        mi->use_inbody_headers = 1;
1028        mi->content_top = mi->content;
1029        git_config(git_mailinfo_config, &mi);
1030}
1031
1032static void clear_mailinfo(struct mailinfo *mi)
1033{
1034        int i;
1035
1036        strbuf_release(&mi->name);
1037        strbuf_release(&mi->email);
1038        strbuf_release(&mi->charset);
1039        free(mi->message_id);
1040
1041        for (i = 0; mi->p_hdr_data[i]; i++)
1042                strbuf_release(mi->p_hdr_data[i]);
1043        free(mi->p_hdr_data);
1044        for (i = 0; mi->s_hdr_data[i]; i++)
1045                strbuf_release(mi->s_hdr_data[i]);
1046        free(mi->s_hdr_data);
1047
1048        while (mi->content < mi->content_top) {
1049                free(*(mi->content_top));
1050                mi->content_top--;
1051        }
1052}
1053
1054static const char mailinfo_usage[] =
1055        "git mailinfo [-k | -b] [-m | --message-id] [-u | --encoding=<encoding> | -n] [--scissors | --no-scissors] <msg> <patch> < mail >info";
1056
1057int cmd_mailinfo(int argc, const char **argv, const char *prefix)
1058{
1059        const char *def_charset;
1060        struct mailinfo mi;
1061        int status;
1062
1063        /* NEEDSWORK: might want to do the optional .git/ directory
1064         * discovery
1065         */
1066        setup_mailinfo(&mi);
1067
1068        def_charset = get_commit_output_encoding();
1069        mi.metainfo_charset = def_charset;
1070
1071        while (1 < argc && argv[1][0] == '-') {
1072                if (!strcmp(argv[1], "-k"))
1073                        mi.keep_subject = 1;
1074                else if (!strcmp(argv[1], "-b"))
1075                        mi.keep_non_patch_brackets_in_subject = 1;
1076                else if (!strcmp(argv[1], "-m") || !strcmp(argv[1], "--message-id"))
1077                        mi.add_message_id = 1;
1078                else if (!strcmp(argv[1], "-u"))
1079                        mi.metainfo_charset = def_charset;
1080                else if (!strcmp(argv[1], "-n"))
1081                        mi.metainfo_charset = NULL;
1082                else if (starts_with(argv[1], "--encoding="))
1083                        mi.metainfo_charset = argv[1] + 11;
1084                else if (!strcmp(argv[1], "--scissors"))
1085                        mi.use_scissors = 1;
1086                else if (!strcmp(argv[1], "--no-scissors"))
1087                        mi.use_scissors = 0;
1088                else if (!strcmp(argv[1], "--no-inbody-headers"))
1089                        mi.use_inbody_headers = 0;
1090                else
1091                        usage(mailinfo_usage);
1092                argc--; argv++;
1093        }
1094
1095        if (argc != 3)
1096                usage(mailinfo_usage);
1097
1098        mi.input = stdin;
1099        mi.output = stdout;
1100        status = !!mailinfo(&mi, argv[1], argv[2]);
1101        clear_mailinfo(&mi);
1102
1103        return status;
1104}