convert.con commit convert: add filter.<driver>.process option (edcc858)
   1#include "cache.h"
   2#include "attr.h"
   3#include "run-command.h"
   4#include "quote.h"
   5#include "sigchain.h"
   6#include "pkt-line.h"
   7
   8/*
   9 * convert.c - convert a file when checking it out and checking it in.
  10 *
  11 * This should use the pathname to decide on whether it wants to do some
  12 * more interesting conversions (automatic gzip/unzip, general format
  13 * conversions etc etc), but by default it just does automatic CRLF<->LF
  14 * translation when the "text" attribute or "auto_crlf" option is set.
  15 */
  16
  17/* Stat bits: When BIN is set, the txt bits are unset */
  18#define CONVERT_STAT_BITS_TXT_LF    0x1
  19#define CONVERT_STAT_BITS_TXT_CRLF  0x2
  20#define CONVERT_STAT_BITS_BIN       0x4
  21
  22enum crlf_action {
  23        CRLF_UNDEFINED,
  24        CRLF_BINARY,
  25        CRLF_TEXT,
  26        CRLF_TEXT_INPUT,
  27        CRLF_TEXT_CRLF,
  28        CRLF_AUTO,
  29        CRLF_AUTO_INPUT,
  30        CRLF_AUTO_CRLF
  31};
  32
  33struct text_stat {
  34        /* NUL, CR, LF and CRLF counts */
  35        unsigned nul, lonecr, lonelf, crlf;
  36
  37        /* These are just approximations! */
  38        unsigned printable, nonprintable;
  39};
  40
  41static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
  42{
  43        unsigned long i;
  44
  45        memset(stats, 0, sizeof(*stats));
  46
  47        for (i = 0; i < size; i++) {
  48                unsigned char c = buf[i];
  49                if (c == '\r') {
  50                        if (i+1 < size && buf[i+1] == '\n') {
  51                                stats->crlf++;
  52                                i++;
  53                        } else
  54                                stats->lonecr++;
  55                        continue;
  56                }
  57                if (c == '\n') {
  58                        stats->lonelf++;
  59                        continue;
  60                }
  61                if (c == 127)
  62                        /* DEL */
  63                        stats->nonprintable++;
  64                else if (c < 32) {
  65                        switch (c) {
  66                                /* BS, HT, ESC and FF */
  67                        case '\b': case '\t': case '\033': case '\014':
  68                                stats->printable++;
  69                                break;
  70                        case 0:
  71                                stats->nul++;
  72                                /* fall through */
  73                        default:
  74                                stats->nonprintable++;
  75                        }
  76                }
  77                else
  78                        stats->printable++;
  79        }
  80
  81        /* If file ends with EOF then don't count this EOF as non-printable. */
  82        if (size >= 1 && buf[size-1] == '\032')
  83                stats->nonprintable--;
  84}
  85
  86/*
  87 * The same heuristics as diff.c::mmfile_is_binary()
  88 * We treat files with bare CR as binary
  89 */
  90static int convert_is_binary(unsigned long size, const struct text_stat *stats)
  91{
  92        if (stats->lonecr)
  93                return 1;
  94        if (stats->nul)
  95                return 1;
  96        if ((stats->printable >> 7) < stats->nonprintable)
  97                return 1;
  98        return 0;
  99}
 100
 101static unsigned int gather_convert_stats(const char *data, unsigned long size)
 102{
 103        struct text_stat stats;
 104        int ret = 0;
 105        if (!data || !size)
 106                return 0;
 107        gather_stats(data, size, &stats);
 108        if (convert_is_binary(size, &stats))
 109                ret |= CONVERT_STAT_BITS_BIN;
 110        if (stats.crlf)
 111                ret |= CONVERT_STAT_BITS_TXT_CRLF;
 112        if (stats.lonelf)
 113                ret |=  CONVERT_STAT_BITS_TXT_LF;
 114
 115        return ret;
 116}
 117
 118static const char *gather_convert_stats_ascii(const char *data, unsigned long size)
 119{
 120        unsigned int convert_stats = gather_convert_stats(data, size);
 121
 122        if (convert_stats & CONVERT_STAT_BITS_BIN)
 123                return "-text";
 124        switch (convert_stats) {
 125        case CONVERT_STAT_BITS_TXT_LF:
 126                return "lf";
 127        case CONVERT_STAT_BITS_TXT_CRLF:
 128                return "crlf";
 129        case CONVERT_STAT_BITS_TXT_LF | CONVERT_STAT_BITS_TXT_CRLF:
 130                return "mixed";
 131        default:
 132                return "none";
 133        }
 134}
 135
 136const char *get_cached_convert_stats_ascii(const char *path)
 137{
 138        const char *ret;
 139        unsigned long sz;
 140        void *data = read_blob_data_from_cache(path, &sz);
 141        ret = gather_convert_stats_ascii(data, sz);
 142        free(data);
 143        return ret;
 144}
 145
 146const char *get_wt_convert_stats_ascii(const char *path)
 147{
 148        const char *ret = "";
 149        struct strbuf sb = STRBUF_INIT;
 150        if (strbuf_read_file(&sb, path, 0) >= 0)
 151                ret = gather_convert_stats_ascii(sb.buf, sb.len);
 152        strbuf_release(&sb);
 153        return ret;
 154}
 155
 156static int text_eol_is_crlf(void)
 157{
 158        if (auto_crlf == AUTO_CRLF_TRUE)
 159                return 1;
 160        else if (auto_crlf == AUTO_CRLF_INPUT)
 161                return 0;
 162        if (core_eol == EOL_CRLF)
 163                return 1;
 164        if (core_eol == EOL_UNSET && EOL_NATIVE == EOL_CRLF)
 165                return 1;
 166        return 0;
 167}
 168
 169static enum eol output_eol(enum crlf_action crlf_action)
 170{
 171        switch (crlf_action) {
 172        case CRLF_BINARY:
 173                return EOL_UNSET;
 174        case CRLF_TEXT_CRLF:
 175                return EOL_CRLF;
 176        case CRLF_TEXT_INPUT:
 177                return EOL_LF;
 178        case CRLF_UNDEFINED:
 179        case CRLF_AUTO_CRLF:
 180                return EOL_CRLF;
 181        case CRLF_AUTO_INPUT:
 182                return EOL_LF;
 183        case CRLF_TEXT:
 184        case CRLF_AUTO:
 185                /* fall through */
 186                return text_eol_is_crlf() ? EOL_CRLF : EOL_LF;
 187        }
 188        warning("Illegal crlf_action %d\n", (int)crlf_action);
 189        return core_eol;
 190}
 191
 192static void check_safe_crlf(const char *path, enum crlf_action crlf_action,
 193                            struct text_stat *old_stats, struct text_stat *new_stats,
 194                            enum safe_crlf checksafe)
 195{
 196        if (old_stats->crlf && !new_stats->crlf ) {
 197                /*
 198                 * CRLFs would not be restored by checkout
 199                 */
 200                if (checksafe == SAFE_CRLF_WARN)
 201                        warning("CRLF will be replaced by LF in %s.\nThe file will have its original line endings in your working directory.", path);
 202                else /* i.e. SAFE_CRLF_FAIL */
 203                        die("CRLF would be replaced by LF in %s.", path);
 204        } else if (old_stats->lonelf && !new_stats->lonelf ) {
 205                /*
 206                 * CRLFs would be added by checkout
 207                 */
 208                if (checksafe == SAFE_CRLF_WARN)
 209                        warning("LF will be replaced by CRLF in %s.\nThe file will have its original line endings in your working directory.", path);
 210                else /* i.e. SAFE_CRLF_FAIL */
 211                        die("LF would be replaced by CRLF in %s", path);
 212        }
 213}
 214
 215static int has_cr_in_index(const char *path)
 216{
 217        unsigned long sz;
 218        void *data;
 219        int has_cr;
 220
 221        data = read_blob_data_from_cache(path, &sz);
 222        if (!data)
 223                return 0;
 224        has_cr = memchr(data, '\r', sz) != NULL;
 225        free(data);
 226        return has_cr;
 227}
 228
 229static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats,
 230                                   enum crlf_action crlf_action)
 231{
 232        if (output_eol(crlf_action) != EOL_CRLF)
 233                return 0;
 234        /* No "naked" LF? Nothing to convert, regardless. */
 235        if (!stats->lonelf)
 236                return 0;
 237
 238        if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
 239                /* If we have any CR or CRLF line endings, we do not touch it */
 240                /* This is the new safer autocrlf-handling */
 241                if (stats->lonecr || stats->crlf)
 242                        return 0;
 243
 244                if (convert_is_binary(len, stats))
 245                        return 0;
 246        }
 247        return 1;
 248
 249}
 250
 251static int crlf_to_git(const char *path, const char *src, size_t len,
 252                       struct strbuf *buf,
 253                       enum crlf_action crlf_action, enum safe_crlf checksafe)
 254{
 255        struct text_stat stats;
 256        char *dst;
 257        int convert_crlf_into_lf;
 258
 259        if (crlf_action == CRLF_BINARY ||
 260            (src && !len))
 261                return 0;
 262
 263        /*
 264         * If we are doing a dry-run and have no source buffer, there is
 265         * nothing to analyze; we must assume we would convert.
 266         */
 267        if (!buf && !src)
 268                return 1;
 269
 270        gather_stats(src, len, &stats);
 271        /* Optimization: No CRLF? Nothing to convert, regardless. */
 272        convert_crlf_into_lf = !!stats.crlf;
 273
 274        if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
 275                if (convert_is_binary(len, &stats))
 276                        return 0;
 277                /*
 278                 * If the file in the index has any CR in it, do not convert.
 279                 * This is the new safer autocrlf handling.
 280                 */
 281                if (checksafe == SAFE_CRLF_RENORMALIZE)
 282                        checksafe = SAFE_CRLF_FALSE;
 283                else if (has_cr_in_index(path))
 284                        convert_crlf_into_lf = 0;
 285        }
 286        if (checksafe && len) {
 287                struct text_stat new_stats;
 288                memcpy(&new_stats, &stats, sizeof(new_stats));
 289                /* simulate "git add" */
 290                if (convert_crlf_into_lf) {
 291                        new_stats.lonelf += new_stats.crlf;
 292                        new_stats.crlf = 0;
 293                }
 294                /* simulate "git checkout" */
 295                if (will_convert_lf_to_crlf(len, &new_stats, crlf_action)) {
 296                        new_stats.crlf += new_stats.lonelf;
 297                        new_stats.lonelf = 0;
 298                }
 299                check_safe_crlf(path, crlf_action, &stats, &new_stats, checksafe);
 300        }
 301        if (!convert_crlf_into_lf)
 302                return 0;
 303
 304        /*
 305         * At this point all of our source analysis is done, and we are sure we
 306         * would convert. If we are in dry-run mode, we can give an answer.
 307         */
 308        if (!buf)
 309                return 1;
 310
 311        /* only grow if not in place */
 312        if (strbuf_avail(buf) + buf->len < len)
 313                strbuf_grow(buf, len - buf->len);
 314        dst = buf->buf;
 315        if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
 316                /*
 317                 * If we guessed, we already know we rejected a file with
 318                 * lone CR, and we can strip a CR without looking at what
 319                 * follow it.
 320                 */
 321                do {
 322                        unsigned char c = *src++;
 323                        if (c != '\r')
 324                                *dst++ = c;
 325                } while (--len);
 326        } else {
 327                do {
 328                        unsigned char c = *src++;
 329                        if (! (c == '\r' && (1 < len && *src == '\n')))
 330                                *dst++ = c;
 331                } while (--len);
 332        }
 333        strbuf_setlen(buf, dst - buf->buf);
 334        return 1;
 335}
 336
 337static int crlf_to_worktree(const char *path, const char *src, size_t len,
 338                            struct strbuf *buf, enum crlf_action crlf_action)
 339{
 340        char *to_free = NULL;
 341        struct text_stat stats;
 342
 343        if (!len || output_eol(crlf_action) != EOL_CRLF)
 344                return 0;
 345
 346        gather_stats(src, len, &stats);
 347        if (!will_convert_lf_to_crlf(len, &stats, crlf_action))
 348                return 0;
 349
 350        /* are we "faking" in place editing ? */
 351        if (src == buf->buf)
 352                to_free = strbuf_detach(buf, NULL);
 353
 354        strbuf_grow(buf, len + stats.lonelf);
 355        for (;;) {
 356                const char *nl = memchr(src, '\n', len);
 357                if (!nl)
 358                        break;
 359                if (nl > src && nl[-1] == '\r') {
 360                        strbuf_add(buf, src, nl + 1 - src);
 361                } else {
 362                        strbuf_add(buf, src, nl - src);
 363                        strbuf_addstr(buf, "\r\n");
 364                }
 365                len -= nl + 1 - src;
 366                src  = nl + 1;
 367        }
 368        strbuf_add(buf, src, len);
 369
 370        free(to_free);
 371        return 1;
 372}
 373
 374struct filter_params {
 375        const char *src;
 376        unsigned long size;
 377        int fd;
 378        const char *cmd;
 379        const char *path;
 380};
 381
 382static int filter_buffer_or_fd(int in, int out, void *data)
 383{
 384        /*
 385         * Spawn cmd and feed the buffer contents through its stdin.
 386         */
 387        struct child_process child_process = CHILD_PROCESS_INIT;
 388        struct filter_params *params = (struct filter_params *)data;
 389        int write_err, status;
 390        const char *argv[] = { NULL, NULL };
 391
 392        /* apply % substitution to cmd */
 393        struct strbuf cmd = STRBUF_INIT;
 394        struct strbuf path = STRBUF_INIT;
 395        struct strbuf_expand_dict_entry dict[] = {
 396                { "f", NULL, },
 397                { NULL, NULL, },
 398        };
 399
 400        /* quote the path to preserve spaces, etc. */
 401        sq_quote_buf(&path, params->path);
 402        dict[0].value = path.buf;
 403
 404        /* expand all %f with the quoted path */
 405        strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
 406        strbuf_release(&path);
 407
 408        argv[0] = cmd.buf;
 409
 410        child_process.argv = argv;
 411        child_process.use_shell = 1;
 412        child_process.in = -1;
 413        child_process.out = out;
 414
 415        if (start_command(&child_process))
 416                return error("cannot fork to run external filter '%s'", params->cmd);
 417
 418        sigchain_push(SIGPIPE, SIG_IGN);
 419
 420        if (params->src) {
 421                write_err = (write_in_full(child_process.in,
 422                                           params->src, params->size) < 0);
 423                if (errno == EPIPE)
 424                        write_err = 0;
 425        } else {
 426                write_err = copy_fd(params->fd, child_process.in);
 427                if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
 428                        write_err = 0;
 429        }
 430
 431        if (close(child_process.in))
 432                write_err = 1;
 433        if (write_err)
 434                error("cannot feed the input to external filter '%s'", params->cmd);
 435
 436        sigchain_pop(SIGPIPE);
 437
 438        status = finish_command(&child_process);
 439        if (status)
 440                error("external filter '%s' failed %d", params->cmd, status);
 441
 442        strbuf_release(&cmd);
 443        return (write_err || status);
 444}
 445
 446static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
 447                        struct strbuf *dst, const char *cmd)
 448{
 449        /*
 450         * Create a pipeline to have the command filter the buffer's
 451         * contents.
 452         *
 453         * (child --> cmd) --> us
 454         */
 455        int err = 0;
 456        struct strbuf nbuf = STRBUF_INIT;
 457        struct async async;
 458        struct filter_params params;
 459
 460        memset(&async, 0, sizeof(async));
 461        async.proc = filter_buffer_or_fd;
 462        async.data = &params;
 463        async.out = -1;
 464        params.src = src;
 465        params.size = len;
 466        params.fd = fd;
 467        params.cmd = cmd;
 468        params.path = path;
 469
 470        fflush(NULL);
 471        if (start_async(&async))
 472                return 0;       /* error was already reported */
 473
 474        if (strbuf_read(&nbuf, async.out, len) < 0) {
 475                err = error("read from external filter '%s' failed", cmd);
 476        }
 477        if (close(async.out)) {
 478                err = error("read from external filter '%s' failed", cmd);
 479        }
 480        if (finish_async(&async)) {
 481                err = error("external filter '%s' failed", cmd);
 482        }
 483
 484        if (!err) {
 485                strbuf_swap(dst, &nbuf);
 486        }
 487        strbuf_release(&nbuf);
 488        return !err;
 489}
 490
 491#define CAP_CLEAN    (1u<<0)
 492#define CAP_SMUDGE   (1u<<1)
 493
 494struct cmd2process {
 495        struct hashmap_entry ent; /* must be the first member! */
 496        unsigned int supported_capabilities;
 497        const char *cmd;
 498        struct child_process process;
 499};
 500
 501static int cmd_process_map_initialized;
 502static struct hashmap cmd_process_map;
 503
 504static int cmd2process_cmp(const struct cmd2process *e1,
 505                           const struct cmd2process *e2,
 506                           const void *unused)
 507{
 508        return strcmp(e1->cmd, e2->cmd);
 509}
 510
 511static struct cmd2process *find_multi_file_filter_entry(struct hashmap *hashmap, const char *cmd)
 512{
 513        struct cmd2process key;
 514        hashmap_entry_init(&key, strhash(cmd));
 515        key.cmd = cmd;
 516        return hashmap_get(hashmap, &key, NULL);
 517}
 518
 519static int packet_write_list(int fd, const char *line, ...)
 520{
 521        va_list args;
 522        int err;
 523        va_start(args, line);
 524        for (;;) {
 525                if (!line)
 526                        break;
 527                if (strlen(line) > LARGE_PACKET_DATA_MAX)
 528                        return -1;
 529                err = packet_write_fmt_gently(fd, "%s\n", line);
 530                if (err)
 531                        return err;
 532                line = va_arg(args, const char*);
 533        }
 534        va_end(args);
 535        return packet_flush_gently(fd);
 536}
 537
 538static void read_multi_file_filter_status(int fd, struct strbuf *status)
 539{
 540        struct strbuf **pair;
 541        char *line;
 542        for (;;) {
 543                line = packet_read_line(fd, NULL);
 544                if (!line)
 545                        break;
 546                pair = strbuf_split_str(line, '=', 2);
 547                if (pair[0] && pair[0]->len && pair[1]) {
 548                        /* the last "status=<foo>" line wins */
 549                        if (!strcmp(pair[0]->buf, "status=")) {
 550                                strbuf_reset(status);
 551                                strbuf_addbuf(status, pair[1]);
 552                        }
 553                }
 554                strbuf_list_free(pair);
 555        }
 556}
 557
 558static void kill_multi_file_filter(struct hashmap *hashmap, struct cmd2process *entry)
 559{
 560        if (!entry)
 561                return;
 562
 563        entry->process.clean_on_exit = 0;
 564        kill(entry->process.pid, SIGTERM);
 565        finish_command(&entry->process);
 566
 567        hashmap_remove(hashmap, entry, NULL);
 568        free(entry);
 569}
 570
 571static void stop_multi_file_filter(struct child_process *process)
 572{
 573        sigchain_push(SIGPIPE, SIG_IGN);
 574        /* Closing the pipe signals the filter to initiate a shutdown. */
 575        close(process->in);
 576        close(process->out);
 577        sigchain_pop(SIGPIPE);
 578        /* Finish command will wait until the shutdown is complete. */
 579        finish_command(process);
 580}
 581
 582static struct cmd2process *start_multi_file_filter(struct hashmap *hashmap, const char *cmd)
 583{
 584        int err;
 585        struct cmd2process *entry;
 586        struct child_process *process;
 587        const char *argv[] = { cmd, NULL };
 588        struct string_list cap_list = STRING_LIST_INIT_NODUP;
 589        char *cap_buf;
 590        const char *cap_name;
 591
 592        entry = xmalloc(sizeof(*entry));
 593        entry->cmd = cmd;
 594        entry->supported_capabilities = 0;
 595        process = &entry->process;
 596
 597        child_process_init(process);
 598        process->argv = argv;
 599        process->use_shell = 1;
 600        process->in = -1;
 601        process->out = -1;
 602        process->clean_on_exit = 1;
 603        process->clean_on_exit_handler = stop_multi_file_filter;
 604
 605        if (start_command(process)) {
 606                error("cannot fork to run external filter '%s'", cmd);
 607                return NULL;
 608        }
 609
 610        hashmap_entry_init(entry, strhash(cmd));
 611
 612        sigchain_push(SIGPIPE, SIG_IGN);
 613
 614        err = packet_write_list(process->in, "git-filter-client", "version=2", NULL);
 615        if (err)
 616                goto done;
 617
 618        err = strcmp(packet_read_line(process->out, NULL), "git-filter-server");
 619        if (err) {
 620                error("external filter '%s' does not support filter protocol version 2", cmd);
 621                goto done;
 622        }
 623        err = strcmp(packet_read_line(process->out, NULL), "version=2");
 624        if (err)
 625                goto done;
 626        err = packet_read_line(process->out, NULL) != NULL;
 627        if (err)
 628                goto done;
 629
 630        err = packet_write_list(process->in, "capability=clean", "capability=smudge", NULL);
 631
 632        for (;;) {
 633                cap_buf = packet_read_line(process->out, NULL);
 634                if (!cap_buf)
 635                        break;
 636                string_list_split_in_place(&cap_list, cap_buf, '=', 1);
 637
 638                if (cap_list.nr != 2 || strcmp(cap_list.items[0].string, "capability"))
 639                        continue;
 640
 641                cap_name = cap_list.items[1].string;
 642                if (!strcmp(cap_name, "clean")) {
 643                        entry->supported_capabilities |= CAP_CLEAN;
 644                } else if (!strcmp(cap_name, "smudge")) {
 645                        entry->supported_capabilities |= CAP_SMUDGE;
 646                } else {
 647                        warning(
 648                                "external filter '%s' requested unsupported filter capability '%s'",
 649                                cmd, cap_name
 650                        );
 651                }
 652
 653                string_list_clear(&cap_list, 0);
 654        }
 655
 656done:
 657        sigchain_pop(SIGPIPE);
 658
 659        if (err || errno == EPIPE) {
 660                error("initialization for external filter '%s' failed", cmd);
 661                kill_multi_file_filter(hashmap, entry);
 662                return NULL;
 663        }
 664
 665        hashmap_add(hashmap, entry);
 666        return entry;
 667}
 668
 669static int apply_multi_file_filter(const char *path, const char *src, size_t len,
 670                                   int fd, struct strbuf *dst, const char *cmd,
 671                                   const unsigned int wanted_capability)
 672{
 673        int err;
 674        struct cmd2process *entry;
 675        struct child_process *process;
 676        struct strbuf nbuf = STRBUF_INIT;
 677        struct strbuf filter_status = STRBUF_INIT;
 678        const char *filter_type;
 679
 680        if (!cmd_process_map_initialized) {
 681                cmd_process_map_initialized = 1;
 682                hashmap_init(&cmd_process_map, (hashmap_cmp_fn) cmd2process_cmp, 0);
 683                entry = NULL;
 684        } else {
 685                entry = find_multi_file_filter_entry(&cmd_process_map, cmd);
 686        }
 687
 688        fflush(NULL);
 689
 690        if (!entry) {
 691                entry = start_multi_file_filter(&cmd_process_map, cmd);
 692                if (!entry)
 693                        return 0;
 694        }
 695        process = &entry->process;
 696
 697        if (!(wanted_capability & entry->supported_capabilities))
 698                return 0;
 699
 700        if (CAP_CLEAN & wanted_capability)
 701                filter_type = "clean";
 702        else if (CAP_SMUDGE & wanted_capability)
 703                filter_type = "smudge";
 704        else
 705                die("unexpected filter type");
 706
 707        sigchain_push(SIGPIPE, SIG_IGN);
 708
 709        assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
 710        err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
 711        if (err)
 712                goto done;
 713
 714        err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
 715        if (err) {
 716                error("path name too long for external filter");
 717                goto done;
 718        }
 719
 720        err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
 721        if (err)
 722                goto done;
 723
 724        err = packet_flush_gently(process->in);
 725        if (err)
 726                goto done;
 727
 728        if (fd >= 0)
 729                err = write_packetized_from_fd(fd, process->in);
 730        else
 731                err = write_packetized_from_buf(src, len, process->in);
 732        if (err)
 733                goto done;
 734
 735        read_multi_file_filter_status(process->out, &filter_status);
 736        err = strcmp(filter_status.buf, "success");
 737        if (err)
 738                goto done;
 739
 740        err = read_packetized_to_strbuf(process->out, &nbuf) < 0;
 741        if (err)
 742                goto done;
 743
 744        read_multi_file_filter_status(process->out, &filter_status);
 745        err = strcmp(filter_status.buf, "success");
 746
 747done:
 748        sigchain_pop(SIGPIPE);
 749
 750        if (err || errno == EPIPE) {
 751                if (!strcmp(filter_status.buf, "error")) {
 752                        /* The filter signaled a problem with the file. */
 753                } else if (!strcmp(filter_status.buf, "abort")) {
 754                        /*
 755                         * The filter signaled a permanent problem. Don't try to filter
 756                         * files with the same command for the lifetime of the current
 757                         * Git process.
 758                         */
 759                         entry->supported_capabilities &= ~wanted_capability;
 760                } else {
 761                        /*
 762                         * Something went wrong with the protocol filter.
 763                         * Force shutdown and restart if another blob requires filtering.
 764                         */
 765                        error("external filter '%s' failed", cmd);
 766                        kill_multi_file_filter(&cmd_process_map, entry);
 767                }
 768        } else {
 769                strbuf_swap(dst, &nbuf);
 770        }
 771        strbuf_release(&nbuf);
 772        return !err;
 773}
 774
 775static struct convert_driver {
 776        const char *name;
 777        struct convert_driver *next;
 778        const char *smudge;
 779        const char *clean;
 780        const char *process;
 781        int required;
 782} *user_convert, **user_convert_tail;
 783
 784static int apply_filter(const char *path, const char *src, size_t len,
 785                        int fd, struct strbuf *dst, struct convert_driver *drv,
 786                        const unsigned int wanted_capability)
 787{
 788        const char *cmd = NULL;
 789
 790        if (!drv)
 791                return 0;
 792
 793        if (!dst)
 794                return 1;
 795
 796        if ((CAP_CLEAN & wanted_capability) && !drv->process && drv->clean)
 797                cmd = drv->clean;
 798        else if ((CAP_SMUDGE & wanted_capability) && !drv->process && drv->smudge)
 799                cmd = drv->smudge;
 800
 801        if (cmd && *cmd)
 802                return apply_single_file_filter(path, src, len, fd, dst, cmd);
 803        else if (drv->process && *drv->process)
 804                return apply_multi_file_filter(path, src, len, fd, dst, drv->process, wanted_capability);
 805
 806        return 0;
 807}
 808
 809static int read_convert_config(const char *var, const char *value, void *cb)
 810{
 811        const char *key, *name;
 812        int namelen;
 813        struct convert_driver *drv;
 814
 815        /*
 816         * External conversion drivers are configured using
 817         * "filter.<name>.variable".
 818         */
 819        if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
 820                return 0;
 821        for (drv = user_convert; drv; drv = drv->next)
 822                if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
 823                        break;
 824        if (!drv) {
 825                drv = xcalloc(1, sizeof(struct convert_driver));
 826                drv->name = xmemdupz(name, namelen);
 827                *user_convert_tail = drv;
 828                user_convert_tail = &(drv->next);
 829        }
 830
 831        /*
 832         * filter.<name>.smudge and filter.<name>.clean specifies
 833         * the command line:
 834         *
 835         *      command-line
 836         *
 837         * The command-line will not be interpolated in any way.
 838         */
 839
 840        if (!strcmp("smudge", key))
 841                return git_config_string(&drv->smudge, var, value);
 842
 843        if (!strcmp("clean", key))
 844                return git_config_string(&drv->clean, var, value);
 845
 846        if (!strcmp("process", key))
 847                return git_config_string(&drv->process, var, value);
 848
 849        if (!strcmp("required", key)) {
 850                drv->required = git_config_bool(var, value);
 851                return 0;
 852        }
 853
 854        return 0;
 855}
 856
 857static int count_ident(const char *cp, unsigned long size)
 858{
 859        /*
 860         * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
 861         */
 862        int cnt = 0;
 863        char ch;
 864
 865        while (size) {
 866                ch = *cp++;
 867                size--;
 868                if (ch != '$')
 869                        continue;
 870                if (size < 3)
 871                        break;
 872                if (memcmp("Id", cp, 2))
 873                        continue;
 874                ch = cp[2];
 875                cp += 3;
 876                size -= 3;
 877                if (ch == '$')
 878                        cnt++; /* $Id$ */
 879                if (ch != ':')
 880                        continue;
 881
 882                /*
 883                 * "$Id: ... "; scan up to the closing dollar sign and discard.
 884                 */
 885                while (size) {
 886                        ch = *cp++;
 887                        size--;
 888                        if (ch == '$') {
 889                                cnt++;
 890                                break;
 891                        }
 892                        if (ch == '\n')
 893                                break;
 894                }
 895        }
 896        return cnt;
 897}
 898
 899static int ident_to_git(const char *path, const char *src, size_t len,
 900                        struct strbuf *buf, int ident)
 901{
 902        char *dst, *dollar;
 903
 904        if (!ident || (src && !count_ident(src, len)))
 905                return 0;
 906
 907        if (!buf)
 908                return 1;
 909
 910        /* only grow if not in place */
 911        if (strbuf_avail(buf) + buf->len < len)
 912                strbuf_grow(buf, len - buf->len);
 913        dst = buf->buf;
 914        for (;;) {
 915                dollar = memchr(src, '$', len);
 916                if (!dollar)
 917                        break;
 918                memmove(dst, src, dollar + 1 - src);
 919                dst += dollar + 1 - src;
 920                len -= dollar + 1 - src;
 921                src  = dollar + 1;
 922
 923                if (len > 3 && !memcmp(src, "Id:", 3)) {
 924                        dollar = memchr(src + 3, '$', len - 3);
 925                        if (!dollar)
 926                                break;
 927                        if (memchr(src + 3, '\n', dollar - src - 3)) {
 928                                /* Line break before the next dollar. */
 929                                continue;
 930                        }
 931
 932                        memcpy(dst, "Id$", 3);
 933                        dst += 3;
 934                        len -= dollar + 1 - src;
 935                        src  = dollar + 1;
 936                }
 937        }
 938        memmove(dst, src, len);
 939        strbuf_setlen(buf, dst + len - buf->buf);
 940        return 1;
 941}
 942
 943static int ident_to_worktree(const char *path, const char *src, size_t len,
 944                             struct strbuf *buf, int ident)
 945{
 946        unsigned char sha1[20];
 947        char *to_free = NULL, *dollar, *spc;
 948        int cnt;
 949
 950        if (!ident)
 951                return 0;
 952
 953        cnt = count_ident(src, len);
 954        if (!cnt)
 955                return 0;
 956
 957        /* are we "faking" in place editing ? */
 958        if (src == buf->buf)
 959                to_free = strbuf_detach(buf, NULL);
 960        hash_sha1_file(src, len, "blob", sha1);
 961
 962        strbuf_grow(buf, len + cnt * 43);
 963        for (;;) {
 964                /* step 1: run to the next '$' */
 965                dollar = memchr(src, '$', len);
 966                if (!dollar)
 967                        break;
 968                strbuf_add(buf, src, dollar + 1 - src);
 969                len -= dollar + 1 - src;
 970                src  = dollar + 1;
 971
 972                /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
 973                if (len < 3 || memcmp("Id", src, 2))
 974                        continue;
 975
 976                /* step 3: skip over Id$ or Id:xxxxx$ */
 977                if (src[2] == '$') {
 978                        src += 3;
 979                        len -= 3;
 980                } else if (src[2] == ':') {
 981                        /*
 982                         * It's possible that an expanded Id has crept its way into the
 983                         * repository, we cope with that by stripping the expansion out.
 984                         * This is probably not a good idea, since it will cause changes
 985                         * on checkout, which won't go away by stash, but let's keep it
 986                         * for git-style ids.
 987                         */
 988                        dollar = memchr(src + 3, '$', len - 3);
 989                        if (!dollar) {
 990                                /* incomplete keyword, no more '$', so just quit the loop */
 991                                break;
 992                        }
 993
 994                        if (memchr(src + 3, '\n', dollar - src - 3)) {
 995                                /* Line break before the next dollar. */
 996                                continue;
 997                        }
 998
 999                        spc = memchr(src + 4, ' ', dollar - src - 4);
1000                        if (spc && spc < dollar-1) {
1001                                /* There are spaces in unexpected places.
1002                                 * This is probably an id from some other
1003                                 * versioning system. Keep it for now.
1004                                 */
1005                                continue;
1006                        }
1007
1008                        len -= dollar + 1 - src;
1009                        src  = dollar + 1;
1010                } else {
1011                        /* it wasn't a "Id$" or "Id:xxxx$" */
1012                        continue;
1013                }
1014
1015                /* step 4: substitute */
1016                strbuf_addstr(buf, "Id: ");
1017                strbuf_add(buf, sha1_to_hex(sha1), 40);
1018                strbuf_addstr(buf, " $");
1019        }
1020        strbuf_add(buf, src, len);
1021
1022        free(to_free);
1023        return 1;
1024}
1025
1026static enum crlf_action git_path_check_crlf(struct git_attr_check *check)
1027{
1028        const char *value = check->value;
1029
1030        if (ATTR_TRUE(value))
1031                return CRLF_TEXT;
1032        else if (ATTR_FALSE(value))
1033                return CRLF_BINARY;
1034        else if (ATTR_UNSET(value))
1035                ;
1036        else if (!strcmp(value, "input"))
1037                return CRLF_TEXT_INPUT;
1038        else if (!strcmp(value, "auto"))
1039                return CRLF_AUTO;
1040        return CRLF_UNDEFINED;
1041}
1042
1043static enum eol git_path_check_eol(struct git_attr_check *check)
1044{
1045        const char *value = check->value;
1046
1047        if (ATTR_UNSET(value))
1048                ;
1049        else if (!strcmp(value, "lf"))
1050                return EOL_LF;
1051        else if (!strcmp(value, "crlf"))
1052                return EOL_CRLF;
1053        return EOL_UNSET;
1054}
1055
1056static struct convert_driver *git_path_check_convert(struct git_attr_check *check)
1057{
1058        const char *value = check->value;
1059        struct convert_driver *drv;
1060
1061        if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1062                return NULL;
1063        for (drv = user_convert; drv; drv = drv->next)
1064                if (!strcmp(value, drv->name))
1065                        return drv;
1066        return NULL;
1067}
1068
1069static int git_path_check_ident(struct git_attr_check *check)
1070{
1071        const char *value = check->value;
1072
1073        return !!ATTR_TRUE(value);
1074}
1075
1076struct conv_attrs {
1077        struct convert_driver *drv;
1078        enum crlf_action attr_action; /* What attr says */
1079        enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
1080        int ident;
1081};
1082
1083static const char *conv_attr_name[] = {
1084        "crlf", "ident", "filter", "eol", "text",
1085};
1086#define NUM_CONV_ATTRS ARRAY_SIZE(conv_attr_name)
1087
1088static void convert_attrs(struct conv_attrs *ca, const char *path)
1089{
1090        int i;
1091        static struct git_attr_check ccheck[NUM_CONV_ATTRS];
1092
1093        if (!ccheck[0].attr) {
1094                for (i = 0; i < NUM_CONV_ATTRS; i++)
1095                        ccheck[i].attr = git_attr(conv_attr_name[i]);
1096                user_convert_tail = &user_convert;
1097                git_config(read_convert_config, NULL);
1098        }
1099
1100        if (!git_check_attr(path, NUM_CONV_ATTRS, ccheck)) {
1101                ca->crlf_action = git_path_check_crlf(ccheck + 4);
1102                if (ca->crlf_action == CRLF_UNDEFINED)
1103                        ca->crlf_action = git_path_check_crlf(ccheck + 0);
1104                ca->attr_action = ca->crlf_action;
1105                ca->ident = git_path_check_ident(ccheck + 1);
1106                ca->drv = git_path_check_convert(ccheck + 2);
1107                if (ca->crlf_action != CRLF_BINARY) {
1108                        enum eol eol_attr = git_path_check_eol(ccheck + 3);
1109                        if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1110                                ca->crlf_action = CRLF_AUTO_INPUT;
1111                        else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1112                                ca->crlf_action = CRLF_AUTO_CRLF;
1113                        else if (eol_attr == EOL_LF)
1114                                ca->crlf_action = CRLF_TEXT_INPUT;
1115                        else if (eol_attr == EOL_CRLF)
1116                                ca->crlf_action = CRLF_TEXT_CRLF;
1117                }
1118                ca->attr_action = ca->crlf_action;
1119        } else {
1120                ca->drv = NULL;
1121                ca->crlf_action = CRLF_UNDEFINED;
1122                ca->ident = 0;
1123        }
1124        if (ca->crlf_action == CRLF_TEXT)
1125                ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1126        if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1127                ca->crlf_action = CRLF_BINARY;
1128        if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1129                ca->crlf_action = CRLF_AUTO_CRLF;
1130        if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1131                ca->crlf_action = CRLF_AUTO_INPUT;
1132}
1133
1134int would_convert_to_git_filter_fd(const char *path)
1135{
1136        struct conv_attrs ca;
1137
1138        convert_attrs(&ca, path);
1139        if (!ca.drv)
1140                return 0;
1141
1142        /*
1143         * Apply a filter to an fd only if the filter is required to succeed.
1144         * We must die if the filter fails, because the original data before
1145         * filtering is not available.
1146         */
1147        if (!ca.drv->required)
1148                return 0;
1149
1150        return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN);
1151}
1152
1153const char *get_convert_attr_ascii(const char *path)
1154{
1155        struct conv_attrs ca;
1156
1157        convert_attrs(&ca, path);
1158        switch (ca.attr_action) {
1159        case CRLF_UNDEFINED:
1160                return "";
1161        case CRLF_BINARY:
1162                return "-text";
1163        case CRLF_TEXT:
1164                return "text";
1165        case CRLF_TEXT_INPUT:
1166                return "text eol=lf";
1167        case CRLF_TEXT_CRLF:
1168                return "text eol=crlf";
1169        case CRLF_AUTO:
1170                return "text=auto";
1171        case CRLF_AUTO_CRLF:
1172                return "text=auto eol=crlf";
1173        case CRLF_AUTO_INPUT:
1174                return "text=auto eol=lf";
1175        }
1176        return "";
1177}
1178
1179int convert_to_git(const char *path, const char *src, size_t len,
1180                   struct strbuf *dst, enum safe_crlf checksafe)
1181{
1182        int ret = 0;
1183        struct conv_attrs ca;
1184
1185        convert_attrs(&ca, path);
1186
1187        ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN);
1188        if (!ret && ca.drv && ca.drv->required)
1189                die("%s: clean filter '%s' failed", path, ca.drv->name);
1190
1191        if (ret && dst) {
1192                src = dst->buf;
1193                len = dst->len;
1194        }
1195        ret |= crlf_to_git(path, src, len, dst, ca.crlf_action, checksafe);
1196        if (ret && dst) {
1197                src = dst->buf;
1198                len = dst->len;
1199        }
1200        return ret | ident_to_git(path, src, len, dst, ca.ident);
1201}
1202
1203void convert_to_git_filter_fd(const char *path, int fd, struct strbuf *dst,
1204                              enum safe_crlf checksafe)
1205{
1206        struct conv_attrs ca;
1207        convert_attrs(&ca, path);
1208
1209        assert(ca.drv);
1210        assert(ca.drv->clean || ca.drv->process);
1211
1212        if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN))
1213                die("%s: clean filter '%s' failed", path, ca.drv->name);
1214
1215        crlf_to_git(path, dst->buf, dst->len, dst, ca.crlf_action, checksafe);
1216        ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
1217}
1218
1219static int convert_to_working_tree_internal(const char *path, const char *src,
1220                                            size_t len, struct strbuf *dst,
1221                                            int normalizing)
1222{
1223        int ret = 0, ret_filter = 0;
1224        struct conv_attrs ca;
1225
1226        convert_attrs(&ca, path);
1227
1228        ret |= ident_to_worktree(path, src, len, dst, ca.ident);
1229        if (ret) {
1230                src = dst->buf;
1231                len = dst->len;
1232        }
1233        /*
1234         * CRLF conversion can be skipped if normalizing, unless there
1235         * is a smudge or process filter (even if the process filter doesn't
1236         * support smudge).  The filters might expect CRLFs.
1237         */
1238        if ((ca.drv && (ca.drv->smudge || ca.drv->process)) || !normalizing) {
1239                ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
1240                if (ret) {
1241                        src = dst->buf;
1242                        len = dst->len;
1243                }
1244        }
1245
1246        ret_filter = apply_filter(path, src, len, -1, dst, ca.drv, CAP_SMUDGE);
1247        if (!ret_filter && ca.drv && ca.drv->required)
1248                die("%s: smudge filter %s failed", path, ca.drv->name);
1249
1250        return ret | ret_filter;
1251}
1252
1253int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
1254{
1255        return convert_to_working_tree_internal(path, src, len, dst, 0);
1256}
1257
1258int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
1259{
1260        int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
1261        if (ret) {
1262                src = dst->buf;
1263                len = dst->len;
1264        }
1265        return ret | convert_to_git(path, src, len, dst, SAFE_CRLF_RENORMALIZE);
1266}
1267
1268/*****************************************************************
1269 *
1270 * Streaming conversion support
1271 *
1272 *****************************************************************/
1273
1274typedef int (*filter_fn)(struct stream_filter *,
1275                         const char *input, size_t *isize_p,
1276                         char *output, size_t *osize_p);
1277typedef void (*free_fn)(struct stream_filter *);
1278
1279struct stream_filter_vtbl {
1280        filter_fn filter;
1281        free_fn free;
1282};
1283
1284struct stream_filter {
1285        struct stream_filter_vtbl *vtbl;
1286};
1287
1288static int null_filter_fn(struct stream_filter *filter,
1289                          const char *input, size_t *isize_p,
1290                          char *output, size_t *osize_p)
1291{
1292        size_t count;
1293
1294        if (!input)
1295                return 0; /* we do not keep any states */
1296        count = *isize_p;
1297        if (*osize_p < count)
1298                count = *osize_p;
1299        if (count) {
1300                memmove(output, input, count);
1301                *isize_p -= count;
1302                *osize_p -= count;
1303        }
1304        return 0;
1305}
1306
1307static void null_free_fn(struct stream_filter *filter)
1308{
1309        ; /* nothing -- null instances are shared */
1310}
1311
1312static struct stream_filter_vtbl null_vtbl = {
1313        null_filter_fn,
1314        null_free_fn,
1315};
1316
1317static struct stream_filter null_filter_singleton = {
1318        &null_vtbl,
1319};
1320
1321int is_null_stream_filter(struct stream_filter *filter)
1322{
1323        return filter == &null_filter_singleton;
1324}
1325
1326
1327/*
1328 * LF-to-CRLF filter
1329 */
1330
1331struct lf_to_crlf_filter {
1332        struct stream_filter filter;
1333        unsigned has_held:1;
1334        char held;
1335};
1336
1337static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1338                                const char *input, size_t *isize_p,
1339                                char *output, size_t *osize_p)
1340{
1341        size_t count, o = 0;
1342        struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1343
1344        /*
1345         * We may be holding onto the CR to see if it is followed by a
1346         * LF, in which case we would need to go to the main loop.
1347         * Otherwise, just emit it to the output stream.
1348         */
1349        if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1350                output[o++] = lf_to_crlf->held;
1351                lf_to_crlf->has_held = 0;
1352        }
1353
1354        /* We are told to drain */
1355        if (!input) {
1356                *osize_p -= o;
1357                return 0;
1358        }
1359
1360        count = *isize_p;
1361        if (count || lf_to_crlf->has_held) {
1362                size_t i;
1363                int was_cr = 0;
1364
1365                if (lf_to_crlf->has_held) {
1366                        was_cr = 1;
1367                        lf_to_crlf->has_held = 0;
1368                }
1369
1370                for (i = 0; o < *osize_p && i < count; i++) {
1371                        char ch = input[i];
1372
1373                        if (ch == '\n') {
1374                                output[o++] = '\r';
1375                        } else if (was_cr) {
1376                                /*
1377                                 * Previous round saw CR and it is not followed
1378                                 * by a LF; emit the CR before processing the
1379                                 * current character.
1380                                 */
1381                                output[o++] = '\r';
1382                        }
1383
1384                        /*
1385                         * We may have consumed the last output slot,
1386                         * in which case we need to break out of this
1387                         * loop; hold the current character before
1388                         * returning.
1389                         */
1390                        if (*osize_p <= o) {
1391                                lf_to_crlf->has_held = 1;
1392                                lf_to_crlf->held = ch;
1393                                continue; /* break but increment i */
1394                        }
1395
1396                        if (ch == '\r') {
1397                                was_cr = 1;
1398                                continue;
1399                        }
1400
1401                        was_cr = 0;
1402                        output[o++] = ch;
1403                }
1404
1405                *osize_p -= o;
1406                *isize_p -= i;
1407
1408                if (!lf_to_crlf->has_held && was_cr) {
1409                        lf_to_crlf->has_held = 1;
1410                        lf_to_crlf->held = '\r';
1411                }
1412        }
1413        return 0;
1414}
1415
1416static void lf_to_crlf_free_fn(struct stream_filter *filter)
1417{
1418        free(filter);
1419}
1420
1421static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1422        lf_to_crlf_filter_fn,
1423        lf_to_crlf_free_fn,
1424};
1425
1426static struct stream_filter *lf_to_crlf_filter(void)
1427{
1428        struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1429
1430        lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1431        return (struct stream_filter *)lf_to_crlf;
1432}
1433
1434/*
1435 * Cascade filter
1436 */
1437#define FILTER_BUFFER 1024
1438struct cascade_filter {
1439        struct stream_filter filter;
1440        struct stream_filter *one;
1441        struct stream_filter *two;
1442        char buf[FILTER_BUFFER];
1443        int end, ptr;
1444};
1445
1446static int cascade_filter_fn(struct stream_filter *filter,
1447                             const char *input, size_t *isize_p,
1448                             char *output, size_t *osize_p)
1449{
1450        struct cascade_filter *cas = (struct cascade_filter *) filter;
1451        size_t filled = 0;
1452        size_t sz = *osize_p;
1453        size_t to_feed, remaining;
1454
1455        /*
1456         * input -- (one) --> buf -- (two) --> output
1457         */
1458        while (filled < sz) {
1459                remaining = sz - filled;
1460
1461                /* do we already have something to feed two with? */
1462                if (cas->ptr < cas->end) {
1463                        to_feed = cas->end - cas->ptr;
1464                        if (stream_filter(cas->two,
1465                                          cas->buf + cas->ptr, &to_feed,
1466                                          output + filled, &remaining))
1467                                return -1;
1468                        cas->ptr += (cas->end - cas->ptr) - to_feed;
1469                        filled = sz - remaining;
1470                        continue;
1471                }
1472
1473                /* feed one from upstream and have it emit into our buffer */
1474                to_feed = input ? *isize_p : 0;
1475                if (input && !to_feed)
1476                        break;
1477                remaining = sizeof(cas->buf);
1478                if (stream_filter(cas->one,
1479                                  input, &to_feed,
1480                                  cas->buf, &remaining))
1481                        return -1;
1482                cas->end = sizeof(cas->buf) - remaining;
1483                cas->ptr = 0;
1484                if (input) {
1485                        size_t fed = *isize_p - to_feed;
1486                        *isize_p -= fed;
1487                        input += fed;
1488                }
1489
1490                /* do we know that we drained one completely? */
1491                if (input || cas->end)
1492                        continue;
1493
1494                /* tell two to drain; we have nothing more to give it */
1495                to_feed = 0;
1496                remaining = sz - filled;
1497                if (stream_filter(cas->two,
1498                                  NULL, &to_feed,
1499                                  output + filled, &remaining))
1500                        return -1;
1501                if (remaining == (sz - filled))
1502                        break; /* completely drained two */
1503                filled = sz - remaining;
1504        }
1505        *osize_p -= filled;
1506        return 0;
1507}
1508
1509static void cascade_free_fn(struct stream_filter *filter)
1510{
1511        struct cascade_filter *cas = (struct cascade_filter *)filter;
1512        free_stream_filter(cas->one);
1513        free_stream_filter(cas->two);
1514        free(filter);
1515}
1516
1517static struct stream_filter_vtbl cascade_vtbl = {
1518        cascade_filter_fn,
1519        cascade_free_fn,
1520};
1521
1522static struct stream_filter *cascade_filter(struct stream_filter *one,
1523                                            struct stream_filter *two)
1524{
1525        struct cascade_filter *cascade;
1526
1527        if (!one || is_null_stream_filter(one))
1528                return two;
1529        if (!two || is_null_stream_filter(two))
1530                return one;
1531
1532        cascade = xmalloc(sizeof(*cascade));
1533        cascade->one = one;
1534        cascade->two = two;
1535        cascade->end = cascade->ptr = 0;
1536        cascade->filter.vtbl = &cascade_vtbl;
1537        return (struct stream_filter *)cascade;
1538}
1539
1540/*
1541 * ident filter
1542 */
1543#define IDENT_DRAINING (-1)
1544#define IDENT_SKIPPING (-2)
1545struct ident_filter {
1546        struct stream_filter filter;
1547        struct strbuf left;
1548        int state;
1549        char ident[45]; /* ": x40 $" */
1550};
1551
1552static int is_foreign_ident(const char *str)
1553{
1554        int i;
1555
1556        if (!skip_prefix(str, "$Id: ", &str))
1557                return 0;
1558        for (i = 0; str[i]; i++) {
1559                if (isspace(str[i]) && str[i+1] != '$')
1560                        return 1;
1561        }
1562        return 0;
1563}
1564
1565static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1566{
1567        size_t to_drain = ident->left.len;
1568
1569        if (*osize_p < to_drain)
1570                to_drain = *osize_p;
1571        if (to_drain) {
1572                memcpy(*output_p, ident->left.buf, to_drain);
1573                strbuf_remove(&ident->left, 0, to_drain);
1574                *output_p += to_drain;
1575                *osize_p -= to_drain;
1576        }
1577        if (!ident->left.len)
1578                ident->state = 0;
1579}
1580
1581static int ident_filter_fn(struct stream_filter *filter,
1582                           const char *input, size_t *isize_p,
1583                           char *output, size_t *osize_p)
1584{
1585        struct ident_filter *ident = (struct ident_filter *)filter;
1586        static const char head[] = "$Id";
1587
1588        if (!input) {
1589                /* drain upon eof */
1590                switch (ident->state) {
1591                default:
1592                        strbuf_add(&ident->left, head, ident->state);
1593                case IDENT_SKIPPING:
1594                        /* fallthru */
1595                case IDENT_DRAINING:
1596                        ident_drain(ident, &output, osize_p);
1597                }
1598                return 0;
1599        }
1600
1601        while (*isize_p || (ident->state == IDENT_DRAINING)) {
1602                int ch;
1603
1604                if (ident->state == IDENT_DRAINING) {
1605                        ident_drain(ident, &output, osize_p);
1606                        if (!*osize_p)
1607                                break;
1608                        continue;
1609                }
1610
1611                ch = *(input++);
1612                (*isize_p)--;
1613
1614                if (ident->state == IDENT_SKIPPING) {
1615                        /*
1616                         * Skipping until '$' or LF, but keeping them
1617                         * in case it is a foreign ident.
1618                         */
1619                        strbuf_addch(&ident->left, ch);
1620                        if (ch != '\n' && ch != '$')
1621                                continue;
1622                        if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1623                                strbuf_setlen(&ident->left, sizeof(head) - 1);
1624                                strbuf_addstr(&ident->left, ident->ident);
1625                        }
1626                        ident->state = IDENT_DRAINING;
1627                        continue;
1628                }
1629
1630                if (ident->state < sizeof(head) &&
1631                    head[ident->state] == ch) {
1632                        ident->state++;
1633                        continue;
1634                }
1635
1636                if (ident->state)
1637                        strbuf_add(&ident->left, head, ident->state);
1638                if (ident->state == sizeof(head) - 1) {
1639                        if (ch != ':' && ch != '$') {
1640                                strbuf_addch(&ident->left, ch);
1641                                ident->state = 0;
1642                                continue;
1643                        }
1644
1645                        if (ch == ':') {
1646                                strbuf_addch(&ident->left, ch);
1647                                ident->state = IDENT_SKIPPING;
1648                        } else {
1649                                strbuf_addstr(&ident->left, ident->ident);
1650                                ident->state = IDENT_DRAINING;
1651                        }
1652                        continue;
1653                }
1654
1655                strbuf_addch(&ident->left, ch);
1656                ident->state = IDENT_DRAINING;
1657        }
1658        return 0;
1659}
1660
1661static void ident_free_fn(struct stream_filter *filter)
1662{
1663        struct ident_filter *ident = (struct ident_filter *)filter;
1664        strbuf_release(&ident->left);
1665        free(filter);
1666}
1667
1668static struct stream_filter_vtbl ident_vtbl = {
1669        ident_filter_fn,
1670        ident_free_fn,
1671};
1672
1673static struct stream_filter *ident_filter(const unsigned char *sha1)
1674{
1675        struct ident_filter *ident = xmalloc(sizeof(*ident));
1676
1677        xsnprintf(ident->ident, sizeof(ident->ident),
1678                  ": %s $", sha1_to_hex(sha1));
1679        strbuf_init(&ident->left, 0);
1680        ident->filter.vtbl = &ident_vtbl;
1681        ident->state = 0;
1682        return (struct stream_filter *)ident;
1683}
1684
1685/*
1686 * Return an appropriately constructed filter for the path, or NULL if
1687 * the contents cannot be filtered without reading the whole thing
1688 * in-core.
1689 *
1690 * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1691 * large binary blob you would want us not to slurp into the memory!
1692 */
1693struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1694{
1695        struct conv_attrs ca;
1696        struct stream_filter *filter = NULL;
1697
1698        convert_attrs(&ca, path);
1699        if (ca.drv && (ca.drv->process || ca.drv->smudge || ca.drv->clean))
1700                return NULL;
1701
1702        if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
1703                return NULL;
1704
1705        if (ca.ident)
1706                filter = ident_filter(sha1);
1707
1708        if (output_eol(ca.crlf_action) == EOL_CRLF)
1709                filter = cascade_filter(filter, lf_to_crlf_filter());
1710        else
1711                filter = cascade_filter(filter, &null_filter_singleton);
1712
1713        return filter;
1714}
1715
1716void free_stream_filter(struct stream_filter *filter)
1717{
1718        filter->vtbl->free(filter);
1719}
1720
1721int stream_filter(struct stream_filter *filter,
1722                  const char *input, size_t *isize_p,
1723                  char *output, size_t *osize_p)
1724{
1725        return filter->vtbl->filter(filter, input, isize_p, output, osize_p);
1726}