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