a2b15e2624702c90bd05d5a457df4c03694020c3
   1/*
   2 * Another stupid program, this one parsing the headers of an
   3 * email to figure out authorship and subject
   4 */
   5#define _GNU_SOURCE
   6#include <stdio.h>
   7#include <stdlib.h>
   8#include <string.h>
   9#include <ctype.h>
  10#ifndef NO_ICONV
  11#include <iconv.h>
  12#endif
  13#include "git-compat-util.h"
  14#include "cache.h"
  15
  16static FILE *cmitmsg, *patchfile;
  17
  18static int keep_subject = 0;
  19static char *metainfo_charset = NULL;
  20static char line[1000];
  21static char date[1000];
  22static char name[1000];
  23static char email[1000];
  24static char subject[1000];
  25
  26static enum  {
  27        TE_DONTCARE, TE_QP, TE_BASE64,
  28} transfer_encoding;
  29static char charset[256];
  30
  31static char multipart_boundary[1000];
  32static int multipart_boundary_len;
  33static int patch_lines = 0;
  34
  35static char *sanity_check(char *name, char *email)
  36{
  37        int len = strlen(name);
  38        if (len < 3 || len > 60)
  39                return email;
  40        if (strchr(name, '@') || strchr(name, '<') || strchr(name, '>'))
  41                return email;
  42        return name;
  43}
  44
  45static int bogus_from(char *line)
  46{
  47        /* John Doe <johndoe> */
  48        char *bra, *ket, *dst, *cp;
  49
  50        /* This is fallback, so do not bother if we already have an
  51         * e-mail address.
  52         */ 
  53        if (*email)
  54                return 0;
  55
  56        bra = strchr(line, '<');
  57        if (!bra)
  58                return 0;
  59        ket = strchr(bra, '>');
  60        if (!ket)
  61                return 0;
  62
  63        for (dst = email, cp = bra+1; cp < ket; )
  64                *dst++ = *cp++;
  65        *dst = 0;
  66        for (cp = line; isspace(*cp); cp++)
  67                ;
  68        for (bra--; isspace(*bra); bra--)
  69                *bra = 0;
  70        cp = sanity_check(cp, email);
  71        strcpy(name, cp);
  72        return 1;
  73}
  74
  75static int handle_from(char *line)
  76{
  77        char *at = strchr(line, '@');
  78        char *dst;
  79
  80        if (!at)
  81                return bogus_from(line);
  82
  83        /*
  84         * If we already have one email, don't take any confusing lines
  85         */
  86        if (*email && strchr(at+1, '@'))
  87                return 0;
  88
  89        /* Pick up the string around '@', possibly delimited with <>
  90         * pair; that is the email part.  White them out while copying.
  91         */
  92        while (at > line) {
  93                char c = at[-1];
  94                if (isspace(c))
  95                        break;
  96                if (c == '<') {
  97                        at[-1] = ' ';
  98                        break;
  99                }
 100                at--;
 101        }
 102        dst = email;
 103        for (;;) {
 104                unsigned char c = *at;
 105                if (!c || c == '>' || isspace(c)) {
 106                        if (c == '>')
 107                                *at = ' ';
 108                        break;
 109                }
 110                *at++ = ' ';
 111                *dst++ = c;
 112        }
 113        *dst++ = 0;
 114
 115        /* The remainder is name.  It could be "John Doe <john.doe@xz>"
 116         * or "john.doe@xz (John Doe)", but we have whited out the
 117         * email part, so trim from both ends, possibly removing
 118         * the () pair at the end.
 119         */
 120        at = line + strlen(line);
 121        while (at > line) {
 122                unsigned char c = *--at;
 123                if (!isspace(c)) {
 124                        at[(c == ')') ? 0 : 1] = 0;
 125                        break;
 126                }
 127        }
 128
 129        at = line;
 130        for (;;) {
 131                unsigned char c = *at;
 132                if (!c || !isspace(c)) {
 133                        if (c == '(')
 134                                at++;
 135                        break;
 136                }
 137                at++;
 138        }
 139        at = sanity_check(at, email);
 140        strcpy(name, at);
 141        return 1;
 142}
 143
 144static int handle_date(char *line)
 145{
 146        strcpy(date, line);
 147        return 0;
 148}
 149
 150static int handle_subject(char *line)
 151{
 152        strcpy(subject, line);
 153        return 0;
 154}
 155
 156/* NOTE NOTE NOTE.  We do not claim we do full MIME.  We just attempt
 157 * to have enough heuristics to grok MIME encoded patches often found
 158 * on our mailing lists.  For example, we do not even treat header lines
 159 * case insensitively.
 160 */
 161
 162static int slurp_attr(const char *line, const char *name, char *attr)
 163{
 164        char *ends, *ap = strcasestr(line, name);
 165        size_t sz;
 166
 167        if (!ap) {
 168                *attr = 0;
 169                return 0;
 170        }
 171        ap += strlen(name);
 172        if (*ap == '"') {
 173                ap++;
 174                ends = "\"";
 175        }
 176        else
 177                ends = "; \t";
 178        sz = strcspn(ap, ends);
 179        memcpy(attr, ap, sz);
 180        attr[sz] = 0;
 181        return 1;
 182}
 183
 184static int handle_subcontent_type(char *line)
 185{
 186        /* We do not want to mess with boundary.  Note that we do not
 187         * handle nested multipart.
 188         */
 189        if (strcasestr(line, "boundary=")) {
 190                fprintf(stderr, "Not handling nested multipart message.\n");
 191                exit(1);
 192        }
 193        slurp_attr(line, "charset=", charset);
 194        if (*charset) {
 195                int i, c;
 196                for (i = 0; (c = charset[i]) != 0; i++)
 197                        charset[i] = tolower(c);
 198        }
 199        return 0;
 200}
 201
 202static int handle_content_type(char *line)
 203{
 204        *multipart_boundary = 0;
 205        if (slurp_attr(line, "boundary=", multipart_boundary + 2)) {
 206                memcpy(multipart_boundary, "--", 2);
 207                multipart_boundary_len = strlen(multipart_boundary);
 208        }
 209        slurp_attr(line, "charset=", charset);
 210        return 0;
 211}
 212
 213static int handle_content_transfer_encoding(char *line)
 214{
 215        if (strcasestr(line, "base64"))
 216                transfer_encoding = TE_BASE64;
 217        else if (strcasestr(line, "quoted-printable"))
 218                transfer_encoding = TE_QP;
 219        else
 220                transfer_encoding = TE_DONTCARE;
 221        return 0;
 222}
 223
 224static int is_multipart_boundary(const char *line)
 225{
 226        return (!memcmp(line, multipart_boundary, multipart_boundary_len));
 227}
 228
 229static int eatspace(char *line)
 230{
 231        int len = strlen(line);
 232        while (len > 0 && isspace(line[len-1]))
 233                line[--len] = 0;
 234        return len;
 235}
 236
 237#define SEEN_FROM 01
 238#define SEEN_DATE 02
 239#define SEEN_SUBJECT 04
 240#define SEEN_PREFIX  0x08
 241
 242/* First lines of body can have From:, Date:, and Subject: */
 243static void handle_inbody_header(int *seen, char *line)
 244{
 245        if (*seen & SEEN_PREFIX)
 246                return;
 247        if (!memcmp("From:", line, 5) && isspace(line[5])) {
 248                if (!(*seen & SEEN_FROM) && handle_from(line+6)) {
 249                        *seen |= SEEN_FROM;
 250                        return;
 251                }
 252        }
 253        if (!memcmp("Date:", line, 5) && isspace(line[5])) {
 254                if (!(*seen & SEEN_DATE)) {
 255                        handle_date(line+6);
 256                        *seen |= SEEN_DATE;
 257                        return;
 258                }
 259        }
 260        if (!memcmp("Subject:", line, 8) && isspace(line[8])) {
 261                if (!(*seen & SEEN_SUBJECT)) {
 262                        handle_subject(line+9);
 263                        *seen |= SEEN_SUBJECT;
 264                        return;
 265                }
 266        }
 267        if (!memcmp("[PATCH]", line, 7) && isspace(line[7])) {
 268                if (!(*seen & SEEN_SUBJECT)) {
 269                        handle_subject(line);
 270                        *seen |= SEEN_SUBJECT;
 271                        return;
 272                }
 273        }
 274        *seen |= SEEN_PREFIX;
 275}
 276
 277static char *cleanup_subject(char *subject)
 278{
 279        if (keep_subject)
 280                return subject;
 281        for (;;) {
 282                char *p;
 283                int len, remove;
 284                switch (*subject) {
 285                case 'r': case 'R':
 286                        if (!memcmp("e:", subject+1, 2)) {
 287                                subject +=3;
 288                                continue;
 289                        }
 290                        break;
 291                case ' ': case '\t': case ':':
 292                        subject++;
 293                        continue;
 294
 295                case '[':
 296                        p = strchr(subject, ']');
 297                        if (!p) {
 298                                subject++;
 299                                continue;
 300                        }
 301                        len = strlen(p);
 302                        remove = p - subject;
 303                        if (remove <= len *2) {
 304                                subject = p+1;
 305                                continue;
 306                        }       
 307                        break;
 308                }
 309                return subject;
 310        }
 311}                       
 312
 313static void cleanup_space(char *buf)
 314{
 315        unsigned char c;
 316        while ((c = *buf) != 0) {
 317                buf++;
 318                if (isspace(c)) {
 319                        buf[-1] = ' ';
 320                        c = *buf;
 321                        while (isspace(c)) {
 322                                int len = strlen(buf);
 323                                memmove(buf, buf+1, len);
 324                                c = *buf;
 325                        }
 326                }
 327        }
 328}
 329
 330static void decode_header_bq(char *it);
 331typedef int (*header_fn_t)(char *);
 332struct header_def {
 333        const char *name;
 334        header_fn_t func;
 335        int namelen;
 336};
 337
 338static void check_header(char *line, struct header_def *header)
 339{
 340        int i;
 341
 342        if (header[0].namelen <= 0) {
 343                for (i = 0; header[i].name; i++)
 344                        header[i].namelen = strlen(header[i].name);
 345        }
 346        for (i = 0; header[i].name; i++) {
 347                int len = header[i].namelen;
 348                if (!strncasecmp(line, header[i].name, len) &&
 349                    line[len] == ':' && isspace(line[len + 1])) {
 350                        /* Unwrap inline B and Q encoding, and optionally
 351                         * normalize the meta information to utf8.
 352                         */
 353                        decode_header_bq(line + len + 2);
 354                        header[i].func(line + len + 2);
 355                        break;
 356                }
 357        }
 358}
 359
 360static void check_subheader_line(char *line)
 361{
 362        static struct header_def header[] = {
 363                { "Content-Type", handle_subcontent_type },
 364                { "Content-Transfer-Encoding",
 365                  handle_content_transfer_encoding },
 366                { NULL },
 367        };
 368        check_header(line, header);
 369}
 370static void check_header_line(char *line)
 371{
 372        static struct header_def header[] = {
 373                { "From", handle_from },
 374                { "Date", handle_date },
 375                { "Subject", handle_subject },
 376                { "Content-Type", handle_content_type },
 377                { "Content-Transfer-Encoding",
 378                  handle_content_transfer_encoding },
 379                { NULL },
 380        };
 381        check_header(line, header);
 382}
 383
 384static int read_one_header_line(char *line, int sz, FILE *in)
 385{
 386        int ofs = 0;
 387        while (ofs < sz) {
 388                const char *colon;
 389                int peek, len;
 390                if (fgets(line + ofs, sz - ofs, in) == NULL)
 391                        break;
 392                len = eatspace(line + ofs);
 393                if (len == 0)
 394                        break;
 395                colon = strchr(line, ':');
 396                if (!colon || !isspace(colon[1])) {
 397                        /* Re-add the newline */
 398                        line[ofs + len] = '\n';
 399                        line[ofs + len + 1] = '\0';
 400                        break;
 401                }
 402                ofs += len;
 403                /* Yuck, 2822 header "folding" */
 404                peek = fgetc(in); ungetc(peek, in);
 405                if (peek != ' ' && peek != '\t')
 406                        break;
 407        }
 408        /* Count mbox From headers as headers */
 409        if (!ofs && !memcmp(line, "From ", 5))
 410                ofs = 1;
 411        return ofs;
 412}
 413
 414static unsigned hexval(int c)
 415{
 416        if (c >= '0' && c <= '9')
 417                return c - '0';
 418        if (c >= 'a' && c <= 'f')
 419                return c - 'a' + 10;
 420        if (c >= 'A' && c <= 'F')
 421                return c - 'A' + 10;
 422        return ~0;
 423}
 424
 425static int decode_q_segment(char *in, char *ot, char *ep, int rfc2047)
 426{
 427        int c;
 428        while ((c = *in++) != 0 && (in <= ep)) {
 429                if (c == '=') {
 430                        int d = *in++;
 431                        if (d == '\n' || !d)
 432                                break; /* drop trailing newline */
 433                        *ot++ = ((hexval(d) << 4) | hexval(*in++));
 434                        continue;
 435                }
 436                if (rfc2047 && c == '_') /* rfc2047 4.2 (2) */
 437                        c = 0x20;
 438                *ot++ = c;
 439        }
 440        *ot = 0;
 441        return 0;
 442}
 443
 444static int decode_b_segment(char *in, char *ot, char *ep)
 445{
 446        /* Decode in..ep, possibly in-place to ot */
 447        int c, pos = 0, acc = 0;
 448
 449        while ((c = *in++) != 0 && (in <= ep)) {
 450                if (c == '+')
 451                        c = 62;
 452                else if (c == '/')
 453                        c = 63;
 454                else if ('A' <= c && c <= 'Z')
 455                        c -= 'A';
 456                else if ('a' <= c && c <= 'z')
 457                        c -= 'a' - 26;
 458                else if ('0' <= c && c <= '9')
 459                        c -= '0' - 52;
 460                else if (c == '=') {
 461                        /* padding is almost like (c == 0), except we do
 462                         * not output NUL resulting only from it;
 463                         * for now we just trust the data.
 464                         */
 465                        c = 0;
 466                }
 467                else
 468                        continue; /* garbage */
 469                switch (pos++) {
 470                case 0:
 471                        acc = (c << 2);
 472                        break;
 473                case 1:
 474                        *ot++ = (acc | (c >> 4));
 475                        acc = (c & 15) << 4;
 476                        break;
 477                case 2:
 478                        *ot++ = (acc | (c >> 2));
 479                        acc = (c & 3) << 6;
 480                        break;
 481                case 3:
 482                        *ot++ = (acc | c);
 483                        acc = pos = 0;
 484                        break;
 485                }
 486        }
 487        *ot = 0;
 488        return 0;
 489}
 490
 491static void convert_to_utf8(char *line, char *charset)
 492{
 493#ifndef NO_ICONV
 494        char *in, *out;
 495        size_t insize, outsize, nrc;
 496        char outbuf[4096]; /* cheat */
 497        static char latin_one[] = "latin1";
 498        char *input_charset = *charset ? charset : latin_one;
 499        iconv_t conv = iconv_open(metainfo_charset, input_charset);
 500
 501        if (conv == (iconv_t) -1) {
 502                static int warned_latin1_once = 0;
 503                if (input_charset != latin_one) {
 504                        fprintf(stderr, "cannot convert from %s to %s\n",
 505                                input_charset, metainfo_charset);
 506                        *charset = 0;
 507                }
 508                else if (!warned_latin1_once) {
 509                        warned_latin1_once = 1;
 510                        fprintf(stderr, "tried to convert from %s to %s, "
 511                                "but your iconv does not work with it.\n",
 512                                input_charset, metainfo_charset);
 513                }
 514                return;
 515        }
 516        in = line;
 517        insize = strlen(in);
 518        out = outbuf;
 519        outsize = sizeof(outbuf);
 520        nrc = iconv(conv, &in, &insize, &out, &outsize);
 521        iconv_close(conv);
 522        if (nrc == (size_t) -1)
 523                return;
 524        *out = 0;
 525        strcpy(line, outbuf);
 526#endif
 527}
 528
 529static void decode_header_bq(char *it)
 530{
 531        char *in, *out, *ep, *cp, *sp;
 532        char outbuf[1000];
 533
 534        in = it;
 535        out = outbuf;
 536        while ((ep = strstr(in, "=?")) != NULL) {
 537                int sz, encoding;
 538                char charset_q[256], piecebuf[256];
 539                if (in != ep) {
 540                        sz = ep - in;
 541                        memcpy(out, in, sz);
 542                        out += sz;
 543                        in += sz;
 544                }
 545                /* E.g.
 546                 * ep : "=?iso-2022-jp?B?GyR...?= foo"
 547                 * ep : "=?ISO-8859-1?Q?Foo=FCbar?= baz"
 548                 */
 549                ep += 2;
 550                cp = strchr(ep, '?');
 551                if (!cp)
 552                        return; /* no munging */
 553                for (sp = ep; sp < cp; sp++)
 554                        charset_q[sp - ep] = tolower(*sp);
 555                charset_q[cp - ep] = 0;
 556                encoding = cp[1];
 557                if (!encoding || cp[2] != '?')
 558                        return; /* no munging */
 559                ep = strstr(cp + 3, "?=");
 560                if (!ep)
 561                        return; /* no munging */
 562                switch (tolower(encoding)) {
 563                default:
 564                        return; /* no munging */
 565                case 'b':
 566                        sz = decode_b_segment(cp + 3, piecebuf, ep);
 567                        break;
 568                case 'q':
 569                        sz = decode_q_segment(cp + 3, piecebuf, ep, 1);
 570                        break;
 571                }
 572                if (sz < 0)
 573                        return;
 574                if (metainfo_charset)
 575                        convert_to_utf8(piecebuf, charset_q);
 576                strcpy(out, piecebuf);
 577                out += strlen(out);
 578                in = ep + 2;
 579        }
 580        strcpy(out, in);
 581        strcpy(it, outbuf);
 582}
 583
 584static void decode_transfer_encoding(char *line)
 585{
 586        char *ep;
 587
 588        switch (transfer_encoding) {
 589        case TE_QP:
 590                ep = line + strlen(line);
 591                decode_q_segment(line, line, ep, 0);
 592                break;
 593        case TE_BASE64:
 594                ep = line + strlen(line);
 595                decode_b_segment(line, line, ep);
 596                break;
 597        case TE_DONTCARE:
 598                break;
 599        }
 600}
 601
 602static void handle_info(void)
 603{
 604        char *sub;
 605
 606        sub = cleanup_subject(subject);
 607        cleanup_space(name);
 608        cleanup_space(date);
 609        cleanup_space(email);
 610        cleanup_space(sub);
 611
 612        printf("Author: %s\nEmail: %s\nSubject: %s\nDate: %s\n\n",
 613               name, email, sub, date);
 614}
 615
 616/* We are inside message body and have read line[] already.
 617 * Spit out the commit log.
 618 */
 619static int handle_commit_msg(int *seen)
 620{
 621        if (!cmitmsg)
 622                return 0;
 623        do {
 624                if (!memcmp("diff -", line, 6) ||
 625                    !memcmp("---", line, 3) ||
 626                    !memcmp("Index: ", line, 7))
 627                        break;
 628                if ((multipart_boundary[0] && is_multipart_boundary(line))) {
 629                        /* We come here when the first part had only
 630                         * the commit message without any patch.  We
 631                         * pretend we have not seen this line yet, and
 632                         * go back to the loop.
 633                         */
 634                        return 1;
 635                }
 636
 637                /* Unwrap transfer encoding and optionally
 638                 * normalize the log message to UTF-8.
 639                 */
 640                decode_transfer_encoding(line);
 641                if (metainfo_charset)
 642                        convert_to_utf8(line, charset);
 643
 644                handle_inbody_header(seen, line);
 645                if (!(*seen & SEEN_PREFIX))
 646                        continue;
 647
 648                fputs(line, cmitmsg);
 649        } while (fgets(line, sizeof(line), stdin) != NULL);
 650        fclose(cmitmsg);
 651        cmitmsg = NULL;
 652        return 0;
 653}
 654
 655/* We have done the commit message and have the first
 656 * line of the patch in line[].
 657 */
 658static void handle_patch(void)
 659{
 660        do {
 661                if (multipart_boundary[0] && is_multipart_boundary(line))
 662                        break;
 663                /* Only unwrap transfer encoding but otherwise do not
 664                 * do anything.  We do *NOT* want UTF-8 conversion
 665                 * here; we are dealing with the user payload.
 666                 */
 667                decode_transfer_encoding(line);
 668                fputs(line, patchfile);
 669                patch_lines++;
 670        } while (fgets(line, sizeof(line), stdin) != NULL);
 671}
 672
 673/* multipart boundary and transfer encoding are set up for us, and we
 674 * are at the end of the sub header.  do equivalent of handle_body up
 675 * to the next boundary without closing patchfile --- we will expect
 676 * that the first part to contain commit message and a patch, and
 677 * handle other parts as pure patches.
 678 */
 679static int handle_multipart_one_part(int *seen)
 680{
 681        int n = 0;
 682
 683        while (fgets(line, sizeof(line), stdin) != NULL) {
 684        again:
 685                n++;
 686                if (is_multipart_boundary(line))
 687                        break;
 688                if (handle_commit_msg(seen))
 689                        goto again;
 690                handle_patch();
 691                break;
 692        }
 693        if (n == 0)
 694                return -1;
 695        return 0;
 696}
 697
 698static void handle_multipart_body(void)
 699{
 700        int seen = 0;
 701        int part_num = 0;
 702
 703        /* Skip up to the first boundary */
 704        while (fgets(line, sizeof(line), stdin) != NULL)
 705                if (is_multipart_boundary(line)) {
 706                        part_num = 1;
 707                        break;
 708                }
 709        if (!part_num)
 710                return;
 711        /* We are on boundary line.  Start slurping the subhead. */
 712        while (1) {
 713                int hdr = read_one_header_line(line, sizeof(line), stdin);
 714                if (!hdr) {
 715                        if (handle_multipart_one_part(&seen) < 0)
 716                                return;
 717                        /* Reset per part headers */
 718                        transfer_encoding = TE_DONTCARE;
 719                        charset[0] = 0;
 720                }
 721                else
 722                        check_subheader_line(line);
 723        }
 724        fclose(patchfile);
 725        if (!patch_lines) {
 726                fprintf(stderr, "No patch found\n");
 727                exit(1);
 728        }
 729}
 730
 731/* Non multipart message */
 732static void handle_body(void)
 733{
 734        int seen = 0;
 735
 736        if (line[0] || fgets(line, sizeof(line), stdin) != NULL) {
 737                handle_commit_msg(&seen);
 738                handle_patch();
 739        }
 740        fclose(patchfile);
 741        if (!patch_lines) {
 742                fprintf(stderr, "No patch found\n");
 743                exit(1);
 744        }
 745}
 746
 747static const char mailinfo_usage[] =
 748        "git-mailinfo [-k] [-u | --encoding=<encoding>] msg patch <mail >info";
 749
 750int main(int argc, char **argv)
 751{
 752        /* NEEDSWORK: might want to do the optional .git/ directory
 753         * discovery
 754         */
 755        git_config(git_default_config);
 756
 757        while (1 < argc && argv[1][0] == '-') {
 758                if (!strcmp(argv[1], "-k"))
 759                        keep_subject = 1;
 760                else if (!strcmp(argv[1], "-u"))
 761                        metainfo_charset = git_commit_encoding;
 762                else if (!strncmp(argv[1], "--encoding=", 11))
 763                        metainfo_charset = argv[1] + 11;
 764                else
 765                        usage(mailinfo_usage);
 766                argc--; argv++;
 767        }
 768
 769        if (argc != 3)
 770                usage(mailinfo_usage);
 771        cmitmsg = fopen(argv[1], "w");
 772        if (!cmitmsg) {
 773                perror(argv[1]);
 774                exit(1);
 775        }
 776        patchfile = fopen(argv[2], "w");
 777        if (!patchfile) {
 778                perror(argv[2]);
 779                exit(1);
 780        }
 781        while (1) {
 782                int hdr = read_one_header_line(line, sizeof(line), stdin);
 783                if (!hdr) {
 784                        if (multipart_boundary[0])
 785                                handle_multipart_body();
 786                        else
 787                                handle_body();
 788                        handle_info();
 789                        break;
 790                }
 791                check_header_line(line);
 792        }
 793        return 0;
 794}