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