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