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