2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
11 #include "string-list.h"
17 #include "run-command.h"
20 #include "tree-walk.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"
30 #include "mergesort.h"
33 #include "fetch-object.h"
34 #include "object-store.h"
36 /* The maximum size for an object header. */
37 #define MAX_HEADER_LEN 32
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"
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"
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
53 static const struct object_id empty_blob_oid = {
54 EMPTY_BLOB_SHA1_BIN_LITERAL
57 static void git_hash_sha1_init(git_hash_ctx *ctx)
59 git_SHA1_Init(&ctx->sha1);
62 static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
64 git_SHA1_Update(&ctx->sha1, data, len);
67 static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
69 git_SHA1_Final(hash, &ctx->sha1);
72 static void git_hash_unknown_init(git_hash_ctx *ctx)
74 BUG("trying to init unknown hash");
77 static void git_hash_unknown_update(git_hash_ctx *ctx, const void *data, size_t len)
79 BUG("trying to update unknown hash");
82 static void git_hash_unknown_final(unsigned char *hash, git_hash_ctx *ctx)
84 BUG("trying to finalize unknown hash");
87 const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
93 git_hash_unknown_init,
94 git_hash_unknown_update,
95 git_hash_unknown_final,
101 /* "sha1", big-endian */
106 git_hash_sha1_update,
113 const char *empty_tree_oid_hex(void)
115 static char buf[GIT_MAX_HEXSZ + 1];
116 return oid_to_hex_r(buf, the_hash_algo->empty_tree);
119 const char *empty_blob_oid_hex(void)
121 static char buf[GIT_MAX_HEXSZ + 1];
122 return oid_to_hex_r(buf, the_hash_algo->empty_blob);
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
131 static struct cached_object {
132 struct object_id oid;
133 enum object_type type;
137 static int cached_object_nr, cached_object_alloc;
139 static struct cached_object empty_tree = {
140 { EMPTY_TREE_SHA1_BIN_LITERAL },
146 static struct cached_object *find_cached_object(const struct object_id *oid)
149 struct cached_object *co = cached_objects;
151 for (i = 0; i < cached_object_nr; i++, co++) {
152 if (oideq(&co->oid, oid))
155 if (oideq(oid, the_hash_algo->empty_tree))
161 static int get_conv_flags(unsigned flags)
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;
172 int mkdir_in_gitdir(const char *path)
174 if (mkdir(path, 0777)) {
175 int saved_errno = errno;
177 struct strbuf sb = STRBUF_INIT;
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?
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)) {
198 return adjust_shared_perm(path);
201 enum scld_error safe_create_leading_directories(char *path)
203 char *next_component = path + offset_1st_component(path);
204 enum scld_error ret = SCLD_OK;
206 while (ret == SCLD_OK && next_component) {
208 char *slash = next_component, slash_character;
210 while (*slash && !is_dir_sep(*slash))
216 next_component = slash + 1;
217 while (is_dir_sep(*next_component))
219 if (!*next_component)
222 slash_character = *slash;
224 if (!stat(path, &st)) {
226 if (!S_ISDIR(st.st_mode)) {
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)
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
247 } else if (adjust_shared_perm(path)) {
250 *slash = slash_character;
255 enum scld_error safe_create_leading_directories_const(const char *path)
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);
268 int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
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.
276 int remove_directories_remaining = 1;
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.
285 int create_directories_remaining = 3;
287 /* A scratch copy of path, filled lazily if we need it: */
288 struct strbuf path_copy = STRBUF_INIT;
301 if (errno == EISDIR && remove_directories_remaining-- > 0) {
303 * A directory is in the way. Maybe it is empty; try
307 strbuf_addstr(&path_copy, path);
309 if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
311 } else if (errno == ENOENT && create_directories_remaining-- > 0) {
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
318 enum scld_error scld_result;
321 strbuf_addstr(&path_copy, path);
324 scld_result = safe_create_leading_directories(path_copy.buf);
325 if (scld_result == SCLD_OK)
327 } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
331 strbuf_release(&path_copy);
336 static void fill_sha1_path(struct strbuf *buf, const unsigned char *sha1)
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]);
345 strbuf_addch(buf, '/');
349 void loose_object_path(struct repository *r, struct strbuf *buf,
350 const unsigned char *sha1)
353 strbuf_addstr(buf, r->objects->objectdir);
354 strbuf_addch(buf, '/');
355 fill_sha1_path(buf, sha1);
358 struct strbuf *alt_scratch_buf(struct object_directory *odb)
360 strbuf_setlen(&odb->scratch, odb->base_len);
361 return &odb->scratch;
364 static const char *alt_sha1_path(struct object_directory *odb,
365 const unsigned char *sha1)
367 struct strbuf *buf = alt_scratch_buf(odb);
368 fill_sha1_path(buf, sha1);
373 * Return non-zero iff the path is usable as an alternate object database.
375 static int alt_odb_usable(struct raw_object_store *o,
377 const char *normalized_objdir)
379 struct object_directory *odb;
381 /* Detect cases where alternate disappeared */
382 if (!is_directory(path->buf)) {
383 error(_("object directory %s does not exist; "
384 "check .git/objects/info/alternates"),
390 * Prevent the common mistake of listing the same
391 * thing twice, or object directory itself.
393 for (odb = o->alt_odb_list; odb; odb = odb->next) {
394 if (!fspathcmp(path->buf, odb->path))
397 if (!fspathcmp(path->buf, normalized_objdir))
404 * Prepare alternate object database registry.
406 * The variable alt_odb_list points at the list of struct
407 * object_directory. The elements on this list come from
408 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
409 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
410 * whose contents is similar to that environment variable but can be
411 * LF separated. Its base points at a statically allocated buffer that
412 * contains "/the/directory/corresponding/to/.git/objects/...", while
413 * its name points just after the slash at the end of ".git/objects/"
414 * in the example above, and has enough space to hold 40-byte hex
415 * SHA1, an extra slash for the first level indirection, and the
418 static void read_info_alternates(struct repository *r,
419 const char *relative_base,
421 static int link_alt_odb_entry(struct repository *r, const char *entry,
422 const char *relative_base, int depth, const char *normalized_objdir)
424 struct object_directory *ent;
425 struct strbuf pathbuf = STRBUF_INIT;
427 if (!is_absolute_path(entry) && relative_base) {
428 strbuf_realpath(&pathbuf, relative_base, 1);
429 strbuf_addch(&pathbuf, '/');
431 strbuf_addstr(&pathbuf, entry);
433 if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
434 error(_("unable to normalize alternate object path: %s"),
436 strbuf_release(&pathbuf);
441 * The trailing slash after the directory name is given by
442 * this function at the end. Remove duplicates.
444 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
445 strbuf_setlen(&pathbuf, pathbuf.len - 1);
447 if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir)) {
448 strbuf_release(&pathbuf);
452 ent = alloc_alt_odb(pathbuf.buf);
454 /* add the alternate entry */
455 *r->objects->alt_odb_tail = ent;
456 r->objects->alt_odb_tail = &(ent->next);
459 /* recursively add alternates */
460 read_info_alternates(r, pathbuf.buf, depth + 1);
462 strbuf_release(&pathbuf);
466 static const char *parse_alt_odb_entry(const char *string,
474 if (*string == '#') {
475 /* comment; consume up to next separator */
476 end = strchrnul(string, sep);
477 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
479 * quoted path; unquote_c_style has copied the
480 * data for us and set "end". Broken quoting (e.g.,
481 * an entry that doesn't end with a quote) falls
482 * back to the unquoted case below.
485 /* normal, unquoted path */
486 end = strchrnul(string, sep);
487 strbuf_add(out, string, end - string);
495 static void link_alt_odb_entries(struct repository *r, const char *alt,
496 int sep, const char *relative_base, int depth)
498 struct strbuf objdirbuf = STRBUF_INIT;
499 struct strbuf entry = STRBUF_INIT;
505 error(_("%s: ignoring alternate object stores, nesting too deep"),
510 strbuf_add_absolute_path(&objdirbuf, r->objects->objectdir);
511 if (strbuf_normalize_path(&objdirbuf) < 0)
512 die(_("unable to normalize object directory: %s"),
516 alt = parse_alt_odb_entry(alt, sep, &entry);
519 link_alt_odb_entry(r, entry.buf,
520 relative_base, depth, objdirbuf.buf);
522 strbuf_release(&entry);
523 strbuf_release(&objdirbuf);
526 static void read_info_alternates(struct repository *r,
527 const char *relative_base,
531 struct strbuf buf = STRBUF_INIT;
533 path = xstrfmt("%s/info/alternates", relative_base);
534 if (strbuf_read_file(&buf, path, 1024) < 0) {
535 warn_on_fopen_errors(path);
540 link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
541 strbuf_release(&buf);
545 struct object_directory *alloc_alt_odb(const char *dir)
547 struct object_directory *ent;
549 FLEX_ALLOC_STR(ent, path, dir);
550 strbuf_init(&ent->scratch, 0);
551 strbuf_addf(&ent->scratch, "%s/", dir);
552 ent->base_len = ent->scratch.len;
557 void add_to_alternates_file(const char *reference)
559 struct lock_file lock = LOCK_INIT;
560 char *alts = git_pathdup("objects/info/alternates");
564 hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
565 out = fdopen_lock_file(&lock, "w");
567 die_errno(_("unable to fdopen alternates lockfile"));
569 in = fopen(alts, "r");
571 struct strbuf line = STRBUF_INIT;
573 while (strbuf_getline(&line, in) != EOF) {
574 if (!strcmp(reference, line.buf)) {
578 fprintf_or_die(out, "%s\n", line.buf);
581 strbuf_release(&line);
584 else if (errno != ENOENT)
585 die_errno(_("unable to read alternates file"));
588 rollback_lock_file(&lock);
590 fprintf_or_die(out, "%s\n", reference);
591 if (commit_lock_file(&lock))
592 die_errno(_("unable to move new alternates file into place"));
593 if (the_repository->objects->alt_odb_tail)
594 link_alt_odb_entries(the_repository, reference,
600 void add_to_alternates_memory(const char *reference)
603 * Make sure alternates are initialized, or else our entry may be
604 * overwritten when they are.
606 prepare_alt_odb(the_repository);
608 link_alt_odb_entries(the_repository, reference,
613 * Compute the exact path an alternate is at and returns it. In case of
614 * error NULL is returned and the human readable error is added to `err`
615 * `path` may be relative and should point to $GIT_DIR.
616 * `err` must not be null.
618 char *compute_alternate_path(const char *path, struct strbuf *err)
620 char *ref_git = NULL;
621 const char *repo, *ref_git_s;
624 ref_git_s = real_path_if_valid(path);
627 strbuf_addf(err, _("path '%s' does not exist"), path);
631 * Beware: read_gitfile(), real_path() and mkpath()
632 * return static buffer
634 ref_git = xstrdup(ref_git_s);
636 repo = read_gitfile(ref_git);
638 repo = read_gitfile(mkpath("%s/.git", ref_git));
641 ref_git = xstrdup(repo);
644 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
645 char *ref_git_git = mkpathdup("%s/.git", ref_git);
647 ref_git = ref_git_git;
648 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
649 struct strbuf sb = STRBUF_INIT;
651 if (get_common_dir(&sb, ref_git)) {
653 _("reference repository '%s' as a linked "
654 "checkout is not supported yet."),
659 strbuf_addf(err, _("reference repository '%s' is not a "
660 "local repository."), path);
664 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
665 strbuf_addf(err, _("reference repository '%s' is shallow"),
671 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
673 _("reference repository '%s' is grafted"),
681 FREE_AND_NULL(ref_git);
687 int foreach_alt_odb(alt_odb_fn fn, void *cb)
689 struct object_directory *ent;
692 prepare_alt_odb(the_repository);
693 for (ent = the_repository->objects->alt_odb_list; ent; ent = ent->next) {
701 void prepare_alt_odb(struct repository *r)
703 if (r->objects->alt_odb_tail)
706 r->objects->alt_odb_tail = &r->objects->alt_odb_list;
707 link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
709 read_info_alternates(r, r->objects->objectdir, 0);
712 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
713 static int freshen_file(const char *fn)
716 t.actime = t.modtime = time(NULL);
717 return !utime(fn, &t);
721 * All of the check_and_freshen functions return 1 if the file exists and was
722 * freshened (if freshening was requested), 0 otherwise. If they return
723 * 0, you should not assume that it is safe to skip a write of the object (it
724 * either does not exist on disk, or has a stale mtime and may be subject to
727 int check_and_freshen_file(const char *fn, int freshen)
729 if (access(fn, F_OK))
731 if (freshen && !freshen_file(fn))
736 static int check_and_freshen_local(const struct object_id *oid, int freshen)
738 static struct strbuf buf = STRBUF_INIT;
740 loose_object_path(the_repository, &buf, oid->hash);
742 return check_and_freshen_file(buf.buf, freshen);
745 static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
747 struct object_directory *odb;
748 prepare_alt_odb(the_repository);
749 for (odb = the_repository->objects->alt_odb_list; odb; odb = odb->next) {
750 const char *path = alt_sha1_path(odb, oid->hash);
751 if (check_and_freshen_file(path, freshen))
757 static int check_and_freshen(const struct object_id *oid, int freshen)
759 return check_and_freshen_local(oid, freshen) ||
760 check_and_freshen_nonlocal(oid, freshen);
763 int has_loose_object_nonlocal(const struct object_id *oid)
765 return check_and_freshen_nonlocal(oid, 0);
768 static int has_loose_object(const struct object_id *oid)
770 return check_and_freshen(oid, 0);
773 static void mmap_limit_check(size_t length)
775 static size_t limit = 0;
777 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
782 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX),
783 (uintmax_t)length, (uintmax_t)limit);
786 void *xmmap_gently(void *start, size_t length,
787 int prot, int flags, int fd, off_t offset)
791 mmap_limit_check(length);
792 ret = mmap(start, length, prot, flags, fd, offset);
793 if (ret == MAP_FAILED) {
796 release_pack_memory(length);
797 ret = mmap(start, length, prot, flags, fd, offset);
802 void *xmmap(void *start, size_t length,
803 int prot, int flags, int fd, off_t offset)
805 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
806 if (ret == MAP_FAILED)
807 die_errno(_("mmap failed"));
812 * With an in-core object data in "map", rehash it to make sure the
813 * object name actually matches "sha1" to detect object corruption.
814 * With "map" == NULL, try reading the object named with "sha1" using
815 * the streaming interface and rehash it to do the same.
817 int check_object_signature(const struct object_id *oid, void *map,
818 unsigned long size, const char *type)
820 struct object_id real_oid;
821 enum object_type obj_type;
822 struct git_istream *st;
824 char hdr[MAX_HEADER_LEN];
828 hash_object_file(map, size, type, &real_oid);
829 return !oideq(oid, &real_oid) ? -1 : 0;
832 st = open_istream(oid, &obj_type, &size, NULL);
836 /* Generate the header */
837 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", type_name(obj_type), size) + 1;
840 the_hash_algo->init_fn(&c);
841 the_hash_algo->update_fn(&c, hdr, hdrlen);
844 ssize_t readlen = read_istream(st, buf, sizeof(buf));
852 the_hash_algo->update_fn(&c, buf, readlen);
854 the_hash_algo->final_fn(real_oid.hash, &c);
856 return !oideq(oid, &real_oid) ? -1 : 0;
859 int git_open_cloexec(const char *name, int flags)
862 static int o_cloexec = O_CLOEXEC;
864 fd = open(name, flags | o_cloexec);
865 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
866 /* Try again w/o O_CLOEXEC: the kernel might not support it */
867 o_cloexec &= ~O_CLOEXEC;
868 fd = open(name, flags | o_cloexec);
871 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
873 static int fd_cloexec = FD_CLOEXEC;
875 if (!o_cloexec && 0 <= fd && fd_cloexec) {
876 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
877 int flags = fcntl(fd, F_GETFD);
878 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
887 * Find "sha1" as a loose object in the local repository or in an alternate.
888 * Returns 0 on success, negative on failure.
890 * The "path" out-parameter will give the path of the object we found (if any).
891 * Note that it may point to static storage and is only valid until another
892 * call to loose_object_path(), etc.
894 static int stat_sha1_file(struct repository *r, const unsigned char *sha1,
895 struct stat *st, const char **path)
897 struct object_directory *odb;
898 static struct strbuf buf = STRBUF_INIT;
900 loose_object_path(r, &buf, sha1);
903 if (!lstat(*path, st))
908 for (odb = r->objects->alt_odb_list; odb; odb = odb->next) {
909 *path = alt_sha1_path(odb, sha1);
910 if (!lstat(*path, st))
918 * Like stat_sha1_file(), but actually open the object and return the
919 * descriptor. See the caveats on the "path" parameter above.
921 static int open_sha1_file(struct repository *r,
922 const unsigned char *sha1, const char **path)
925 struct object_directory *odb;
926 int most_interesting_errno;
927 static struct strbuf buf = STRBUF_INIT;
929 loose_object_path(r, &buf, sha1);
932 fd = git_open(*path);
935 most_interesting_errno = errno;
938 for (odb = r->objects->alt_odb_list; odb; odb = odb->next) {
939 *path = alt_sha1_path(odb, sha1);
940 fd = git_open(*path);
943 if (most_interesting_errno == ENOENT)
944 most_interesting_errno = errno;
946 errno = most_interesting_errno;
951 * Map the loose object at "path" if it is not NULL, or the path found by
952 * searching for a loose object named "sha1".
954 static void *map_sha1_file_1(struct repository *r, const char *path,
955 const unsigned char *sha1, unsigned long *size)
963 fd = open_sha1_file(r, sha1, &path);
968 if (!fstat(fd, &st)) {
969 *size = xsize_t(st.st_size);
971 /* mmap() is forbidden on empty files */
972 error(_("object file %s is empty"), path);
975 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
982 void *map_sha1_file(struct repository *r,
983 const unsigned char *sha1, unsigned long *size)
985 return map_sha1_file_1(r, NULL, sha1, size);
988 static int unpack_sha1_short_header(git_zstream *stream,
989 unsigned char *map, unsigned long mapsize,
990 void *buffer, unsigned long bufsiz)
992 /* Get the data stream */
993 memset(stream, 0, sizeof(*stream));
994 stream->next_in = map;
995 stream->avail_in = mapsize;
996 stream->next_out = buffer;
997 stream->avail_out = bufsiz;
999 git_inflate_init(stream);
1000 return git_inflate(stream, 0);
1003 int unpack_sha1_header(git_zstream *stream,
1004 unsigned char *map, unsigned long mapsize,
1005 void *buffer, unsigned long bufsiz)
1007 int status = unpack_sha1_short_header(stream, map, mapsize,
1013 /* Make sure we have the terminating NUL */
1014 if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1019 static int unpack_sha1_header_to_strbuf(git_zstream *stream, unsigned char *map,
1020 unsigned long mapsize, void *buffer,
1021 unsigned long bufsiz, struct strbuf *header)
1025 status = unpack_sha1_short_header(stream, map, mapsize, buffer, bufsiz);
1030 * Check if entire header is unpacked in the first iteration.
1032 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1036 * buffer[0..bufsiz] was not large enough. Copy the partial
1037 * result out to header, and then append the result of further
1038 * reading the stream.
1040 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1041 stream->next_out = buffer;
1042 stream->avail_out = bufsiz;
1045 status = git_inflate(stream, 0);
1046 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1047 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1049 stream->next_out = buffer;
1050 stream->avail_out = bufsiz;
1051 } while (status != Z_STREAM_END);
1055 static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1057 int bytes = strlen(buffer) + 1;
1058 unsigned char *buf = xmallocz(size);
1062 n = stream->total_out - bytes;
1065 memcpy(buf, (char *) buffer + bytes, n);
1067 if (bytes <= size) {
1069 * The above condition must be (bytes <= size), not
1070 * (bytes < size). In other words, even though we
1071 * expect no more output and set avail_out to zero,
1072 * the input zlib stream may have bytes that express
1073 * "this concludes the stream", and we *do* want to
1076 * Otherwise we would not be able to test that we
1077 * consumed all the input to reach the expected size;
1078 * we also want to check that zlib tells us that all
1079 * went well with status == Z_STREAM_END at the end.
1081 stream->next_out = buf + bytes;
1082 stream->avail_out = size - bytes;
1083 while (status == Z_OK)
1084 status = git_inflate(stream, Z_FINISH);
1086 if (status == Z_STREAM_END && !stream->avail_in) {
1087 git_inflate_end(stream);
1092 error(_("corrupt loose object '%s'"), sha1_to_hex(sha1));
1093 else if (stream->avail_in)
1094 error(_("garbage at end of loose object '%s'"),
1101 * We used to just use "sscanf()", but that's actually way
1102 * too permissive for what we want to check. So do an anal
1103 * object header parse by hand.
1105 static int parse_sha1_header_extended(const char *hdr, struct object_info *oi,
1108 const char *type_buf = hdr;
1110 int type, type_len = 0;
1113 * The type can be of any size but is followed by
1125 type = type_from_string_gently(type_buf, type_len, 1);
1127 strbuf_add(oi->type_name, type_buf, type_len);
1129 * Set type to 0 if its an unknown object and
1130 * we're obtaining the type using '--allow-unknown-type'
1133 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1136 die(_("invalid object type"));
1141 * The length must follow immediately, and be in canonical
1142 * decimal format (ie "010" is not valid).
1144 size = *hdr++ - '0';
1149 unsigned long c = *hdr - '0';
1153 size = size * 10 + c;
1161 * The length must be followed by a zero byte
1163 return *hdr ? -1 : type;
1166 int parse_sha1_header(const char *hdr, unsigned long *sizep)
1168 struct object_info oi = OBJECT_INFO_INIT;
1171 return parse_sha1_header_extended(hdr, &oi, 0);
1174 static int sha1_loose_object_info(struct repository *r,
1175 const unsigned char *sha1,
1176 struct object_info *oi, int flags)
1179 unsigned long mapsize;
1182 char hdr[MAX_HEADER_LEN];
1183 struct strbuf hdrbuf = STRBUF_INIT;
1184 unsigned long size_scratch;
1186 if (oi->delta_base_sha1)
1187 hashclr(oi->delta_base_sha1);
1190 * If we don't care about type or size, then we don't
1191 * need to look inside the object at all. Note that we
1192 * do not optimize out the stat call, even if the
1193 * caller doesn't care about the disk-size, since our
1194 * return value implicitly indicates whether the
1195 * object even exists.
1197 if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
1200 if (stat_sha1_file(r, sha1, &st, &path) < 0)
1203 *oi->disk_sizep = st.st_size;
1207 map = map_sha1_file(r, sha1, &mapsize);
1212 oi->sizep = &size_scratch;
1215 *oi->disk_sizep = mapsize;
1216 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
1217 if (unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
1218 status = error(_("unable to unpack %s header with --allow-unknown-type"),
1220 } else if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1221 status = error(_("unable to unpack %s header"),
1225 else if (hdrbuf.len) {
1226 if ((status = parse_sha1_header_extended(hdrbuf.buf, oi, flags)) < 0)
1227 status = error(_("unable to parse %s header with --allow-unknown-type"),
1229 } else if ((status = parse_sha1_header_extended(hdr, oi, flags)) < 0)
1230 status = error(_("unable to parse %s header"), sha1_to_hex(sha1));
1232 if (status >= 0 && oi->contentp) {
1233 *oi->contentp = unpack_sha1_rest(&stream, hdr,
1235 if (!*oi->contentp) {
1236 git_inflate_end(&stream);
1240 git_inflate_end(&stream);
1242 munmap(map, mapsize);
1243 if (status && oi->typep)
1244 *oi->typep = status;
1245 if (oi->sizep == &size_scratch)
1247 strbuf_release(&hdrbuf);
1248 oi->whence = OI_LOOSE;
1249 return (status < 0) ? status : 0;
1252 int fetch_if_missing = 1;
1254 int oid_object_info_extended(struct repository *r, const struct object_id *oid,
1255 struct object_info *oi, unsigned flags)
1257 static struct object_info blank_oi = OBJECT_INFO_INIT;
1258 struct pack_entry e;
1260 const struct object_id *real = oid;
1261 int already_retried = 0;
1263 if (flags & OBJECT_INFO_LOOKUP_REPLACE)
1264 real = lookup_replace_object(r, oid);
1266 if (is_null_oid(real))
1272 if (!(flags & OBJECT_INFO_SKIP_CACHED)) {
1273 struct cached_object *co = find_cached_object(real);
1276 *(oi->typep) = co->type;
1278 *(oi->sizep) = co->size;
1280 *(oi->disk_sizep) = 0;
1281 if (oi->delta_base_sha1)
1282 hashclr(oi->delta_base_sha1);
1284 strbuf_addstr(oi->type_name, type_name(co->type));
1286 *oi->contentp = xmemdupz(co->buf, co->size);
1287 oi->whence = OI_CACHED;
1293 if (find_pack_entry(r, real, &e))
1296 if (flags & OBJECT_INFO_IGNORE_LOOSE)
1299 /* Most likely it's a loose object. */
1300 if (!sha1_loose_object_info(r, real->hash, oi, flags))
1303 /* Not a loose object; someone else may have just packed it. */
1304 if (!(flags & OBJECT_INFO_QUICK)) {
1305 reprepare_packed_git(r);
1306 if (find_pack_entry(r, real, &e))
1310 /* Check if it is a missing object */
1311 if (fetch_if_missing && repository_format_partial_clone &&
1312 !already_retried && r == the_repository) {
1314 * TODO Investigate having fetch_object() return
1315 * TODO error/success and stopping the music here.
1316 * TODO Pass a repository struct through fetch_object,
1317 * such that arbitrary repositories work.
1319 fetch_objects(repository_format_partial_clone, real, 1);
1320 already_retried = 1;
1327 if (oi == &blank_oi)
1329 * We know that the caller doesn't actually need the
1330 * information below, so return early.
1333 rtype = packed_object_info(r, e.p, e.offset, oi);
1335 mark_bad_packed_object(e.p, real->hash);
1336 return oid_object_info_extended(r, real, oi, 0);
1337 } else if (oi->whence == OI_PACKED) {
1338 oi->u.packed.offset = e.offset;
1339 oi->u.packed.pack = e.p;
1340 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1341 rtype == OBJ_OFS_DELTA);
1347 /* returns enum object_type or negative */
1348 int oid_object_info(struct repository *r,
1349 const struct object_id *oid,
1350 unsigned long *sizep)
1352 enum object_type type;
1353 struct object_info oi = OBJECT_INFO_INIT;
1357 if (oid_object_info_extended(r, oid, &oi,
1358 OBJECT_INFO_LOOKUP_REPLACE) < 0)
1363 static void *read_object(const unsigned char *sha1, enum object_type *type,
1364 unsigned long *size)
1366 struct object_id oid;
1367 struct object_info oi = OBJECT_INFO_INIT;
1371 oi.contentp = &content;
1373 hashcpy(oid.hash, sha1);
1375 if (oid_object_info_extended(the_repository, &oid, &oi, 0) < 0)
1380 int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1381 struct object_id *oid)
1383 struct cached_object *co;
1385 hash_object_file(buf, len, type_name(type), oid);
1386 if (has_sha1_file(oid->hash) || find_cached_object(oid))
1388 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1389 co = &cached_objects[cached_object_nr++];
1392 co->buf = xmalloc(len);
1393 memcpy(co->buf, buf, len);
1394 oidcpy(&co->oid, oid);
1399 * This function dies on corrupt objects; the callers who want to
1400 * deal with them should arrange to call read_object() and give error
1401 * messages themselves.
1403 void *read_object_file_extended(const struct object_id *oid,
1404 enum object_type *type,
1405 unsigned long *size,
1409 const struct packed_git *p;
1412 const struct object_id *repl = lookup_replace ?
1413 lookup_replace_object(the_repository, oid) : oid;
1416 data = read_object(repl->hash, type, size);
1420 if (errno && errno != ENOENT)
1421 die_errno(_("failed to read object %s"), oid_to_hex(oid));
1423 /* die if we replaced an object with one that does not exist */
1425 die(_("replacement %s not found for %s"),
1426 oid_to_hex(repl), oid_to_hex(oid));
1428 if (!stat_sha1_file(the_repository, repl->hash, &st, &path))
1429 die(_("loose object %s (stored in %s) is corrupt"),
1430 oid_to_hex(repl), path);
1432 if ((p = has_packed_and_bad(repl->hash)) != NULL)
1433 die(_("packed object %s (stored in %s) is corrupt"),
1434 oid_to_hex(repl), p->pack_name);
1439 void *read_object_with_reference(const struct object_id *oid,
1440 const char *required_type_name,
1441 unsigned long *size,
1442 struct object_id *actual_oid_return)
1444 enum object_type type, required_type;
1446 unsigned long isize;
1447 struct object_id actual_oid;
1449 required_type = type_from_string(required_type_name);
1450 oidcpy(&actual_oid, oid);
1452 int ref_length = -1;
1453 const char *ref_type = NULL;
1455 buffer = read_object_file(&actual_oid, &type, &isize);
1458 if (type == required_type) {
1460 if (actual_oid_return)
1461 oidcpy(actual_oid_return, &actual_oid);
1464 /* Handle references */
1465 else if (type == OBJ_COMMIT)
1467 else if (type == OBJ_TAG)
1468 ref_type = "object ";
1473 ref_length = strlen(ref_type);
1475 if (ref_length + the_hash_algo->hexsz > isize ||
1476 memcmp(buffer, ref_type, ref_length) ||
1477 get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
1482 /* Now we have the ID of the referred-to object in
1483 * actual_oid. Check again. */
1487 static void write_object_file_prepare(const void *buf, unsigned long len,
1488 const char *type, struct object_id *oid,
1489 char *hdr, int *hdrlen)
1493 /* Generate the header */
1494 *hdrlen = xsnprintf(hdr, *hdrlen, "%s %lu", type, len)+1;
1497 the_hash_algo->init_fn(&c);
1498 the_hash_algo->update_fn(&c, hdr, *hdrlen);
1499 the_hash_algo->update_fn(&c, buf, len);
1500 the_hash_algo->final_fn(oid->hash, &c);
1504 * Move the just written object into its final resting place.
1506 int finalize_object_file(const char *tmpfile, const char *filename)
1510 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
1512 else if (link(tmpfile, filename))
1516 * Coda hack - coda doesn't like cross-directory links,
1517 * so we fall back to a rename, which will mean that it
1518 * won't be able to check collisions, but that's not a
1521 * The same holds for FAT formatted media.
1523 * When this succeeds, we just return. We have nothing
1526 if (ret && ret != EEXIST) {
1528 if (!rename(tmpfile, filename))
1532 unlink_or_warn(tmpfile);
1534 if (ret != EEXIST) {
1535 return error_errno(_("unable to write sha1 filename %s"), filename);
1537 /* FIXME!!! Collision check here ? */
1541 if (adjust_shared_perm(filename))
1542 return error(_("unable to set permission to '%s'"), filename);
1546 static int write_buffer(int fd, const void *buf, size_t len)
1548 if (write_in_full(fd, buf, len) < 0)
1549 return error_errno(_("file write error"));
1553 int hash_object_file(const void *buf, unsigned long len, const char *type,
1554 struct object_id *oid)
1556 char hdr[MAX_HEADER_LEN];
1557 int hdrlen = sizeof(hdr);
1558 write_object_file_prepare(buf, len, type, oid, hdr, &hdrlen);
1562 /* Finalize a file on disk, and close it. */
1563 static void close_sha1_file(int fd)
1565 if (fsync_object_files)
1566 fsync_or_die(fd, "sha1 file");
1568 die_errno(_("error when closing sha1 file"));
1571 /* Size of directory component, including the ending '/' */
1572 static inline int directory_size(const char *filename)
1574 const char *s = strrchr(filename, '/');
1577 return s - filename + 1;
1581 * This creates a temporary file in the same directory as the final
1584 * We want to avoid cross-directory filename renames, because those
1585 * can have problems on various filesystems (FAT, NFS, Coda).
1587 static int create_tmpfile(struct strbuf *tmp, const char *filename)
1589 int fd, dirlen = directory_size(filename);
1592 strbuf_add(tmp, filename, dirlen);
1593 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
1594 fd = git_mkstemp_mode(tmp->buf, 0444);
1595 if (fd < 0 && dirlen && errno == ENOENT) {
1597 * Make sure the directory exists; note that the contents
1598 * of the buffer are undefined after mkstemp returns an
1599 * error, so we have to rewrite the whole buffer from
1603 strbuf_add(tmp, filename, dirlen - 1);
1604 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
1606 if (adjust_shared_perm(tmp->buf))
1610 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
1611 fd = git_mkstemp_mode(tmp->buf, 0444);
1616 static int write_loose_object(const struct object_id *oid, char *hdr,
1617 int hdrlen, const void *buf, unsigned long len,
1621 unsigned char compressed[4096];
1624 struct object_id parano_oid;
1625 static struct strbuf tmp_file = STRBUF_INIT;
1626 static struct strbuf filename = STRBUF_INIT;
1628 loose_object_path(the_repository, &filename, oid->hash);
1630 fd = create_tmpfile(&tmp_file, filename.buf);
1632 if (errno == EACCES)
1633 return error(_("insufficient permission for adding an object to repository database %s"), get_object_directory());
1635 return error_errno(_("unable to create temporary file"));
1639 git_deflate_init(&stream, zlib_compression_level);
1640 stream.next_out = compressed;
1641 stream.avail_out = sizeof(compressed);
1642 the_hash_algo->init_fn(&c);
1644 /* First header.. */
1645 stream.next_in = (unsigned char *)hdr;
1646 stream.avail_in = hdrlen;
1647 while (git_deflate(&stream, 0) == Z_OK)
1649 the_hash_algo->update_fn(&c, hdr, hdrlen);
1651 /* Then the data itself.. */
1652 stream.next_in = (void *)buf;
1653 stream.avail_in = len;
1655 unsigned char *in0 = stream.next_in;
1656 ret = git_deflate(&stream, Z_FINISH);
1657 the_hash_algo->update_fn(&c, in0, stream.next_in - in0);
1658 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
1659 die(_("unable to write sha1 file"));
1660 stream.next_out = compressed;
1661 stream.avail_out = sizeof(compressed);
1662 } while (ret == Z_OK);
1664 if (ret != Z_STREAM_END)
1665 die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
1667 ret = git_deflate_end_gently(&stream);
1669 die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
1671 the_hash_algo->final_fn(parano_oid.hash, &c);
1672 if (!oideq(oid, ¶no_oid))
1673 die(_("confused by unstable object source data for %s"),
1676 close_sha1_file(fd);
1681 utb.modtime = mtime;
1682 if (utime(tmp_file.buf, &utb) < 0)
1683 warning_errno(_("failed utime() on %s"), tmp_file.buf);
1686 return finalize_object_file(tmp_file.buf, filename.buf);
1689 static int freshen_loose_object(const struct object_id *oid)
1691 return check_and_freshen(oid, 1);
1694 static int freshen_packed_object(const struct object_id *oid)
1696 struct pack_entry e;
1697 if (!find_pack_entry(the_repository, oid, &e))
1701 if (!freshen_file(e.p->pack_name))
1707 int write_object_file(const void *buf, unsigned long len, const char *type,
1708 struct object_id *oid)
1710 char hdr[MAX_HEADER_LEN];
1711 int hdrlen = sizeof(hdr);
1713 /* Normally if we have it in the pack then we do not bother writing
1714 * it out into .git/objects/??/?{38} file.
1716 write_object_file_prepare(buf, len, type, oid, hdr, &hdrlen);
1717 if (freshen_packed_object(oid) || freshen_loose_object(oid))
1719 return write_loose_object(oid, hdr, hdrlen, buf, len, 0);
1722 int hash_object_file_literally(const void *buf, unsigned long len,
1723 const char *type, struct object_id *oid,
1727 int hdrlen, status = 0;
1729 /* type string, SP, %lu of the length plus NUL must fit this */
1730 hdrlen = strlen(type) + MAX_HEADER_LEN;
1731 header = xmalloc(hdrlen);
1732 write_object_file_prepare(buf, len, type, oid, header, &hdrlen);
1734 if (!(flags & HASH_WRITE_OBJECT))
1736 if (freshen_packed_object(oid) || freshen_loose_object(oid))
1738 status = write_loose_object(oid, header, hdrlen, buf, len, 0);
1745 int force_object_loose(const struct object_id *oid, time_t mtime)
1749 enum object_type type;
1750 char hdr[MAX_HEADER_LEN];
1754 if (has_loose_object(oid))
1756 buf = read_object(oid->hash, &type, &len);
1758 return error(_("cannot read sha1_file for %s"), oid_to_hex(oid));
1759 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", type_name(type), len) + 1;
1760 ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime);
1766 int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
1768 struct object_id oid;
1769 if (!startup_info->have_repository)
1771 hashcpy(oid.hash, sha1);
1772 return oid_object_info_extended(the_repository, &oid, NULL,
1773 flags | OBJECT_INFO_SKIP_CACHED) >= 0;
1776 int has_object_file(const struct object_id *oid)
1778 return has_sha1_file(oid->hash);
1781 int has_object_file_with_flags(const struct object_id *oid, int flags)
1783 return has_sha1_file_with_flags(oid->hash, flags);
1786 static void check_tree(const void *buf, size_t size)
1788 struct tree_desc desc;
1789 struct name_entry entry;
1791 init_tree_desc(&desc, buf, size);
1792 while (tree_entry(&desc, &entry))
1794 * tree_entry() will die() on malformed entries */
1798 static void check_commit(const void *buf, size_t size)
1801 memset(&c, 0, sizeof(c));
1802 if (parse_commit_buffer(the_repository, &c, buf, size, 0))
1803 die(_("corrupt commit"));
1806 static void check_tag(const void *buf, size_t size)
1809 memset(&t, 0, sizeof(t));
1810 if (parse_tag_buffer(the_repository, &t, buf, size))
1811 die(_("corrupt tag"));
1814 static int index_mem(struct index_state *istate,
1815 struct object_id *oid, void *buf, size_t size,
1816 enum object_type type,
1817 const char *path, unsigned flags)
1819 int ret, re_allocated = 0;
1820 int write_object = flags & HASH_WRITE_OBJECT;
1826 * Convert blobs to git internal format
1828 if ((type == OBJ_BLOB) && path) {
1829 struct strbuf nbuf = STRBUF_INIT;
1830 if (convert_to_git(istate, path, buf, size, &nbuf,
1831 get_conv_flags(flags))) {
1832 buf = strbuf_detach(&nbuf, &size);
1836 if (flags & HASH_FORMAT_CHECK) {
1837 if (type == OBJ_TREE)
1838 check_tree(buf, size);
1839 if (type == OBJ_COMMIT)
1840 check_commit(buf, size);
1841 if (type == OBJ_TAG)
1842 check_tag(buf, size);
1846 ret = write_object_file(buf, size, type_name(type), oid);
1848 ret = hash_object_file(buf, size, type_name(type), oid);
1854 static int index_stream_convert_blob(struct index_state *istate,
1855 struct object_id *oid,
1861 const int write_object = flags & HASH_WRITE_OBJECT;
1862 struct strbuf sbuf = STRBUF_INIT;
1865 assert(would_convert_to_git_filter_fd(istate, path));
1867 convert_to_git_filter_fd(istate, path, fd, &sbuf,
1868 get_conv_flags(flags));
1871 ret = write_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
1874 ret = hash_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
1876 strbuf_release(&sbuf);
1880 static int index_pipe(struct index_state *istate, struct object_id *oid,
1881 int fd, enum object_type type,
1882 const char *path, unsigned flags)
1884 struct strbuf sbuf = STRBUF_INIT;
1887 if (strbuf_read(&sbuf, fd, 4096) >= 0)
1888 ret = index_mem(istate, oid, sbuf.buf, sbuf.len, type, path, flags);
1891 strbuf_release(&sbuf);
1895 #define SMALL_FILE_SIZE (32*1024)
1897 static int index_core(struct index_state *istate,
1898 struct object_id *oid, int fd, size_t size,
1899 enum object_type type, const char *path,
1905 ret = index_mem(istate, oid, "", size, type, path, flags);
1906 } else if (size <= SMALL_FILE_SIZE) {
1907 char *buf = xmalloc(size);
1908 ssize_t read_result = read_in_full(fd, buf, size);
1909 if (read_result < 0)
1910 ret = error_errno(_("read error while indexing %s"),
1911 path ? path : "<unknown>");
1912 else if (read_result != size)
1913 ret = error(_("short read while indexing %s"),
1914 path ? path : "<unknown>");
1916 ret = index_mem(istate, oid, buf, size, type, path, flags);
1919 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1920 ret = index_mem(istate, oid, buf, size, type, path, flags);
1927 * This creates one packfile per large blob unless bulk-checkin
1928 * machinery is "plugged".
1930 * This also bypasses the usual "convert-to-git" dance, and that is on
1931 * purpose. We could write a streaming version of the converting
1932 * functions and insert that before feeding the data to fast-import
1933 * (or equivalent in-core API described above). However, that is
1934 * somewhat complicated, as we do not know the size of the filter
1935 * result, which we need to know beforehand when writing a git object.
1936 * Since the primary motivation for trying to stream from the working
1937 * tree file and to avoid mmaping it in core is to deal with large
1938 * binary blobs, they generally do not want to get any conversion, and
1939 * callers should avoid this code path when filters are requested.
1941 static int index_stream(struct object_id *oid, int fd, size_t size,
1942 enum object_type type, const char *path,
1945 return index_bulk_checkin(oid, fd, size, type, path, flags);
1948 int index_fd(struct index_state *istate, struct object_id *oid,
1949 int fd, struct stat *st,
1950 enum object_type type, const char *path, unsigned flags)
1955 * Call xsize_t() only when needed to avoid potentially unnecessary
1956 * die() for large files.
1958 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path))
1959 ret = index_stream_convert_blob(istate, oid, fd, path, flags);
1960 else if (!S_ISREG(st->st_mode))
1961 ret = index_pipe(istate, oid, fd, type, path, flags);
1962 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
1963 (path && would_convert_to_git(istate, path)))
1964 ret = index_core(istate, oid, fd, xsize_t(st->st_size),
1967 ret = index_stream(oid, fd, xsize_t(st->st_size), type, path,
1973 int index_path(struct index_state *istate, struct object_id *oid,
1974 const char *path, struct stat *st, unsigned flags)
1977 struct strbuf sb = STRBUF_INIT;
1980 switch (st->st_mode & S_IFMT) {
1982 fd = open(path, O_RDONLY);
1984 return error_errno("open(\"%s\")", path);
1985 if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
1986 return error(_("%s: failed to insert into database"),
1990 if (strbuf_readlink(&sb, path, st->st_size))
1991 return error_errno("readlink(\"%s\")", path);
1992 if (!(flags & HASH_WRITE_OBJECT))
1993 hash_object_file(sb.buf, sb.len, blob_type, oid);
1994 else if (write_object_file(sb.buf, sb.len, blob_type, oid))
1995 rc = error(_("%s: failed to insert into database"), path);
1996 strbuf_release(&sb);
1999 return resolve_gitlink_ref(path, "HEAD", oid);
2001 return error(_("%s: unsupported file type"), path);
2006 int read_pack_header(int fd, struct pack_header *header)
2008 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
2009 /* "eof before pack header was fully read" */
2010 return PH_ERROR_EOF;
2012 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2013 /* "protocol error (pack signature mismatch detected)" */
2014 return PH_ERROR_PACK_SIGNATURE;
2015 if (!pack_version_ok(header->hdr_version))
2016 /* "protocol error (pack version unsupported)" */
2017 return PH_ERROR_PROTOCOL;
2021 void assert_oid_type(const struct object_id *oid, enum object_type expect)
2023 enum object_type type = oid_object_info(the_repository, oid, NULL);
2025 die(_("%s is not a valid object"), oid_to_hex(oid));
2027 die(_("%s is not a valid '%s' object"), oid_to_hex(oid),
2031 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
2032 struct strbuf *path,
2033 each_loose_object_fn obj_cb,
2034 each_loose_cruft_fn cruft_cb,
2035 each_loose_subdir_fn subdir_cb,
2038 size_t origlen, baselen;
2042 struct object_id oid;
2044 if (subdir_nr > 0xff)
2045 BUG("invalid loose object subdirectory: %x", subdir_nr);
2047 origlen = path->len;
2048 strbuf_complete(path, '/');
2049 strbuf_addf(path, "%02x", subdir_nr);
2051 dir = opendir(path->buf);
2053 if (errno != ENOENT)
2054 r = error_errno(_("unable to open %s"), path->buf);
2055 strbuf_setlen(path, origlen);
2059 oid.hash[0] = subdir_nr;
2060 strbuf_addch(path, '/');
2061 baselen = path->len;
2063 while ((de = readdir(dir))) {
2065 if (is_dot_or_dotdot(de->d_name))
2068 namelen = strlen(de->d_name);
2069 strbuf_setlen(path, baselen);
2070 strbuf_add(path, de->d_name, namelen);
2071 if (namelen == the_hash_algo->hexsz - 2 &&
2072 !hex_to_bytes(oid.hash + 1, de->d_name,
2073 the_hash_algo->rawsz - 1)) {
2075 r = obj_cb(&oid, path->buf, data);
2083 r = cruft_cb(de->d_name, path->buf, data);
2090 strbuf_setlen(path, baselen - 1);
2091 if (!r && subdir_cb)
2092 r = subdir_cb(subdir_nr, path->buf, data);
2094 strbuf_setlen(path, origlen);
2099 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2100 each_loose_object_fn obj_cb,
2101 each_loose_cruft_fn cruft_cb,
2102 each_loose_subdir_fn subdir_cb,
2108 for (i = 0; i < 256; i++) {
2109 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2118 int for_each_loose_file_in_objdir(const char *path,
2119 each_loose_object_fn obj_cb,
2120 each_loose_cruft_fn cruft_cb,
2121 each_loose_subdir_fn subdir_cb,
2124 struct strbuf buf = STRBUF_INIT;
2127 strbuf_addstr(&buf, path);
2128 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2130 strbuf_release(&buf);
2135 struct loose_alt_odb_data {
2136 each_loose_object_fn *cb;
2140 static int loose_from_alt_odb(struct object_directory *odb,
2143 struct loose_alt_odb_data *data = vdata;
2144 struct strbuf buf = STRBUF_INIT;
2147 strbuf_addstr(&buf, odb->path);
2148 r = for_each_loose_file_in_objdir_buf(&buf,
2149 data->cb, NULL, NULL,
2151 strbuf_release(&buf);
2155 int for_each_loose_object(each_loose_object_fn cb, void *data,
2156 enum for_each_object_flags flags)
2158 struct loose_alt_odb_data alt;
2161 r = for_each_loose_file_in_objdir(get_object_directory(),
2162 cb, NULL, NULL, data);
2166 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2171 return foreach_alt_odb(loose_from_alt_odb, &alt);
2174 static int check_stream_sha1(git_zstream *stream,
2178 const unsigned char *expected_sha1)
2181 unsigned char real_sha1[GIT_MAX_RAWSZ];
2182 unsigned char buf[4096];
2183 unsigned long total_read;
2186 the_hash_algo->init_fn(&c);
2187 the_hash_algo->update_fn(&c, hdr, stream->total_out);
2190 * We already read some bytes into hdr, but the ones up to the NUL
2191 * do not count against the object's content size.
2193 total_read = stream->total_out - strlen(hdr) - 1;
2196 * This size comparison must be "<=" to read the final zlib packets;
2197 * see the comment in unpack_sha1_rest for details.
2199 while (total_read <= size &&
2200 (status == Z_OK || status == Z_BUF_ERROR)) {
2201 stream->next_out = buf;
2202 stream->avail_out = sizeof(buf);
2203 if (size - total_read < stream->avail_out)
2204 stream->avail_out = size - total_read;
2205 status = git_inflate(stream, Z_FINISH);
2206 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
2207 total_read += stream->next_out - buf;
2209 git_inflate_end(stream);
2211 if (status != Z_STREAM_END) {
2212 error(_("corrupt loose object '%s'"), sha1_to_hex(expected_sha1));
2215 if (stream->avail_in) {
2216 error(_("garbage at end of loose object '%s'"),
2217 sha1_to_hex(expected_sha1));
2221 the_hash_algo->final_fn(real_sha1, &c);
2222 if (!hasheq(expected_sha1, real_sha1)) {
2223 error(_("sha1 mismatch for %s (expected %s)"), path,
2224 sha1_to_hex(expected_sha1));
2231 int read_loose_object(const char *path,
2232 const struct object_id *expected_oid,
2233 enum object_type *type,
2234 unsigned long *size,
2239 unsigned long mapsize;
2241 char hdr[MAX_HEADER_LEN];
2245 map = map_sha1_file_1(the_repository, path, NULL, &mapsize);
2247 error_errno(_("unable to mmap %s"), path);
2251 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
2252 error(_("unable to unpack header of %s"), path);
2256 *type = parse_sha1_header(hdr, size);
2258 error(_("unable to parse header of %s"), path);
2259 git_inflate_end(&stream);
2263 if (*type == OBJ_BLOB && *size > big_file_threshold) {
2264 if (check_stream_sha1(&stream, hdr, *size, path, expected_oid->hash) < 0)
2267 *contents = unpack_sha1_rest(&stream, hdr, *size, expected_oid->hash);
2269 error(_("unable to unpack contents of %s"), path);
2270 git_inflate_end(&stream);
2273 if (check_object_signature(expected_oid, *contents,
2274 *size, type_name(*type))) {
2275 error(_("sha1 mismatch for %s (expected %s)"), path,
2276 oid_to_hex(expected_oid));
2282 ret = 0; /* everything checks out */
2286 munmap(map, mapsize);