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