hash: set, copy, and use algo field in struct object_id
[git] / object-file.c
1 /*
2  * GIT - The information manager from hell
3  *
4  * Copyright (C) Linus Torvalds, 2005
5  *
6  * This handles basic git object files - packing, unpacking,
7  * creation etc.
8  */
9 #include "cache.h"
10 #include "config.h"
11 #include "string-list.h"
12 #include "lockfile.h"
13 #include "delta.h"
14 #include "pack.h"
15 #include "blob.h"
16 #include "commit.h"
17 #include "run-command.h"
18 #include "tag.h"
19 #include "tree.h"
20 #include "tree-walk.h"
21 #include "refs.h"
22 #include "pack-revindex.h"
23 #include "hash-lookup.h"
24 #include "bulk-checkin.h"
25 #include "repository.h"
26 #include "replace-object.h"
27 #include "streaming.h"
28 #include "dir.h"
29 #include "list.h"
30 #include "mergesort.h"
31 #include "quote.h"
32 #include "packfile.h"
33 #include "object-store.h"
34 #include "promisor-remote.h"
35
36 /* The maximum size for an object header. */
37 #define MAX_HEADER_LEN 32
38
39
40 #define EMPTY_TREE_SHA1_BIN_LITERAL \
41          "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60" \
42          "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04"
43 #define EMPTY_TREE_SHA256_BIN_LITERAL \
44         "\x6e\xf1\x9b\x41\x22\x5c\x53\x69\xf1\xc1" \
45         "\x04\xd4\x5d\x8d\x85\xef\xa9\xb0\x57\xb5" \
46         "\x3b\x14\xb4\xb9\xb9\x39\xdd\x74\xde\xcc" \
47         "\x53\x21"
48
49 #define EMPTY_BLOB_SHA1_BIN_LITERAL \
50         "\xe6\x9d\xe2\x9b\xb2\xd1\xd6\x43\x4b\x8b" \
51         "\x29\xae\x77\x5a\xd8\xc2\xe4\x8c\x53\x91"
52 #define EMPTY_BLOB_SHA256_BIN_LITERAL \
53         "\x47\x3a\x0f\x4c\x3b\xe8\xa9\x36\x81\xa2" \
54         "\x67\xe3\xb1\xe9\xa7\xdc\xda\x11\x85\x43" \
55         "\x6f\xe1\x41\xf7\x74\x91\x20\xa3\x03\x72" \
56         "\x18\x13"
57
58 const struct object_id null_oid;
59 static const struct object_id empty_tree_oid = {
60         .hash = EMPTY_TREE_SHA1_BIN_LITERAL,
61         .algo = GIT_HASH_SHA1,
62 };
63 static const struct object_id empty_blob_oid = {
64         .hash = EMPTY_BLOB_SHA1_BIN_LITERAL,
65         .algo = GIT_HASH_SHA1,
66 };
67 static const struct object_id empty_tree_oid_sha256 = {
68         .hash = EMPTY_TREE_SHA256_BIN_LITERAL,
69         .algo = GIT_HASH_SHA256,
70 };
71 static const struct object_id empty_blob_oid_sha256 = {
72         .hash = EMPTY_BLOB_SHA256_BIN_LITERAL,
73         .algo = GIT_HASH_SHA256,
74 };
75
76 static void git_hash_sha1_init(git_hash_ctx *ctx)
77 {
78         git_SHA1_Init(&ctx->sha1);
79 }
80
81 static void git_hash_sha1_clone(git_hash_ctx *dst, const git_hash_ctx *src)
82 {
83         git_SHA1_Clone(&dst->sha1, &src->sha1);
84 }
85
86 static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
87 {
88         git_SHA1_Update(&ctx->sha1, data, len);
89 }
90
91 static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
92 {
93         git_SHA1_Final(hash, &ctx->sha1);
94 }
95
96 static void git_hash_sha1_final_oid(struct object_id *oid, git_hash_ctx *ctx)
97 {
98         git_SHA1_Final(oid->hash, &ctx->sha1);
99         memset(oid->hash + GIT_SHA1_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA1_RAWSZ);
100         oid->algo = GIT_HASH_SHA1;
101 }
102
103
104 static void git_hash_sha256_init(git_hash_ctx *ctx)
105 {
106         git_SHA256_Init(&ctx->sha256);
107 }
108
109 static void git_hash_sha256_clone(git_hash_ctx *dst, const git_hash_ctx *src)
110 {
111         git_SHA256_Clone(&dst->sha256, &src->sha256);
112 }
113
114 static void git_hash_sha256_update(git_hash_ctx *ctx, const void *data, size_t len)
115 {
116         git_SHA256_Update(&ctx->sha256, data, len);
117 }
118
119 static void git_hash_sha256_final(unsigned char *hash, git_hash_ctx *ctx)
120 {
121         git_SHA256_Final(hash, &ctx->sha256);
122 }
123
124 static void git_hash_sha256_final_oid(struct object_id *oid, git_hash_ctx *ctx)
125 {
126         git_SHA256_Final(oid->hash, &ctx->sha256);
127         /*
128          * This currently does nothing, so the compiler should optimize it out,
129          * but keep it in case we extend the hash size again.
130          */
131         memset(oid->hash + GIT_SHA256_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA256_RAWSZ);
132         oid->algo = GIT_HASH_SHA256;
133 }
134
135 static void git_hash_unknown_init(git_hash_ctx *ctx)
136 {
137         BUG("trying to init unknown hash");
138 }
139
140 static void git_hash_unknown_clone(git_hash_ctx *dst, const git_hash_ctx *src)
141 {
142         BUG("trying to clone unknown hash");
143 }
144
145 static void git_hash_unknown_update(git_hash_ctx *ctx, const void *data, size_t len)
146 {
147         BUG("trying to update unknown hash");
148 }
149
150 static void git_hash_unknown_final(unsigned char *hash, git_hash_ctx *ctx)
151 {
152         BUG("trying to finalize unknown hash");
153 }
154
155 static void git_hash_unknown_final_oid(struct object_id *oid, git_hash_ctx *ctx)
156 {
157         BUG("trying to finalize unknown hash");
158 }
159
160
161 const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
162         {
163                 NULL,
164                 0x00000000,
165                 0,
166                 0,
167                 0,
168                 git_hash_unknown_init,
169                 git_hash_unknown_clone,
170                 git_hash_unknown_update,
171                 git_hash_unknown_final,
172                 git_hash_unknown_final_oid,
173                 NULL,
174                 NULL,
175         },
176         {
177                 "sha1",
178                 /* "sha1", big-endian */
179                 0x73686131,
180                 GIT_SHA1_RAWSZ,
181                 GIT_SHA1_HEXSZ,
182                 GIT_SHA1_BLKSZ,
183                 git_hash_sha1_init,
184                 git_hash_sha1_clone,
185                 git_hash_sha1_update,
186                 git_hash_sha1_final,
187                 git_hash_sha1_final_oid,
188                 &empty_tree_oid,
189                 &empty_blob_oid,
190         },
191         {
192                 "sha256",
193                 /* "s256", big-endian */
194                 0x73323536,
195                 GIT_SHA256_RAWSZ,
196                 GIT_SHA256_HEXSZ,
197                 GIT_SHA256_BLKSZ,
198                 git_hash_sha256_init,
199                 git_hash_sha256_clone,
200                 git_hash_sha256_update,
201                 git_hash_sha256_final,
202                 git_hash_sha256_final_oid,
203                 &empty_tree_oid_sha256,
204                 &empty_blob_oid_sha256,
205         }
206 };
207
208 const char *empty_tree_oid_hex(void)
209 {
210         static char buf[GIT_MAX_HEXSZ + 1];
211         return oid_to_hex_r(buf, the_hash_algo->empty_tree);
212 }
213
214 const char *empty_blob_oid_hex(void)
215 {
216         static char buf[GIT_MAX_HEXSZ + 1];
217         return oid_to_hex_r(buf, the_hash_algo->empty_blob);
218 }
219
220 int hash_algo_by_name(const char *name)
221 {
222         int i;
223         if (!name)
224                 return GIT_HASH_UNKNOWN;
225         for (i = 1; i < GIT_HASH_NALGOS; i++)
226                 if (!strcmp(name, hash_algos[i].name))
227                         return i;
228         return GIT_HASH_UNKNOWN;
229 }
230
231 int hash_algo_by_id(uint32_t format_id)
232 {
233         int i;
234         for (i = 1; i < GIT_HASH_NALGOS; i++)
235                 if (format_id == hash_algos[i].format_id)
236                         return i;
237         return GIT_HASH_UNKNOWN;
238 }
239
240 int hash_algo_by_length(int len)
241 {
242         int i;
243         for (i = 1; i < GIT_HASH_NALGOS; i++)
244                 if (len == hash_algos[i].rawsz)
245                         return i;
246         return GIT_HASH_UNKNOWN;
247 }
248
249 /*
250  * This is meant to hold a *small* number of objects that you would
251  * want read_object_file() to be able to return, but yet you do not want
252  * to write them into the object store (e.g. a browse-only
253  * application).
254  */
255 static struct cached_object {
256         struct object_id oid;
257         enum object_type type;
258         void *buf;
259         unsigned long size;
260 } *cached_objects;
261 static int cached_object_nr, cached_object_alloc;
262
263 static struct cached_object empty_tree = {
264         { EMPTY_TREE_SHA1_BIN_LITERAL },
265         OBJ_TREE,
266         "",
267         0
268 };
269
270 static struct cached_object *find_cached_object(const struct object_id *oid)
271 {
272         int i;
273         struct cached_object *co = cached_objects;
274
275         for (i = 0; i < cached_object_nr; i++, co++) {
276                 if (oideq(&co->oid, oid))
277                         return co;
278         }
279         if (oideq(oid, the_hash_algo->empty_tree))
280                 return &empty_tree;
281         return NULL;
282 }
283
284
285 static int get_conv_flags(unsigned flags)
286 {
287         if (flags & HASH_RENORMALIZE)
288                 return CONV_EOL_RENORMALIZE;
289         else if (flags & HASH_WRITE_OBJECT)
290                 return global_conv_flags_eol | CONV_WRITE_OBJECT;
291         else
292                 return 0;
293 }
294
295
296 int mkdir_in_gitdir(const char *path)
297 {
298         if (mkdir(path, 0777)) {
299                 int saved_errno = errno;
300                 struct stat st;
301                 struct strbuf sb = STRBUF_INIT;
302
303                 if (errno != EEXIST)
304                         return -1;
305                 /*
306                  * Are we looking at a path in a symlinked worktree
307                  * whose original repository does not yet have it?
308                  * e.g. .git/rr-cache pointing at its original
309                  * repository in which the user hasn't performed any
310                  * conflict resolution yet?
311                  */
312                 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
313                     strbuf_readlink(&sb, path, st.st_size) ||
314                     !is_absolute_path(sb.buf) ||
315                     mkdir(sb.buf, 0777)) {
316                         strbuf_release(&sb);
317                         errno = saved_errno;
318                         return -1;
319                 }
320                 strbuf_release(&sb);
321         }
322         return adjust_shared_perm(path);
323 }
324
325 static enum scld_error safe_create_leading_directories_1(char *path, int share)
326 {
327         char *next_component = path + offset_1st_component(path);
328         enum scld_error ret = SCLD_OK;
329
330         while (ret == SCLD_OK && next_component) {
331                 struct stat st;
332                 char *slash = next_component, slash_character;
333
334                 while (*slash && !is_dir_sep(*slash))
335                         slash++;
336
337                 if (!*slash)
338                         break;
339
340                 next_component = slash + 1;
341                 while (is_dir_sep(*next_component))
342                         next_component++;
343                 if (!*next_component)
344                         break;
345
346                 slash_character = *slash;
347                 *slash = '\0';
348                 if (!stat(path, &st)) {
349                         /* path exists */
350                         if (!S_ISDIR(st.st_mode)) {
351                                 errno = ENOTDIR;
352                                 ret = SCLD_EXISTS;
353                         }
354                 } else if (mkdir(path, 0777)) {
355                         if (errno == EEXIST &&
356                             !stat(path, &st) && S_ISDIR(st.st_mode))
357                                 ; /* somebody created it since we checked */
358                         else if (errno == ENOENT)
359                                 /*
360                                  * Either mkdir() failed because
361                                  * somebody just pruned the containing
362                                  * directory, or stat() failed because
363                                  * the file that was in our way was
364                                  * just removed.  Either way, inform
365                                  * the caller that it might be worth
366                                  * trying again:
367                                  */
368                                 ret = SCLD_VANISHED;
369                         else
370                                 ret = SCLD_FAILED;
371                 } else if (share && adjust_shared_perm(path)) {
372                         ret = SCLD_PERMS;
373                 }
374                 *slash = slash_character;
375         }
376         return ret;
377 }
378
379 enum scld_error safe_create_leading_directories(char *path)
380 {
381         return safe_create_leading_directories_1(path, 1);
382 }
383
384 enum scld_error safe_create_leading_directories_no_share(char *path)
385 {
386         return safe_create_leading_directories_1(path, 0);
387 }
388
389 enum scld_error safe_create_leading_directories_const(const char *path)
390 {
391         int save_errno;
392         /* path points to cache entries, so xstrdup before messing with it */
393         char *buf = xstrdup(path);
394         enum scld_error result = safe_create_leading_directories(buf);
395
396         save_errno = errno;
397         free(buf);
398         errno = save_errno;
399         return result;
400 }
401
402 int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
403 {
404         /*
405          * The number of times we will try to remove empty directories
406          * in the way of path. This is only 1 because if another
407          * process is racily creating directories that conflict with
408          * us, we don't want to fight against them.
409          */
410         int remove_directories_remaining = 1;
411
412         /*
413          * The number of times that we will try to create the
414          * directories containing path. We are willing to attempt this
415          * more than once, because another process could be trying to
416          * clean up empty directories at the same time as we are
417          * trying to create them.
418          */
419         int create_directories_remaining = 3;
420
421         /* A scratch copy of path, filled lazily if we need it: */
422         struct strbuf path_copy = STRBUF_INIT;
423
424         int ret, save_errno;
425
426         /* Sanity check: */
427         assert(*path);
428
429 retry_fn:
430         ret = fn(path, cb);
431         save_errno = errno;
432         if (!ret)
433                 goto out;
434
435         if (errno == EISDIR && remove_directories_remaining-- > 0) {
436                 /*
437                  * A directory is in the way. Maybe it is empty; try
438                  * to remove it:
439                  */
440                 if (!path_copy.len)
441                         strbuf_addstr(&path_copy, path);
442
443                 if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
444                         goto retry_fn;
445         } else if (errno == ENOENT && create_directories_remaining-- > 0) {
446                 /*
447                  * Maybe the containing directory didn't exist, or
448                  * maybe it was just deleted by a process that is
449                  * racing with us to clean up empty directories. Try
450                  * to create it:
451                  */
452                 enum scld_error scld_result;
453
454                 if (!path_copy.len)
455                         strbuf_addstr(&path_copy, path);
456
457                 do {
458                         scld_result = safe_create_leading_directories(path_copy.buf);
459                         if (scld_result == SCLD_OK)
460                                 goto retry_fn;
461                 } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
462         }
463
464 out:
465         strbuf_release(&path_copy);
466         errno = save_errno;
467         return ret;
468 }
469
470 static void fill_loose_path(struct strbuf *buf, const struct object_id *oid)
471 {
472         int i;
473         for (i = 0; i < the_hash_algo->rawsz; i++) {
474                 static char hex[] = "0123456789abcdef";
475                 unsigned int val = oid->hash[i];
476                 strbuf_addch(buf, hex[val >> 4]);
477                 strbuf_addch(buf, hex[val & 0xf]);
478                 if (!i)
479                         strbuf_addch(buf, '/');
480         }
481 }
482
483 static const char *odb_loose_path(struct object_directory *odb,
484                                   struct strbuf *buf,
485                                   const struct object_id *oid)
486 {
487         strbuf_reset(buf);
488         strbuf_addstr(buf, odb->path);
489         strbuf_addch(buf, '/');
490         fill_loose_path(buf, oid);
491         return buf->buf;
492 }
493
494 const char *loose_object_path(struct repository *r, struct strbuf *buf,
495                               const struct object_id *oid)
496 {
497         return odb_loose_path(r->objects->odb, buf, oid);
498 }
499
500 /*
501  * Return non-zero iff the path is usable as an alternate object database.
502  */
503 static int alt_odb_usable(struct raw_object_store *o,
504                           struct strbuf *path,
505                           const char *normalized_objdir)
506 {
507         struct object_directory *odb;
508
509         /* Detect cases where alternate disappeared */
510         if (!is_directory(path->buf)) {
511                 error(_("object directory %s does not exist; "
512                         "check .git/objects/info/alternates"),
513                       path->buf);
514                 return 0;
515         }
516
517         /*
518          * Prevent the common mistake of listing the same
519          * thing twice, or object directory itself.
520          */
521         for (odb = o->odb; odb; odb = odb->next) {
522                 if (!fspathcmp(path->buf, odb->path))
523                         return 0;
524         }
525         if (!fspathcmp(path->buf, normalized_objdir))
526                 return 0;
527
528         return 1;
529 }
530
531 /*
532  * Prepare alternate object database registry.
533  *
534  * The variable alt_odb_list points at the list of struct
535  * object_directory.  The elements on this list come from
536  * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
537  * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
538  * whose contents is similar to that environment variable but can be
539  * LF separated.  Its base points at a statically allocated buffer that
540  * contains "/the/directory/corresponding/to/.git/objects/...", while
541  * its name points just after the slash at the end of ".git/objects/"
542  * in the example above, and has enough space to hold all hex characters
543  * of the object ID, an extra slash for the first level indirection, and
544  * the terminating NUL.
545  */
546 static void read_info_alternates(struct repository *r,
547                                  const char *relative_base,
548                                  int depth);
549 static int link_alt_odb_entry(struct repository *r, const char *entry,
550         const char *relative_base, int depth, const char *normalized_objdir)
551 {
552         struct object_directory *ent;
553         struct strbuf pathbuf = STRBUF_INIT;
554
555         if (!is_absolute_path(entry) && relative_base) {
556                 strbuf_realpath(&pathbuf, relative_base, 1);
557                 strbuf_addch(&pathbuf, '/');
558         }
559         strbuf_addstr(&pathbuf, entry);
560
561         if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
562                 error(_("unable to normalize alternate object path: %s"),
563                       pathbuf.buf);
564                 strbuf_release(&pathbuf);
565                 return -1;
566         }
567
568         /*
569          * The trailing slash after the directory name is given by
570          * this function at the end. Remove duplicates.
571          */
572         while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
573                 strbuf_setlen(&pathbuf, pathbuf.len - 1);
574
575         if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir)) {
576                 strbuf_release(&pathbuf);
577                 return -1;
578         }
579
580         CALLOC_ARRAY(ent, 1);
581         ent->path = xstrdup(pathbuf.buf);
582
583         /* add the alternate entry */
584         *r->objects->odb_tail = ent;
585         r->objects->odb_tail = &(ent->next);
586         ent->next = NULL;
587
588         /* recursively add alternates */
589         read_info_alternates(r, pathbuf.buf, depth + 1);
590
591         strbuf_release(&pathbuf);
592         return 0;
593 }
594
595 static const char *parse_alt_odb_entry(const char *string,
596                                        int sep,
597                                        struct strbuf *out)
598 {
599         const char *end;
600
601         strbuf_reset(out);
602
603         if (*string == '#') {
604                 /* comment; consume up to next separator */
605                 end = strchrnul(string, sep);
606         } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
607                 /*
608                  * quoted path; unquote_c_style has copied the
609                  * data for us and set "end". Broken quoting (e.g.,
610                  * an entry that doesn't end with a quote) falls
611                  * back to the unquoted case below.
612                  */
613         } else {
614                 /* normal, unquoted path */
615                 end = strchrnul(string, sep);
616                 strbuf_add(out, string, end - string);
617         }
618
619         if (*end)
620                 end++;
621         return end;
622 }
623
624 static void link_alt_odb_entries(struct repository *r, const char *alt,
625                                  int sep, const char *relative_base, int depth)
626 {
627         struct strbuf objdirbuf = STRBUF_INIT;
628         struct strbuf entry = STRBUF_INIT;
629
630         if (!alt || !*alt)
631                 return;
632
633         if (depth > 5) {
634                 error(_("%s: ignoring alternate object stores, nesting too deep"),
635                                 relative_base);
636                 return;
637         }
638
639         strbuf_add_absolute_path(&objdirbuf, r->objects->odb->path);
640         if (strbuf_normalize_path(&objdirbuf) < 0)
641                 die(_("unable to normalize object directory: %s"),
642                     objdirbuf.buf);
643
644         while (*alt) {
645                 alt = parse_alt_odb_entry(alt, sep, &entry);
646                 if (!entry.len)
647                         continue;
648                 link_alt_odb_entry(r, entry.buf,
649                                    relative_base, depth, objdirbuf.buf);
650         }
651         strbuf_release(&entry);
652         strbuf_release(&objdirbuf);
653 }
654
655 static void read_info_alternates(struct repository *r,
656                                  const char *relative_base,
657                                  int depth)
658 {
659         char *path;
660         struct strbuf buf = STRBUF_INIT;
661
662         path = xstrfmt("%s/info/alternates", relative_base);
663         if (strbuf_read_file(&buf, path, 1024) < 0) {
664                 warn_on_fopen_errors(path);
665                 free(path);
666                 return;
667         }
668
669         link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
670         strbuf_release(&buf);
671         free(path);
672 }
673
674 void add_to_alternates_file(const char *reference)
675 {
676         struct lock_file lock = LOCK_INIT;
677         char *alts = git_pathdup("objects/info/alternates");
678         FILE *in, *out;
679         int found = 0;
680
681         hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
682         out = fdopen_lock_file(&lock, "w");
683         if (!out)
684                 die_errno(_("unable to fdopen alternates lockfile"));
685
686         in = fopen(alts, "r");
687         if (in) {
688                 struct strbuf line = STRBUF_INIT;
689
690                 while (strbuf_getline(&line, in) != EOF) {
691                         if (!strcmp(reference, line.buf)) {
692                                 found = 1;
693                                 break;
694                         }
695                         fprintf_or_die(out, "%s\n", line.buf);
696                 }
697
698                 strbuf_release(&line);
699                 fclose(in);
700         }
701         else if (errno != ENOENT)
702                 die_errno(_("unable to read alternates file"));
703
704         if (found) {
705                 rollback_lock_file(&lock);
706         } else {
707                 fprintf_or_die(out, "%s\n", reference);
708                 if (commit_lock_file(&lock))
709                         die_errno(_("unable to move new alternates file into place"));
710                 if (the_repository->objects->loaded_alternates)
711                         link_alt_odb_entries(the_repository, reference,
712                                              '\n', NULL, 0);
713         }
714         free(alts);
715 }
716
717 void add_to_alternates_memory(const char *reference)
718 {
719         /*
720          * Make sure alternates are initialized, or else our entry may be
721          * overwritten when they are.
722          */
723         prepare_alt_odb(the_repository);
724
725         link_alt_odb_entries(the_repository, reference,
726                              '\n', NULL, 0);
727 }
728
729 /*
730  * Compute the exact path an alternate is at and returns it. In case of
731  * error NULL is returned and the human readable error is added to `err`
732  * `path` may be relative and should point to $GIT_DIR.
733  * `err` must not be null.
734  */
735 char *compute_alternate_path(const char *path, struct strbuf *err)
736 {
737         char *ref_git = NULL;
738         const char *repo;
739         int seen_error = 0;
740
741         ref_git = real_pathdup(path, 0);
742         if (!ref_git) {
743                 seen_error = 1;
744                 strbuf_addf(err, _("path '%s' does not exist"), path);
745                 goto out;
746         }
747
748         repo = read_gitfile(ref_git);
749         if (!repo)
750                 repo = read_gitfile(mkpath("%s/.git", ref_git));
751         if (repo) {
752                 free(ref_git);
753                 ref_git = xstrdup(repo);
754         }
755
756         if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
757                 char *ref_git_git = mkpathdup("%s/.git", ref_git);
758                 free(ref_git);
759                 ref_git = ref_git_git;
760         } else if (!is_directory(mkpath("%s/objects", ref_git))) {
761                 struct strbuf sb = STRBUF_INIT;
762                 seen_error = 1;
763                 if (get_common_dir(&sb, ref_git)) {
764                         strbuf_addf(err,
765                                     _("reference repository '%s' as a linked "
766                                       "checkout is not supported yet."),
767                                     path);
768                         goto out;
769                 }
770
771                 strbuf_addf(err, _("reference repository '%s' is not a "
772                                         "local repository."), path);
773                 goto out;
774         }
775
776         if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
777                 strbuf_addf(err, _("reference repository '%s' is shallow"),
778                             path);
779                 seen_error = 1;
780                 goto out;
781         }
782
783         if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
784                 strbuf_addf(err,
785                             _("reference repository '%s' is grafted"),
786                             path);
787                 seen_error = 1;
788                 goto out;
789         }
790
791 out:
792         if (seen_error) {
793                 FREE_AND_NULL(ref_git);
794         }
795
796         return ref_git;
797 }
798
799 static void fill_alternate_refs_command(struct child_process *cmd,
800                                         const char *repo_path)
801 {
802         const char *value;
803
804         if (!git_config_get_value("core.alternateRefsCommand", &value)) {
805                 cmd->use_shell = 1;
806
807                 strvec_push(&cmd->args, value);
808                 strvec_push(&cmd->args, repo_path);
809         } else {
810                 cmd->git_cmd = 1;
811
812                 strvec_pushf(&cmd->args, "--git-dir=%s", repo_path);
813                 strvec_push(&cmd->args, "for-each-ref");
814                 strvec_push(&cmd->args, "--format=%(objectname)");
815
816                 if (!git_config_get_value("core.alternateRefsPrefixes", &value)) {
817                         strvec_push(&cmd->args, "--");
818                         strvec_split(&cmd->args, value);
819                 }
820         }
821
822         cmd->env = local_repo_env;
823         cmd->out = -1;
824 }
825
826 static void read_alternate_refs(const char *path,
827                                 alternate_ref_fn *cb,
828                                 void *data)
829 {
830         struct child_process cmd = CHILD_PROCESS_INIT;
831         struct strbuf line = STRBUF_INIT;
832         FILE *fh;
833
834         fill_alternate_refs_command(&cmd, path);
835
836         if (start_command(&cmd))
837                 return;
838
839         fh = xfdopen(cmd.out, "r");
840         while (strbuf_getline_lf(&line, fh) != EOF) {
841                 struct object_id oid;
842                 const char *p;
843
844                 if (parse_oid_hex(line.buf, &oid, &p) || *p) {
845                         warning(_("invalid line while parsing alternate refs: %s"),
846                                 line.buf);
847                         break;
848                 }
849
850                 cb(&oid, data);
851         }
852
853         fclose(fh);
854         finish_command(&cmd);
855         strbuf_release(&line);
856 }
857
858 struct alternate_refs_data {
859         alternate_ref_fn *fn;
860         void *data;
861 };
862
863 static int refs_from_alternate_cb(struct object_directory *e,
864                                   void *data)
865 {
866         struct strbuf path = STRBUF_INIT;
867         size_t base_len;
868         struct alternate_refs_data *cb = data;
869
870         if (!strbuf_realpath(&path, e->path, 0))
871                 goto out;
872         if (!strbuf_strip_suffix(&path, "/objects"))
873                 goto out;
874         base_len = path.len;
875
876         /* Is this a git repository with refs? */
877         strbuf_addstr(&path, "/refs");
878         if (!is_directory(path.buf))
879                 goto out;
880         strbuf_setlen(&path, base_len);
881
882         read_alternate_refs(path.buf, cb->fn, cb->data);
883
884 out:
885         strbuf_release(&path);
886         return 0;
887 }
888
889 void for_each_alternate_ref(alternate_ref_fn fn, void *data)
890 {
891         struct alternate_refs_data cb;
892         cb.fn = fn;
893         cb.data = data;
894         foreach_alt_odb(refs_from_alternate_cb, &cb);
895 }
896
897 int foreach_alt_odb(alt_odb_fn fn, void *cb)
898 {
899         struct object_directory *ent;
900         int r = 0;
901
902         prepare_alt_odb(the_repository);
903         for (ent = the_repository->objects->odb->next; ent; ent = ent->next) {
904                 r = fn(ent, cb);
905                 if (r)
906                         break;
907         }
908         return r;
909 }
910
911 void prepare_alt_odb(struct repository *r)
912 {
913         if (r->objects->loaded_alternates)
914                 return;
915
916         link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
917
918         read_info_alternates(r, r->objects->odb->path, 0);
919         r->objects->loaded_alternates = 1;
920 }
921
922 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
923 static int freshen_file(const char *fn)
924 {
925         return !utime(fn, NULL);
926 }
927
928 /*
929  * All of the check_and_freshen functions return 1 if the file exists and was
930  * freshened (if freshening was requested), 0 otherwise. If they return
931  * 0, you should not assume that it is safe to skip a write of the object (it
932  * either does not exist on disk, or has a stale mtime and may be subject to
933  * pruning).
934  */
935 int check_and_freshen_file(const char *fn, int freshen)
936 {
937         if (access(fn, F_OK))
938                 return 0;
939         if (freshen && !freshen_file(fn))
940                 return 0;
941         return 1;
942 }
943
944 static int check_and_freshen_odb(struct object_directory *odb,
945                                  const struct object_id *oid,
946                                  int freshen)
947 {
948         static struct strbuf path = STRBUF_INIT;
949         odb_loose_path(odb, &path, oid);
950         return check_and_freshen_file(path.buf, freshen);
951 }
952
953 static int check_and_freshen_local(const struct object_id *oid, int freshen)
954 {
955         return check_and_freshen_odb(the_repository->objects->odb, oid, freshen);
956 }
957
958 static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
959 {
960         struct object_directory *odb;
961
962         prepare_alt_odb(the_repository);
963         for (odb = the_repository->objects->odb->next; odb; odb = odb->next) {
964                 if (check_and_freshen_odb(odb, oid, freshen))
965                         return 1;
966         }
967         return 0;
968 }
969
970 static int check_and_freshen(const struct object_id *oid, int freshen)
971 {
972         return check_and_freshen_local(oid, freshen) ||
973                check_and_freshen_nonlocal(oid, freshen);
974 }
975
976 int has_loose_object_nonlocal(const struct object_id *oid)
977 {
978         return check_and_freshen_nonlocal(oid, 0);
979 }
980
981 static int has_loose_object(const struct object_id *oid)
982 {
983         return check_and_freshen(oid, 0);
984 }
985
986 static void mmap_limit_check(size_t length)
987 {
988         static size_t limit = 0;
989         if (!limit) {
990                 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
991                 if (!limit)
992                         limit = SIZE_MAX;
993         }
994         if (length > limit)
995                 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX),
996                     (uintmax_t)length, (uintmax_t)limit);
997 }
998
999 void *xmmap_gently(void *start, size_t length,
1000                   int prot, int flags, int fd, off_t offset)
1001 {
1002         void *ret;
1003
1004         mmap_limit_check(length);
1005         ret = mmap(start, length, prot, flags, fd, offset);
1006         if (ret == MAP_FAILED && !length)
1007                 ret = NULL;
1008         return ret;
1009 }
1010
1011 void *xmmap(void *start, size_t length,
1012         int prot, int flags, int fd, off_t offset)
1013 {
1014         void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
1015         if (ret == MAP_FAILED)
1016                 die_errno(_("mmap failed"));
1017         return ret;
1018 }
1019
1020 /*
1021  * With an in-core object data in "map", rehash it to make sure the
1022  * object name actually matches "oid" to detect object corruption.
1023  * With "map" == NULL, try reading the object named with "oid" using
1024  * the streaming interface and rehash it to do the same.
1025  */
1026 int check_object_signature(struct repository *r, const struct object_id *oid,
1027                            void *map, unsigned long size, const char *type)
1028 {
1029         struct object_id real_oid;
1030         enum object_type obj_type;
1031         struct git_istream *st;
1032         git_hash_ctx c;
1033         char hdr[MAX_HEADER_LEN];
1034         int hdrlen;
1035
1036         if (map) {
1037                 hash_object_file(r->hash_algo, map, size, type, &real_oid);
1038                 return !oideq(oid, &real_oid) ? -1 : 0;
1039         }
1040
1041         st = open_istream(r, oid, &obj_type, &size, NULL);
1042         if (!st)
1043                 return -1;
1044
1045         /* Generate the header */
1046         hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %"PRIuMAX , type_name(obj_type), (uintmax_t)size) + 1;
1047
1048         /* Sha1.. */
1049         r->hash_algo->init_fn(&c);
1050         r->hash_algo->update_fn(&c, hdr, hdrlen);
1051         for (;;) {
1052                 char buf[1024 * 16];
1053                 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1054
1055                 if (readlen < 0) {
1056                         close_istream(st);
1057                         return -1;
1058                 }
1059                 if (!readlen)
1060                         break;
1061                 r->hash_algo->update_fn(&c, buf, readlen);
1062         }
1063         r->hash_algo->final_oid_fn(&real_oid, &c);
1064         close_istream(st);
1065         return !oideq(oid, &real_oid) ? -1 : 0;
1066 }
1067
1068 int git_open_cloexec(const char *name, int flags)
1069 {
1070         int fd;
1071         static int o_cloexec = O_CLOEXEC;
1072
1073         fd = open(name, flags | o_cloexec);
1074         if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
1075                 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1076                 o_cloexec &= ~O_CLOEXEC;
1077                 fd = open(name, flags | o_cloexec);
1078         }
1079
1080 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
1081         {
1082                 static int fd_cloexec = FD_CLOEXEC;
1083
1084                 if (!o_cloexec && 0 <= fd && fd_cloexec) {
1085                         /* Opened w/o O_CLOEXEC?  try with fcntl(2) to add it */
1086                         int flags = fcntl(fd, F_GETFD);
1087                         if (fcntl(fd, F_SETFD, flags | fd_cloexec))
1088                                 fd_cloexec = 0;
1089                 }
1090         }
1091 #endif
1092         return fd;
1093 }
1094
1095 /*
1096  * Find "oid" as a loose object in the local repository or in an alternate.
1097  * Returns 0 on success, negative on failure.
1098  *
1099  * The "path" out-parameter will give the path of the object we found (if any).
1100  * Note that it may point to static storage and is only valid until another
1101  * call to stat_loose_object().
1102  */
1103 static int stat_loose_object(struct repository *r, const struct object_id *oid,
1104                              struct stat *st, const char **path)
1105 {
1106         struct object_directory *odb;
1107         static struct strbuf buf = STRBUF_INIT;
1108
1109         prepare_alt_odb(r);
1110         for (odb = r->objects->odb; odb; odb = odb->next) {
1111                 *path = odb_loose_path(odb, &buf, oid);
1112                 if (!lstat(*path, st))
1113                         return 0;
1114         }
1115
1116         return -1;
1117 }
1118
1119 /*
1120  * Like stat_loose_object(), but actually open the object and return the
1121  * descriptor. See the caveats on the "path" parameter above.
1122  */
1123 static int open_loose_object(struct repository *r,
1124                              const struct object_id *oid, const char **path)
1125 {
1126         int fd;
1127         struct object_directory *odb;
1128         int most_interesting_errno = ENOENT;
1129         static struct strbuf buf = STRBUF_INIT;
1130
1131         prepare_alt_odb(r);
1132         for (odb = r->objects->odb; odb; odb = odb->next) {
1133                 *path = odb_loose_path(odb, &buf, oid);
1134                 fd = git_open(*path);
1135                 if (fd >= 0)
1136                         return fd;
1137
1138                 if (most_interesting_errno == ENOENT)
1139                         most_interesting_errno = errno;
1140         }
1141         errno = most_interesting_errno;
1142         return -1;
1143 }
1144
1145 static int quick_has_loose(struct repository *r,
1146                            const struct object_id *oid)
1147 {
1148         struct object_directory *odb;
1149
1150         prepare_alt_odb(r);
1151         for (odb = r->objects->odb; odb; odb = odb->next) {
1152                 if (oid_array_lookup(odb_loose_cache(odb, oid), oid) >= 0)
1153                         return 1;
1154         }
1155         return 0;
1156 }
1157
1158 /*
1159  * Map the loose object at "path" if it is not NULL, or the path found by
1160  * searching for a loose object named "oid".
1161  */
1162 static void *map_loose_object_1(struct repository *r, const char *path,
1163                              const struct object_id *oid, unsigned long *size)
1164 {
1165         void *map;
1166         int fd;
1167
1168         if (path)
1169                 fd = git_open(path);
1170         else
1171                 fd = open_loose_object(r, oid, &path);
1172         map = NULL;
1173         if (fd >= 0) {
1174                 struct stat st;
1175
1176                 if (!fstat(fd, &st)) {
1177                         *size = xsize_t(st.st_size);
1178                         if (!*size) {
1179                                 /* mmap() is forbidden on empty files */
1180                                 error(_("object file %s is empty"), path);
1181                                 close(fd);
1182                                 return NULL;
1183                         }
1184                         map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1185                 }
1186                 close(fd);
1187         }
1188         return map;
1189 }
1190
1191 void *map_loose_object(struct repository *r,
1192                        const struct object_id *oid,
1193                        unsigned long *size)
1194 {
1195         return map_loose_object_1(r, NULL, oid, size);
1196 }
1197
1198 static int unpack_loose_short_header(git_zstream *stream,
1199                                      unsigned char *map, unsigned long mapsize,
1200                                      void *buffer, unsigned long bufsiz)
1201 {
1202         int ret;
1203
1204         /* Get the data stream */
1205         memset(stream, 0, sizeof(*stream));
1206         stream->next_in = map;
1207         stream->avail_in = mapsize;
1208         stream->next_out = buffer;
1209         stream->avail_out = bufsiz;
1210
1211         git_inflate_init(stream);
1212         obj_read_unlock();
1213         ret = git_inflate(stream, 0);
1214         obj_read_lock();
1215
1216         return ret;
1217 }
1218
1219 int unpack_loose_header(git_zstream *stream,
1220                         unsigned char *map, unsigned long mapsize,
1221                         void *buffer, unsigned long bufsiz)
1222 {
1223         int status = unpack_loose_short_header(stream, map, mapsize,
1224                                                buffer, bufsiz);
1225
1226         if (status < Z_OK)
1227                 return status;
1228
1229         /* Make sure we have the terminating NUL */
1230         if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1231                 return -1;
1232         return 0;
1233 }
1234
1235 static int unpack_loose_header_to_strbuf(git_zstream *stream, unsigned char *map,
1236                                          unsigned long mapsize, void *buffer,
1237                                          unsigned long bufsiz, struct strbuf *header)
1238 {
1239         int status;
1240
1241         status = unpack_loose_short_header(stream, map, mapsize, buffer, bufsiz);
1242         if (status < Z_OK)
1243                 return -1;
1244
1245         /*
1246          * Check if entire header is unpacked in the first iteration.
1247          */
1248         if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1249                 return 0;
1250
1251         /*
1252          * buffer[0..bufsiz] was not large enough.  Copy the partial
1253          * result out to header, and then append the result of further
1254          * reading the stream.
1255          */
1256         strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1257         stream->next_out = buffer;
1258         stream->avail_out = bufsiz;
1259
1260         do {
1261                 obj_read_unlock();
1262                 status = git_inflate(stream, 0);
1263                 obj_read_lock();
1264                 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1265                 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1266                         return 0;
1267                 stream->next_out = buffer;
1268                 stream->avail_out = bufsiz;
1269         } while (status != Z_STREAM_END);
1270         return -1;
1271 }
1272
1273 static void *unpack_loose_rest(git_zstream *stream,
1274                                void *buffer, unsigned long size,
1275                                const struct object_id *oid)
1276 {
1277         int bytes = strlen(buffer) + 1;
1278         unsigned char *buf = xmallocz(size);
1279         unsigned long n;
1280         int status = Z_OK;
1281
1282         n = stream->total_out - bytes;
1283         if (n > size)
1284                 n = size;
1285         memcpy(buf, (char *) buffer + bytes, n);
1286         bytes = n;
1287         if (bytes <= size) {
1288                 /*
1289                  * The above condition must be (bytes <= size), not
1290                  * (bytes < size).  In other words, even though we
1291                  * expect no more output and set avail_out to zero,
1292                  * the input zlib stream may have bytes that express
1293                  * "this concludes the stream", and we *do* want to
1294                  * eat that input.
1295                  *
1296                  * Otherwise we would not be able to test that we
1297                  * consumed all the input to reach the expected size;
1298                  * we also want to check that zlib tells us that all
1299                  * went well with status == Z_STREAM_END at the end.
1300                  */
1301                 stream->next_out = buf + bytes;
1302                 stream->avail_out = size - bytes;
1303                 while (status == Z_OK) {
1304                         obj_read_unlock();
1305                         status = git_inflate(stream, Z_FINISH);
1306                         obj_read_lock();
1307                 }
1308         }
1309         if (status == Z_STREAM_END && !stream->avail_in) {
1310                 git_inflate_end(stream);
1311                 return buf;
1312         }
1313
1314         if (status < 0)
1315                 error(_("corrupt loose object '%s'"), oid_to_hex(oid));
1316         else if (stream->avail_in)
1317                 error(_("garbage at end of loose object '%s'"),
1318                       oid_to_hex(oid));
1319         free(buf);
1320         return NULL;
1321 }
1322
1323 /*
1324  * We used to just use "sscanf()", but that's actually way
1325  * too permissive for what we want to check. So do an anal
1326  * object header parse by hand.
1327  */
1328 static int parse_loose_header_extended(const char *hdr, struct object_info *oi,
1329                                        unsigned int flags)
1330 {
1331         const char *type_buf = hdr;
1332         unsigned long size;
1333         int type, type_len = 0;
1334
1335         /*
1336          * The type can be of any size but is followed by
1337          * a space.
1338          */
1339         for (;;) {
1340                 char c = *hdr++;
1341                 if (!c)
1342                         return -1;
1343                 if (c == ' ')
1344                         break;
1345                 type_len++;
1346         }
1347
1348         type = type_from_string_gently(type_buf, type_len, 1);
1349         if (oi->type_name)
1350                 strbuf_add(oi->type_name, type_buf, type_len);
1351         /*
1352          * Set type to 0 if its an unknown object and
1353          * we're obtaining the type using '--allow-unknown-type'
1354          * option.
1355          */
1356         if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1357                 type = 0;
1358         else if (type < 0)
1359                 die(_("invalid object type"));
1360         if (oi->typep)
1361                 *oi->typep = type;
1362
1363         /*
1364          * The length must follow immediately, and be in canonical
1365          * decimal format (ie "010" is not valid).
1366          */
1367         size = *hdr++ - '0';
1368         if (size > 9)
1369                 return -1;
1370         if (size) {
1371                 for (;;) {
1372                         unsigned long c = *hdr - '0';
1373                         if (c > 9)
1374                                 break;
1375                         hdr++;
1376                         size = size * 10 + c;
1377                 }
1378         }
1379
1380         if (oi->sizep)
1381                 *oi->sizep = size;
1382
1383         /*
1384          * The length must be followed by a zero byte
1385          */
1386         return *hdr ? -1 : type;
1387 }
1388
1389 int parse_loose_header(const char *hdr, unsigned long *sizep)
1390 {
1391         struct object_info oi = OBJECT_INFO_INIT;
1392
1393         oi.sizep = sizep;
1394         return parse_loose_header_extended(hdr, &oi, 0);
1395 }
1396
1397 static int loose_object_info(struct repository *r,
1398                              const struct object_id *oid,
1399                              struct object_info *oi, int flags)
1400 {
1401         int status = 0;
1402         unsigned long mapsize;
1403         void *map;
1404         git_zstream stream;
1405         char hdr[MAX_HEADER_LEN];
1406         struct strbuf hdrbuf = STRBUF_INIT;
1407         unsigned long size_scratch;
1408
1409         if (oi->delta_base_oid)
1410                 oidclr(oi->delta_base_oid);
1411
1412         /*
1413          * If we don't care about type or size, then we don't
1414          * need to look inside the object at all. Note that we
1415          * do not optimize out the stat call, even if the
1416          * caller doesn't care about the disk-size, since our
1417          * return value implicitly indicates whether the
1418          * object even exists.
1419          */
1420         if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
1421                 const char *path;
1422                 struct stat st;
1423                 if (!oi->disk_sizep && (flags & OBJECT_INFO_QUICK))
1424                         return quick_has_loose(r, oid) ? 0 : -1;
1425                 if (stat_loose_object(r, oid, &st, &path) < 0)
1426                         return -1;
1427                 if (oi->disk_sizep)
1428                         *oi->disk_sizep = st.st_size;
1429                 return 0;
1430         }
1431
1432         map = map_loose_object(r, oid, &mapsize);
1433         if (!map)
1434                 return -1;
1435
1436         if (!oi->sizep)
1437                 oi->sizep = &size_scratch;
1438
1439         if (oi->disk_sizep)
1440                 *oi->disk_sizep = mapsize;
1441         if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
1442                 if (unpack_loose_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
1443                         status = error(_("unable to unpack %s header with --allow-unknown-type"),
1444                                        oid_to_hex(oid));
1445         } else if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1446                 status = error(_("unable to unpack %s header"),
1447                                oid_to_hex(oid));
1448         if (status < 0)
1449                 ; /* Do nothing */
1450         else if (hdrbuf.len) {
1451                 if ((status = parse_loose_header_extended(hdrbuf.buf, oi, flags)) < 0)
1452                         status = error(_("unable to parse %s header with --allow-unknown-type"),
1453                                        oid_to_hex(oid));
1454         } else if ((status = parse_loose_header_extended(hdr, oi, flags)) < 0)
1455                 status = error(_("unable to parse %s header"), oid_to_hex(oid));
1456
1457         if (status >= 0 && oi->contentp) {
1458                 *oi->contentp = unpack_loose_rest(&stream, hdr,
1459                                                   *oi->sizep, oid);
1460                 if (!*oi->contentp) {
1461                         git_inflate_end(&stream);
1462                         status = -1;
1463                 }
1464         } else
1465                 git_inflate_end(&stream);
1466
1467         munmap(map, mapsize);
1468         if (status && oi->typep)
1469                 *oi->typep = status;
1470         if (oi->sizep == &size_scratch)
1471                 oi->sizep = NULL;
1472         strbuf_release(&hdrbuf);
1473         oi->whence = OI_LOOSE;
1474         return (status < 0) ? status : 0;
1475 }
1476
1477 int obj_read_use_lock = 0;
1478 pthread_mutex_t obj_read_mutex;
1479
1480 void enable_obj_read_lock(void)
1481 {
1482         if (obj_read_use_lock)
1483                 return;
1484
1485         obj_read_use_lock = 1;
1486         init_recursive_mutex(&obj_read_mutex);
1487 }
1488
1489 void disable_obj_read_lock(void)
1490 {
1491         if (!obj_read_use_lock)
1492                 return;
1493
1494         obj_read_use_lock = 0;
1495         pthread_mutex_destroy(&obj_read_mutex);
1496 }
1497
1498 int fetch_if_missing = 1;
1499
1500 static int do_oid_object_info_extended(struct repository *r,
1501                                        const struct object_id *oid,
1502                                        struct object_info *oi, unsigned flags)
1503 {
1504         static struct object_info blank_oi = OBJECT_INFO_INIT;
1505         struct cached_object *co;
1506         struct pack_entry e;
1507         int rtype;
1508         const struct object_id *real = oid;
1509         int already_retried = 0;
1510
1511
1512         if (flags & OBJECT_INFO_LOOKUP_REPLACE)
1513                 real = lookup_replace_object(r, oid);
1514
1515         if (is_null_oid(real))
1516                 return -1;
1517
1518         if (!oi)
1519                 oi = &blank_oi;
1520
1521         co = find_cached_object(real);
1522         if (co) {
1523                 if (oi->typep)
1524                         *(oi->typep) = co->type;
1525                 if (oi->sizep)
1526                         *(oi->sizep) = co->size;
1527                 if (oi->disk_sizep)
1528                         *(oi->disk_sizep) = 0;
1529                 if (oi->delta_base_oid)
1530                         oidclr(oi->delta_base_oid);
1531                 if (oi->type_name)
1532                         strbuf_addstr(oi->type_name, type_name(co->type));
1533                 if (oi->contentp)
1534                         *oi->contentp = xmemdupz(co->buf, co->size);
1535                 oi->whence = OI_CACHED;
1536                 return 0;
1537         }
1538
1539         while (1) {
1540                 if (find_pack_entry(r, real, &e))
1541                         break;
1542
1543                 if (flags & OBJECT_INFO_IGNORE_LOOSE)
1544                         return -1;
1545
1546                 /* Most likely it's a loose object. */
1547                 if (!loose_object_info(r, real, oi, flags))
1548                         return 0;
1549
1550                 /* Not a loose object; someone else may have just packed it. */
1551                 if (!(flags & OBJECT_INFO_QUICK)) {
1552                         reprepare_packed_git(r);
1553                         if (find_pack_entry(r, real, &e))
1554                                 break;
1555                 }
1556
1557                 /* Check if it is a missing object */
1558                 if (fetch_if_missing && has_promisor_remote() &&
1559                     !already_retried && r == the_repository &&
1560                     !(flags & OBJECT_INFO_SKIP_FETCH_OBJECT)) {
1561                         /*
1562                          * TODO Investigate checking promisor_remote_get_direct()
1563                          * TODO return value and stopping on error here.
1564                          * TODO Pass a repository struct through
1565                          * promisor_remote_get_direct(), such that arbitrary
1566                          * repositories work.
1567                          */
1568                         promisor_remote_get_direct(r, real, 1);
1569                         already_retried = 1;
1570                         continue;
1571                 }
1572
1573                 return -1;
1574         }
1575
1576         if (oi == &blank_oi)
1577                 /*
1578                  * We know that the caller doesn't actually need the
1579                  * information below, so return early.
1580                  */
1581                 return 0;
1582         rtype = packed_object_info(r, e.p, e.offset, oi);
1583         if (rtype < 0) {
1584                 mark_bad_packed_object(e.p, real->hash);
1585                 return do_oid_object_info_extended(r, real, oi, 0);
1586         } else if (oi->whence == OI_PACKED) {
1587                 oi->u.packed.offset = e.offset;
1588                 oi->u.packed.pack = e.p;
1589                 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1590                                          rtype == OBJ_OFS_DELTA);
1591         }
1592
1593         return 0;
1594 }
1595
1596 int oid_object_info_extended(struct repository *r, const struct object_id *oid,
1597                              struct object_info *oi, unsigned flags)
1598 {
1599         int ret;
1600         obj_read_lock();
1601         ret = do_oid_object_info_extended(r, oid, oi, flags);
1602         obj_read_unlock();
1603         return ret;
1604 }
1605
1606
1607 /* returns enum object_type or negative */
1608 int oid_object_info(struct repository *r,
1609                     const struct object_id *oid,
1610                     unsigned long *sizep)
1611 {
1612         enum object_type type;
1613         struct object_info oi = OBJECT_INFO_INIT;
1614
1615         oi.typep = &type;
1616         oi.sizep = sizep;
1617         if (oid_object_info_extended(r, oid, &oi,
1618                                       OBJECT_INFO_LOOKUP_REPLACE) < 0)
1619                 return -1;
1620         return type;
1621 }
1622
1623 static void *read_object(struct repository *r,
1624                          const struct object_id *oid, enum object_type *type,
1625                          unsigned long *size)
1626 {
1627         struct object_info oi = OBJECT_INFO_INIT;
1628         void *content;
1629         oi.typep = type;
1630         oi.sizep = size;
1631         oi.contentp = &content;
1632
1633         if (oid_object_info_extended(r, oid, &oi, 0) < 0)
1634                 return NULL;
1635         return content;
1636 }
1637
1638 int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1639                         struct object_id *oid)
1640 {
1641         struct cached_object *co;
1642
1643         hash_object_file(the_hash_algo, buf, len, type_name(type), oid);
1644         if (has_object_file_with_flags(oid, OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT) ||
1645             find_cached_object(oid))
1646                 return 0;
1647         ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1648         co = &cached_objects[cached_object_nr++];
1649         co->size = len;
1650         co->type = type;
1651         co->buf = xmalloc(len);
1652         memcpy(co->buf, buf, len);
1653         oidcpy(&co->oid, oid);
1654         return 0;
1655 }
1656
1657 /*
1658  * This function dies on corrupt objects; the callers who want to
1659  * deal with them should arrange to call read_object() and give error
1660  * messages themselves.
1661  */
1662 void *read_object_file_extended(struct repository *r,
1663                                 const struct object_id *oid,
1664                                 enum object_type *type,
1665                                 unsigned long *size,
1666                                 int lookup_replace)
1667 {
1668         void *data;
1669         const struct packed_git *p;
1670         const char *path;
1671         struct stat st;
1672         const struct object_id *repl = lookup_replace ?
1673                 lookup_replace_object(r, oid) : oid;
1674
1675         errno = 0;
1676         data = read_object(r, repl, type, size);
1677         if (data)
1678                 return data;
1679
1680         obj_read_lock();
1681         if (errno && errno != ENOENT)
1682                 die_errno(_("failed to read object %s"), oid_to_hex(oid));
1683
1684         /* die if we replaced an object with one that does not exist */
1685         if (repl != oid)
1686                 die(_("replacement %s not found for %s"),
1687                     oid_to_hex(repl), oid_to_hex(oid));
1688
1689         if (!stat_loose_object(r, repl, &st, &path))
1690                 die(_("loose object %s (stored in %s) is corrupt"),
1691                     oid_to_hex(repl), path);
1692
1693         if ((p = has_packed_and_bad(r, repl->hash)) != NULL)
1694                 die(_("packed object %s (stored in %s) is corrupt"),
1695                     oid_to_hex(repl), p->pack_name);
1696         obj_read_unlock();
1697
1698         return NULL;
1699 }
1700
1701 void *read_object_with_reference(struct repository *r,
1702                                  const struct object_id *oid,
1703                                  const char *required_type_name,
1704                                  unsigned long *size,
1705                                  struct object_id *actual_oid_return)
1706 {
1707         enum object_type type, required_type;
1708         void *buffer;
1709         unsigned long isize;
1710         struct object_id actual_oid;
1711
1712         required_type = type_from_string(required_type_name);
1713         oidcpy(&actual_oid, oid);
1714         while (1) {
1715                 int ref_length = -1;
1716                 const char *ref_type = NULL;
1717
1718                 buffer = repo_read_object_file(r, &actual_oid, &type, &isize);
1719                 if (!buffer)
1720                         return NULL;
1721                 if (type == required_type) {
1722                         *size = isize;
1723                         if (actual_oid_return)
1724                                 oidcpy(actual_oid_return, &actual_oid);
1725                         return buffer;
1726                 }
1727                 /* Handle references */
1728                 else if (type == OBJ_COMMIT)
1729                         ref_type = "tree ";
1730                 else if (type == OBJ_TAG)
1731                         ref_type = "object ";
1732                 else {
1733                         free(buffer);
1734                         return NULL;
1735                 }
1736                 ref_length = strlen(ref_type);
1737
1738                 if (ref_length + the_hash_algo->hexsz > isize ||
1739                     memcmp(buffer, ref_type, ref_length) ||
1740                     get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
1741                         free(buffer);
1742                         return NULL;
1743                 }
1744                 free(buffer);
1745                 /* Now we have the ID of the referred-to object in
1746                  * actual_oid.  Check again. */
1747         }
1748 }
1749
1750 static void write_object_file_prepare(const struct git_hash_algo *algo,
1751                                       const void *buf, unsigned long len,
1752                                       const char *type, struct object_id *oid,
1753                                       char *hdr, int *hdrlen)
1754 {
1755         git_hash_ctx c;
1756
1757         /* Generate the header */
1758         *hdrlen = xsnprintf(hdr, *hdrlen, "%s %"PRIuMAX , type, (uintmax_t)len)+1;
1759
1760         /* Sha1.. */
1761         algo->init_fn(&c);
1762         algo->update_fn(&c, hdr, *hdrlen);
1763         algo->update_fn(&c, buf, len);
1764         algo->final_oid_fn(oid, &c);
1765 }
1766
1767 /*
1768  * Move the just written object into its final resting place.
1769  */
1770 int finalize_object_file(const char *tmpfile, const char *filename)
1771 {
1772         int ret = 0;
1773
1774         if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
1775                 goto try_rename;
1776         else if (link(tmpfile, filename))
1777                 ret = errno;
1778
1779         /*
1780          * Coda hack - coda doesn't like cross-directory links,
1781          * so we fall back to a rename, which will mean that it
1782          * won't be able to check collisions, but that's not a
1783          * big deal.
1784          *
1785          * The same holds for FAT formatted media.
1786          *
1787          * When this succeeds, we just return.  We have nothing
1788          * left to unlink.
1789          */
1790         if (ret && ret != EEXIST) {
1791         try_rename:
1792                 if (!rename(tmpfile, filename))
1793                         goto out;
1794                 ret = errno;
1795         }
1796         unlink_or_warn(tmpfile);
1797         if (ret) {
1798                 if (ret != EEXIST) {
1799                         return error_errno(_("unable to write file %s"), filename);
1800                 }
1801                 /* FIXME!!! Collision check here ? */
1802         }
1803
1804 out:
1805         if (adjust_shared_perm(filename))
1806                 return error(_("unable to set permission to '%s'"), filename);
1807         return 0;
1808 }
1809
1810 static int write_buffer(int fd, const void *buf, size_t len)
1811 {
1812         if (write_in_full(fd, buf, len) < 0)
1813                 return error_errno(_("file write error"));
1814         return 0;
1815 }
1816
1817 int hash_object_file(const struct git_hash_algo *algo, const void *buf,
1818                      unsigned long len, const char *type,
1819                      struct object_id *oid)
1820 {
1821         char hdr[MAX_HEADER_LEN];
1822         int hdrlen = sizeof(hdr);
1823         write_object_file_prepare(algo, buf, len, type, oid, hdr, &hdrlen);
1824         return 0;
1825 }
1826
1827 /* Finalize a file on disk, and close it. */
1828 static void close_loose_object(int fd)
1829 {
1830         if (fsync_object_files)
1831                 fsync_or_die(fd, "loose object file");
1832         if (close(fd) != 0)
1833                 die_errno(_("error when closing loose object file"));
1834 }
1835
1836 /* Size of directory component, including the ending '/' */
1837 static inline int directory_size(const char *filename)
1838 {
1839         const char *s = strrchr(filename, '/');
1840         if (!s)
1841                 return 0;
1842         return s - filename + 1;
1843 }
1844
1845 /*
1846  * This creates a temporary file in the same directory as the final
1847  * 'filename'
1848  *
1849  * We want to avoid cross-directory filename renames, because those
1850  * can have problems on various filesystems (FAT, NFS, Coda).
1851  */
1852 static int create_tmpfile(struct strbuf *tmp, const char *filename)
1853 {
1854         int fd, dirlen = directory_size(filename);
1855
1856         strbuf_reset(tmp);
1857         strbuf_add(tmp, filename, dirlen);
1858         strbuf_addstr(tmp, "tmp_obj_XXXXXX");
1859         fd = git_mkstemp_mode(tmp->buf, 0444);
1860         if (fd < 0 && dirlen && errno == ENOENT) {
1861                 /*
1862                  * Make sure the directory exists; note that the contents
1863                  * of the buffer are undefined after mkstemp returns an
1864                  * error, so we have to rewrite the whole buffer from
1865                  * scratch.
1866                  */
1867                 strbuf_reset(tmp);
1868                 strbuf_add(tmp, filename, dirlen - 1);
1869                 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
1870                         return -1;
1871                 if (adjust_shared_perm(tmp->buf))
1872                         return -1;
1873
1874                 /* Try again */
1875                 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
1876                 fd = git_mkstemp_mode(tmp->buf, 0444);
1877         }
1878         return fd;
1879 }
1880
1881 static int write_loose_object(const struct object_id *oid, char *hdr,
1882                               int hdrlen, const void *buf, unsigned long len,
1883                               time_t mtime)
1884 {
1885         int fd, ret;
1886         unsigned char compressed[4096];
1887         git_zstream stream;
1888         git_hash_ctx c;
1889         struct object_id parano_oid;
1890         static struct strbuf tmp_file = STRBUF_INIT;
1891         static struct strbuf filename = STRBUF_INIT;
1892
1893         loose_object_path(the_repository, &filename, oid);
1894
1895         fd = create_tmpfile(&tmp_file, filename.buf);
1896         if (fd < 0) {
1897                 if (errno == EACCES)
1898                         return error(_("insufficient permission for adding an object to repository database %s"), get_object_directory());
1899                 else
1900                         return error_errno(_("unable to create temporary file"));
1901         }
1902
1903         /* Set it up */
1904         git_deflate_init(&stream, zlib_compression_level);
1905         stream.next_out = compressed;
1906         stream.avail_out = sizeof(compressed);
1907         the_hash_algo->init_fn(&c);
1908
1909         /* First header.. */
1910         stream.next_in = (unsigned char *)hdr;
1911         stream.avail_in = hdrlen;
1912         while (git_deflate(&stream, 0) == Z_OK)
1913                 ; /* nothing */
1914         the_hash_algo->update_fn(&c, hdr, hdrlen);
1915
1916         /* Then the data itself.. */
1917         stream.next_in = (void *)buf;
1918         stream.avail_in = len;
1919         do {
1920                 unsigned char *in0 = stream.next_in;
1921                 ret = git_deflate(&stream, Z_FINISH);
1922                 the_hash_algo->update_fn(&c, in0, stream.next_in - in0);
1923                 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
1924                         die(_("unable to write loose object file"));
1925                 stream.next_out = compressed;
1926                 stream.avail_out = sizeof(compressed);
1927         } while (ret == Z_OK);
1928
1929         if (ret != Z_STREAM_END)
1930                 die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
1931                     ret);
1932         ret = git_deflate_end_gently(&stream);
1933         if (ret != Z_OK)
1934                 die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
1935                     ret);
1936         the_hash_algo->final_oid_fn(&parano_oid, &c);
1937         if (!oideq(oid, &parano_oid))
1938                 die(_("confused by unstable object source data for %s"),
1939                     oid_to_hex(oid));
1940
1941         close_loose_object(fd);
1942
1943         if (mtime) {
1944                 struct utimbuf utb;
1945                 utb.actime = mtime;
1946                 utb.modtime = mtime;
1947                 if (utime(tmp_file.buf, &utb) < 0)
1948                         warning_errno(_("failed utime() on %s"), tmp_file.buf);
1949         }
1950
1951         return finalize_object_file(tmp_file.buf, filename.buf);
1952 }
1953
1954 static int freshen_loose_object(const struct object_id *oid)
1955 {
1956         return check_and_freshen(oid, 1);
1957 }
1958
1959 static int freshen_packed_object(const struct object_id *oid)
1960 {
1961         struct pack_entry e;
1962         if (!find_pack_entry(the_repository, oid, &e))
1963                 return 0;
1964         if (e.p->freshened)
1965                 return 1;
1966         if (!freshen_file(e.p->pack_name))
1967                 return 0;
1968         e.p->freshened = 1;
1969         return 1;
1970 }
1971
1972 int write_object_file(const void *buf, unsigned long len, const char *type,
1973                       struct object_id *oid)
1974 {
1975         char hdr[MAX_HEADER_LEN];
1976         int hdrlen = sizeof(hdr);
1977
1978         /* Normally if we have it in the pack then we do not bother writing
1979          * it out into .git/objects/??/?{38} file.
1980          */
1981         write_object_file_prepare(the_hash_algo, buf, len, type, oid, hdr,
1982                                   &hdrlen);
1983         if (freshen_packed_object(oid) || freshen_loose_object(oid))
1984                 return 0;
1985         return write_loose_object(oid, hdr, hdrlen, buf, len, 0);
1986 }
1987
1988 int hash_object_file_literally(const void *buf, unsigned long len,
1989                                const char *type, struct object_id *oid,
1990                                unsigned flags)
1991 {
1992         char *header;
1993         int hdrlen, status = 0;
1994
1995         /* type string, SP, %lu of the length plus NUL must fit this */
1996         hdrlen = strlen(type) + MAX_HEADER_LEN;
1997         header = xmalloc(hdrlen);
1998         write_object_file_prepare(the_hash_algo, buf, len, type, oid, header,
1999                                   &hdrlen);
2000
2001         if (!(flags & HASH_WRITE_OBJECT))
2002                 goto cleanup;
2003         if (freshen_packed_object(oid) || freshen_loose_object(oid))
2004                 goto cleanup;
2005         status = write_loose_object(oid, header, hdrlen, buf, len, 0);
2006
2007 cleanup:
2008         free(header);
2009         return status;
2010 }
2011
2012 int force_object_loose(const struct object_id *oid, time_t mtime)
2013 {
2014         void *buf;
2015         unsigned long len;
2016         enum object_type type;
2017         char hdr[MAX_HEADER_LEN];
2018         int hdrlen;
2019         int ret;
2020
2021         if (has_loose_object(oid))
2022                 return 0;
2023         buf = read_object(the_repository, oid, &type, &len);
2024         if (!buf)
2025                 return error(_("cannot read object for %s"), oid_to_hex(oid));
2026         hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %"PRIuMAX , type_name(type), (uintmax_t)len) + 1;
2027         ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime);
2028         free(buf);
2029
2030         return ret;
2031 }
2032
2033 int has_object(struct repository *r, const struct object_id *oid,
2034                unsigned flags)
2035 {
2036         int quick = !(flags & HAS_OBJECT_RECHECK_PACKED);
2037         unsigned object_info_flags = OBJECT_INFO_SKIP_FETCH_OBJECT |
2038                 (quick ? OBJECT_INFO_QUICK : 0);
2039
2040         if (!startup_info->have_repository)
2041                 return 0;
2042         return oid_object_info_extended(r, oid, NULL, object_info_flags) >= 0;
2043 }
2044
2045 int repo_has_object_file_with_flags(struct repository *r,
2046                                     const struct object_id *oid, int flags)
2047 {
2048         if (!startup_info->have_repository)
2049                 return 0;
2050         return oid_object_info_extended(r, oid, NULL, flags) >= 0;
2051 }
2052
2053 int repo_has_object_file(struct repository *r,
2054                          const struct object_id *oid)
2055 {
2056         return repo_has_object_file_with_flags(r, oid, 0);
2057 }
2058
2059 static void check_tree(const void *buf, size_t size)
2060 {
2061         struct tree_desc desc;
2062         struct name_entry entry;
2063
2064         init_tree_desc(&desc, buf, size);
2065         while (tree_entry(&desc, &entry))
2066                 /* do nothing
2067                  * tree_entry() will die() on malformed entries */
2068                 ;
2069 }
2070
2071 static void check_commit(const void *buf, size_t size)
2072 {
2073         struct commit c;
2074         memset(&c, 0, sizeof(c));
2075         if (parse_commit_buffer(the_repository, &c, buf, size, 0))
2076                 die(_("corrupt commit"));
2077 }
2078
2079 static void check_tag(const void *buf, size_t size)
2080 {
2081         struct tag t;
2082         memset(&t, 0, sizeof(t));
2083         if (parse_tag_buffer(the_repository, &t, buf, size))
2084                 die(_("corrupt tag"));
2085 }
2086
2087 static int index_mem(struct index_state *istate,
2088                      struct object_id *oid, void *buf, size_t size,
2089                      enum object_type type,
2090                      const char *path, unsigned flags)
2091 {
2092         int ret, re_allocated = 0;
2093         int write_object = flags & HASH_WRITE_OBJECT;
2094
2095         if (!type)
2096                 type = OBJ_BLOB;
2097
2098         /*
2099          * Convert blobs to git internal format
2100          */
2101         if ((type == OBJ_BLOB) && path) {
2102                 struct strbuf nbuf = STRBUF_INIT;
2103                 if (convert_to_git(istate, path, buf, size, &nbuf,
2104                                    get_conv_flags(flags))) {
2105                         buf = strbuf_detach(&nbuf, &size);
2106                         re_allocated = 1;
2107                 }
2108         }
2109         if (flags & HASH_FORMAT_CHECK) {
2110                 if (type == OBJ_TREE)
2111                         check_tree(buf, size);
2112                 if (type == OBJ_COMMIT)
2113                         check_commit(buf, size);
2114                 if (type == OBJ_TAG)
2115                         check_tag(buf, size);
2116         }
2117
2118         if (write_object)
2119                 ret = write_object_file(buf, size, type_name(type), oid);
2120         else
2121                 ret = hash_object_file(the_hash_algo, buf, size,
2122                                        type_name(type), oid);
2123         if (re_allocated)
2124                 free(buf);
2125         return ret;
2126 }
2127
2128 static int index_stream_convert_blob(struct index_state *istate,
2129                                      struct object_id *oid,
2130                                      int fd,
2131                                      const char *path,
2132                                      unsigned flags)
2133 {
2134         int ret;
2135         const int write_object = flags & HASH_WRITE_OBJECT;
2136         struct strbuf sbuf = STRBUF_INIT;
2137
2138         assert(path);
2139         assert(would_convert_to_git_filter_fd(istate, path));
2140
2141         convert_to_git_filter_fd(istate, path, fd, &sbuf,
2142                                  get_conv_flags(flags));
2143
2144         if (write_object)
2145                 ret = write_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
2146                                         oid);
2147         else
2148                 ret = hash_object_file(the_hash_algo, sbuf.buf, sbuf.len,
2149                                        type_name(OBJ_BLOB), oid);
2150         strbuf_release(&sbuf);
2151         return ret;
2152 }
2153
2154 static int index_pipe(struct index_state *istate, struct object_id *oid,
2155                       int fd, enum object_type type,
2156                       const char *path, unsigned flags)
2157 {
2158         struct strbuf sbuf = STRBUF_INIT;
2159         int ret;
2160
2161         if (strbuf_read(&sbuf, fd, 4096) >= 0)
2162                 ret = index_mem(istate, oid, sbuf.buf, sbuf.len, type, path, flags);
2163         else
2164                 ret = -1;
2165         strbuf_release(&sbuf);
2166         return ret;
2167 }
2168
2169 #define SMALL_FILE_SIZE (32*1024)
2170
2171 static int index_core(struct index_state *istate,
2172                       struct object_id *oid, int fd, size_t size,
2173                       enum object_type type, const char *path,
2174                       unsigned flags)
2175 {
2176         int ret;
2177
2178         if (!size) {
2179                 ret = index_mem(istate, oid, "", size, type, path, flags);
2180         } else if (size <= SMALL_FILE_SIZE) {
2181                 char *buf = xmalloc(size);
2182                 ssize_t read_result = read_in_full(fd, buf, size);
2183                 if (read_result < 0)
2184                         ret = error_errno(_("read error while indexing %s"),
2185                                           path ? path : "<unknown>");
2186                 else if (read_result != size)
2187                         ret = error(_("short read while indexing %s"),
2188                                     path ? path : "<unknown>");
2189                 else
2190                         ret = index_mem(istate, oid, buf, size, type, path, flags);
2191                 free(buf);
2192         } else {
2193                 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2194                 ret = index_mem(istate, oid, buf, size, type, path, flags);
2195                 munmap(buf, size);
2196         }
2197         return ret;
2198 }
2199
2200 /*
2201  * This creates one packfile per large blob unless bulk-checkin
2202  * machinery is "plugged".
2203  *
2204  * This also bypasses the usual "convert-to-git" dance, and that is on
2205  * purpose. We could write a streaming version of the converting
2206  * functions and insert that before feeding the data to fast-import
2207  * (or equivalent in-core API described above). However, that is
2208  * somewhat complicated, as we do not know the size of the filter
2209  * result, which we need to know beforehand when writing a git object.
2210  * Since the primary motivation for trying to stream from the working
2211  * tree file and to avoid mmaping it in core is to deal with large
2212  * binary blobs, they generally do not want to get any conversion, and
2213  * callers should avoid this code path when filters are requested.
2214  */
2215 static int index_stream(struct object_id *oid, int fd, size_t size,
2216                         enum object_type type, const char *path,
2217                         unsigned flags)
2218 {
2219         return index_bulk_checkin(oid, fd, size, type, path, flags);
2220 }
2221
2222 int index_fd(struct index_state *istate, struct object_id *oid,
2223              int fd, struct stat *st,
2224              enum object_type type, const char *path, unsigned flags)
2225 {
2226         int ret;
2227
2228         /*
2229          * Call xsize_t() only when needed to avoid potentially unnecessary
2230          * die() for large files.
2231          */
2232         if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path))
2233                 ret = index_stream_convert_blob(istate, oid, fd, path, flags);
2234         else if (!S_ISREG(st->st_mode))
2235                 ret = index_pipe(istate, oid, fd, type, path, flags);
2236         else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
2237                  (path && would_convert_to_git(istate, path)))
2238                 ret = index_core(istate, oid, fd, xsize_t(st->st_size),
2239                                  type, path, flags);
2240         else
2241                 ret = index_stream(oid, fd, xsize_t(st->st_size), type, path,
2242                                    flags);
2243         close(fd);
2244         return ret;
2245 }
2246
2247 int index_path(struct index_state *istate, struct object_id *oid,
2248                const char *path, struct stat *st, unsigned flags)
2249 {
2250         int fd;
2251         struct strbuf sb = STRBUF_INIT;
2252         int rc = 0;
2253
2254         switch (st->st_mode & S_IFMT) {
2255         case S_IFREG:
2256                 fd = open(path, O_RDONLY);
2257                 if (fd < 0)
2258                         return error_errno("open(\"%s\")", path);
2259                 if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
2260                         return error(_("%s: failed to insert into database"),
2261                                      path);
2262                 break;
2263         case S_IFLNK:
2264                 if (strbuf_readlink(&sb, path, st->st_size))
2265                         return error_errno("readlink(\"%s\")", path);
2266                 if (!(flags & HASH_WRITE_OBJECT))
2267                         hash_object_file(the_hash_algo, sb.buf, sb.len,
2268                                          blob_type, oid);
2269                 else if (write_object_file(sb.buf, sb.len, blob_type, oid))
2270                         rc = error(_("%s: failed to insert into database"), path);
2271                 strbuf_release(&sb);
2272                 break;
2273         case S_IFDIR:
2274                 return resolve_gitlink_ref(path, "HEAD", oid);
2275         default:
2276                 return error(_("%s: unsupported file type"), path);
2277         }
2278         return rc;
2279 }
2280
2281 int read_pack_header(int fd, struct pack_header *header)
2282 {
2283         if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
2284                 /* "eof before pack header was fully read" */
2285                 return PH_ERROR_EOF;
2286
2287         if (header->hdr_signature != htonl(PACK_SIGNATURE))
2288                 /* "protocol error (pack signature mismatch detected)" */
2289                 return PH_ERROR_PACK_SIGNATURE;
2290         if (!pack_version_ok(header->hdr_version))
2291                 /* "protocol error (pack version unsupported)" */
2292                 return PH_ERROR_PROTOCOL;
2293         return 0;
2294 }
2295
2296 void assert_oid_type(const struct object_id *oid, enum object_type expect)
2297 {
2298         enum object_type type = oid_object_info(the_repository, oid, NULL);
2299         if (type < 0)
2300                 die(_("%s is not a valid object"), oid_to_hex(oid));
2301         if (type != expect)
2302                 die(_("%s is not a valid '%s' object"), oid_to_hex(oid),
2303                     type_name(expect));
2304 }
2305
2306 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
2307                                 struct strbuf *path,
2308                                 each_loose_object_fn obj_cb,
2309                                 each_loose_cruft_fn cruft_cb,
2310                                 each_loose_subdir_fn subdir_cb,
2311                                 void *data)
2312 {
2313         size_t origlen, baselen;
2314         DIR *dir;
2315         struct dirent *de;
2316         int r = 0;
2317         struct object_id oid;
2318
2319         if (subdir_nr > 0xff)
2320                 BUG("invalid loose object subdirectory: %x", subdir_nr);
2321
2322         origlen = path->len;
2323         strbuf_complete(path, '/');
2324         strbuf_addf(path, "%02x", subdir_nr);
2325
2326         dir = opendir(path->buf);
2327         if (!dir) {
2328                 if (errno != ENOENT)
2329                         r = error_errno(_("unable to open %s"), path->buf);
2330                 strbuf_setlen(path, origlen);
2331                 return r;
2332         }
2333
2334         oid.hash[0] = subdir_nr;
2335         strbuf_addch(path, '/');
2336         baselen = path->len;
2337
2338         while ((de = readdir(dir))) {
2339                 size_t namelen;
2340                 if (is_dot_or_dotdot(de->d_name))
2341                         continue;
2342
2343                 namelen = strlen(de->d_name);
2344                 strbuf_setlen(path, baselen);
2345                 strbuf_add(path, de->d_name, namelen);
2346                 if (namelen == the_hash_algo->hexsz - 2 &&
2347                     !hex_to_bytes(oid.hash + 1, de->d_name,
2348                                   the_hash_algo->rawsz - 1)) {
2349                         oid_set_algo(&oid, the_hash_algo);
2350                         if (obj_cb) {
2351                                 r = obj_cb(&oid, path->buf, data);
2352                                 if (r)
2353                                         break;
2354                         }
2355                         continue;
2356                 }
2357
2358                 if (cruft_cb) {
2359                         r = cruft_cb(de->d_name, path->buf, data);
2360                         if (r)
2361                                 break;
2362                 }
2363         }
2364         closedir(dir);
2365
2366         strbuf_setlen(path, baselen - 1);
2367         if (!r && subdir_cb)
2368                 r = subdir_cb(subdir_nr, path->buf, data);
2369
2370         strbuf_setlen(path, origlen);
2371
2372         return r;
2373 }
2374
2375 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2376                             each_loose_object_fn obj_cb,
2377                             each_loose_cruft_fn cruft_cb,
2378                             each_loose_subdir_fn subdir_cb,
2379                             void *data)
2380 {
2381         int r = 0;
2382         int i;
2383
2384         for (i = 0; i < 256; i++) {
2385                 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2386                                                 subdir_cb, data);
2387                 if (r)
2388                         break;
2389         }
2390
2391         return r;
2392 }
2393
2394 int for_each_loose_file_in_objdir(const char *path,
2395                                   each_loose_object_fn obj_cb,
2396                                   each_loose_cruft_fn cruft_cb,
2397                                   each_loose_subdir_fn subdir_cb,
2398                                   void *data)
2399 {
2400         struct strbuf buf = STRBUF_INIT;
2401         int r;
2402
2403         strbuf_addstr(&buf, path);
2404         r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2405                                               subdir_cb, data);
2406         strbuf_release(&buf);
2407
2408         return r;
2409 }
2410
2411 int for_each_loose_object(each_loose_object_fn cb, void *data,
2412                           enum for_each_object_flags flags)
2413 {
2414         struct object_directory *odb;
2415
2416         prepare_alt_odb(the_repository);
2417         for (odb = the_repository->objects->odb; odb; odb = odb->next) {
2418                 int r = for_each_loose_file_in_objdir(odb->path, cb, NULL,
2419                                                       NULL, data);
2420                 if (r)
2421                         return r;
2422
2423                 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2424                         break;
2425         }
2426
2427         return 0;
2428 }
2429
2430 static int append_loose_object(const struct object_id *oid, const char *path,
2431                                void *data)
2432 {
2433         oid_array_append(data, oid);
2434         return 0;
2435 }
2436
2437 struct oid_array *odb_loose_cache(struct object_directory *odb,
2438                                   const struct object_id *oid)
2439 {
2440         int subdir_nr = oid->hash[0];
2441         struct strbuf buf = STRBUF_INIT;
2442
2443         if (subdir_nr < 0 ||
2444             subdir_nr >= ARRAY_SIZE(odb->loose_objects_subdir_seen))
2445                 BUG("subdir_nr out of range");
2446
2447         if (odb->loose_objects_subdir_seen[subdir_nr])
2448                 return &odb->loose_objects_cache[subdir_nr];
2449
2450         strbuf_addstr(&buf, odb->path);
2451         for_each_file_in_obj_subdir(subdir_nr, &buf,
2452                                     append_loose_object,
2453                                     NULL, NULL,
2454                                     &odb->loose_objects_cache[subdir_nr]);
2455         odb->loose_objects_subdir_seen[subdir_nr] = 1;
2456         strbuf_release(&buf);
2457         return &odb->loose_objects_cache[subdir_nr];
2458 }
2459
2460 void odb_clear_loose_cache(struct object_directory *odb)
2461 {
2462         int i;
2463
2464         for (i = 0; i < ARRAY_SIZE(odb->loose_objects_cache); i++)
2465                 oid_array_clear(&odb->loose_objects_cache[i]);
2466         memset(&odb->loose_objects_subdir_seen, 0,
2467                sizeof(odb->loose_objects_subdir_seen));
2468 }
2469
2470 static int check_stream_oid(git_zstream *stream,
2471                             const char *hdr,
2472                             unsigned long size,
2473                             const char *path,
2474                             const struct object_id *expected_oid)
2475 {
2476         git_hash_ctx c;
2477         struct object_id real_oid;
2478         unsigned char buf[4096];
2479         unsigned long total_read;
2480         int status = Z_OK;
2481
2482         the_hash_algo->init_fn(&c);
2483         the_hash_algo->update_fn(&c, hdr, stream->total_out);
2484
2485         /*
2486          * We already read some bytes into hdr, but the ones up to the NUL
2487          * do not count against the object's content size.
2488          */
2489         total_read = stream->total_out - strlen(hdr) - 1;
2490
2491         /*
2492          * This size comparison must be "<=" to read the final zlib packets;
2493          * see the comment in unpack_loose_rest for details.
2494          */
2495         while (total_read <= size &&
2496                (status == Z_OK ||
2497                 (status == Z_BUF_ERROR && !stream->avail_out))) {
2498                 stream->next_out = buf;
2499                 stream->avail_out = sizeof(buf);
2500                 if (size - total_read < stream->avail_out)
2501                         stream->avail_out = size - total_read;
2502                 status = git_inflate(stream, Z_FINISH);
2503                 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
2504                 total_read += stream->next_out - buf;
2505         }
2506         git_inflate_end(stream);
2507
2508         if (status != Z_STREAM_END) {
2509                 error(_("corrupt loose object '%s'"), oid_to_hex(expected_oid));
2510                 return -1;
2511         }
2512         if (stream->avail_in) {
2513                 error(_("garbage at end of loose object '%s'"),
2514                       oid_to_hex(expected_oid));
2515                 return -1;
2516         }
2517
2518         the_hash_algo->final_oid_fn(&real_oid, &c);
2519         if (!oideq(expected_oid, &real_oid)) {
2520                 error(_("hash mismatch for %s (expected %s)"), path,
2521                       oid_to_hex(expected_oid));
2522                 return -1;
2523         }
2524
2525         return 0;
2526 }
2527
2528 int read_loose_object(const char *path,
2529                       const struct object_id *expected_oid,
2530                       enum object_type *type,
2531                       unsigned long *size,
2532                       void **contents)
2533 {
2534         int ret = -1;
2535         void *map = NULL;
2536         unsigned long mapsize;
2537         git_zstream stream;
2538         char hdr[MAX_HEADER_LEN];
2539
2540         *contents = NULL;
2541
2542         map = map_loose_object_1(the_repository, path, NULL, &mapsize);
2543         if (!map) {
2544                 error_errno(_("unable to mmap %s"), path);
2545                 goto out;
2546         }
2547
2548         if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
2549                 error(_("unable to unpack header of %s"), path);
2550                 goto out;
2551         }
2552
2553         *type = parse_loose_header(hdr, size);
2554         if (*type < 0) {
2555                 error(_("unable to parse header of %s"), path);
2556                 git_inflate_end(&stream);
2557                 goto out;
2558         }
2559
2560         if (*type == OBJ_BLOB && *size > big_file_threshold) {
2561                 if (check_stream_oid(&stream, hdr, *size, path, expected_oid) < 0)
2562                         goto out;
2563         } else {
2564                 *contents = unpack_loose_rest(&stream, hdr, *size, expected_oid);
2565                 if (!*contents) {
2566                         error(_("unable to unpack contents of %s"), path);
2567                         git_inflate_end(&stream);
2568                         goto out;
2569                 }
2570                 if (check_object_signature(the_repository, expected_oid,
2571                                            *contents, *size,
2572                                            type_name(*type))) {
2573                         error(_("hash mismatch for %s (expected %s)"), path,
2574                               oid_to_hex(expected_oid));
2575                         free(*contents);
2576                         goto out;
2577                 }
2578         }
2579
2580         ret = 0; /* everything checks out */
2581
2582 out:
2583         if (map)
2584                 munmap(map, mapsize);
2585         return ret;
2586 }