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