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