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