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