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