builtin/receive-pack: convert one use of EMPTY_TREE_SHA1_HEX
[git/debian.git] / sha1_file.c
blob11598b43eba73f7649ec8c9b3b4c5e0f2e98e270
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 /* The maximum size for an object header. */
36 #define MAX_HEADER_LEN 32
38 const unsigned char null_sha1[GIT_MAX_RAWSZ];
39 const struct object_id null_oid;
40 const struct object_id empty_tree_oid = {
41 EMPTY_TREE_SHA1_BIN_LITERAL
43 const struct object_id empty_blob_oid = {
44 EMPTY_BLOB_SHA1_BIN_LITERAL
47 static void git_hash_sha1_init(git_hash_ctx *ctx)
49 git_SHA1_Init(&ctx->sha1);
52 static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
54 git_SHA1_Update(&ctx->sha1, data, len);
57 static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
59 git_SHA1_Final(hash, &ctx->sha1);
62 static void git_hash_unknown_init(git_hash_ctx *ctx)
64 die("trying to init unknown hash");
67 static void git_hash_unknown_update(git_hash_ctx *ctx, const void *data, size_t len)
69 die("trying to update unknown hash");
72 static void git_hash_unknown_final(unsigned char *hash, git_hash_ctx *ctx)
74 die("trying to finalize unknown hash");
77 const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
79 NULL,
80 0x00000000,
83 git_hash_unknown_init,
84 git_hash_unknown_update,
85 git_hash_unknown_final,
86 NULL,
87 NULL,
90 "sha-1",
91 /* "sha1", big-endian */
92 0x73686131,
93 GIT_SHA1_RAWSZ,
94 GIT_SHA1_HEXSZ,
95 git_hash_sha1_init,
96 git_hash_sha1_update,
97 git_hash_sha1_final,
98 &empty_tree_oid,
99 &empty_blob_oid,
103 const char *empty_tree_oid_hex(void)
105 static char buf[GIT_MAX_HEXSZ + 1];
106 return oid_to_hex_r(buf, the_hash_algo->empty_tree);
109 const char *empty_blob_oid_hex(void)
111 static char buf[GIT_MAX_HEXSZ + 1];
112 return oid_to_hex_r(buf, the_hash_algo->empty_blob);
116 * This is meant to hold a *small* number of objects that you would
117 * want read_sha1_file() to be able to return, but yet you do not want
118 * to write them into the object store (e.g. a browse-only
119 * application).
121 static struct cached_object {
122 unsigned char sha1[20];
123 enum object_type type;
124 void *buf;
125 unsigned long size;
126 } *cached_objects;
127 static int cached_object_nr, cached_object_alloc;
129 static struct cached_object empty_tree = {
130 EMPTY_TREE_SHA1_BIN_LITERAL,
131 OBJ_TREE,
136 static struct cached_object *find_cached_object(const unsigned char *sha1)
138 int i;
139 struct cached_object *co = cached_objects;
141 for (i = 0; i < cached_object_nr; i++, co++) {
142 if (!hashcmp(co->sha1, sha1))
143 return co;
145 if (!hashcmp(sha1, empty_tree.sha1))
146 return &empty_tree;
147 return NULL;
151 static int get_conv_flags(unsigned flags)
153 if (flags & HASH_RENORMALIZE)
154 return CONV_EOL_RENORMALIZE;
155 else if (flags & HASH_WRITE_OBJECT)
156 return global_conv_flags_eol;
157 else
158 return 0;
162 int mkdir_in_gitdir(const char *path)
164 if (mkdir(path, 0777)) {
165 int saved_errno = errno;
166 struct stat st;
167 struct strbuf sb = STRBUF_INIT;
169 if (errno != EEXIST)
170 return -1;
172 * Are we looking at a path in a symlinked worktree
173 * whose original repository does not yet have it?
174 * e.g. .git/rr-cache pointing at its original
175 * repository in which the user hasn't performed any
176 * conflict resolution yet?
178 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
179 strbuf_readlink(&sb, path, st.st_size) ||
180 !is_absolute_path(sb.buf) ||
181 mkdir(sb.buf, 0777)) {
182 strbuf_release(&sb);
183 errno = saved_errno;
184 return -1;
186 strbuf_release(&sb);
188 return adjust_shared_perm(path);
191 enum scld_error safe_create_leading_directories(char *path)
193 char *next_component = path + offset_1st_component(path);
194 enum scld_error ret = SCLD_OK;
196 while (ret == SCLD_OK && next_component) {
197 struct stat st;
198 char *slash = next_component, slash_character;
200 while (*slash && !is_dir_sep(*slash))
201 slash++;
203 if (!*slash)
204 break;
206 next_component = slash + 1;
207 while (is_dir_sep(*next_component))
208 next_component++;
209 if (!*next_component)
210 break;
212 slash_character = *slash;
213 *slash = '\0';
214 if (!stat(path, &st)) {
215 /* path exists */
216 if (!S_ISDIR(st.st_mode)) {
217 errno = ENOTDIR;
218 ret = SCLD_EXISTS;
220 } else if (mkdir(path, 0777)) {
221 if (errno == EEXIST &&
222 !stat(path, &st) && S_ISDIR(st.st_mode))
223 ; /* somebody created it since we checked */
224 else if (errno == ENOENT)
226 * Either mkdir() failed because
227 * somebody just pruned the containing
228 * directory, or stat() failed because
229 * the file that was in our way was
230 * just removed. Either way, inform
231 * the caller that it might be worth
232 * trying again:
234 ret = SCLD_VANISHED;
235 else
236 ret = SCLD_FAILED;
237 } else if (adjust_shared_perm(path)) {
238 ret = SCLD_PERMS;
240 *slash = slash_character;
242 return ret;
245 enum scld_error safe_create_leading_directories_const(const char *path)
247 int save_errno;
248 /* path points to cache entries, so xstrdup before messing with it */
249 char *buf = xstrdup(path);
250 enum scld_error result = safe_create_leading_directories(buf);
252 save_errno = errno;
253 free(buf);
254 errno = save_errno;
255 return result;
258 int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
261 * The number of times we will try to remove empty directories
262 * in the way of path. This is only 1 because if another
263 * process is racily creating directories that conflict with
264 * us, we don't want to fight against them.
266 int remove_directories_remaining = 1;
269 * The number of times that we will try to create the
270 * directories containing path. We are willing to attempt this
271 * more than once, because another process could be trying to
272 * clean up empty directories at the same time as we are
273 * trying to create them.
275 int create_directories_remaining = 3;
277 /* A scratch copy of path, filled lazily if we need it: */
278 struct strbuf path_copy = STRBUF_INIT;
280 int ret, save_errno;
282 /* Sanity check: */
283 assert(*path);
285 retry_fn:
286 ret = fn(path, cb);
287 save_errno = errno;
288 if (!ret)
289 goto out;
291 if (errno == EISDIR && remove_directories_remaining-- > 0) {
293 * A directory is in the way. Maybe it is empty; try
294 * to remove it:
296 if (!path_copy.len)
297 strbuf_addstr(&path_copy, path);
299 if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
300 goto retry_fn;
301 } else if (errno == ENOENT && create_directories_remaining-- > 0) {
303 * Maybe the containing directory didn't exist, or
304 * maybe it was just deleted by a process that is
305 * racing with us to clean up empty directories. Try
306 * to create it:
308 enum scld_error scld_result;
310 if (!path_copy.len)
311 strbuf_addstr(&path_copy, path);
313 do {
314 scld_result = safe_create_leading_directories(path_copy.buf);
315 if (scld_result == SCLD_OK)
316 goto retry_fn;
317 } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
320 out:
321 strbuf_release(&path_copy);
322 errno = save_errno;
323 return ret;
326 static void fill_sha1_path(struct strbuf *buf, const unsigned char *sha1)
328 int i;
329 for (i = 0; i < 20; i++) {
330 static char hex[] = "0123456789abcdef";
331 unsigned int val = sha1[i];
332 strbuf_addch(buf, hex[val >> 4]);
333 strbuf_addch(buf, hex[val & 0xf]);
334 if (!i)
335 strbuf_addch(buf, '/');
339 void sha1_file_name(struct repository *r, struct strbuf *buf, const unsigned char *sha1)
341 strbuf_addstr(buf, r->objects->objectdir);
342 strbuf_addch(buf, '/');
343 fill_sha1_path(buf, sha1);
346 struct strbuf *alt_scratch_buf(struct alternate_object_database *alt)
348 strbuf_setlen(&alt->scratch, alt->base_len);
349 return &alt->scratch;
352 static const char *alt_sha1_path(struct alternate_object_database *alt,
353 const unsigned char *sha1)
355 struct strbuf *buf = alt_scratch_buf(alt);
356 fill_sha1_path(buf, sha1);
357 return buf->buf;
361 * Return non-zero iff the path is usable as an alternate object database.
363 static int alt_odb_usable(struct raw_object_store *o,
364 struct strbuf *path,
365 const char *normalized_objdir)
367 struct alternate_object_database *alt;
369 /* Detect cases where alternate disappeared */
370 if (!is_directory(path->buf)) {
371 error("object directory %s does not exist; "
372 "check .git/objects/info/alternates.",
373 path->buf);
374 return 0;
378 * Prevent the common mistake of listing the same
379 * thing twice, or object directory itself.
381 for (alt = o->alt_odb_list; alt; alt = alt->next) {
382 if (!fspathcmp(path->buf, alt->path))
383 return 0;
385 if (!fspathcmp(path->buf, normalized_objdir))
386 return 0;
388 return 1;
392 * Prepare alternate object database registry.
394 * The variable alt_odb_list points at the list of struct
395 * alternate_object_database. The elements on this list come from
396 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
397 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
398 * whose contents is similar to that environment variable but can be
399 * LF separated. Its base points at a statically allocated buffer that
400 * contains "/the/directory/corresponding/to/.git/objects/...", while
401 * its name points just after the slash at the end of ".git/objects/"
402 * in the example above, and has enough space to hold 40-byte hex
403 * SHA1, an extra slash for the first level indirection, and the
404 * terminating NUL.
406 static void read_info_alternates(struct repository *r,
407 const char *relative_base,
408 int depth);
409 static int link_alt_odb_entry(struct repository *r, const char *entry,
410 const char *relative_base, int depth, const char *normalized_objdir)
412 struct alternate_object_database *ent;
413 struct strbuf pathbuf = STRBUF_INIT;
415 if (!is_absolute_path(entry) && relative_base) {
416 strbuf_realpath(&pathbuf, relative_base, 1);
417 strbuf_addch(&pathbuf, '/');
419 strbuf_addstr(&pathbuf, entry);
421 if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
422 error("unable to normalize alternate object path: %s",
423 pathbuf.buf);
424 strbuf_release(&pathbuf);
425 return -1;
429 * The trailing slash after the directory name is given by
430 * this function at the end. Remove duplicates.
432 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
433 strbuf_setlen(&pathbuf, pathbuf.len - 1);
435 if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir)) {
436 strbuf_release(&pathbuf);
437 return -1;
440 ent = alloc_alt_odb(pathbuf.buf);
442 /* add the alternate entry */
443 *r->objects->alt_odb_tail = ent;
444 r->objects->alt_odb_tail = &(ent->next);
445 ent->next = NULL;
447 /* recursively add alternates */
448 read_info_alternates(r, pathbuf.buf, depth + 1);
450 strbuf_release(&pathbuf);
451 return 0;
454 static const char *parse_alt_odb_entry(const char *string,
455 int sep,
456 struct strbuf *out)
458 const char *end;
460 strbuf_reset(out);
462 if (*string == '#') {
463 /* comment; consume up to next separator */
464 end = strchrnul(string, sep);
465 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
467 * quoted path; unquote_c_style has copied the
468 * data for us and set "end". Broken quoting (e.g.,
469 * an entry that doesn't end with a quote) falls
470 * back to the unquoted case below.
472 } else {
473 /* normal, unquoted path */
474 end = strchrnul(string, sep);
475 strbuf_add(out, string, end - string);
478 if (*end)
479 end++;
480 return end;
483 static void link_alt_odb_entries(struct repository *r, const char *alt,
484 int sep, const char *relative_base, int depth)
486 struct strbuf objdirbuf = STRBUF_INIT;
487 struct strbuf entry = STRBUF_INIT;
489 if (!alt || !*alt)
490 return;
492 if (depth > 5) {
493 error("%s: ignoring alternate object stores, nesting too deep.",
494 relative_base);
495 return;
498 strbuf_add_absolute_path(&objdirbuf, r->objects->objectdir);
499 if (strbuf_normalize_path(&objdirbuf) < 0)
500 die("unable to normalize object directory: %s",
501 objdirbuf.buf);
503 while (*alt) {
504 alt = parse_alt_odb_entry(alt, sep, &entry);
505 if (!entry.len)
506 continue;
507 link_alt_odb_entry(r, entry.buf,
508 relative_base, depth, objdirbuf.buf);
510 strbuf_release(&entry);
511 strbuf_release(&objdirbuf);
514 static void read_info_alternates(struct repository *r,
515 const char *relative_base,
516 int depth)
518 char *path;
519 struct strbuf buf = STRBUF_INIT;
521 path = xstrfmt("%s/info/alternates", relative_base);
522 if (strbuf_read_file(&buf, path, 1024) < 0) {
523 warn_on_fopen_errors(path);
524 free(path);
525 return;
528 link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
529 strbuf_release(&buf);
530 free(path);
533 struct alternate_object_database *alloc_alt_odb(const char *dir)
535 struct alternate_object_database *ent;
537 FLEX_ALLOC_STR(ent, path, dir);
538 strbuf_init(&ent->scratch, 0);
539 strbuf_addf(&ent->scratch, "%s/", dir);
540 ent->base_len = ent->scratch.len;
542 return ent;
545 void add_to_alternates_file(const char *reference)
547 struct lock_file lock = LOCK_INIT;
548 char *alts = git_pathdup("objects/info/alternates");
549 FILE *in, *out;
550 int found = 0;
552 hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
553 out = fdopen_lock_file(&lock, "w");
554 if (!out)
555 die_errno("unable to fdopen alternates lockfile");
557 in = fopen(alts, "r");
558 if (in) {
559 struct strbuf line = STRBUF_INIT;
561 while (strbuf_getline(&line, in) != EOF) {
562 if (!strcmp(reference, line.buf)) {
563 found = 1;
564 break;
566 fprintf_or_die(out, "%s\n", line.buf);
569 strbuf_release(&line);
570 fclose(in);
572 else if (errno != ENOENT)
573 die_errno("unable to read alternates file");
575 if (found) {
576 rollback_lock_file(&lock);
577 } else {
578 fprintf_or_die(out, "%s\n", reference);
579 if (commit_lock_file(&lock))
580 die_errno("unable to move new alternates file into place");
581 if (the_repository->objects->alt_odb_tail)
582 link_alt_odb_entries(the_repository, reference,
583 '\n', NULL, 0);
585 free(alts);
588 void add_to_alternates_memory(const char *reference)
591 * Make sure alternates are initialized, or else our entry may be
592 * overwritten when they are.
594 prepare_alt_odb(the_repository);
596 link_alt_odb_entries(the_repository, reference,
597 '\n', NULL, 0);
601 * Compute the exact path an alternate is at and returns it. In case of
602 * error NULL is returned and the human readable error is added to `err`
603 * `path` may be relative and should point to $GITDIR.
604 * `err` must not be null.
606 char *compute_alternate_path(const char *path, struct strbuf *err)
608 char *ref_git = NULL;
609 const char *repo, *ref_git_s;
610 int seen_error = 0;
612 ref_git_s = real_path_if_valid(path);
613 if (!ref_git_s) {
614 seen_error = 1;
615 strbuf_addf(err, _("path '%s' does not exist"), path);
616 goto out;
617 } else
619 * Beware: read_gitfile(), real_path() and mkpath()
620 * return static buffer
622 ref_git = xstrdup(ref_git_s);
624 repo = read_gitfile(ref_git);
625 if (!repo)
626 repo = read_gitfile(mkpath("%s/.git", ref_git));
627 if (repo) {
628 free(ref_git);
629 ref_git = xstrdup(repo);
632 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
633 char *ref_git_git = mkpathdup("%s/.git", ref_git);
634 free(ref_git);
635 ref_git = ref_git_git;
636 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
637 struct strbuf sb = STRBUF_INIT;
638 seen_error = 1;
639 if (get_common_dir(&sb, ref_git)) {
640 strbuf_addf(err,
641 _("reference repository '%s' as a linked "
642 "checkout is not supported yet."),
643 path);
644 goto out;
647 strbuf_addf(err, _("reference repository '%s' is not a "
648 "local repository."), path);
649 goto out;
652 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
653 strbuf_addf(err, _("reference repository '%s' is shallow"),
654 path);
655 seen_error = 1;
656 goto out;
659 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
660 strbuf_addf(err,
661 _("reference repository '%s' is grafted"),
662 path);
663 seen_error = 1;
664 goto out;
667 out:
668 if (seen_error) {
669 FREE_AND_NULL(ref_git);
672 return ref_git;
675 int foreach_alt_odb(alt_odb_fn fn, void *cb)
677 struct alternate_object_database *ent;
678 int r = 0;
680 prepare_alt_odb(the_repository);
681 for (ent = the_repository->objects->alt_odb_list; ent; ent = ent->next) {
682 r = fn(ent, cb);
683 if (r)
684 break;
686 return r;
689 void prepare_alt_odb(struct repository *r)
691 if (r->objects->alt_odb_tail)
692 return;
694 r->objects->alt_odb_tail = &r->objects->alt_odb_list;
695 link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
697 read_info_alternates(r, r->objects->objectdir, 0);
700 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
701 static int freshen_file(const char *fn)
703 struct utimbuf t;
704 t.actime = t.modtime = time(NULL);
705 return !utime(fn, &t);
709 * All of the check_and_freshen functions return 1 if the file exists and was
710 * freshened (if freshening was requested), 0 otherwise. If they return
711 * 0, you should not assume that it is safe to skip a write of the object (it
712 * either does not exist on disk, or has a stale mtime and may be subject to
713 * pruning).
715 int check_and_freshen_file(const char *fn, int freshen)
717 if (access(fn, F_OK))
718 return 0;
719 if (freshen && !freshen_file(fn))
720 return 0;
721 return 1;
724 static int check_and_freshen_local(const struct object_id *oid, int freshen)
726 static struct strbuf buf = STRBUF_INIT;
728 strbuf_reset(&buf);
729 sha1_file_name(the_repository, &buf, oid->hash);
731 return check_and_freshen_file(buf.buf, freshen);
734 static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
736 struct alternate_object_database *alt;
737 prepare_alt_odb(the_repository);
738 for (alt = the_repository->objects->alt_odb_list; alt; alt = alt->next) {
739 const char *path = alt_sha1_path(alt, oid->hash);
740 if (check_and_freshen_file(path, freshen))
741 return 1;
743 return 0;
746 static int check_and_freshen(const struct object_id *oid, int freshen)
748 return check_and_freshen_local(oid, freshen) ||
749 check_and_freshen_nonlocal(oid, freshen);
752 int has_loose_object_nonlocal(const struct object_id *oid)
754 return check_and_freshen_nonlocal(oid, 0);
757 static int has_loose_object(const struct object_id *oid)
759 return check_and_freshen(oid, 0);
762 static void mmap_limit_check(size_t length)
764 static size_t limit = 0;
765 if (!limit) {
766 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
767 if (!limit)
768 limit = SIZE_MAX;
770 if (length > limit)
771 die("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX,
772 (uintmax_t)length, (uintmax_t)limit);
775 void *xmmap_gently(void *start, size_t length,
776 int prot, int flags, int fd, off_t offset)
778 void *ret;
780 mmap_limit_check(length);
781 ret = mmap(start, length, prot, flags, fd, offset);
782 if (ret == MAP_FAILED) {
783 if (!length)
784 return NULL;
785 release_pack_memory(length);
786 ret = mmap(start, length, prot, flags, fd, offset);
788 return ret;
791 void *xmmap(void *start, size_t length,
792 int prot, int flags, int fd, off_t offset)
794 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
795 if (ret == MAP_FAILED)
796 die_errno("mmap failed");
797 return ret;
801 * With an in-core object data in "map", rehash it to make sure the
802 * object name actually matches "sha1" to detect object corruption.
803 * With "map" == NULL, try reading the object named with "sha1" using
804 * the streaming interface and rehash it to do the same.
806 int check_object_signature(const struct object_id *oid, void *map,
807 unsigned long size, const char *type)
809 struct object_id real_oid;
810 enum object_type obj_type;
811 struct git_istream *st;
812 git_hash_ctx c;
813 char hdr[MAX_HEADER_LEN];
814 int hdrlen;
816 if (map) {
817 hash_object_file(map, size, type, &real_oid);
818 return oidcmp(oid, &real_oid) ? -1 : 0;
821 st = open_istream(oid, &obj_type, &size, NULL);
822 if (!st)
823 return -1;
825 /* Generate the header */
826 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", type_name(obj_type), size) + 1;
828 /* Sha1.. */
829 the_hash_algo->init_fn(&c);
830 the_hash_algo->update_fn(&c, hdr, hdrlen);
831 for (;;) {
832 char buf[1024 * 16];
833 ssize_t readlen = read_istream(st, buf, sizeof(buf));
835 if (readlen < 0) {
836 close_istream(st);
837 return -1;
839 if (!readlen)
840 break;
841 the_hash_algo->update_fn(&c, buf, readlen);
843 the_hash_algo->final_fn(real_oid.hash, &c);
844 close_istream(st);
845 return oidcmp(oid, &real_oid) ? -1 : 0;
848 int git_open_cloexec(const char *name, int flags)
850 int fd;
851 static int o_cloexec = O_CLOEXEC;
853 fd = open(name, flags | o_cloexec);
854 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
855 /* Try again w/o O_CLOEXEC: the kernel might not support it */
856 o_cloexec &= ~O_CLOEXEC;
857 fd = open(name, flags | o_cloexec);
860 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
862 static int fd_cloexec = FD_CLOEXEC;
864 if (!o_cloexec && 0 <= fd && fd_cloexec) {
865 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
866 int flags = fcntl(fd, F_GETFD);
867 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
868 fd_cloexec = 0;
871 #endif
872 return fd;
876 * Find "sha1" as a loose object in the local repository or in an alternate.
877 * Returns 0 on success, negative on failure.
879 * The "path" out-parameter will give the path of the object we found (if any).
880 * Note that it may point to static storage and is only valid until another
881 * call to sha1_file_name(), etc.
883 static int stat_sha1_file(struct repository *r, const unsigned char *sha1,
884 struct stat *st, const char **path)
886 struct alternate_object_database *alt;
887 static struct strbuf buf = STRBUF_INIT;
889 strbuf_reset(&buf);
890 sha1_file_name(r, &buf, sha1);
891 *path = buf.buf;
893 if (!lstat(*path, st))
894 return 0;
896 prepare_alt_odb(r);
897 errno = ENOENT;
898 for (alt = r->objects->alt_odb_list; alt; alt = alt->next) {
899 *path = alt_sha1_path(alt, sha1);
900 if (!lstat(*path, st))
901 return 0;
904 return -1;
908 * Like stat_sha1_file(), but actually open the object and return the
909 * descriptor. See the caveats on the "path" parameter above.
911 static int open_sha1_file(struct repository *r,
912 const unsigned char *sha1, const char **path)
914 int fd;
915 struct alternate_object_database *alt;
916 int most_interesting_errno;
917 static struct strbuf buf = STRBUF_INIT;
919 strbuf_reset(&buf);
920 sha1_file_name(r, &buf, sha1);
921 *path = buf.buf;
923 fd = git_open(*path);
924 if (fd >= 0)
925 return fd;
926 most_interesting_errno = errno;
928 prepare_alt_odb(r);
929 for (alt = r->objects->alt_odb_list; alt; alt = alt->next) {
930 *path = alt_sha1_path(alt, sha1);
931 fd = git_open(*path);
932 if (fd >= 0)
933 return fd;
934 if (most_interesting_errno == ENOENT)
935 most_interesting_errno = errno;
937 errno = most_interesting_errno;
938 return -1;
942 * Map the loose object at "path" if it is not NULL, or the path found by
943 * searching for a loose object named "sha1".
945 static void *map_sha1_file_1(struct repository *r, const char *path,
946 const unsigned char *sha1, unsigned long *size)
948 void *map;
949 int fd;
951 if (path)
952 fd = git_open(path);
953 else
954 fd = open_sha1_file(r, sha1, &path);
955 map = NULL;
956 if (fd >= 0) {
957 struct stat st;
959 if (!fstat(fd, &st)) {
960 *size = xsize_t(st.st_size);
961 if (!*size) {
962 /* mmap() is forbidden on empty files */
963 error("object file %s is empty", path);
964 return NULL;
966 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
968 close(fd);
970 return map;
973 void *map_sha1_file(struct repository *r,
974 const unsigned char *sha1, unsigned long *size)
976 return map_sha1_file_1(r, NULL, sha1, size);
979 static int unpack_sha1_short_header(git_zstream *stream,
980 unsigned char *map, unsigned long mapsize,
981 void *buffer, unsigned long bufsiz)
983 /* Get the data stream */
984 memset(stream, 0, sizeof(*stream));
985 stream->next_in = map;
986 stream->avail_in = mapsize;
987 stream->next_out = buffer;
988 stream->avail_out = bufsiz;
990 git_inflate_init(stream);
991 return git_inflate(stream, 0);
994 int unpack_sha1_header(git_zstream *stream,
995 unsigned char *map, unsigned long mapsize,
996 void *buffer, unsigned long bufsiz)
998 int status = unpack_sha1_short_header(stream, map, mapsize,
999 buffer, bufsiz);
1001 if (status < Z_OK)
1002 return status;
1004 /* Make sure we have the terminating NUL */
1005 if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1006 return -1;
1007 return 0;
1010 static int unpack_sha1_header_to_strbuf(git_zstream *stream, unsigned char *map,
1011 unsigned long mapsize, void *buffer,
1012 unsigned long bufsiz, struct strbuf *header)
1014 int status;
1016 status = unpack_sha1_short_header(stream, map, mapsize, buffer, bufsiz);
1017 if (status < Z_OK)
1018 return -1;
1021 * Check if entire header is unpacked in the first iteration.
1023 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1024 return 0;
1027 * buffer[0..bufsiz] was not large enough. Copy the partial
1028 * result out to header, and then append the result of further
1029 * reading the stream.
1031 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1032 stream->next_out = buffer;
1033 stream->avail_out = bufsiz;
1035 do {
1036 status = git_inflate(stream, 0);
1037 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1038 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1039 return 0;
1040 stream->next_out = buffer;
1041 stream->avail_out = bufsiz;
1042 } while (status != Z_STREAM_END);
1043 return -1;
1046 static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1048 int bytes = strlen(buffer) + 1;
1049 unsigned char *buf = xmallocz(size);
1050 unsigned long n;
1051 int status = Z_OK;
1053 n = stream->total_out - bytes;
1054 if (n > size)
1055 n = size;
1056 memcpy(buf, (char *) buffer + bytes, n);
1057 bytes = n;
1058 if (bytes <= size) {
1060 * The above condition must be (bytes <= size), not
1061 * (bytes < size). In other words, even though we
1062 * expect no more output and set avail_out to zero,
1063 * the input zlib stream may have bytes that express
1064 * "this concludes the stream", and we *do* want to
1065 * eat that input.
1067 * Otherwise we would not be able to test that we
1068 * consumed all the input to reach the expected size;
1069 * we also want to check that zlib tells us that all
1070 * went well with status == Z_STREAM_END at the end.
1072 stream->next_out = buf + bytes;
1073 stream->avail_out = size - bytes;
1074 while (status == Z_OK)
1075 status = git_inflate(stream, Z_FINISH);
1077 if (status == Z_STREAM_END && !stream->avail_in) {
1078 git_inflate_end(stream);
1079 return buf;
1082 if (status < 0)
1083 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1084 else if (stream->avail_in)
1085 error("garbage at end of loose object '%s'",
1086 sha1_to_hex(sha1));
1087 free(buf);
1088 return NULL;
1092 * We used to just use "sscanf()", but that's actually way
1093 * too permissive for what we want to check. So do an anal
1094 * object header parse by hand.
1096 static int parse_sha1_header_extended(const char *hdr, struct object_info *oi,
1097 unsigned int flags)
1099 const char *type_buf = hdr;
1100 unsigned long size;
1101 int type, type_len = 0;
1104 * The type can be of any size but is followed by
1105 * a space.
1107 for (;;) {
1108 char c = *hdr++;
1109 if (!c)
1110 return -1;
1111 if (c == ' ')
1112 break;
1113 type_len++;
1116 type = type_from_string_gently(type_buf, type_len, 1);
1117 if (oi->type_name)
1118 strbuf_add(oi->type_name, type_buf, type_len);
1120 * Set type to 0 if its an unknown object and
1121 * we're obtaining the type using '--allow-unknown-type'
1122 * option.
1124 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1125 type = 0;
1126 else if (type < 0)
1127 die("invalid object type");
1128 if (oi->typep)
1129 *oi->typep = type;
1132 * The length must follow immediately, and be in canonical
1133 * decimal format (ie "010" is not valid).
1135 size = *hdr++ - '0';
1136 if (size > 9)
1137 return -1;
1138 if (size) {
1139 for (;;) {
1140 unsigned long c = *hdr - '0';
1141 if (c > 9)
1142 break;
1143 hdr++;
1144 size = size * 10 + c;
1148 if (oi->sizep)
1149 *oi->sizep = size;
1152 * The length must be followed by a zero byte
1154 return *hdr ? -1 : type;
1157 int parse_sha1_header(const char *hdr, unsigned long *sizep)
1159 struct object_info oi = OBJECT_INFO_INIT;
1161 oi.sizep = sizep;
1162 return parse_sha1_header_extended(hdr, &oi, 0);
1165 static int sha1_loose_object_info(struct repository *r,
1166 const unsigned char *sha1,
1167 struct object_info *oi, int flags)
1169 int status = 0;
1170 unsigned long mapsize;
1171 void *map;
1172 git_zstream stream;
1173 char hdr[MAX_HEADER_LEN];
1174 struct strbuf hdrbuf = STRBUF_INIT;
1175 unsigned long size_scratch;
1177 if (oi->delta_base_sha1)
1178 hashclr(oi->delta_base_sha1);
1181 * If we don't care about type or size, then we don't
1182 * need to look inside the object at all. Note that we
1183 * do not optimize out the stat call, even if the
1184 * caller doesn't care about the disk-size, since our
1185 * return value implicitly indicates whether the
1186 * object even exists.
1188 if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
1189 const char *path;
1190 struct stat st;
1191 if (stat_sha1_file(r, sha1, &st, &path) < 0)
1192 return -1;
1193 if (oi->disk_sizep)
1194 *oi->disk_sizep = st.st_size;
1195 return 0;
1198 map = map_sha1_file(r, sha1, &mapsize);
1199 if (!map)
1200 return -1;
1202 if (!oi->sizep)
1203 oi->sizep = &size_scratch;
1205 if (oi->disk_sizep)
1206 *oi->disk_sizep = mapsize;
1207 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
1208 if (unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
1209 status = error("unable to unpack %s header with --allow-unknown-type",
1210 sha1_to_hex(sha1));
1211 } else if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1212 status = error("unable to unpack %s header",
1213 sha1_to_hex(sha1));
1214 if (status < 0)
1215 ; /* Do nothing */
1216 else if (hdrbuf.len) {
1217 if ((status = parse_sha1_header_extended(hdrbuf.buf, oi, flags)) < 0)
1218 status = error("unable to parse %s header with --allow-unknown-type",
1219 sha1_to_hex(sha1));
1220 } else if ((status = parse_sha1_header_extended(hdr, oi, flags)) < 0)
1221 status = error("unable to parse %s header", sha1_to_hex(sha1));
1223 if (status >= 0 && oi->contentp) {
1224 *oi->contentp = unpack_sha1_rest(&stream, hdr,
1225 *oi->sizep, sha1);
1226 if (!*oi->contentp) {
1227 git_inflate_end(&stream);
1228 status = -1;
1230 } else
1231 git_inflate_end(&stream);
1233 munmap(map, mapsize);
1234 if (status && oi->typep)
1235 *oi->typep = status;
1236 if (oi->sizep == &size_scratch)
1237 oi->sizep = NULL;
1238 strbuf_release(&hdrbuf);
1239 oi->whence = OI_LOOSE;
1240 return (status < 0) ? status : 0;
1243 int fetch_if_missing = 1;
1245 int oid_object_info_extended(const struct object_id *oid, struct object_info *oi, unsigned flags)
1247 static struct object_info blank_oi = OBJECT_INFO_INIT;
1248 struct pack_entry e;
1249 int rtype;
1250 const struct object_id *real = oid;
1251 int already_retried = 0;
1253 if (flags & OBJECT_INFO_LOOKUP_REPLACE)
1254 real = lookup_replace_object(oid);
1256 if (is_null_oid(real))
1257 return -1;
1259 if (!oi)
1260 oi = &blank_oi;
1262 if (!(flags & OBJECT_INFO_SKIP_CACHED)) {
1263 struct cached_object *co = find_cached_object(real->hash);
1264 if (co) {
1265 if (oi->typep)
1266 *(oi->typep) = co->type;
1267 if (oi->sizep)
1268 *(oi->sizep) = co->size;
1269 if (oi->disk_sizep)
1270 *(oi->disk_sizep) = 0;
1271 if (oi->delta_base_sha1)
1272 hashclr(oi->delta_base_sha1);
1273 if (oi->type_name)
1274 strbuf_addstr(oi->type_name, type_name(co->type));
1275 if (oi->contentp)
1276 *oi->contentp = xmemdupz(co->buf, co->size);
1277 oi->whence = OI_CACHED;
1278 return 0;
1282 while (1) {
1283 if (find_pack_entry(the_repository, real, &e))
1284 break;
1286 if (flags & OBJECT_INFO_IGNORE_LOOSE)
1287 return -1;
1289 /* Most likely it's a loose object. */
1290 if (!sha1_loose_object_info(the_repository, real->hash, oi, flags))
1291 return 0;
1293 /* Not a loose object; someone else may have just packed it. */
1294 if (!(flags & OBJECT_INFO_QUICK)) {
1295 reprepare_packed_git(the_repository);
1296 if (find_pack_entry(the_repository, real, &e))
1297 break;
1300 /* Check if it is a missing object */
1301 if (fetch_if_missing && repository_format_partial_clone &&
1302 !already_retried) {
1304 * TODO Investigate haveing fetch_object() return
1305 * TODO error/success and stopping the music here.
1307 fetch_object(repository_format_partial_clone, real->hash);
1308 already_retried = 1;
1309 continue;
1312 return -1;
1315 if (oi == &blank_oi)
1317 * We know that the caller doesn't actually need the
1318 * information below, so return early.
1320 return 0;
1321 rtype = packed_object_info(e.p, e.offset, oi);
1322 if (rtype < 0) {
1323 mark_bad_packed_object(e.p, real->hash);
1324 return oid_object_info_extended(real, oi, 0);
1325 } else if (oi->whence == OI_PACKED) {
1326 oi->u.packed.offset = e.offset;
1327 oi->u.packed.pack = e.p;
1328 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1329 rtype == OBJ_OFS_DELTA);
1332 return 0;
1335 /* returns enum object_type or negative */
1336 int oid_object_info(const struct object_id *oid, unsigned long *sizep)
1338 enum object_type type;
1339 struct object_info oi = OBJECT_INFO_INIT;
1341 oi.typep = &type;
1342 oi.sizep = sizep;
1343 if (oid_object_info_extended(oid, &oi,
1344 OBJECT_INFO_LOOKUP_REPLACE) < 0)
1345 return -1;
1346 return type;
1349 static void *read_object(const unsigned char *sha1, enum object_type *type,
1350 unsigned long *size)
1352 struct object_id oid;
1353 struct object_info oi = OBJECT_INFO_INIT;
1354 void *content;
1355 oi.typep = type;
1356 oi.sizep = size;
1357 oi.contentp = &content;
1359 hashcpy(oid.hash, sha1);
1361 if (oid_object_info_extended(&oid, &oi, 0) < 0)
1362 return NULL;
1363 return content;
1366 int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1367 struct object_id *oid)
1369 struct cached_object *co;
1371 hash_object_file(buf, len, type_name(type), oid);
1372 if (has_sha1_file(oid->hash) || find_cached_object(oid->hash))
1373 return 0;
1374 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1375 co = &cached_objects[cached_object_nr++];
1376 co->size = len;
1377 co->type = type;
1378 co->buf = xmalloc(len);
1379 memcpy(co->buf, buf, len);
1380 hashcpy(co->sha1, oid->hash);
1381 return 0;
1385 * This function dies on corrupt objects; the callers who want to
1386 * deal with them should arrange to call read_object() and give error
1387 * messages themselves.
1389 void *read_object_file_extended(const struct object_id *oid,
1390 enum object_type *type,
1391 unsigned long *size,
1392 int lookup_replace)
1394 void *data;
1395 const struct packed_git *p;
1396 const char *path;
1397 struct stat st;
1398 const struct object_id *repl = lookup_replace ? lookup_replace_object(oid)
1399 : oid;
1401 errno = 0;
1402 data = read_object(repl->hash, type, size);
1403 if (data)
1404 return data;
1406 if (errno && errno != ENOENT)
1407 die_errno("failed to read object %s", oid_to_hex(oid));
1409 /* die if we replaced an object with one that does not exist */
1410 if (repl != oid)
1411 die("replacement %s not found for %s",
1412 oid_to_hex(repl), oid_to_hex(oid));
1414 if (!stat_sha1_file(the_repository, repl->hash, &st, &path))
1415 die("loose object %s (stored in %s) is corrupt",
1416 oid_to_hex(repl), path);
1418 if ((p = has_packed_and_bad(repl->hash)) != NULL)
1419 die("packed object %s (stored in %s) is corrupt",
1420 oid_to_hex(repl), p->pack_name);
1422 return NULL;
1425 void *read_object_with_reference(const struct object_id *oid,
1426 const char *required_type_name,
1427 unsigned long *size,
1428 struct object_id *actual_oid_return)
1430 enum object_type type, required_type;
1431 void *buffer;
1432 unsigned long isize;
1433 struct object_id actual_oid;
1435 required_type = type_from_string(required_type_name);
1436 oidcpy(&actual_oid, oid);
1437 while (1) {
1438 int ref_length = -1;
1439 const char *ref_type = NULL;
1441 buffer = read_object_file(&actual_oid, &type, &isize);
1442 if (!buffer)
1443 return NULL;
1444 if (type == required_type) {
1445 *size = isize;
1446 if (actual_oid_return)
1447 oidcpy(actual_oid_return, &actual_oid);
1448 return buffer;
1450 /* Handle references */
1451 else if (type == OBJ_COMMIT)
1452 ref_type = "tree ";
1453 else if (type == OBJ_TAG)
1454 ref_type = "object ";
1455 else {
1456 free(buffer);
1457 return NULL;
1459 ref_length = strlen(ref_type);
1461 if (ref_length + GIT_SHA1_HEXSZ > isize ||
1462 memcmp(buffer, ref_type, ref_length) ||
1463 get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
1464 free(buffer);
1465 return NULL;
1467 free(buffer);
1468 /* Now we have the ID of the referred-to object in
1469 * actual_oid. Check again. */
1473 static void write_object_file_prepare(const void *buf, unsigned long len,
1474 const char *type, struct object_id *oid,
1475 char *hdr, int *hdrlen)
1477 git_hash_ctx c;
1479 /* Generate the header */
1480 *hdrlen = xsnprintf(hdr, *hdrlen, "%s %lu", type, len)+1;
1482 /* Sha1.. */
1483 the_hash_algo->init_fn(&c);
1484 the_hash_algo->update_fn(&c, hdr, *hdrlen);
1485 the_hash_algo->update_fn(&c, buf, len);
1486 the_hash_algo->final_fn(oid->hash, &c);
1490 * Move the just written object into its final resting place.
1492 int finalize_object_file(const char *tmpfile, const char *filename)
1494 int ret = 0;
1496 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
1497 goto try_rename;
1498 else if (link(tmpfile, filename))
1499 ret = errno;
1502 * Coda hack - coda doesn't like cross-directory links,
1503 * so we fall back to a rename, which will mean that it
1504 * won't be able to check collisions, but that's not a
1505 * big deal.
1507 * The same holds for FAT formatted media.
1509 * When this succeeds, we just return. We have nothing
1510 * left to unlink.
1512 if (ret && ret != EEXIST) {
1513 try_rename:
1514 if (!rename(tmpfile, filename))
1515 goto out;
1516 ret = errno;
1518 unlink_or_warn(tmpfile);
1519 if (ret) {
1520 if (ret != EEXIST) {
1521 return error_errno("unable to write sha1 filename %s", filename);
1523 /* FIXME!!! Collision check here ? */
1526 out:
1527 if (adjust_shared_perm(filename))
1528 return error("unable to set permission to '%s'", filename);
1529 return 0;
1532 static int write_buffer(int fd, const void *buf, size_t len)
1534 if (write_in_full(fd, buf, len) < 0)
1535 return error_errno("file write error");
1536 return 0;
1539 int hash_object_file(const void *buf, unsigned long len, const char *type,
1540 struct object_id *oid)
1542 char hdr[MAX_HEADER_LEN];
1543 int hdrlen = sizeof(hdr);
1544 write_object_file_prepare(buf, len, type, oid, hdr, &hdrlen);
1545 return 0;
1548 /* Finalize a file on disk, and close it. */
1549 static void close_sha1_file(int fd)
1551 if (fsync_object_files)
1552 fsync_or_die(fd, "sha1 file");
1553 if (close(fd) != 0)
1554 die_errno("error when closing sha1 file");
1557 /* Size of directory component, including the ending '/' */
1558 static inline int directory_size(const char *filename)
1560 const char *s = strrchr(filename, '/');
1561 if (!s)
1562 return 0;
1563 return s - filename + 1;
1567 * This creates a temporary file in the same directory as the final
1568 * 'filename'
1570 * We want to avoid cross-directory filename renames, because those
1571 * can have problems on various filesystems (FAT, NFS, Coda).
1573 static int create_tmpfile(struct strbuf *tmp, const char *filename)
1575 int fd, dirlen = directory_size(filename);
1577 strbuf_reset(tmp);
1578 strbuf_add(tmp, filename, dirlen);
1579 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
1580 fd = git_mkstemp_mode(tmp->buf, 0444);
1581 if (fd < 0 && dirlen && errno == ENOENT) {
1583 * Make sure the directory exists; note that the contents
1584 * of the buffer are undefined after mkstemp returns an
1585 * error, so we have to rewrite the whole buffer from
1586 * scratch.
1588 strbuf_reset(tmp);
1589 strbuf_add(tmp, filename, dirlen - 1);
1590 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
1591 return -1;
1592 if (adjust_shared_perm(tmp->buf))
1593 return -1;
1595 /* Try again */
1596 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
1597 fd = git_mkstemp_mode(tmp->buf, 0444);
1599 return fd;
1602 static int write_loose_object(const struct object_id *oid, char *hdr,
1603 int hdrlen, const void *buf, unsigned long len,
1604 time_t mtime)
1606 int fd, ret;
1607 unsigned char compressed[4096];
1608 git_zstream stream;
1609 git_hash_ctx c;
1610 struct object_id parano_oid;
1611 static struct strbuf tmp_file = STRBUF_INIT;
1612 static struct strbuf filename = STRBUF_INIT;
1614 strbuf_reset(&filename);
1615 sha1_file_name(the_repository, &filename, oid->hash);
1617 fd = create_tmpfile(&tmp_file, filename.buf);
1618 if (fd < 0) {
1619 if (errno == EACCES)
1620 return error("insufficient permission for adding an object to repository database %s", get_object_directory());
1621 else
1622 return error_errno("unable to create temporary file");
1625 /* Set it up */
1626 git_deflate_init(&stream, zlib_compression_level);
1627 stream.next_out = compressed;
1628 stream.avail_out = sizeof(compressed);
1629 the_hash_algo->init_fn(&c);
1631 /* First header.. */
1632 stream.next_in = (unsigned char *)hdr;
1633 stream.avail_in = hdrlen;
1634 while (git_deflate(&stream, 0) == Z_OK)
1635 ; /* nothing */
1636 the_hash_algo->update_fn(&c, hdr, hdrlen);
1638 /* Then the data itself.. */
1639 stream.next_in = (void *)buf;
1640 stream.avail_in = len;
1641 do {
1642 unsigned char *in0 = stream.next_in;
1643 ret = git_deflate(&stream, Z_FINISH);
1644 the_hash_algo->update_fn(&c, in0, stream.next_in - in0);
1645 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
1646 die("unable to write sha1 file");
1647 stream.next_out = compressed;
1648 stream.avail_out = sizeof(compressed);
1649 } while (ret == Z_OK);
1651 if (ret != Z_STREAM_END)
1652 die("unable to deflate new object %s (%d)", oid_to_hex(oid),
1653 ret);
1654 ret = git_deflate_end_gently(&stream);
1655 if (ret != Z_OK)
1656 die("deflateEnd on object %s failed (%d)", oid_to_hex(oid),
1657 ret);
1658 the_hash_algo->final_fn(parano_oid.hash, &c);
1659 if (oidcmp(oid, &parano_oid) != 0)
1660 die("confused by unstable object source data for %s",
1661 oid_to_hex(oid));
1663 close_sha1_file(fd);
1665 if (mtime) {
1666 struct utimbuf utb;
1667 utb.actime = mtime;
1668 utb.modtime = mtime;
1669 if (utime(tmp_file.buf, &utb) < 0)
1670 warning_errno("failed utime() on %s", tmp_file.buf);
1673 return finalize_object_file(tmp_file.buf, filename.buf);
1676 static int freshen_loose_object(const struct object_id *oid)
1678 return check_and_freshen(oid, 1);
1681 static int freshen_packed_object(const struct object_id *oid)
1683 struct pack_entry e;
1684 if (!find_pack_entry(the_repository, oid, &e))
1685 return 0;
1686 if (e.p->freshened)
1687 return 1;
1688 if (!freshen_file(e.p->pack_name))
1689 return 0;
1690 e.p->freshened = 1;
1691 return 1;
1694 int write_object_file(const void *buf, unsigned long len, const char *type,
1695 struct object_id *oid)
1697 char hdr[MAX_HEADER_LEN];
1698 int hdrlen = sizeof(hdr);
1700 /* Normally if we have it in the pack then we do not bother writing
1701 * it out into .git/objects/??/?{38} file.
1703 write_object_file_prepare(buf, len, type, oid, hdr, &hdrlen);
1704 if (freshen_packed_object(oid) || freshen_loose_object(oid))
1705 return 0;
1706 return write_loose_object(oid, hdr, hdrlen, buf, len, 0);
1709 int hash_object_file_literally(const void *buf, unsigned long len,
1710 const char *type, struct object_id *oid,
1711 unsigned flags)
1713 char *header;
1714 int hdrlen, status = 0;
1716 /* type string, SP, %lu of the length plus NUL must fit this */
1717 hdrlen = strlen(type) + MAX_HEADER_LEN;
1718 header = xmalloc(hdrlen);
1719 write_object_file_prepare(buf, len, type, oid, header, &hdrlen);
1721 if (!(flags & HASH_WRITE_OBJECT))
1722 goto cleanup;
1723 if (freshen_packed_object(oid) || freshen_loose_object(oid))
1724 goto cleanup;
1725 status = write_loose_object(oid, header, hdrlen, buf, len, 0);
1727 cleanup:
1728 free(header);
1729 return status;
1732 int force_object_loose(const struct object_id *oid, time_t mtime)
1734 void *buf;
1735 unsigned long len;
1736 enum object_type type;
1737 char hdr[MAX_HEADER_LEN];
1738 int hdrlen;
1739 int ret;
1741 if (has_loose_object(oid))
1742 return 0;
1743 buf = read_object(oid->hash, &type, &len);
1744 if (!buf)
1745 return error("cannot read sha1_file for %s", oid_to_hex(oid));
1746 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", type_name(type), len) + 1;
1747 ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime);
1748 free(buf);
1750 return ret;
1753 int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
1755 struct object_id oid;
1756 if (!startup_info->have_repository)
1757 return 0;
1758 hashcpy(oid.hash, sha1);
1759 return oid_object_info_extended(&oid, NULL,
1760 flags | OBJECT_INFO_SKIP_CACHED) >= 0;
1763 int has_object_file(const struct object_id *oid)
1765 return has_sha1_file(oid->hash);
1768 int has_object_file_with_flags(const struct object_id *oid, int flags)
1770 return has_sha1_file_with_flags(oid->hash, flags);
1773 static void check_tree(const void *buf, size_t size)
1775 struct tree_desc desc;
1776 struct name_entry entry;
1778 init_tree_desc(&desc, buf, size);
1779 while (tree_entry(&desc, &entry))
1780 /* do nothing
1781 * tree_entry() will die() on malformed entries */
1785 static void check_commit(const void *buf, size_t size)
1787 struct commit c;
1788 memset(&c, 0, sizeof(c));
1789 if (parse_commit_buffer(&c, buf, size))
1790 die("corrupt commit");
1793 static void check_tag(const void *buf, size_t size)
1795 struct tag t;
1796 memset(&t, 0, sizeof(t));
1797 if (parse_tag_buffer(&t, buf, size))
1798 die("corrupt tag");
1801 static int index_mem(struct object_id *oid, void *buf, size_t size,
1802 enum object_type type,
1803 const char *path, unsigned flags)
1805 int ret, re_allocated = 0;
1806 int write_object = flags & HASH_WRITE_OBJECT;
1808 if (!type)
1809 type = OBJ_BLOB;
1812 * Convert blobs to git internal format
1814 if ((type == OBJ_BLOB) && path) {
1815 struct strbuf nbuf = STRBUF_INIT;
1816 if (convert_to_git(&the_index, path, buf, size, &nbuf,
1817 get_conv_flags(flags))) {
1818 buf = strbuf_detach(&nbuf, &size);
1819 re_allocated = 1;
1822 if (flags & HASH_FORMAT_CHECK) {
1823 if (type == OBJ_TREE)
1824 check_tree(buf, size);
1825 if (type == OBJ_COMMIT)
1826 check_commit(buf, size);
1827 if (type == OBJ_TAG)
1828 check_tag(buf, size);
1831 if (write_object)
1832 ret = write_object_file(buf, size, type_name(type), oid);
1833 else
1834 ret = hash_object_file(buf, size, type_name(type), oid);
1835 if (re_allocated)
1836 free(buf);
1837 return ret;
1840 static int index_stream_convert_blob(struct object_id *oid, int fd,
1841 const char *path, unsigned flags)
1843 int ret;
1844 const int write_object = flags & HASH_WRITE_OBJECT;
1845 struct strbuf sbuf = STRBUF_INIT;
1847 assert(path);
1848 assert(would_convert_to_git_filter_fd(path));
1850 convert_to_git_filter_fd(&the_index, path, fd, &sbuf,
1851 get_conv_flags(flags));
1853 if (write_object)
1854 ret = write_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
1855 oid);
1856 else
1857 ret = hash_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
1858 oid);
1859 strbuf_release(&sbuf);
1860 return ret;
1863 static int index_pipe(struct object_id *oid, int fd, enum object_type type,
1864 const char *path, unsigned flags)
1866 struct strbuf sbuf = STRBUF_INIT;
1867 int ret;
1869 if (strbuf_read(&sbuf, fd, 4096) >= 0)
1870 ret = index_mem(oid, sbuf.buf, sbuf.len, type, path, flags);
1871 else
1872 ret = -1;
1873 strbuf_release(&sbuf);
1874 return ret;
1877 #define SMALL_FILE_SIZE (32*1024)
1879 static int index_core(struct object_id *oid, int fd, size_t size,
1880 enum object_type type, const char *path,
1881 unsigned flags)
1883 int ret;
1885 if (!size) {
1886 ret = index_mem(oid, "", size, type, path, flags);
1887 } else if (size <= SMALL_FILE_SIZE) {
1888 char *buf = xmalloc(size);
1889 ssize_t read_result = read_in_full(fd, buf, size);
1890 if (read_result < 0)
1891 ret = error_errno("read error while indexing %s",
1892 path ? path : "<unknown>");
1893 else if (read_result != size)
1894 ret = error("short read while indexing %s",
1895 path ? path : "<unknown>");
1896 else
1897 ret = index_mem(oid, buf, size, type, path, flags);
1898 free(buf);
1899 } else {
1900 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1901 ret = index_mem(oid, buf, size, type, path, flags);
1902 munmap(buf, size);
1904 return ret;
1908 * This creates one packfile per large blob unless bulk-checkin
1909 * machinery is "plugged".
1911 * This also bypasses the usual "convert-to-git" dance, and that is on
1912 * purpose. We could write a streaming version of the converting
1913 * functions and insert that before feeding the data to fast-import
1914 * (or equivalent in-core API described above). However, that is
1915 * somewhat complicated, as we do not know the size of the filter
1916 * result, which we need to know beforehand when writing a git object.
1917 * Since the primary motivation for trying to stream from the working
1918 * tree file and to avoid mmaping it in core is to deal with large
1919 * binary blobs, they generally do not want to get any conversion, and
1920 * callers should avoid this code path when filters are requested.
1922 static int index_stream(struct object_id *oid, int fd, size_t size,
1923 enum object_type type, const char *path,
1924 unsigned flags)
1926 return index_bulk_checkin(oid, fd, size, type, path, flags);
1929 int index_fd(struct object_id *oid, int fd, struct stat *st,
1930 enum object_type type, const char *path, unsigned flags)
1932 int ret;
1935 * Call xsize_t() only when needed to avoid potentially unnecessary
1936 * die() for large files.
1938 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(path))
1939 ret = index_stream_convert_blob(oid, fd, path, flags);
1940 else if (!S_ISREG(st->st_mode))
1941 ret = index_pipe(oid, fd, type, path, flags);
1942 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
1943 (path && would_convert_to_git(&the_index, path)))
1944 ret = index_core(oid, fd, xsize_t(st->st_size), type, path,
1945 flags);
1946 else
1947 ret = index_stream(oid, fd, xsize_t(st->st_size), type, path,
1948 flags);
1949 close(fd);
1950 return ret;
1953 int index_path(struct object_id *oid, const char *path, struct stat *st, unsigned flags)
1955 int fd;
1956 struct strbuf sb = STRBUF_INIT;
1957 int rc = 0;
1959 switch (st->st_mode & S_IFMT) {
1960 case S_IFREG:
1961 fd = open(path, O_RDONLY);
1962 if (fd < 0)
1963 return error_errno("open(\"%s\")", path);
1964 if (index_fd(oid, fd, st, OBJ_BLOB, path, flags) < 0)
1965 return error("%s: failed to insert into database",
1966 path);
1967 break;
1968 case S_IFLNK:
1969 if (strbuf_readlink(&sb, path, st->st_size))
1970 return error_errno("readlink(\"%s\")", path);
1971 if (!(flags & HASH_WRITE_OBJECT))
1972 hash_object_file(sb.buf, sb.len, blob_type, oid);
1973 else if (write_object_file(sb.buf, sb.len, blob_type, oid))
1974 rc = error("%s: failed to insert into database", path);
1975 strbuf_release(&sb);
1976 break;
1977 case S_IFDIR:
1978 return resolve_gitlink_ref(path, "HEAD", oid);
1979 default:
1980 return error("%s: unsupported file type", path);
1982 return rc;
1985 int read_pack_header(int fd, struct pack_header *header)
1987 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
1988 /* "eof before pack header was fully read" */
1989 return PH_ERROR_EOF;
1991 if (header->hdr_signature != htonl(PACK_SIGNATURE))
1992 /* "protocol error (pack signature mismatch detected)" */
1993 return PH_ERROR_PACK_SIGNATURE;
1994 if (!pack_version_ok(header->hdr_version))
1995 /* "protocol error (pack version unsupported)" */
1996 return PH_ERROR_PROTOCOL;
1997 return 0;
2000 void assert_oid_type(const struct object_id *oid, enum object_type expect)
2002 enum object_type type = oid_object_info(oid, NULL);
2003 if (type < 0)
2004 die("%s is not a valid object", oid_to_hex(oid));
2005 if (type != expect)
2006 die("%s is not a valid '%s' object", oid_to_hex(oid),
2007 type_name(expect));
2010 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
2011 struct strbuf *path,
2012 each_loose_object_fn obj_cb,
2013 each_loose_cruft_fn cruft_cb,
2014 each_loose_subdir_fn subdir_cb,
2015 void *data)
2017 size_t origlen, baselen;
2018 DIR *dir;
2019 struct dirent *de;
2020 int r = 0;
2021 struct object_id oid;
2023 if (subdir_nr > 0xff)
2024 BUG("invalid loose object subdirectory: %x", subdir_nr);
2026 origlen = path->len;
2027 strbuf_complete(path, '/');
2028 strbuf_addf(path, "%02x", subdir_nr);
2030 dir = opendir(path->buf);
2031 if (!dir) {
2032 if (errno != ENOENT)
2033 r = error_errno("unable to open %s", path->buf);
2034 strbuf_setlen(path, origlen);
2035 return r;
2038 oid.hash[0] = subdir_nr;
2039 strbuf_addch(path, '/');
2040 baselen = path->len;
2042 while ((de = readdir(dir))) {
2043 size_t namelen;
2044 if (is_dot_or_dotdot(de->d_name))
2045 continue;
2047 namelen = strlen(de->d_name);
2048 strbuf_setlen(path, baselen);
2049 strbuf_add(path, de->d_name, namelen);
2050 if (namelen == GIT_SHA1_HEXSZ - 2 &&
2051 !hex_to_bytes(oid.hash + 1, de->d_name,
2052 GIT_SHA1_RAWSZ - 1)) {
2053 if (obj_cb) {
2054 r = obj_cb(&oid, path->buf, data);
2055 if (r)
2056 break;
2058 continue;
2061 if (cruft_cb) {
2062 r = cruft_cb(de->d_name, path->buf, data);
2063 if (r)
2064 break;
2067 closedir(dir);
2069 strbuf_setlen(path, baselen - 1);
2070 if (!r && subdir_cb)
2071 r = subdir_cb(subdir_nr, path->buf, data);
2073 strbuf_setlen(path, origlen);
2075 return r;
2078 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2079 each_loose_object_fn obj_cb,
2080 each_loose_cruft_fn cruft_cb,
2081 each_loose_subdir_fn subdir_cb,
2082 void *data)
2084 int r = 0;
2085 int i;
2087 for (i = 0; i < 256; i++) {
2088 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2089 subdir_cb, data);
2090 if (r)
2091 break;
2094 return r;
2097 int for_each_loose_file_in_objdir(const char *path,
2098 each_loose_object_fn obj_cb,
2099 each_loose_cruft_fn cruft_cb,
2100 each_loose_subdir_fn subdir_cb,
2101 void *data)
2103 struct strbuf buf = STRBUF_INIT;
2104 int r;
2106 strbuf_addstr(&buf, path);
2107 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2108 subdir_cb, data);
2109 strbuf_release(&buf);
2111 return r;
2114 struct loose_alt_odb_data {
2115 each_loose_object_fn *cb;
2116 void *data;
2119 static int loose_from_alt_odb(struct alternate_object_database *alt,
2120 void *vdata)
2122 struct loose_alt_odb_data *data = vdata;
2123 struct strbuf buf = STRBUF_INIT;
2124 int r;
2126 strbuf_addstr(&buf, alt->path);
2127 r = for_each_loose_file_in_objdir_buf(&buf,
2128 data->cb, NULL, NULL,
2129 data->data);
2130 strbuf_release(&buf);
2131 return r;
2134 int for_each_loose_object(each_loose_object_fn cb, void *data, unsigned flags)
2136 struct loose_alt_odb_data alt;
2137 int r;
2139 r = for_each_loose_file_in_objdir(get_object_directory(),
2140 cb, NULL, NULL, data);
2141 if (r)
2142 return r;
2144 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2145 return 0;
2147 alt.cb = cb;
2148 alt.data = data;
2149 return foreach_alt_odb(loose_from_alt_odb, &alt);
2152 static int check_stream_sha1(git_zstream *stream,
2153 const char *hdr,
2154 unsigned long size,
2155 const char *path,
2156 const unsigned char *expected_sha1)
2158 git_hash_ctx c;
2159 unsigned char real_sha1[GIT_MAX_RAWSZ];
2160 unsigned char buf[4096];
2161 unsigned long total_read;
2162 int status = Z_OK;
2164 the_hash_algo->init_fn(&c);
2165 the_hash_algo->update_fn(&c, hdr, stream->total_out);
2168 * We already read some bytes into hdr, but the ones up to the NUL
2169 * do not count against the object's content size.
2171 total_read = stream->total_out - strlen(hdr) - 1;
2174 * This size comparison must be "<=" to read the final zlib packets;
2175 * see the comment in unpack_sha1_rest for details.
2177 while (total_read <= size &&
2178 (status == Z_OK || status == Z_BUF_ERROR)) {
2179 stream->next_out = buf;
2180 stream->avail_out = sizeof(buf);
2181 if (size - total_read < stream->avail_out)
2182 stream->avail_out = size - total_read;
2183 status = git_inflate(stream, Z_FINISH);
2184 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
2185 total_read += stream->next_out - buf;
2187 git_inflate_end(stream);
2189 if (status != Z_STREAM_END) {
2190 error("corrupt loose object '%s'", sha1_to_hex(expected_sha1));
2191 return -1;
2193 if (stream->avail_in) {
2194 error("garbage at end of loose object '%s'",
2195 sha1_to_hex(expected_sha1));
2196 return -1;
2199 the_hash_algo->final_fn(real_sha1, &c);
2200 if (hashcmp(expected_sha1, real_sha1)) {
2201 error("sha1 mismatch for %s (expected %s)", path,
2202 sha1_to_hex(expected_sha1));
2203 return -1;
2206 return 0;
2209 int read_loose_object(const char *path,
2210 const struct object_id *expected_oid,
2211 enum object_type *type,
2212 unsigned long *size,
2213 void **contents)
2215 int ret = -1;
2216 void *map = NULL;
2217 unsigned long mapsize;
2218 git_zstream stream;
2219 char hdr[MAX_HEADER_LEN];
2221 *contents = NULL;
2223 map = map_sha1_file_1(the_repository, path, NULL, &mapsize);
2224 if (!map) {
2225 error_errno("unable to mmap %s", path);
2226 goto out;
2229 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
2230 error("unable to unpack header of %s", path);
2231 goto out;
2234 *type = parse_sha1_header(hdr, size);
2235 if (*type < 0) {
2236 error("unable to parse header of %s", path);
2237 git_inflate_end(&stream);
2238 goto out;
2241 if (*type == OBJ_BLOB) {
2242 if (check_stream_sha1(&stream, hdr, *size, path, expected_oid->hash) < 0)
2243 goto out;
2244 } else {
2245 *contents = unpack_sha1_rest(&stream, hdr, *size, expected_oid->hash);
2246 if (!*contents) {
2247 error("unable to unpack contents of %s", path);
2248 git_inflate_end(&stream);
2249 goto out;
2251 if (check_object_signature(expected_oid, *contents,
2252 *size, type_name(*type))) {
2253 error("sha1 mismatch for %s (expected %s)", path,
2254 oid_to_hex(expected_oid));
2255 free(*contents);
2256 goto out;
2260 ret = 0; /* everything checks out */
2262 out:
2263 if (map)
2264 munmap(map, mapsize);
2265 return ret;