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