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