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