sha1_file: add raw_object_store argument to alt_odb_usable
[alt-git.git] / sha1_file.c
blob097c372d030e42da75f40643fc74efcfc7fe2a4e
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
7 * creation etc.
8 */
9 #include "cache.h"
10 #include "config.h"
11 #include "string-list.h"
12 #include "lockfile.h"
13 #include "delta.h"
14 #include "pack.h"
15 #include "blob.h"
16 #include "commit.h"
17 #include "run-command.h"
18 #include "tag.h"
19 #include "tree.h"
20 #include "tree-walk.h"
21 #include "refs.h"
22 #include "pack-revindex.h"
23 #include "sha1-lookup.h"
24 #include "bulk-checkin.h"
25 #include "repository.h"
26 #include "streaming.h"
27 #include "dir.h"
28 #include "list.h"
29 #include "mergesort.h"
30 #include "quote.h"
31 #include "packfile.h"
32 #include "fetch-object.h"
33 #include "object-store.h"
35 const unsigned char null_sha1[GIT_MAX_RAWSZ];
36 const struct object_id null_oid;
37 const struct object_id empty_tree_oid = {
38 EMPTY_TREE_SHA1_BIN_LITERAL
40 const struct object_id empty_blob_oid = {
41 EMPTY_BLOB_SHA1_BIN_LITERAL
44 static void git_hash_sha1_init(void *ctx)
46 git_SHA1_Init((git_SHA_CTX *)ctx);
49 static void git_hash_sha1_update(void *ctx, const void *data, size_t len)
51 git_SHA1_Update((git_SHA_CTX *)ctx, data, len);
54 static void git_hash_sha1_final(unsigned char *hash, void *ctx)
56 git_SHA1_Final(hash, (git_SHA_CTX *)ctx);
59 static void git_hash_unknown_init(void *ctx)
61 die("trying to init unknown hash");
64 static void git_hash_unknown_update(void *ctx, const void *data, size_t len)
66 die("trying to update unknown hash");
69 static void git_hash_unknown_final(unsigned char *hash, void *ctx)
71 die("trying to finalize unknown hash");
74 const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
76 NULL,
77 0x00000000,
81 git_hash_unknown_init,
82 git_hash_unknown_update,
83 git_hash_unknown_final,
84 NULL,
85 NULL,
88 "sha-1",
89 /* "sha1", big-endian */
90 0x73686131,
91 sizeof(git_SHA_CTX),
92 GIT_SHA1_RAWSZ,
93 GIT_SHA1_HEXSZ,
94 git_hash_sha1_init,
95 git_hash_sha1_update,
96 git_hash_sha1_final,
97 &empty_tree_oid,
98 &empty_blob_oid,
103 * This is meant to hold a *small* number of objects that you would
104 * want read_sha1_file() to be able to return, but yet you do not want
105 * to write them into the object store (e.g. a browse-only
106 * application).
108 static struct cached_object {
109 unsigned char sha1[20];
110 enum object_type type;
111 void *buf;
112 unsigned long size;
113 } *cached_objects;
114 static int cached_object_nr, cached_object_alloc;
116 static struct cached_object empty_tree = {
117 EMPTY_TREE_SHA1_BIN_LITERAL,
118 OBJ_TREE,
123 static struct cached_object *find_cached_object(const unsigned char *sha1)
125 int i;
126 struct cached_object *co = cached_objects;
128 for (i = 0; i < cached_object_nr; i++, co++) {
129 if (!hashcmp(co->sha1, sha1))
130 return co;
132 if (!hashcmp(sha1, empty_tree.sha1))
133 return &empty_tree;
134 return NULL;
138 static int get_conv_flags(unsigned flags)
140 if (flags & HASH_RENORMALIZE)
141 return CONV_EOL_RENORMALIZE;
142 else if (flags & HASH_WRITE_OBJECT)
143 return global_conv_flags_eol;
144 else
145 return 0;
149 int mkdir_in_gitdir(const char *path)
151 if (mkdir(path, 0777)) {
152 int saved_errno = errno;
153 struct stat st;
154 struct strbuf sb = STRBUF_INIT;
156 if (errno != EEXIST)
157 return -1;
159 * Are we looking at a path in a symlinked worktree
160 * whose original repository does not yet have it?
161 * e.g. .git/rr-cache pointing at its original
162 * repository in which the user hasn't performed any
163 * conflict resolution yet?
165 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
166 strbuf_readlink(&sb, path, st.st_size) ||
167 !is_absolute_path(sb.buf) ||
168 mkdir(sb.buf, 0777)) {
169 strbuf_release(&sb);
170 errno = saved_errno;
171 return -1;
173 strbuf_release(&sb);
175 return adjust_shared_perm(path);
178 enum scld_error safe_create_leading_directories(char *path)
180 char *next_component = path + offset_1st_component(path);
181 enum scld_error ret = SCLD_OK;
183 while (ret == SCLD_OK && next_component) {
184 struct stat st;
185 char *slash = next_component, slash_character;
187 while (*slash && !is_dir_sep(*slash))
188 slash++;
190 if (!*slash)
191 break;
193 next_component = slash + 1;
194 while (is_dir_sep(*next_component))
195 next_component++;
196 if (!*next_component)
197 break;
199 slash_character = *slash;
200 *slash = '\0';
201 if (!stat(path, &st)) {
202 /* path exists */
203 if (!S_ISDIR(st.st_mode)) {
204 errno = ENOTDIR;
205 ret = SCLD_EXISTS;
207 } else if (mkdir(path, 0777)) {
208 if (errno == EEXIST &&
209 !stat(path, &st) && S_ISDIR(st.st_mode))
210 ; /* somebody created it since we checked */
211 else if (errno == ENOENT)
213 * Either mkdir() failed because
214 * somebody just pruned the containing
215 * directory, or stat() failed because
216 * the file that was in our way was
217 * just removed. Either way, inform
218 * the caller that it might be worth
219 * trying again:
221 ret = SCLD_VANISHED;
222 else
223 ret = SCLD_FAILED;
224 } else if (adjust_shared_perm(path)) {
225 ret = SCLD_PERMS;
227 *slash = slash_character;
229 return ret;
232 enum scld_error safe_create_leading_directories_const(const char *path)
234 int save_errno;
235 /* path points to cache entries, so xstrdup before messing with it */
236 char *buf = xstrdup(path);
237 enum scld_error result = safe_create_leading_directories(buf);
239 save_errno = errno;
240 free(buf);
241 errno = save_errno;
242 return result;
245 int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
248 * The number of times we will try to remove empty directories
249 * in the way of path. This is only 1 because if another
250 * process is racily creating directories that conflict with
251 * us, we don't want to fight against them.
253 int remove_directories_remaining = 1;
256 * The number of times that we will try to create the
257 * directories containing path. We are willing to attempt this
258 * more than once, because another process could be trying to
259 * clean up empty directories at the same time as we are
260 * trying to create them.
262 int create_directories_remaining = 3;
264 /* A scratch copy of path, filled lazily if we need it: */
265 struct strbuf path_copy = STRBUF_INIT;
267 int ret, save_errno;
269 /* Sanity check: */
270 assert(*path);
272 retry_fn:
273 ret = fn(path, cb);
274 save_errno = errno;
275 if (!ret)
276 goto out;
278 if (errno == EISDIR && remove_directories_remaining-- > 0) {
280 * A directory is in the way. Maybe it is empty; try
281 * to remove it:
283 if (!path_copy.len)
284 strbuf_addstr(&path_copy, path);
286 if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
287 goto retry_fn;
288 } else if (errno == ENOENT && create_directories_remaining-- > 0) {
290 * Maybe the containing directory didn't exist, or
291 * maybe it was just deleted by a process that is
292 * racing with us to clean up empty directories. Try
293 * to create it:
295 enum scld_error scld_result;
297 if (!path_copy.len)
298 strbuf_addstr(&path_copy, path);
300 do {
301 scld_result = safe_create_leading_directories(path_copy.buf);
302 if (scld_result == SCLD_OK)
303 goto retry_fn;
304 } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
307 out:
308 strbuf_release(&path_copy);
309 errno = save_errno;
310 return ret;
313 static void fill_sha1_path(struct strbuf *buf, const unsigned char *sha1)
315 int i;
316 for (i = 0; i < 20; i++) {
317 static char hex[] = "0123456789abcdef";
318 unsigned int val = sha1[i];
319 strbuf_addch(buf, hex[val >> 4]);
320 strbuf_addch(buf, hex[val & 0xf]);
321 if (!i)
322 strbuf_addch(buf, '/');
326 void sha1_file_name(struct strbuf *buf, const unsigned char *sha1)
328 strbuf_addstr(buf, get_object_directory());
329 strbuf_addch(buf, '/');
330 fill_sha1_path(buf, sha1);
333 struct strbuf *alt_scratch_buf(struct alternate_object_database *alt)
335 strbuf_setlen(&alt->scratch, alt->base_len);
336 return &alt->scratch;
339 static const char *alt_sha1_path(struct alternate_object_database *alt,
340 const unsigned char *sha1)
342 struct strbuf *buf = alt_scratch_buf(alt);
343 fill_sha1_path(buf, sha1);
344 return buf->buf;
348 * Return non-zero iff the path is usable as an alternate object database.
350 static int alt_odb_usable(struct raw_object_store *o,
351 struct strbuf *path,
352 const char *normalized_objdir)
354 struct alternate_object_database *alt;
356 /* Detect cases where alternate disappeared */
357 if (!is_directory(path->buf)) {
358 error("object directory %s does not exist; "
359 "check .git/objects/info/alternates.",
360 path->buf);
361 return 0;
365 * Prevent the common mistake of listing the same
366 * thing twice, or object directory itself.
368 for (alt = o->alt_odb_list; alt; alt = alt->next) {
369 if (!fspathcmp(path->buf, alt->path))
370 return 0;
372 if (!fspathcmp(path->buf, normalized_objdir))
373 return 0;
375 return 1;
379 * Prepare alternate object database registry.
381 * The variable alt_odb_list points at the list of struct
382 * alternate_object_database. The elements on this list come from
383 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
384 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
385 * whose contents is similar to that environment variable but can be
386 * LF separated. Its base points at a statically allocated buffer that
387 * contains "/the/directory/corresponding/to/.git/objects/...", while
388 * its name points just after the slash at the end of ".git/objects/"
389 * in the example above, and has enough space to hold 40-byte hex
390 * SHA1, an extra slash for the first level indirection, and the
391 * terminating NUL.
393 static void read_info_alternates(const char * relative_base, int depth);
394 static int link_alt_odb_entry(const char *entry, const char *relative_base,
395 int depth, const char *normalized_objdir)
397 struct alternate_object_database *ent;
398 struct strbuf pathbuf = STRBUF_INIT;
400 if (!is_absolute_path(entry) && relative_base) {
401 strbuf_realpath(&pathbuf, relative_base, 1);
402 strbuf_addch(&pathbuf, '/');
404 strbuf_addstr(&pathbuf, entry);
406 if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
407 error("unable to normalize alternate object path: %s",
408 pathbuf.buf);
409 strbuf_release(&pathbuf);
410 return -1;
414 * The trailing slash after the directory name is given by
415 * this function at the end. Remove duplicates.
417 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
418 strbuf_setlen(&pathbuf, pathbuf.len - 1);
420 if (!alt_odb_usable(the_repository->objects, &pathbuf, normalized_objdir)) {
421 strbuf_release(&pathbuf);
422 return -1;
425 ent = alloc_alt_odb(pathbuf.buf);
427 /* add the alternate entry */
428 *the_repository->objects->alt_odb_tail = ent;
429 the_repository->objects->alt_odb_tail = &(ent->next);
430 ent->next = NULL;
432 /* recursively add alternates */
433 read_info_alternates(pathbuf.buf, depth + 1);
435 strbuf_release(&pathbuf);
436 return 0;
439 static const char *parse_alt_odb_entry(const char *string,
440 int sep,
441 struct strbuf *out)
443 const char *end;
445 strbuf_reset(out);
447 if (*string == '#') {
448 /* comment; consume up to next separator */
449 end = strchrnul(string, sep);
450 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
452 * quoted path; unquote_c_style has copied the
453 * data for us and set "end". Broken quoting (e.g.,
454 * an entry that doesn't end with a quote) falls
455 * back to the unquoted case below.
457 } else {
458 /* normal, unquoted path */
459 end = strchrnul(string, sep);
460 strbuf_add(out, string, end - string);
463 if (*end)
464 end++;
465 return end;
468 static void link_alt_odb_entries(const char *alt, int sep,
469 const char *relative_base, int depth)
471 struct strbuf objdirbuf = STRBUF_INIT;
472 struct strbuf entry = STRBUF_INIT;
474 if (!alt || !*alt)
475 return;
477 if (depth > 5) {
478 error("%s: ignoring alternate object stores, nesting too deep.",
479 relative_base);
480 return;
483 strbuf_add_absolute_path(&objdirbuf, get_object_directory());
484 if (strbuf_normalize_path(&objdirbuf) < 0)
485 die("unable to normalize object directory: %s",
486 objdirbuf.buf);
488 while (*alt) {
489 alt = parse_alt_odb_entry(alt, sep, &entry);
490 if (!entry.len)
491 continue;
492 link_alt_odb_entry(entry.buf, relative_base, depth, objdirbuf.buf);
494 strbuf_release(&entry);
495 strbuf_release(&objdirbuf);
498 static void read_info_alternates(const char * relative_base, int depth)
500 char *path;
501 struct strbuf buf = STRBUF_INIT;
503 path = xstrfmt("%s/info/alternates", relative_base);
504 if (strbuf_read_file(&buf, path, 1024) < 0) {
505 warn_on_fopen_errors(path);
506 free(path);
507 return;
510 link_alt_odb_entries(buf.buf, '\n', relative_base, depth);
511 strbuf_release(&buf);
512 free(path);
515 struct alternate_object_database *alloc_alt_odb(const char *dir)
517 struct alternate_object_database *ent;
519 FLEX_ALLOC_STR(ent, path, dir);
520 strbuf_init(&ent->scratch, 0);
521 strbuf_addf(&ent->scratch, "%s/", dir);
522 ent->base_len = ent->scratch.len;
524 return ent;
527 void add_to_alternates_file(const char *reference)
529 struct lock_file lock = LOCK_INIT;
530 char *alts = git_pathdup("objects/info/alternates");
531 FILE *in, *out;
532 int found = 0;
534 hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
535 out = fdopen_lock_file(&lock, "w");
536 if (!out)
537 die_errno("unable to fdopen alternates lockfile");
539 in = fopen(alts, "r");
540 if (in) {
541 struct strbuf line = STRBUF_INIT;
543 while (strbuf_getline(&line, in) != EOF) {
544 if (!strcmp(reference, line.buf)) {
545 found = 1;
546 break;
548 fprintf_or_die(out, "%s\n", line.buf);
551 strbuf_release(&line);
552 fclose(in);
554 else if (errno != ENOENT)
555 die_errno("unable to read alternates file");
557 if (found) {
558 rollback_lock_file(&lock);
559 } else {
560 fprintf_or_die(out, "%s\n", reference);
561 if (commit_lock_file(&lock))
562 die_errno("unable to move new alternates file into place");
563 if (the_repository->objects->alt_odb_tail)
564 link_alt_odb_entries(reference, '\n', NULL, 0);
566 free(alts);
569 void add_to_alternates_memory(const char *reference)
572 * Make sure alternates are initialized, or else our entry may be
573 * overwritten when they are.
575 prepare_alt_odb();
577 link_alt_odb_entries(reference, '\n', NULL, 0);
581 * Compute the exact path an alternate is at and returns it. In case of
582 * error NULL is returned and the human readable error is added to `err`
583 * `path` may be relative and should point to $GITDIR.
584 * `err` must not be null.
586 char *compute_alternate_path(const char *path, struct strbuf *err)
588 char *ref_git = NULL;
589 const char *repo, *ref_git_s;
590 int seen_error = 0;
592 ref_git_s = real_path_if_valid(path);
593 if (!ref_git_s) {
594 seen_error = 1;
595 strbuf_addf(err, _("path '%s' does not exist"), path);
596 goto out;
597 } else
599 * Beware: read_gitfile(), real_path() and mkpath()
600 * return static buffer
602 ref_git = xstrdup(ref_git_s);
604 repo = read_gitfile(ref_git);
605 if (!repo)
606 repo = read_gitfile(mkpath("%s/.git", ref_git));
607 if (repo) {
608 free(ref_git);
609 ref_git = xstrdup(repo);
612 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
613 char *ref_git_git = mkpathdup("%s/.git", ref_git);
614 free(ref_git);
615 ref_git = ref_git_git;
616 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
617 struct strbuf sb = STRBUF_INIT;
618 seen_error = 1;
619 if (get_common_dir(&sb, ref_git)) {
620 strbuf_addf(err,
621 _("reference repository '%s' as a linked "
622 "checkout is not supported yet."),
623 path);
624 goto out;
627 strbuf_addf(err, _("reference repository '%s' is not a "
628 "local repository."), path);
629 goto out;
632 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
633 strbuf_addf(err, _("reference repository '%s' is shallow"),
634 path);
635 seen_error = 1;
636 goto out;
639 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
640 strbuf_addf(err,
641 _("reference repository '%s' is grafted"),
642 path);
643 seen_error = 1;
644 goto out;
647 out:
648 if (seen_error) {
649 FREE_AND_NULL(ref_git);
652 return ref_git;
655 int foreach_alt_odb(alt_odb_fn fn, void *cb)
657 struct alternate_object_database *ent;
658 int r = 0;
660 prepare_alt_odb();
661 for (ent = the_repository->objects->alt_odb_list; ent; ent = ent->next) {
662 r = fn(ent, cb);
663 if (r)
664 break;
666 return r;
669 void prepare_alt_odb(void)
671 if (the_repository->objects->alt_odb_tail)
672 return;
674 the_repository->objects->alt_odb_tail =
675 &the_repository->objects->alt_odb_list;
676 link_alt_odb_entries(the_repository->objects->alternate_db,
677 PATH_SEP, NULL, 0);
679 read_info_alternates(get_object_directory(), 0);
682 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
683 static int freshen_file(const char *fn)
685 struct utimbuf t;
686 t.actime = t.modtime = time(NULL);
687 return !utime(fn, &t);
691 * All of the check_and_freshen functions return 1 if the file exists and was
692 * freshened (if freshening was requested), 0 otherwise. If they return
693 * 0, you should not assume that it is safe to skip a write of the object (it
694 * either does not exist on disk, or has a stale mtime and may be subject to
695 * pruning).
697 int check_and_freshen_file(const char *fn, int freshen)
699 if (access(fn, F_OK))
700 return 0;
701 if (freshen && !freshen_file(fn))
702 return 0;
703 return 1;
706 static int check_and_freshen_local(const unsigned char *sha1, int freshen)
708 static struct strbuf buf = STRBUF_INIT;
710 strbuf_reset(&buf);
711 sha1_file_name(&buf, sha1);
713 return check_and_freshen_file(buf.buf, freshen);
716 static int check_and_freshen_nonlocal(const unsigned char *sha1, int freshen)
718 struct alternate_object_database *alt;
719 prepare_alt_odb();
720 for (alt = the_repository->objects->alt_odb_list; alt; alt = alt->next) {
721 const char *path = alt_sha1_path(alt, sha1);
722 if (check_and_freshen_file(path, freshen))
723 return 1;
725 return 0;
728 static int check_and_freshen(const unsigned char *sha1, int freshen)
730 return check_and_freshen_local(sha1, freshen) ||
731 check_and_freshen_nonlocal(sha1, freshen);
734 int has_loose_object_nonlocal(const unsigned char *sha1)
736 return check_and_freshen_nonlocal(sha1, 0);
739 static int has_loose_object(const unsigned char *sha1)
741 return check_and_freshen(sha1, 0);
744 static void mmap_limit_check(size_t length)
746 static size_t limit = 0;
747 if (!limit) {
748 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
749 if (!limit)
750 limit = SIZE_MAX;
752 if (length > limit)
753 die("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX,
754 (uintmax_t)length, (uintmax_t)limit);
757 void *xmmap_gently(void *start, size_t length,
758 int prot, int flags, int fd, off_t offset)
760 void *ret;
762 mmap_limit_check(length);
763 ret = mmap(start, length, prot, flags, fd, offset);
764 if (ret == MAP_FAILED) {
765 if (!length)
766 return NULL;
767 release_pack_memory(length);
768 ret = mmap(start, length, prot, flags, fd, offset);
770 return ret;
773 void *xmmap(void *start, size_t length,
774 int prot, int flags, int fd, off_t offset)
776 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
777 if (ret == MAP_FAILED)
778 die_errno("mmap failed");
779 return ret;
783 * With an in-core object data in "map", rehash it to make sure the
784 * object name actually matches "sha1" to detect object corruption.
785 * With "map" == NULL, try reading the object named with "sha1" using
786 * the streaming interface and rehash it to do the same.
788 int check_sha1_signature(const unsigned char *sha1, void *map,
789 unsigned long size, const char *type)
791 unsigned char real_sha1[20];
792 enum object_type obj_type;
793 struct git_istream *st;
794 git_SHA_CTX c;
795 char hdr[32];
796 int hdrlen;
798 if (map) {
799 hash_sha1_file(map, size, type, real_sha1);
800 return hashcmp(sha1, real_sha1) ? -1 : 0;
803 st = open_istream(sha1, &obj_type, &size, NULL);
804 if (!st)
805 return -1;
807 /* Generate the header */
808 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(obj_type), size) + 1;
810 /* Sha1.. */
811 git_SHA1_Init(&c);
812 git_SHA1_Update(&c, hdr, hdrlen);
813 for (;;) {
814 char buf[1024 * 16];
815 ssize_t readlen = read_istream(st, buf, sizeof(buf));
817 if (readlen < 0) {
818 close_istream(st);
819 return -1;
821 if (!readlen)
822 break;
823 git_SHA1_Update(&c, buf, readlen);
825 git_SHA1_Final(real_sha1, &c);
826 close_istream(st);
827 return hashcmp(sha1, real_sha1) ? -1 : 0;
830 int git_open_cloexec(const char *name, int flags)
832 int fd;
833 static int o_cloexec = O_CLOEXEC;
835 fd = open(name, flags | o_cloexec);
836 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
837 /* Try again w/o O_CLOEXEC: the kernel might not support it */
838 o_cloexec &= ~O_CLOEXEC;
839 fd = open(name, flags | o_cloexec);
842 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
844 static int fd_cloexec = FD_CLOEXEC;
846 if (!o_cloexec && 0 <= fd && fd_cloexec) {
847 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
848 int flags = fcntl(fd, F_GETFD);
849 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
850 fd_cloexec = 0;
853 #endif
854 return fd;
858 * Find "sha1" as a loose object in the local repository or in an alternate.
859 * Returns 0 on success, negative on failure.
861 * The "path" out-parameter will give the path of the object we found (if any).
862 * Note that it may point to static storage and is only valid until another
863 * call to sha1_file_name(), etc.
865 static int stat_sha1_file(const unsigned char *sha1, struct stat *st,
866 const char **path)
868 struct alternate_object_database *alt;
869 static struct strbuf buf = STRBUF_INIT;
871 strbuf_reset(&buf);
872 sha1_file_name(&buf, sha1);
873 *path = buf.buf;
875 if (!lstat(*path, st))
876 return 0;
878 prepare_alt_odb();
879 errno = ENOENT;
880 for (alt = the_repository->objects->alt_odb_list; alt; alt = alt->next) {
881 *path = alt_sha1_path(alt, sha1);
882 if (!lstat(*path, st))
883 return 0;
886 return -1;
890 * Like stat_sha1_file(), but actually open the object and return the
891 * descriptor. See the caveats on the "path" parameter above.
893 static int open_sha1_file(const unsigned char *sha1, const char **path)
895 int fd;
896 struct alternate_object_database *alt;
897 int most_interesting_errno;
898 static struct strbuf buf = STRBUF_INIT;
900 strbuf_reset(&buf);
901 sha1_file_name(&buf, sha1);
902 *path = buf.buf;
904 fd = git_open(*path);
905 if (fd >= 0)
906 return fd;
907 most_interesting_errno = errno;
909 prepare_alt_odb();
910 for (alt = the_repository->objects->alt_odb_list; alt; alt = alt->next) {
911 *path = alt_sha1_path(alt, sha1);
912 fd = git_open(*path);
913 if (fd >= 0)
914 return fd;
915 if (most_interesting_errno == ENOENT)
916 most_interesting_errno = errno;
918 errno = most_interesting_errno;
919 return -1;
923 * Map the loose object at "path" if it is not NULL, or the path found by
924 * searching for a loose object named "sha1".
926 static void *map_sha1_file_1(const char *path,
927 const unsigned char *sha1,
928 unsigned long *size)
930 void *map;
931 int fd;
933 if (path)
934 fd = git_open(path);
935 else
936 fd = open_sha1_file(sha1, &path);
937 map = NULL;
938 if (fd >= 0) {
939 struct stat st;
941 if (!fstat(fd, &st)) {
942 *size = xsize_t(st.st_size);
943 if (!*size) {
944 /* mmap() is forbidden on empty files */
945 error("object file %s is empty", path);
946 return NULL;
948 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
950 close(fd);
952 return map;
955 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
957 return map_sha1_file_1(NULL, sha1, size);
960 static int unpack_sha1_short_header(git_zstream *stream,
961 unsigned char *map, unsigned long mapsize,
962 void *buffer, unsigned long bufsiz)
964 /* Get the data stream */
965 memset(stream, 0, sizeof(*stream));
966 stream->next_in = map;
967 stream->avail_in = mapsize;
968 stream->next_out = buffer;
969 stream->avail_out = bufsiz;
971 git_inflate_init(stream);
972 return git_inflate(stream, 0);
975 int unpack_sha1_header(git_zstream *stream,
976 unsigned char *map, unsigned long mapsize,
977 void *buffer, unsigned long bufsiz)
979 int status = unpack_sha1_short_header(stream, map, mapsize,
980 buffer, bufsiz);
982 if (status < Z_OK)
983 return status;
985 /* Make sure we have the terminating NUL */
986 if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
987 return -1;
988 return 0;
991 static int unpack_sha1_header_to_strbuf(git_zstream *stream, unsigned char *map,
992 unsigned long mapsize, void *buffer,
993 unsigned long bufsiz, struct strbuf *header)
995 int status;
997 status = unpack_sha1_short_header(stream, map, mapsize, buffer, bufsiz);
998 if (status < Z_OK)
999 return -1;
1002 * Check if entire header is unpacked in the first iteration.
1004 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1005 return 0;
1008 * buffer[0..bufsiz] was not large enough. Copy the partial
1009 * result out to header, and then append the result of further
1010 * reading the stream.
1012 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1013 stream->next_out = buffer;
1014 stream->avail_out = bufsiz;
1016 do {
1017 status = git_inflate(stream, 0);
1018 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1019 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1020 return 0;
1021 stream->next_out = buffer;
1022 stream->avail_out = bufsiz;
1023 } while (status != Z_STREAM_END);
1024 return -1;
1027 static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1029 int bytes = strlen(buffer) + 1;
1030 unsigned char *buf = xmallocz(size);
1031 unsigned long n;
1032 int status = Z_OK;
1034 n = stream->total_out - bytes;
1035 if (n > size)
1036 n = size;
1037 memcpy(buf, (char *) buffer + bytes, n);
1038 bytes = n;
1039 if (bytes <= size) {
1041 * The above condition must be (bytes <= size), not
1042 * (bytes < size). In other words, even though we
1043 * expect no more output and set avail_out to zero,
1044 * the input zlib stream may have bytes that express
1045 * "this concludes the stream", and we *do* want to
1046 * eat that input.
1048 * Otherwise we would not be able to test that we
1049 * consumed all the input to reach the expected size;
1050 * we also want to check that zlib tells us that all
1051 * went well with status == Z_STREAM_END at the end.
1053 stream->next_out = buf + bytes;
1054 stream->avail_out = size - bytes;
1055 while (status == Z_OK)
1056 status = git_inflate(stream, Z_FINISH);
1058 if (status == Z_STREAM_END && !stream->avail_in) {
1059 git_inflate_end(stream);
1060 return buf;
1063 if (status < 0)
1064 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1065 else if (stream->avail_in)
1066 error("garbage at end of loose object '%s'",
1067 sha1_to_hex(sha1));
1068 free(buf);
1069 return NULL;
1073 * We used to just use "sscanf()", but that's actually way
1074 * too permissive for what we want to check. So do an anal
1075 * object header parse by hand.
1077 static int parse_sha1_header_extended(const char *hdr, struct object_info *oi,
1078 unsigned int flags)
1080 const char *type_buf = hdr;
1081 unsigned long size;
1082 int type, type_len = 0;
1085 * The type can be of any size but is followed by
1086 * a space.
1088 for (;;) {
1089 char c = *hdr++;
1090 if (!c)
1091 return -1;
1092 if (c == ' ')
1093 break;
1094 type_len++;
1097 type = type_from_string_gently(type_buf, type_len, 1);
1098 if (oi->typename)
1099 strbuf_add(oi->typename, type_buf, type_len);
1101 * Set type to 0 if its an unknown object and
1102 * we're obtaining the type using '--allow-unknown-type'
1103 * option.
1105 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1106 type = 0;
1107 else if (type < 0)
1108 die("invalid object type");
1109 if (oi->typep)
1110 *oi->typep = type;
1113 * The length must follow immediately, and be in canonical
1114 * decimal format (ie "010" is not valid).
1116 size = *hdr++ - '0';
1117 if (size > 9)
1118 return -1;
1119 if (size) {
1120 for (;;) {
1121 unsigned long c = *hdr - '0';
1122 if (c > 9)
1123 break;
1124 hdr++;
1125 size = size * 10 + c;
1129 if (oi->sizep)
1130 *oi->sizep = size;
1133 * The length must be followed by a zero byte
1135 return *hdr ? -1 : type;
1138 int parse_sha1_header(const char *hdr, unsigned long *sizep)
1140 struct object_info oi = OBJECT_INFO_INIT;
1142 oi.sizep = sizep;
1143 return parse_sha1_header_extended(hdr, &oi, 0);
1146 static int sha1_loose_object_info(const unsigned char *sha1,
1147 struct object_info *oi,
1148 int flags)
1150 int status = 0;
1151 unsigned long mapsize;
1152 void *map;
1153 git_zstream stream;
1154 char hdr[32];
1155 struct strbuf hdrbuf = STRBUF_INIT;
1156 unsigned long size_scratch;
1158 if (oi->delta_base_sha1)
1159 hashclr(oi->delta_base_sha1);
1162 * If we don't care about type or size, then we don't
1163 * need to look inside the object at all. Note that we
1164 * do not optimize out the stat call, even if the
1165 * caller doesn't care about the disk-size, since our
1166 * return value implicitly indicates whether the
1167 * object even exists.
1169 if (!oi->typep && !oi->typename && !oi->sizep && !oi->contentp) {
1170 const char *path;
1171 struct stat st;
1172 if (stat_sha1_file(sha1, &st, &path) < 0)
1173 return -1;
1174 if (oi->disk_sizep)
1175 *oi->disk_sizep = st.st_size;
1176 return 0;
1179 map = map_sha1_file(sha1, &mapsize);
1180 if (!map)
1181 return -1;
1183 if (!oi->sizep)
1184 oi->sizep = &size_scratch;
1186 if (oi->disk_sizep)
1187 *oi->disk_sizep = mapsize;
1188 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
1189 if (unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
1190 status = error("unable to unpack %s header with --allow-unknown-type",
1191 sha1_to_hex(sha1));
1192 } else if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1193 status = error("unable to unpack %s header",
1194 sha1_to_hex(sha1));
1195 if (status < 0)
1196 ; /* Do nothing */
1197 else if (hdrbuf.len) {
1198 if ((status = parse_sha1_header_extended(hdrbuf.buf, oi, flags)) < 0)
1199 status = error("unable to parse %s header with --allow-unknown-type",
1200 sha1_to_hex(sha1));
1201 } else if ((status = parse_sha1_header_extended(hdr, oi, flags)) < 0)
1202 status = error("unable to parse %s header", sha1_to_hex(sha1));
1204 if (status >= 0 && oi->contentp) {
1205 *oi->contentp = unpack_sha1_rest(&stream, hdr,
1206 *oi->sizep, sha1);
1207 if (!*oi->contentp) {
1208 git_inflate_end(&stream);
1209 status = -1;
1211 } else
1212 git_inflate_end(&stream);
1214 munmap(map, mapsize);
1215 if (status && oi->typep)
1216 *oi->typep = status;
1217 if (oi->sizep == &size_scratch)
1218 oi->sizep = NULL;
1219 strbuf_release(&hdrbuf);
1220 oi->whence = OI_LOOSE;
1221 return (status < 0) ? status : 0;
1224 int fetch_if_missing = 1;
1226 int sha1_object_info_extended(const unsigned char *sha1, struct object_info *oi, unsigned flags)
1228 static struct object_info blank_oi = OBJECT_INFO_INIT;
1229 struct pack_entry e;
1230 int rtype;
1231 const unsigned char *real = (flags & OBJECT_INFO_LOOKUP_REPLACE) ?
1232 lookup_replace_object(sha1) :
1233 sha1;
1234 int already_retried = 0;
1236 if (is_null_sha1(real))
1237 return -1;
1239 if (!oi)
1240 oi = &blank_oi;
1242 if (!(flags & OBJECT_INFO_SKIP_CACHED)) {
1243 struct cached_object *co = find_cached_object(real);
1244 if (co) {
1245 if (oi->typep)
1246 *(oi->typep) = co->type;
1247 if (oi->sizep)
1248 *(oi->sizep) = co->size;
1249 if (oi->disk_sizep)
1250 *(oi->disk_sizep) = 0;
1251 if (oi->delta_base_sha1)
1252 hashclr(oi->delta_base_sha1);
1253 if (oi->typename)
1254 strbuf_addstr(oi->typename, typename(co->type));
1255 if (oi->contentp)
1256 *oi->contentp = xmemdupz(co->buf, co->size);
1257 oi->whence = OI_CACHED;
1258 return 0;
1262 while (1) {
1263 if (find_pack_entry(real, &e))
1264 break;
1266 /* Most likely it's a loose object. */
1267 if (!sha1_loose_object_info(real, oi, flags))
1268 return 0;
1270 /* Not a loose object; someone else may have just packed it. */
1271 reprepare_packed_git();
1272 if (find_pack_entry(real, &e))
1273 break;
1275 /* Check if it is a missing object */
1276 if (fetch_if_missing && repository_format_partial_clone &&
1277 !already_retried) {
1279 * TODO Investigate haveing fetch_object() return
1280 * TODO error/success and stopping the music here.
1282 fetch_object(repository_format_partial_clone, real);
1283 already_retried = 1;
1284 continue;
1287 return -1;
1290 if (oi == &blank_oi)
1292 * We know that the caller doesn't actually need the
1293 * information below, so return early.
1295 return 0;
1296 rtype = packed_object_info(e.p, e.offset, oi);
1297 if (rtype < 0) {
1298 mark_bad_packed_object(e.p, real);
1299 return sha1_object_info_extended(real, oi, 0);
1300 } else if (oi->whence == OI_PACKED) {
1301 oi->u.packed.offset = e.offset;
1302 oi->u.packed.pack = e.p;
1303 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1304 rtype == OBJ_OFS_DELTA);
1307 return 0;
1310 /* returns enum object_type or negative */
1311 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
1313 enum object_type type;
1314 struct object_info oi = OBJECT_INFO_INIT;
1316 oi.typep = &type;
1317 oi.sizep = sizep;
1318 if (sha1_object_info_extended(sha1, &oi,
1319 OBJECT_INFO_LOOKUP_REPLACE) < 0)
1320 return -1;
1321 return type;
1324 static void *read_object(const unsigned char *sha1, enum object_type *type,
1325 unsigned long *size)
1327 struct object_info oi = OBJECT_INFO_INIT;
1328 void *content;
1329 oi.typep = type;
1330 oi.sizep = size;
1331 oi.contentp = &content;
1333 if (sha1_object_info_extended(sha1, &oi, 0) < 0)
1334 return NULL;
1335 return content;
1338 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
1339 unsigned char *sha1)
1341 struct cached_object *co;
1343 hash_sha1_file(buf, len, typename(type), sha1);
1344 if (has_sha1_file(sha1) || find_cached_object(sha1))
1345 return 0;
1346 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1347 co = &cached_objects[cached_object_nr++];
1348 co->size = len;
1349 co->type = type;
1350 co->buf = xmalloc(len);
1351 memcpy(co->buf, buf, len);
1352 hashcpy(co->sha1, sha1);
1353 return 0;
1357 * This function dies on corrupt objects; the callers who want to
1358 * deal with them should arrange to call read_object() and give error
1359 * messages themselves.
1361 void *read_sha1_file_extended(const unsigned char *sha1,
1362 enum object_type *type,
1363 unsigned long *size,
1364 int lookup_replace)
1366 void *data;
1367 const struct packed_git *p;
1368 const char *path;
1369 struct stat st;
1370 const unsigned char *repl = lookup_replace ? lookup_replace_object(sha1)
1371 : sha1;
1373 errno = 0;
1374 data = read_object(repl, type, size);
1375 if (data)
1376 return data;
1378 if (errno && errno != ENOENT)
1379 die_errno("failed to read object %s", sha1_to_hex(sha1));
1381 /* die if we replaced an object with one that does not exist */
1382 if (repl != sha1)
1383 die("replacement %s not found for %s",
1384 sha1_to_hex(repl), sha1_to_hex(sha1));
1386 if (!stat_sha1_file(repl, &st, &path))
1387 die("loose object %s (stored in %s) is corrupt",
1388 sha1_to_hex(repl), path);
1390 if ((p = has_packed_and_bad(repl)) != NULL)
1391 die("packed object %s (stored in %s) is corrupt",
1392 sha1_to_hex(repl), p->pack_name);
1394 return NULL;
1397 void *read_object_with_reference(const unsigned char *sha1,
1398 const char *required_type_name,
1399 unsigned long *size,
1400 unsigned char *actual_sha1_return)
1402 enum object_type type, required_type;
1403 void *buffer;
1404 unsigned long isize;
1405 unsigned char actual_sha1[20];
1407 required_type = type_from_string(required_type_name);
1408 hashcpy(actual_sha1, sha1);
1409 while (1) {
1410 int ref_length = -1;
1411 const char *ref_type = NULL;
1413 buffer = read_sha1_file(actual_sha1, &type, &isize);
1414 if (!buffer)
1415 return NULL;
1416 if (type == required_type) {
1417 *size = isize;
1418 if (actual_sha1_return)
1419 hashcpy(actual_sha1_return, actual_sha1);
1420 return buffer;
1422 /* Handle references */
1423 else if (type == OBJ_COMMIT)
1424 ref_type = "tree ";
1425 else if (type == OBJ_TAG)
1426 ref_type = "object ";
1427 else {
1428 free(buffer);
1429 return NULL;
1431 ref_length = strlen(ref_type);
1433 if (ref_length + 40 > isize ||
1434 memcmp(buffer, ref_type, ref_length) ||
1435 get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
1436 free(buffer);
1437 return NULL;
1439 free(buffer);
1440 /* Now we have the ID of the referred-to object in
1441 * actual_sha1. Check again. */
1445 static void write_sha1_file_prepare(const void *buf, unsigned long len,
1446 const char *type, unsigned char *sha1,
1447 char *hdr, int *hdrlen)
1449 git_SHA_CTX c;
1451 /* Generate the header */
1452 *hdrlen = xsnprintf(hdr, *hdrlen, "%s %lu", type, len)+1;
1454 /* Sha1.. */
1455 git_SHA1_Init(&c);
1456 git_SHA1_Update(&c, hdr, *hdrlen);
1457 git_SHA1_Update(&c, buf, len);
1458 git_SHA1_Final(sha1, &c);
1462 * Move the just written object into its final resting place.
1464 int finalize_object_file(const char *tmpfile, const char *filename)
1466 int ret = 0;
1468 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
1469 goto try_rename;
1470 else if (link(tmpfile, filename))
1471 ret = errno;
1474 * Coda hack - coda doesn't like cross-directory links,
1475 * so we fall back to a rename, which will mean that it
1476 * won't be able to check collisions, but that's not a
1477 * big deal.
1479 * The same holds for FAT formatted media.
1481 * When this succeeds, we just return. We have nothing
1482 * left to unlink.
1484 if (ret && ret != EEXIST) {
1485 try_rename:
1486 if (!rename(tmpfile, filename))
1487 goto out;
1488 ret = errno;
1490 unlink_or_warn(tmpfile);
1491 if (ret) {
1492 if (ret != EEXIST) {
1493 return error_errno("unable to write sha1 filename %s", filename);
1495 /* FIXME!!! Collision check here ? */
1498 out:
1499 if (adjust_shared_perm(filename))
1500 return error("unable to set permission to '%s'", filename);
1501 return 0;
1504 static int write_buffer(int fd, const void *buf, size_t len)
1506 if (write_in_full(fd, buf, len) < 0)
1507 return error_errno("file write error");
1508 return 0;
1511 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
1512 unsigned char *sha1)
1514 char hdr[32];
1515 int hdrlen = sizeof(hdr);
1516 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1517 return 0;
1520 /* Finalize a file on disk, and close it. */
1521 static void close_sha1_file(int fd)
1523 if (fsync_object_files)
1524 fsync_or_die(fd, "sha1 file");
1525 if (close(fd) != 0)
1526 die_errno("error when closing sha1 file");
1529 /* Size of directory component, including the ending '/' */
1530 static inline int directory_size(const char *filename)
1532 const char *s = strrchr(filename, '/');
1533 if (!s)
1534 return 0;
1535 return s - filename + 1;
1539 * This creates a temporary file in the same directory as the final
1540 * 'filename'
1542 * We want to avoid cross-directory filename renames, because those
1543 * can have problems on various filesystems (FAT, NFS, Coda).
1545 static int create_tmpfile(struct strbuf *tmp, const char *filename)
1547 int fd, dirlen = directory_size(filename);
1549 strbuf_reset(tmp);
1550 strbuf_add(tmp, filename, dirlen);
1551 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
1552 fd = git_mkstemp_mode(tmp->buf, 0444);
1553 if (fd < 0 && dirlen && errno == ENOENT) {
1555 * Make sure the directory exists; note that the contents
1556 * of the buffer are undefined after mkstemp returns an
1557 * error, so we have to rewrite the whole buffer from
1558 * scratch.
1560 strbuf_reset(tmp);
1561 strbuf_add(tmp, filename, dirlen - 1);
1562 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
1563 return -1;
1564 if (adjust_shared_perm(tmp->buf))
1565 return -1;
1567 /* Try again */
1568 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
1569 fd = git_mkstemp_mode(tmp->buf, 0444);
1571 return fd;
1574 static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
1575 const void *buf, unsigned long len, time_t mtime)
1577 int fd, ret;
1578 unsigned char compressed[4096];
1579 git_zstream stream;
1580 git_SHA_CTX c;
1581 unsigned char parano_sha1[20];
1582 static struct strbuf tmp_file = STRBUF_INIT;
1583 static struct strbuf filename = STRBUF_INIT;
1585 strbuf_reset(&filename);
1586 sha1_file_name(&filename, sha1);
1588 fd = create_tmpfile(&tmp_file, filename.buf);
1589 if (fd < 0) {
1590 if (errno == EACCES)
1591 return error("insufficient permission for adding an object to repository database %s", get_object_directory());
1592 else
1593 return error_errno("unable to create temporary file");
1596 /* Set it up */
1597 git_deflate_init(&stream, zlib_compression_level);
1598 stream.next_out = compressed;
1599 stream.avail_out = sizeof(compressed);
1600 git_SHA1_Init(&c);
1602 /* First header.. */
1603 stream.next_in = (unsigned char *)hdr;
1604 stream.avail_in = hdrlen;
1605 while (git_deflate(&stream, 0) == Z_OK)
1606 ; /* nothing */
1607 git_SHA1_Update(&c, hdr, hdrlen);
1609 /* Then the data itself.. */
1610 stream.next_in = (void *)buf;
1611 stream.avail_in = len;
1612 do {
1613 unsigned char *in0 = stream.next_in;
1614 ret = git_deflate(&stream, Z_FINISH);
1615 git_SHA1_Update(&c, in0, stream.next_in - in0);
1616 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
1617 die("unable to write sha1 file");
1618 stream.next_out = compressed;
1619 stream.avail_out = sizeof(compressed);
1620 } while (ret == Z_OK);
1622 if (ret != Z_STREAM_END)
1623 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
1624 ret = git_deflate_end_gently(&stream);
1625 if (ret != Z_OK)
1626 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
1627 git_SHA1_Final(parano_sha1, &c);
1628 if (hashcmp(sha1, parano_sha1) != 0)
1629 die("confused by unstable object source data for %s", sha1_to_hex(sha1));
1631 close_sha1_file(fd);
1633 if (mtime) {
1634 struct utimbuf utb;
1635 utb.actime = mtime;
1636 utb.modtime = mtime;
1637 if (utime(tmp_file.buf, &utb) < 0)
1638 warning_errno("failed utime() on %s", tmp_file.buf);
1641 return finalize_object_file(tmp_file.buf, filename.buf);
1644 static int freshen_loose_object(const unsigned char *sha1)
1646 return check_and_freshen(sha1, 1);
1649 static int freshen_packed_object(const unsigned char *sha1)
1651 struct pack_entry e;
1652 if (!find_pack_entry(sha1, &e))
1653 return 0;
1654 if (e.p->freshened)
1655 return 1;
1656 if (!freshen_file(e.p->pack_name))
1657 return 0;
1658 e.p->freshened = 1;
1659 return 1;
1662 int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *sha1)
1664 char hdr[32];
1665 int hdrlen = sizeof(hdr);
1667 /* Normally if we have it in the pack then we do not bother writing
1668 * it out into .git/objects/??/?{38} file.
1670 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1671 if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
1672 return 0;
1673 return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
1676 int hash_sha1_file_literally(const void *buf, unsigned long len, const char *type,
1677 struct object_id *oid, unsigned flags)
1679 char *header;
1680 int hdrlen, status = 0;
1682 /* type string, SP, %lu of the length plus NUL must fit this */
1683 hdrlen = strlen(type) + 32;
1684 header = xmalloc(hdrlen);
1685 write_sha1_file_prepare(buf, len, type, oid->hash, header, &hdrlen);
1687 if (!(flags & HASH_WRITE_OBJECT))
1688 goto cleanup;
1689 if (freshen_packed_object(oid->hash) || freshen_loose_object(oid->hash))
1690 goto cleanup;
1691 status = write_loose_object(oid->hash, header, hdrlen, buf, len, 0);
1693 cleanup:
1694 free(header);
1695 return status;
1698 int force_object_loose(const unsigned char *sha1, time_t mtime)
1700 void *buf;
1701 unsigned long len;
1702 enum object_type type;
1703 char hdr[32];
1704 int hdrlen;
1705 int ret;
1707 if (has_loose_object(sha1))
1708 return 0;
1709 buf = read_object(sha1, &type, &len);
1710 if (!buf)
1711 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1712 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(type), len) + 1;
1713 ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
1714 free(buf);
1716 return ret;
1719 int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
1721 if (!startup_info->have_repository)
1722 return 0;
1723 return sha1_object_info_extended(sha1, NULL,
1724 flags | OBJECT_INFO_SKIP_CACHED) >= 0;
1727 int has_object_file(const struct object_id *oid)
1729 return has_sha1_file(oid->hash);
1732 int has_object_file_with_flags(const struct object_id *oid, int flags)
1734 return has_sha1_file_with_flags(oid->hash, flags);
1737 static void check_tree(const void *buf, size_t size)
1739 struct tree_desc desc;
1740 struct name_entry entry;
1742 init_tree_desc(&desc, buf, size);
1743 while (tree_entry(&desc, &entry))
1744 /* do nothing
1745 * tree_entry() will die() on malformed entries */
1749 static void check_commit(const void *buf, size_t size)
1751 struct commit c;
1752 memset(&c, 0, sizeof(c));
1753 if (parse_commit_buffer(&c, buf, size))
1754 die("corrupt commit");
1757 static void check_tag(const void *buf, size_t size)
1759 struct tag t;
1760 memset(&t, 0, sizeof(t));
1761 if (parse_tag_buffer(&t, buf, size))
1762 die("corrupt tag");
1765 static int index_mem(struct object_id *oid, void *buf, size_t size,
1766 enum object_type type,
1767 const char *path, unsigned flags)
1769 int ret, re_allocated = 0;
1770 int write_object = flags & HASH_WRITE_OBJECT;
1772 if (!type)
1773 type = OBJ_BLOB;
1776 * Convert blobs to git internal format
1778 if ((type == OBJ_BLOB) && path) {
1779 struct strbuf nbuf = STRBUF_INIT;
1780 if (convert_to_git(&the_index, path, buf, size, &nbuf,
1781 get_conv_flags(flags))) {
1782 buf = strbuf_detach(&nbuf, &size);
1783 re_allocated = 1;
1786 if (flags & HASH_FORMAT_CHECK) {
1787 if (type == OBJ_TREE)
1788 check_tree(buf, size);
1789 if (type == OBJ_COMMIT)
1790 check_commit(buf, size);
1791 if (type == OBJ_TAG)
1792 check_tag(buf, size);
1795 if (write_object)
1796 ret = write_sha1_file(buf, size, typename(type), oid->hash);
1797 else
1798 ret = hash_sha1_file(buf, size, typename(type), oid->hash);
1799 if (re_allocated)
1800 free(buf);
1801 return ret;
1804 static int index_stream_convert_blob(struct object_id *oid, int fd,
1805 const char *path, unsigned flags)
1807 int ret;
1808 const int write_object = flags & HASH_WRITE_OBJECT;
1809 struct strbuf sbuf = STRBUF_INIT;
1811 assert(path);
1812 assert(would_convert_to_git_filter_fd(path));
1814 convert_to_git_filter_fd(&the_index, path, fd, &sbuf,
1815 get_conv_flags(flags));
1817 if (write_object)
1818 ret = write_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
1819 oid->hash);
1820 else
1821 ret = hash_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
1822 oid->hash);
1823 strbuf_release(&sbuf);
1824 return ret;
1827 static int index_pipe(struct object_id *oid, int fd, enum object_type type,
1828 const char *path, unsigned flags)
1830 struct strbuf sbuf = STRBUF_INIT;
1831 int ret;
1833 if (strbuf_read(&sbuf, fd, 4096) >= 0)
1834 ret = index_mem(oid, sbuf.buf, sbuf.len, type, path, flags);
1835 else
1836 ret = -1;
1837 strbuf_release(&sbuf);
1838 return ret;
1841 #define SMALL_FILE_SIZE (32*1024)
1843 static int index_core(struct object_id *oid, int fd, size_t size,
1844 enum object_type type, const char *path,
1845 unsigned flags)
1847 int ret;
1849 if (!size) {
1850 ret = index_mem(oid, "", size, type, path, flags);
1851 } else if (size <= SMALL_FILE_SIZE) {
1852 char *buf = xmalloc(size);
1853 ssize_t read_result = read_in_full(fd, buf, size);
1854 if (read_result < 0)
1855 ret = error_errno("read error while indexing %s",
1856 path ? path : "<unknown>");
1857 else if (read_result != size)
1858 ret = error("short read while indexing %s",
1859 path ? path : "<unknown>");
1860 else
1861 ret = index_mem(oid, buf, size, type, path, flags);
1862 free(buf);
1863 } else {
1864 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1865 ret = index_mem(oid, buf, size, type, path, flags);
1866 munmap(buf, size);
1868 return ret;
1872 * This creates one packfile per large blob unless bulk-checkin
1873 * machinery is "plugged".
1875 * This also bypasses the usual "convert-to-git" dance, and that is on
1876 * purpose. We could write a streaming version of the converting
1877 * functions and insert that before feeding the data to fast-import
1878 * (or equivalent in-core API described above). However, that is
1879 * somewhat complicated, as we do not know the size of the filter
1880 * result, which we need to know beforehand when writing a git object.
1881 * Since the primary motivation for trying to stream from the working
1882 * tree file and to avoid mmaping it in core is to deal with large
1883 * binary blobs, they generally do not want to get any conversion, and
1884 * callers should avoid this code path when filters are requested.
1886 static int index_stream(struct object_id *oid, int fd, size_t size,
1887 enum object_type type, const char *path,
1888 unsigned flags)
1890 return index_bulk_checkin(oid->hash, fd, size, type, path, flags);
1893 int index_fd(struct object_id *oid, int fd, struct stat *st,
1894 enum object_type type, const char *path, unsigned flags)
1896 int ret;
1899 * Call xsize_t() only when needed to avoid potentially unnecessary
1900 * die() for large files.
1902 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(path))
1903 ret = index_stream_convert_blob(oid, fd, path, flags);
1904 else if (!S_ISREG(st->st_mode))
1905 ret = index_pipe(oid, fd, type, path, flags);
1906 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
1907 (path && would_convert_to_git(&the_index, path)))
1908 ret = index_core(oid, fd, xsize_t(st->st_size), type, path,
1909 flags);
1910 else
1911 ret = index_stream(oid, fd, xsize_t(st->st_size), type, path,
1912 flags);
1913 close(fd);
1914 return ret;
1917 int index_path(struct object_id *oid, const char *path, struct stat *st, unsigned flags)
1919 int fd;
1920 struct strbuf sb = STRBUF_INIT;
1921 int rc = 0;
1923 switch (st->st_mode & S_IFMT) {
1924 case S_IFREG:
1925 fd = open(path, O_RDONLY);
1926 if (fd < 0)
1927 return error_errno("open(\"%s\")", path);
1928 if (index_fd(oid, fd, st, OBJ_BLOB, path, flags) < 0)
1929 return error("%s: failed to insert into database",
1930 path);
1931 break;
1932 case S_IFLNK:
1933 if (strbuf_readlink(&sb, path, st->st_size))
1934 return error_errno("readlink(\"%s\")", path);
1935 if (!(flags & HASH_WRITE_OBJECT))
1936 hash_sha1_file(sb.buf, sb.len, blob_type, oid->hash);
1937 else if (write_sha1_file(sb.buf, sb.len, blob_type, oid->hash))
1938 rc = error("%s: failed to insert into database", path);
1939 strbuf_release(&sb);
1940 break;
1941 case S_IFDIR:
1942 return resolve_gitlink_ref(path, "HEAD", oid);
1943 default:
1944 return error("%s: unsupported file type", path);
1946 return rc;
1949 int read_pack_header(int fd, struct pack_header *header)
1951 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
1952 /* "eof before pack header was fully read" */
1953 return PH_ERROR_EOF;
1955 if (header->hdr_signature != htonl(PACK_SIGNATURE))
1956 /* "protocol error (pack signature mismatch detected)" */
1957 return PH_ERROR_PACK_SIGNATURE;
1958 if (!pack_version_ok(header->hdr_version))
1959 /* "protocol error (pack version unsupported)" */
1960 return PH_ERROR_PROTOCOL;
1961 return 0;
1964 void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
1966 enum object_type type = sha1_object_info(sha1, NULL);
1967 if (type < 0)
1968 die("%s is not a valid object", sha1_to_hex(sha1));
1969 if (type != expect)
1970 die("%s is not a valid '%s' object", sha1_to_hex(sha1),
1971 typename(expect));
1974 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
1975 struct strbuf *path,
1976 each_loose_object_fn obj_cb,
1977 each_loose_cruft_fn cruft_cb,
1978 each_loose_subdir_fn subdir_cb,
1979 void *data)
1981 size_t origlen, baselen;
1982 DIR *dir;
1983 struct dirent *de;
1984 int r = 0;
1985 struct object_id oid;
1987 if (subdir_nr > 0xff)
1988 BUG("invalid loose object subdirectory: %x", subdir_nr);
1990 origlen = path->len;
1991 strbuf_complete(path, '/');
1992 strbuf_addf(path, "%02x", subdir_nr);
1994 dir = opendir(path->buf);
1995 if (!dir) {
1996 if (errno != ENOENT)
1997 r = error_errno("unable to open %s", path->buf);
1998 strbuf_setlen(path, origlen);
1999 return r;
2002 oid.hash[0] = subdir_nr;
2003 strbuf_addch(path, '/');
2004 baselen = path->len;
2006 while ((de = readdir(dir))) {
2007 size_t namelen;
2008 if (is_dot_or_dotdot(de->d_name))
2009 continue;
2011 namelen = strlen(de->d_name);
2012 strbuf_setlen(path, baselen);
2013 strbuf_add(path, de->d_name, namelen);
2014 if (namelen == GIT_SHA1_HEXSZ - 2 &&
2015 !hex_to_bytes(oid.hash + 1, de->d_name,
2016 GIT_SHA1_RAWSZ - 1)) {
2017 if (obj_cb) {
2018 r = obj_cb(&oid, path->buf, data);
2019 if (r)
2020 break;
2022 continue;
2025 if (cruft_cb) {
2026 r = cruft_cb(de->d_name, path->buf, data);
2027 if (r)
2028 break;
2031 closedir(dir);
2033 strbuf_setlen(path, baselen - 1);
2034 if (!r && subdir_cb)
2035 r = subdir_cb(subdir_nr, path->buf, data);
2037 strbuf_setlen(path, origlen);
2039 return r;
2042 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2043 each_loose_object_fn obj_cb,
2044 each_loose_cruft_fn cruft_cb,
2045 each_loose_subdir_fn subdir_cb,
2046 void *data)
2048 int r = 0;
2049 int i;
2051 for (i = 0; i < 256; i++) {
2052 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2053 subdir_cb, data);
2054 if (r)
2055 break;
2058 return r;
2061 int for_each_loose_file_in_objdir(const char *path,
2062 each_loose_object_fn obj_cb,
2063 each_loose_cruft_fn cruft_cb,
2064 each_loose_subdir_fn subdir_cb,
2065 void *data)
2067 struct strbuf buf = STRBUF_INIT;
2068 int r;
2070 strbuf_addstr(&buf, path);
2071 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2072 subdir_cb, data);
2073 strbuf_release(&buf);
2075 return r;
2078 struct loose_alt_odb_data {
2079 each_loose_object_fn *cb;
2080 void *data;
2083 static int loose_from_alt_odb(struct alternate_object_database *alt,
2084 void *vdata)
2086 struct loose_alt_odb_data *data = vdata;
2087 struct strbuf buf = STRBUF_INIT;
2088 int r;
2090 strbuf_addstr(&buf, alt->path);
2091 r = for_each_loose_file_in_objdir_buf(&buf,
2092 data->cb, NULL, NULL,
2093 data->data);
2094 strbuf_release(&buf);
2095 return r;
2098 int for_each_loose_object(each_loose_object_fn cb, void *data, unsigned flags)
2100 struct loose_alt_odb_data alt;
2101 int r;
2103 r = for_each_loose_file_in_objdir(get_object_directory(),
2104 cb, NULL, NULL, data);
2105 if (r)
2106 return r;
2108 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2109 return 0;
2111 alt.cb = cb;
2112 alt.data = data;
2113 return foreach_alt_odb(loose_from_alt_odb, &alt);
2116 static int check_stream_sha1(git_zstream *stream,
2117 const char *hdr,
2118 unsigned long size,
2119 const char *path,
2120 const unsigned char *expected_sha1)
2122 git_SHA_CTX c;
2123 unsigned char real_sha1[GIT_MAX_RAWSZ];
2124 unsigned char buf[4096];
2125 unsigned long total_read;
2126 int status = Z_OK;
2128 git_SHA1_Init(&c);
2129 git_SHA1_Update(&c, hdr, stream->total_out);
2132 * We already read some bytes into hdr, but the ones up to the NUL
2133 * do not count against the object's content size.
2135 total_read = stream->total_out - strlen(hdr) - 1;
2138 * This size comparison must be "<=" to read the final zlib packets;
2139 * see the comment in unpack_sha1_rest for details.
2141 while (total_read <= size &&
2142 (status == Z_OK || status == Z_BUF_ERROR)) {
2143 stream->next_out = buf;
2144 stream->avail_out = sizeof(buf);
2145 if (size - total_read < stream->avail_out)
2146 stream->avail_out = size - total_read;
2147 status = git_inflate(stream, Z_FINISH);
2148 git_SHA1_Update(&c, buf, stream->next_out - buf);
2149 total_read += stream->next_out - buf;
2151 git_inflate_end(stream);
2153 if (status != Z_STREAM_END) {
2154 error("corrupt loose object '%s'", sha1_to_hex(expected_sha1));
2155 return -1;
2157 if (stream->avail_in) {
2158 error("garbage at end of loose object '%s'",
2159 sha1_to_hex(expected_sha1));
2160 return -1;
2163 git_SHA1_Final(real_sha1, &c);
2164 if (hashcmp(expected_sha1, real_sha1)) {
2165 error("sha1 mismatch for %s (expected %s)", path,
2166 sha1_to_hex(expected_sha1));
2167 return -1;
2170 return 0;
2173 int read_loose_object(const char *path,
2174 const unsigned char *expected_sha1,
2175 enum object_type *type,
2176 unsigned long *size,
2177 void **contents)
2179 int ret = -1;
2180 void *map = NULL;
2181 unsigned long mapsize;
2182 git_zstream stream;
2183 char hdr[32];
2185 *contents = NULL;
2187 map = map_sha1_file_1(path, NULL, &mapsize);
2188 if (!map) {
2189 error_errno("unable to mmap %s", path);
2190 goto out;
2193 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
2194 error("unable to unpack header of %s", path);
2195 goto out;
2198 *type = parse_sha1_header(hdr, size);
2199 if (*type < 0) {
2200 error("unable to parse header of %s", path);
2201 git_inflate_end(&stream);
2202 goto out;
2205 if (*type == OBJ_BLOB) {
2206 if (check_stream_sha1(&stream, hdr, *size, path, expected_sha1) < 0)
2207 goto out;
2208 } else {
2209 *contents = unpack_sha1_rest(&stream, hdr, *size, expected_sha1);
2210 if (!*contents) {
2211 error("unable to unpack contents of %s", path);
2212 git_inflate_end(&stream);
2213 goto out;
2215 if (check_sha1_signature(expected_sha1, *contents,
2216 *size, typename(*type))) {
2217 error("sha1 mismatch for %s (expected %s)", path,
2218 sha1_to_hex(expected_sha1));
2219 free(*contents);
2220 goto out;
2224 ret = 0; /* everything checks out */
2226 out:
2227 if (map)
2228 munmap(map, mapsize);
2229 return ret;