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