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