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