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