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