]> git.ipfire.org Git - thirdparty/git.git/blame - object-file.c
git maintenance: avoid console window in scheduled tasks on Windows
[thirdparty/git.git] / object-file.c
CommitLineData
0fcfd160
LT
1/*
2 * GIT - The information manager from hell
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 *
e5afd444 6 * This handles basic git object files - packing, unpacking,
0fcfd160
LT
7 * creation etc.
8 */
5e3f94df 9#include "git-compat-util.h"
0b027f6c 10#include "abspath.h"
36bf1958 11#include "alloc.h"
b2141fc1 12#include "config.h"
73359a9b 13#include "convert.h"
32a8f510 14#include "environment.h"
f394e093 15#include "gettext.h"
41771fa4 16#include "hex.h"
6eac50d8 17#include "string-list.h"
697cc8ef 18#include "lockfile.h"
1f688557 19#include "delta.h"
a733cb60 20#include "pack.h"
8e440259
PE
21#include "blob.h"
22#include "commit.h"
4dd1fbc7 23#include "run-command.h"
8e440259
PE
24#include "tag.h"
25#include "tree.h"
c879daa2 26#include "tree-walk.h"
f35a6d3b 27#include "refs.h"
70f5d5d3 28#include "pack-revindex.h"
bc626927 29#include "hash-lookup.h"
568508e7 30#include "bulk-checkin.h"
031dc927 31#include "repository.h"
47f351e9 32#include "replace-object.h"
090ea126 33#include "streaming.h"
543c5caa 34#include "dir.h"
12d95ef6 35#include "list.h"
c4c6effa 36#include "mergesort.h"
cf3c6352 37#include "quote.h"
4f39cd82 38#include "packfile.h"
87bed179 39#include "object-file.h"
90c62155 40#include "object-store.h"
e3d2f20e 41#include "oidtree.h"
b14ed5ad 42#include "promisor-remote.h"
e38da487 43#include "setup.h"
a35e03de 44#include "submodule.h"
69bbbe48 45#include "fsck.h"
d5ebb50d 46#include "wrapper.h"
e05db0fd 47
1af64f73 48/* The maximum size for an object header. */
49#define MAX_HEADER_LEN 32
50
e1ccd7e2 51
52#define EMPTY_TREE_SHA1_BIN_LITERAL \
53 "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60" \
54 "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04"
13eeedb5 55#define EMPTY_TREE_SHA256_BIN_LITERAL \
56 "\x6e\xf1\x9b\x41\x22\x5c\x53\x69\xf1\xc1" \
57 "\x04\xd4\x5d\x8d\x85\xef\xa9\xb0\x57\xb5" \
58 "\x3b\x14\xb4\xb9\xb9\x39\xdd\x74\xde\xcc" \
59 "\x53\x21"
e1ccd7e2 60
61#define EMPTY_BLOB_SHA1_BIN_LITERAL \
62 "\xe6\x9d\xe2\x9b\xb2\xd1\xd6\x43\x4b\x8b" \
63 "\x29\xae\x77\x5a\xd8\xc2\xe4\x8c\x53\x91"
13eeedb5 64#define EMPTY_BLOB_SHA256_BIN_LITERAL \
65 "\x47\x3a\x0f\x4c\x3b\xe8\xa9\x36\x81\xa2" \
66 "\x67\xe3\xb1\xe9\xa7\xdc\xda\x11\x85\x43" \
67 "\x6f\xe1\x41\xf7\x74\x91\x20\xa3\x03\x72" \
68 "\x18\x13"
e1ccd7e2 69
e1ccd7e2 70static const struct object_id empty_tree_oid = {
5a6dce70 71 .hash = EMPTY_TREE_SHA1_BIN_LITERAL,
72 .algo = GIT_HASH_SHA1,
8576fde6 73};
e1ccd7e2 74static const struct object_id empty_blob_oid = {
5a6dce70 75 .hash = EMPTY_BLOB_SHA1_BIN_LITERAL,
76 .algo = GIT_HASH_SHA1,
8576fde6 77};
14228447 78static const struct object_id null_oid_sha1 = {
79 .hash = {0},
80 .algo = GIT_HASH_SHA1,
81};
13eeedb5 82static const struct object_id empty_tree_oid_sha256 = {
5a6dce70 83 .hash = EMPTY_TREE_SHA256_BIN_LITERAL,
84 .algo = GIT_HASH_SHA256,
13eeedb5 85};
86static const struct object_id empty_blob_oid_sha256 = {
5a6dce70 87 .hash = EMPTY_BLOB_SHA256_BIN_LITERAL,
88 .algo = GIT_HASH_SHA256,
13eeedb5 89};
14228447 90static const struct object_id null_oid_sha256 = {
91 .hash = {0},
92 .algo = GIT_HASH_SHA256,
93};
88cd621d 94
ac73cedf 95static void git_hash_sha1_init(git_hash_ctx *ctx)
f50e766b 96{
ac73cedf 97 git_SHA1_Init(&ctx->sha1);
f50e766b 98}
99
768e30ea 100static void git_hash_sha1_clone(git_hash_ctx *dst, const git_hash_ctx *src)
101{
102 git_SHA1_Clone(&dst->sha1, &src->sha1);
103}
104
ac73cedf 105static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
f50e766b 106{
ac73cedf 107 git_SHA1_Update(&ctx->sha1, data, len);
f50e766b 108}
109
ac73cedf 110static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
f50e766b 111{
ac73cedf 112 git_SHA1_Final(hash, &ctx->sha1);
f50e766b 113}
114
ab795f0d 115static void git_hash_sha1_final_oid(struct object_id *oid, git_hash_ctx *ctx)
116{
117 git_SHA1_Final(oid->hash, &ctx->sha1);
118 memset(oid->hash + GIT_SHA1_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA1_RAWSZ);
5a6dce70 119 oid->algo = GIT_HASH_SHA1;
ab795f0d 120}
121
13eeedb5 122
123static void git_hash_sha256_init(git_hash_ctx *ctx)
124{
125 git_SHA256_Init(&ctx->sha256);
126}
127
768e30ea 128static void git_hash_sha256_clone(git_hash_ctx *dst, const git_hash_ctx *src)
129{
130 git_SHA256_Clone(&dst->sha256, &src->sha256);
131}
132
13eeedb5 133static void git_hash_sha256_update(git_hash_ctx *ctx, const void *data, size_t len)
134{
135 git_SHA256_Update(&ctx->sha256, data, len);
136}
137
138static void git_hash_sha256_final(unsigned char *hash, git_hash_ctx *ctx)
139{
140 git_SHA256_Final(hash, &ctx->sha256);
141}
142
ab795f0d 143static void git_hash_sha256_final_oid(struct object_id *oid, git_hash_ctx *ctx)
144{
145 git_SHA256_Final(oid->hash, &ctx->sha256);
146 /*
147 * This currently does nothing, so the compiler should optimize it out,
148 * but keep it in case we extend the hash size again.
149 */
150 memset(oid->hash + GIT_SHA256_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA256_RAWSZ);
5a6dce70 151 oid->algo = GIT_HASH_SHA256;
ab795f0d 152}
153
9eb6cdad 154static void git_hash_unknown_init(git_hash_ctx *ctx UNUSED)
f50e766b 155{
1a07e59c 156 BUG("trying to init unknown hash");
f50e766b 157}
158
9eb6cdad
JK
159static void git_hash_unknown_clone(git_hash_ctx *dst UNUSED,
160 const git_hash_ctx *src UNUSED)
768e30ea 161{
162 BUG("trying to clone unknown hash");
163}
164
9eb6cdad
JK
165static void git_hash_unknown_update(git_hash_ctx *ctx UNUSED,
166 const void *data UNUSED,
167 size_t len UNUSED)
f50e766b 168{
1a07e59c 169 BUG("trying to update unknown hash");
f50e766b 170}
171
9eb6cdad
JK
172static void git_hash_unknown_final(unsigned char *hash UNUSED,
173 git_hash_ctx *ctx UNUSED)
f50e766b 174{
1a07e59c 175 BUG("trying to finalize unknown hash");
f50e766b 176}
177
9eb6cdad
JK
178static void git_hash_unknown_final_oid(struct object_id *oid UNUSED,
179 git_hash_ctx *ctx UNUSED)
ab795f0d 180{
181 BUG("trying to finalize unknown hash");
182}
183
f50e766b 184const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
185 {
0cb9872e
ÆAB
186 .name = NULL,
187 .format_id = 0x00000000,
188 .rawsz = 0,
189 .hexsz = 0,
190 .blksz = 0,
191 .init_fn = git_hash_unknown_init,
192 .clone_fn = git_hash_unknown_clone,
193 .update_fn = git_hash_unknown_update,
194 .final_fn = git_hash_unknown_final,
195 .final_oid_fn = git_hash_unknown_final_oid,
196 .empty_tree = NULL,
197 .empty_blob = NULL,
198 .null_oid = NULL,
f50e766b 199 },
200 {
0cb9872e
ÆAB
201 .name = "sha1",
202 .format_id = GIT_SHA1_FORMAT_ID,
203 .rawsz = GIT_SHA1_RAWSZ,
204 .hexsz = GIT_SHA1_HEXSZ,
205 .blksz = GIT_SHA1_BLKSZ,
206 .init_fn = git_hash_sha1_init,
207 .clone_fn = git_hash_sha1_clone,
208 .update_fn = git_hash_sha1_update,
209 .final_fn = git_hash_sha1_final,
210 .final_oid_fn = git_hash_sha1_final_oid,
211 .empty_tree = &empty_tree_oid,
212 .empty_blob = &empty_blob_oid,
213 .null_oid = &null_oid_sha1,
f50e766b 214 },
13eeedb5 215 {
0cb9872e
ÆAB
216 .name = "sha256",
217 .format_id = GIT_SHA256_FORMAT_ID,
218 .rawsz = GIT_SHA256_RAWSZ,
219 .hexsz = GIT_SHA256_HEXSZ,
220 .blksz = GIT_SHA256_BLKSZ,
221 .init_fn = git_hash_sha256_init,
222 .clone_fn = git_hash_sha256_clone,
223 .update_fn = git_hash_sha256_update,
224 .final_fn = git_hash_sha256_final,
225 .final_oid_fn = git_hash_sha256_final_oid,
226 .empty_tree = &empty_tree_oid_sha256,
227 .empty_blob = &empty_blob_oid_sha256,
228 .null_oid = &null_oid_sha256,
13eeedb5 229 }
f50e766b 230};
231
14228447 232const struct object_id *null_oid(void)
233{
234 return the_hash_algo->null_oid;
235}
236
d8a92ced 237const char *empty_tree_oid_hex(void)
238{
239 static char buf[GIT_MAX_HEXSZ + 1];
240 return oid_to_hex_r(buf, the_hash_algo->empty_tree);
241}
242
243const char *empty_blob_oid_hex(void)
244{
245 static char buf[GIT_MAX_HEXSZ + 1];
246 return oid_to_hex_r(buf, the_hash_algo->empty_blob);
247}
248
2f90b9d9 249int hash_algo_by_name(const char *name)
250{
251 int i;
252 if (!name)
253 return GIT_HASH_UNKNOWN;
254 for (i = 1; i < GIT_HASH_NALGOS; i++)
255 if (!strcmp(name, hash_algos[i].name))
256 return i;
257 return GIT_HASH_UNKNOWN;
258}
259
260int hash_algo_by_id(uint32_t format_id)
261{
262 int i;
263 for (i = 1; i < GIT_HASH_NALGOS; i++)
264 if (format_id == hash_algos[i].format_id)
265 return i;
266 return GIT_HASH_UNKNOWN;
267}
268
95399788 269int hash_algo_by_length(int len)
270{
271 int i;
272 for (i = 1; i < GIT_HASH_NALGOS; i++)
273 if (len == hash_algos[i].rawsz)
274 return i;
275 return GIT_HASH_UNKNOWN;
276}
2f90b9d9 277
c597ba80
NTND
278/*
279 * This is meant to hold a *small* number of objects that you would
c7c33f50 280 * want repo_read_object_file() to be able to return, but yet you do not want
c597ba80
NTND
281 * to write them into the object store (e.g. a browse-only
282 * application).
283 */
284static struct cached_object {
62ba93ea 285 struct object_id oid;
c597ba80
NTND
286 enum object_type type;
287 void *buf;
288 unsigned long size;
289} *cached_objects;
290static int cached_object_nr, cached_object_alloc;
291
292static struct cached_object empty_tree = {
50103649
ÆAB
293 .oid = {
294 .hash = EMPTY_TREE_SHA1_BIN_LITERAL,
295 },
296 .type = OBJ_TREE,
297 .buf = "",
c597ba80
NTND
298};
299
62ba93ea 300static struct cached_object *find_cached_object(const struct object_id *oid)
c597ba80
NTND
301{
302 int i;
303 struct cached_object *co = cached_objects;
304
305 for (i = 0; i < cached_object_nr; i++, co++) {
4a7e27e9 306 if (oideq(&co->oid, oid))
c597ba80
NTND
307 return co;
308 }
4a7e27e9 309 if (oideq(oid, the_hash_algo->empty_tree))
c597ba80
NTND
310 return &empty_tree;
311 return NULL;
312}
313
9472935d 314
8462ff43 315static int get_conv_flags(unsigned flags)
9472935d
TB
316{
317 if (flags & HASH_RENORMALIZE)
8462ff43 318 return CONV_EOL_RENORMALIZE;
9472935d 319 else if (flags & HASH_WRITE_OBJECT)
107642fe 320 return global_conv_flags_eol | CONV_WRITE_OBJECT;
9472935d 321 else
8462ff43 322 return 0;
9472935d
TB
323}
324
325
90a6464b
JH
326int mkdir_in_gitdir(const char *path)
327{
328 if (mkdir(path, 0777)) {
329 int saved_errno = errno;
330 struct stat st;
331 struct strbuf sb = STRBUF_INIT;
332
333 if (errno != EEXIST)
334 return -1;
335 /*
336 * Are we looking at a path in a symlinked worktree
337 * whose original repository does not yet have it?
338 * e.g. .git/rr-cache pointing at its original
339 * repository in which the user hasn't performed any
340 * conflict resolution yet?
341 */
342 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
343 strbuf_readlink(&sb, path, st.st_size) ||
344 !is_absolute_path(sb.buf) ||
345 mkdir(sb.buf, 0777)) {
346 strbuf_release(&sb);
347 errno = saved_errno;
348 return -1;
349 }
350 strbuf_release(&sb);
351 }
352 return adjust_shared_perm(path);
353}
354
eb3c027e 355static enum scld_error safe_create_leading_directories_1(char *path, int share)
b2cb9425 356{
26c8ae2a 357 char *next_component = path + offset_1st_component(path);
0be0521b 358 enum scld_error ret = SCLD_OK;
67d42212 359
0be0521b 360 while (ret == SCLD_OK && next_component) {
f0502332 361 struct stat st;
0f527403 362 char *slash = next_component, slash_character;
f0502332 363
0f527403
MH
364 while (*slash && !is_dir_sep(*slash))
365 slash++;
366
367 if (!*slash)
b2cb9425 368 break;
bf10cf70 369
26c8ae2a 370 next_component = slash + 1;
0f527403 371 while (is_dir_sep(*next_component))
bf10cf70 372 next_component++;
26c8ae2a 373 if (!*next_component)
5f0bdf50 374 break;
831651fd 375
0f527403 376 slash_character = *slash;
831651fd 377 *slash = '\0';
67d42212
JR
378 if (!stat(path, &st)) {
379 /* path exists */
204a047f
MH
380 if (!S_ISDIR(st.st_mode)) {
381 errno = ENOTDIR;
0be0521b 382 ret = SCLD_EXISTS;
204a047f 383 }
53a39721 384 } else if (mkdir(path, 0777)) {
928734d9 385 if (errno == EEXIST &&
9e6f885d 386 !stat(path, &st) && S_ISDIR(st.st_mode))
928734d9 387 ; /* somebody created it since we checked */
18d37e86
MH
388 else if (errno == ENOENT)
389 /*
390 * Either mkdir() failed because
391 * somebody just pruned the containing
392 * directory, or stat() failed because
393 * the file that was in our way was
394 * just removed. Either way, inform
395 * the caller that it might be worth
396 * trying again:
397 */
398 ret = SCLD_VANISHED;
9e6f885d 399 else
0be0521b 400 ret = SCLD_FAILED;
eb3c027e 401 } else if (share && adjust_shared_perm(path)) {
0be0521b 402 ret = SCLD_PERMS;
457f06d6 403 }
0f527403 404 *slash = slash_character;
b2cb9425 405 }
9e6f885d 406 return ret;
b2cb9425 407}
723c31fe 408
eb3c027e
MT
409enum scld_error safe_create_leading_directories(char *path)
410{
411 return safe_create_leading_directories_1(path, 1);
412}
413
414enum scld_error safe_create_leading_directories_no_share(char *path)
415{
416 return safe_create_leading_directories_1(path, 0);
417}
418
0be0521b 419enum scld_error safe_create_leading_directories_const(const char *path)
8e21d63b 420{
02944307 421 int save_errno;
8e21d63b
JK
422 /* path points to cache entries, so xstrdup before messing with it */
423 char *buf = xstrdup(path);
0be0521b 424 enum scld_error result = safe_create_leading_directories(buf);
02944307
MH
425
426 save_errno = errno;
8e21d63b 427 free(buf);
02944307 428 errno = save_errno;
8e21d63b
JK
429 return result;
430}
431
514c5fdd 432static void fill_loose_path(struct strbuf *buf, const struct object_id *oid)
ace1534d
JH
433{
434 int i;
94b5e093 435 for (i = 0; i < the_hash_algo->rawsz; i++) {
ace1534d 436 static char hex[] = "0123456789abcdef";
514c5fdd 437 unsigned int val = oid->hash[i];
f7b7774f
JK
438 strbuf_addch(buf, hex[val >> 4]);
439 strbuf_addch(buf, hex[val & 0xf]);
afbba2f0 440 if (!i)
f7b7774f 441 strbuf_addch(buf, '/');
ace1534d
JH
442 }
443}
444
f0eaf638
JK
445static const char *odb_loose_path(struct object_directory *odb,
446 struct strbuf *buf,
514c5fdd 447 const struct object_id *oid)
0fcfd160 448{
b69fb867 449 strbuf_reset(buf);
f0eaf638 450 strbuf_addstr(buf, odb->path);
34498471 451 strbuf_addch(buf, '/');
514c5fdd 452 fill_loose_path(buf, oid);
f3f043a1 453 return buf->buf;
0fcfd160
LT
454}
455
f3f043a1 456const char *loose_object_path(struct repository *r, struct strbuf *buf,
514c5fdd 457 const struct object_id *oid)
29ec6af2 458{
514c5fdd 459 return odb_loose_path(r->objects->odb, buf, oid);
0fcfd160
LT
460}
461
4ea82473
JK
462/*
463 * Return non-zero iff the path is usable as an alternate object database.
464 */
13313fc3
SB
465static int alt_odb_usable(struct raw_object_store *o,
466 struct strbuf *path,
cf2dc1c2 467 const char *normalized_objdir, khiter_t *pos)
4ea82473 468{
cf2dc1c2 469 int r;
4ea82473
JK
470
471 /* Detect cases where alternate disappeared */
472 if (!is_directory(path->buf)) {
259328b7
NTND
473 error(_("object directory %s does not exist; "
474 "check .git/objects/info/alternates"),
4ea82473
JK
475 path->buf);
476 return 0;
477 }
478
479 /*
480 * Prevent the common mistake of listing the same
481 * thing twice, or object directory itself.
482 */
cf2dc1c2
EW
483 if (!o->odb_by_path) {
484 khiter_t p;
485
486 o->odb_by_path = kh_init_odb_path_map();
487 assert(!o->odb->next);
488 p = kh_put_odb_path_map(o->odb_by_path, o->odb->path, &r);
489 assert(r == 1); /* never used */
490 kh_value(o->odb_by_path, p) = o->odb;
4ea82473 491 }
cf2dc1c2 492 if (fspatheq(path->buf, normalized_objdir))
4ea82473 493 return 0;
cf2dc1c2
EW
494 *pos = kh_put_odb_path_map(o->odb_by_path, path->buf, &r);
495 /* r: 0 = exists, 1 = never used, 2 = deleted */
496 return r == 0 ? 0 : 1;
4ea82473
JK
497}
498
ddd5d056
JH
499/*
500 * Prepare alternate object database registry.
d5a63b99
JH
501 *
502 * The variable alt_odb_list points at the list of struct
263db403 503 * object_directory. The elements on this list come from
d5a63b99
JH
504 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
505 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
1494e038
JH
506 * whose contents is similar to that environment variable but can be
507 * LF separated. Its base points at a statically allocated buffer that
d5a63b99
JH
508 * contains "/the/directory/corresponding/to/.git/objects/...", while
509 * its name points just after the slash at the end of ".git/objects/"
e5afd444
510 * in the example above, and has enough space to hold all hex characters
511 * of the object ID, an extra slash for the first level indirection, and
512 * the terminating NUL.
ddd5d056 513 */
77f012e8
SB
514static void read_info_alternates(struct repository *r,
515 const char *relative_base,
516 int depth);
407532f8 517static int link_alt_odb_entry(struct repository *r, const struct strbuf *entry,
cfc62fc9 518 const char *relative_base, int depth, const char *normalized_objdir)
ace1534d 519{
263db403 520 struct object_directory *ent;
5bdf0a84 521 struct strbuf pathbuf = STRBUF_INIT;
199337d6 522 struct strbuf tmp = STRBUF_INIT;
cf2dc1c2 523 khiter_t pos;
199337d6 524 int ret = -1;
d5a63b99 525
407532f8 526 if (!is_absolute_path(entry->buf) && relative_base) {
4ac9006f 527 strbuf_realpath(&pathbuf, relative_base, 1);
5bdf0a84 528 strbuf_addch(&pathbuf, '/');
c2f493a4 529 }
407532f8 530 strbuf_addbuf(&pathbuf, entry);
c2f493a4 531
199337d6 532 if (!strbuf_realpath(&tmp, pathbuf.buf, 0)) {
259328b7 533 error(_("unable to normalize alternate object path: %s"),
670c359d 534 pathbuf.buf);
199337d6 535 goto error;
670c359d 536 }
199337d6 537 strbuf_swap(&pathbuf, &tmp);
5bdf0a84
HW
538
539 /*
540 * The trailing slash after the directory name is given by
541 * this function at the end. Remove duplicates.
542 */
4ea82473
JK
543 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
544 strbuf_setlen(&pathbuf, pathbuf.len - 1);
5bdf0a84 545
199337d6
GC
546 if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir, &pos))
547 goto error;
c2f493a4 548
ca56dadb 549 CALLOC_ARRAY(ent, 1);
cf2dc1c2
EW
550 /* pathbuf.buf is already in r->objects->odb_by_path */
551 ent->path = strbuf_detach(&pathbuf, NULL);
c2f493a4
MW
552
553 /* add the alternate entry */
f0eaf638
JK
554 *r->objects->odb_tail = ent;
555 r->objects->odb_tail = &(ent->next);
c2f493a4 556 ent->next = NULL;
cf2dc1c2
EW
557 assert(r->objects->odb_by_path);
558 kh_value(r->objects->odb_by_path, pos) = ent;
c2f493a4
MW
559
560 /* recursively add alternates */
cf2dc1c2 561 read_info_alternates(r, ent->path, depth + 1);
199337d6
GC
562 ret = 0;
563 error:
564 strbuf_release(&tmp);
565 strbuf_release(&pathbuf);
566 return ret;
c2f493a4
MW
567}
568
cf3c6352
JK
569static const char *parse_alt_odb_entry(const char *string,
570 int sep,
571 struct strbuf *out)
572{
573 const char *end;
574
575 strbuf_reset(out);
576
577 if (*string == '#') {
578 /* comment; consume up to next separator */
579 end = strchrnul(string, sep);
580 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
581 /*
582 * quoted path; unquote_c_style has copied the
583 * data for us and set "end". Broken quoting (e.g.,
584 * an entry that doesn't end with a quote) falls
585 * back to the unquoted case below.
586 */
587 } else {
588 /* normal, unquoted path */
589 end = strchrnul(string, sep);
590 strbuf_add(out, string, end - string);
591 }
592
593 if (*end)
594 end++;
595 return end;
596}
597
77f012e8
SB
598static void link_alt_odb_entries(struct repository *r, const char *alt,
599 int sep, const char *relative_base, int depth)
c2f493a4 600{
539e7506 601 struct strbuf objdirbuf = STRBUF_INIT;
cf3c6352 602 struct strbuf entry = STRBUF_INIT;
c2f493a4 603
f28e3668
JK
604 if (!alt || !*alt)
605 return;
606
c2f493a4 607 if (depth > 5) {
259328b7 608 error(_("%s: ignoring alternate object stores, nesting too deep"),
c2f493a4
MW
609 relative_base);
610 return;
611 }
612
199337d6 613 strbuf_realpath(&objdirbuf, r->objects->odb->path, 1);
539e7506 614
cf3c6352
JK
615 while (*alt) {
616 alt = parse_alt_odb_entry(alt, sep, &entry);
617 if (!entry.len)
9577e7e3 618 continue;
407532f8 619 link_alt_odb_entry(r, &entry,
cfc62fc9 620 relative_base, depth, objdirbuf.buf);
9577e7e3 621 }
cf3c6352 622 strbuf_release(&entry);
539e7506 623 strbuf_release(&objdirbuf);
d5a63b99
JH
624}
625
77f012e8
SB
626static void read_info_alternates(struct repository *r,
627 const char *relative_base,
628 int depth)
d5a63b99 629{
5015f01c 630 char *path;
dc732bd5 631 struct strbuf buf = STRBUF_INIT;
d5a63b99 632
5015f01c 633 path = xstrfmt("%s/info/alternates", relative_base);
dc732bd5 634 if (strbuf_read_file(&buf, path, 1024) < 0) {
f0f7bebe 635 warn_on_fopen_errors(path);
dc732bd5 636 free(path);
9a217f2a 637 return;
ace1534d 638 }
d5a63b99 639
77f012e8 640 link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
dc732bd5
JK
641 strbuf_release(&buf);
642 free(path);
ace1534d
JH
643}
644
bef70b22
DB
645void add_to_alternates_file(const char *reference)
646{
f132a127 647 struct lock_file lock = LOCK_INIT;
77b9b1d1
JK
648 char *alts = git_pathdup("objects/info/alternates");
649 FILE *in, *out;
f132a127 650 int found = 0;
77b9b1d1 651
f132a127
652 hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
653 out = fdopen_lock_file(&lock, "w");
77b9b1d1 654 if (!out)
259328b7 655 die_errno(_("unable to fdopen alternates lockfile"));
77b9b1d1
JK
656
657 in = fopen(alts, "r");
658 if (in) {
659 struct strbuf line = STRBUF_INIT;
77b9b1d1 660
3f163962 661 while (strbuf_getline(&line, in) != EOF) {
77b9b1d1
JK
662 if (!strcmp(reference, line.buf)) {
663 found = 1;
664 break;
665 }
666 fprintf_or_die(out, "%s\n", line.buf);
667 }
668
669 strbuf_release(&line);
670 fclose(in);
77b9b1d1
JK
671 }
672 else if (errno != ENOENT)
259328b7 673 die_errno(_("unable to read alternates file"));
77b9b1d1 674
f132a127
675 if (found) {
676 rollback_lock_file(&lock);
677 } else {
77b9b1d1 678 fprintf_or_die(out, "%s\n", reference);
f132a127 679 if (commit_lock_file(&lock))
259328b7 680 die_errno(_("unable to move new alternates file into place"));
f0eaf638 681 if (the_repository->objects->loaded_alternates)
93d8d1e2
SB
682 link_alt_odb_entries(the_repository, reference,
683 '\n', NULL, 0);
77b9b1d1
JK
684 }
685 free(alts);
bef70b22
DB
686}
687
a5b34d21
JK
688void add_to_alternates_memory(const char *reference)
689{
690 /*
691 * Make sure alternates are initialized, or else our entry may be
692 * overwritten when they are.
693 */
0b209034 694 prepare_alt_odb(the_repository);
a5b34d21 695
93d8d1e2
SB
696 link_alt_odb_entries(the_repository, reference,
697 '\n', NULL, 0);
a5b34d21
JK
698}
699
b3cecf49
NS
700struct object_directory *set_temporary_primary_odb(const char *dir, int will_destroy)
701{
702 struct object_directory *new_odb;
703
704 /*
705 * Make sure alternates are initialized, or else our entry may be
706 * overwritten when they are.
707 */
708 prepare_alt_odb(the_repository);
709
710 /*
711 * Make a new primary odb and link the old primary ODB in as an
712 * alternate
713 */
714 new_odb = xcalloc(1, sizeof(*new_odb));
715 new_odb->path = xstrdup(dir);
ecd81dfc
NS
716
717 /*
718 * Disable ref updates while a temporary odb is active, since
719 * the objects in the database may roll back.
720 */
721 new_odb->disable_ref_updates = 1;
b3cecf49
NS
722 new_odb->will_destroy = will_destroy;
723 new_odb->next = the_repository->objects->odb;
724 the_repository->objects->odb = new_odb;
725 return new_odb->next;
726}
727
728void restore_primary_odb(struct object_directory *restore_odb, const char *old_path)
729{
730 struct object_directory *cur_odb = the_repository->objects->odb;
731
732 if (strcmp(old_path, cur_odb->path))
733 BUG("expected %s as primary object store; found %s",
734 old_path, cur_odb->path);
735
736 if (cur_odb->next != restore_odb)
737 BUG("we expect the old primary object store to be the first alternate");
738
739 the_repository->objects->odb = restore_odb;
740 free_object_directory(cur_odb);
741}
742
9eeea7d2
SB
743/*
744 * Compute the exact path an alternate is at and returns it. In case of
745 * error NULL is returned and the human readable error is added to `err`
efde7b72 746 * `path` may be relative and should point to $GIT_DIR.
9eeea7d2
SB
747 * `err` must not be null.
748 */
749char *compute_alternate_path(const char *path, struct strbuf *err)
750{
751 char *ref_git = NULL;
4530a85b 752 const char *repo;
9eeea7d2
SB
753 int seen_error = 0;
754
4530a85b
AM
755 ref_git = real_pathdup(path, 0);
756 if (!ref_git) {
9eeea7d2
SB
757 seen_error = 1;
758 strbuf_addf(err, _("path '%s' does not exist"), path);
759 goto out;
4530a85b 760 }
9eeea7d2
SB
761
762 repo = read_gitfile(ref_git);
763 if (!repo)
764 repo = read_gitfile(mkpath("%s/.git", ref_git));
765 if (repo) {
766 free(ref_git);
767 ref_git = xstrdup(repo);
768 }
769
770 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
771 char *ref_git_git = mkpathdup("%s/.git", ref_git);
772 free(ref_git);
773 ref_git = ref_git_git;
774 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
775 struct strbuf sb = STRBUF_INIT;
776 seen_error = 1;
777 if (get_common_dir(&sb, ref_git)) {
778 strbuf_addf(err,
779 _("reference repository '%s' as a linked "
780 "checkout is not supported yet."),
781 path);
782 goto out;
783 }
784
785 strbuf_addf(err, _("reference repository '%s' is not a "
786 "local repository."), path);
787 goto out;
788 }
789
790 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
791 strbuf_addf(err, _("reference repository '%s' is shallow"),
792 path);
793 seen_error = 1;
794 goto out;
795 }
796
797 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
798 strbuf_addf(err,
799 _("reference repository '%s' is grafted"),
800 path);
801 seen_error = 1;
802 goto out;
803 }
804
805out:
806 if (seen_error) {
6a83d902 807 FREE_AND_NULL(ref_git);
9eeea7d2
SB
808 }
809
810 return ref_git;
811}
812
f57a7396
TB
813struct object_directory *find_odb(struct repository *r, const char *obj_dir)
814{
815 struct object_directory *odb;
816 char *obj_dir_real = real_pathdup(obj_dir, 1);
817 struct strbuf odb_path_real = STRBUF_INIT;
818
819 prepare_alt_odb(r);
820 for (odb = r->objects->odb; odb; odb = odb->next) {
821 strbuf_realpath(&odb_path_real, odb->path, 1);
822 if (!strcmp(obj_dir_real, odb_path_real.buf))
823 break;
824 }
825
826 free(obj_dir_real);
827 strbuf_release(&odb_path_real);
828
829 if (!odb)
830 die(_("could not find object directory matching %s"), obj_dir);
831 return odb;
832}
833
709dfa69
JK
834static void fill_alternate_refs_command(struct child_process *cmd,
835 const char *repo_path)
836{
837 const char *value;
838
839 if (!git_config_get_value("core.alternateRefsCommand", &value)) {
840 cmd->use_shell = 1;
841
c972bf4c
JK
842 strvec_push(&cmd->args, value);
843 strvec_push(&cmd->args, repo_path);
709dfa69
JK
844 } else {
845 cmd->git_cmd = 1;
846
c972bf4c
JK
847 strvec_pushf(&cmd->args, "--git-dir=%s", repo_path);
848 strvec_push(&cmd->args, "for-each-ref");
849 strvec_push(&cmd->args, "--format=%(objectname)");
709dfa69
JK
850
851 if (!git_config_get_value("core.alternateRefsPrefixes", &value)) {
c972bf4c
JK
852 strvec_push(&cmd->args, "--");
853 strvec_split(&cmd->args, value);
709dfa69
JK
854 }
855 }
856
29fda24d 857 strvec_pushv(&cmd->env, (const char **)local_repo_env);
709dfa69
JK
858 cmd->out = -1;
859}
860
861static void read_alternate_refs(const char *path,
862 alternate_ref_fn *cb,
863 void *data)
864{
865 struct child_process cmd = CHILD_PROCESS_INIT;
866 struct strbuf line = STRBUF_INIT;
867 FILE *fh;
868
869 fill_alternate_refs_command(&cmd, path);
870
871 if (start_command(&cmd))
872 return;
873
874 fh = xfdopen(cmd.out, "r");
875 while (strbuf_getline_lf(&line, fh) != EOF) {
876 struct object_id oid;
877 const char *p;
878
879 if (parse_oid_hex(line.buf, &oid, &p) || *p) {
880 warning(_("invalid line while parsing alternate refs: %s"),
881 line.buf);
882 break;
883 }
884
885 cb(&oid, data);
886 }
887
888 fclose(fh);
889 finish_command(&cmd);
86ad3ea5 890 strbuf_release(&line);
709dfa69
JK
891}
892
893struct alternate_refs_data {
894 alternate_ref_fn *fn;
895 void *data;
896};
897
898static int refs_from_alternate_cb(struct object_directory *e,
899 void *data)
900{
901 struct strbuf path = STRBUF_INIT;
902 size_t base_len;
903 struct alternate_refs_data *cb = data;
904
905 if (!strbuf_realpath(&path, e->path, 0))
906 goto out;
907 if (!strbuf_strip_suffix(&path, "/objects"))
908 goto out;
909 base_len = path.len;
910
911 /* Is this a git repository with refs? */
912 strbuf_addstr(&path, "/refs");
913 if (!is_directory(path.buf))
914 goto out;
915 strbuf_setlen(&path, base_len);
916
917 read_alternate_refs(path.buf, cb->fn, cb->data);
918
919out:
920 strbuf_release(&path);
921 return 0;
922}
923
924void for_each_alternate_ref(alternate_ref_fn fn, void *data)
925{
926 struct alternate_refs_data cb;
927 cb.fn = fn;
928 cb.data = data;
929 foreach_alt_odb(refs_from_alternate_cb, &cb);
930}
931
fe1b2268 932int foreach_alt_odb(alt_odb_fn fn, void *cb)
d79796bc 933{
263db403 934 struct object_directory *ent;
fe1b2268 935 int r = 0;
d79796bc 936
0b209034 937 prepare_alt_odb(the_repository);
f0eaf638 938 for (ent = the_repository->objects->odb->next; ent; ent = ent->next) {
fe1b2268
JK
939 r = fn(ent, cb);
940 if (r)
941 break;
942 }
943 return r;
d79796bc
JH
944}
945
13068bf0 946void prepare_alt_odb(struct repository *r)
c2f493a4 947{
f0eaf638 948 if (r->objects->loaded_alternates)
7dc24aa5
SP
949 return;
950
13068bf0 951 link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
c2f493a4 952
f0eaf638
JK
953 read_info_alternates(r, r->objects->odb->path, 0);
954 r->objects->loaded_alternates = 1;
c2f493a4
MW
955}
956
d85cd187
PS
957int has_alt_odb(struct repository *r)
958{
959 prepare_alt_odb(r);
960 return !!r->objects->odb->next;
961}
962
3096b2ec 963/* Returns 1 if we have successfully freshened the file, 0 otherwise. */
33d4221c 964static int freshen_file(const char *fn)
ace1534d 965{
312cd761 966 return !utime(fn, NULL);
0f4dc14a 967}
ace1534d 968
3096b2ec
JK
969/*
970 * All of the check_and_freshen functions return 1 if the file exists and was
971 * freshened (if freshening was requested), 0 otherwise. If they return
972 * 0, you should not assume that it is safe to skip a write of the object (it
973 * either does not exist on disk, or has a stale mtime and may be subject to
974 * pruning).
975 */
6a5e6f5e 976int check_and_freshen_file(const char *fn, int freshen)
33d4221c
JK
977{
978 if (access(fn, F_OK))
979 return 0;
3096b2ec 980 if (freshen && !freshen_file(fn))
33d4221c
JK
981 return 0;
982 return 1;
983}
984
f0eaf638
JK
985static int check_and_freshen_odb(struct object_directory *odb,
986 const struct object_id *oid,
987 int freshen)
33d4221c 988{
f0eaf638 989 static struct strbuf path = STRBUF_INIT;
514c5fdd 990 odb_loose_path(odb, &path, oid);
f0eaf638
JK
991 return check_and_freshen_file(path.buf, freshen);
992}
ea657730 993
f0eaf638
JK
994static int check_and_freshen_local(const struct object_id *oid, int freshen)
995{
996 return check_and_freshen_odb(the_repository->objects->odb, oid, freshen);
33d4221c
JK
997}
998
6862ebbf 999static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
0f4dc14a 1000{
263db403 1001 struct object_directory *odb;
f3f043a1 1002
0b209034 1003 prepare_alt_odb(the_repository);
f0eaf638
JK
1004 for (odb = the_repository->objects->odb->next; odb; odb = odb->next) {
1005 if (check_and_freshen_odb(odb, oid, freshen))
c529d75a 1006 return 1;
ace1534d 1007 }
c529d75a 1008 return 0;
ace1534d
JH
1009}
1010
6862ebbf 1011static int check_and_freshen(const struct object_id *oid, int freshen)
33d4221c 1012{
6862ebbf 1013 return check_and_freshen_local(oid, freshen) ||
1014 check_and_freshen_nonlocal(oid, freshen);
33d4221c
JK
1015}
1016
6862ebbf 1017int has_loose_object_nonlocal(const struct object_id *oid)
33d4221c 1018{
6862ebbf 1019 return check_and_freshen_nonlocal(oid, 0);
33d4221c
JK
1020}
1021
b7573536 1022int has_loose_object(const struct object_id *oid)
0f4dc14a 1023{
6862ebbf 1024 return check_and_freshen(oid, 0);
0f4dc14a
BC
1025}
1026
02710228
SP
1027static void mmap_limit_check(size_t length)
1028{
1029 static size_t limit = 0;
1030 if (!limit) {
1031 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
1032 if (!limit)
1033 limit = SIZE_MAX;
1034 }
1035 if (length > limit)
259328b7 1036 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX),
02710228
SP
1037 (uintmax_t)length, (uintmax_t)limit);
1038}
1039
1570856b
JK
1040void *xmmap_gently(void *start, size_t length,
1041 int prot, int flags, int fd, off_t offset)
58ecbd5e 1042{
02710228
SP
1043 void *ret;
1044
1045 mmap_limit_check(length);
1046 ret = mmap(start, length, prot, flags, fd, offset);
9827d4c1
JK
1047 if (ret == MAP_FAILED && !length)
1048 ret = NULL;
58ecbd5e
JN
1049 return ret;
1050}
1051
dc059294
EW
1052const char *mmap_os_err(void)
1053{
1054 static const char blank[] = "";
1055#if defined(__linux__)
1056 if (errno == ENOMEM) {
1057 /* this continues an existing error message: */
1058 static const char enomem[] =
1059", check sys.vm.max_map_count and/or RLIMIT_DATA";
1060 return enomem;
1061 }
1062#endif /* OS-specific bits */
1063 return blank;
1064}
1065
1570856b
JK
1066void *xmmap(void *start, size_t length,
1067 int prot, int flags, int fd, off_t offset)
1068{
1069 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
1070 if (ret == MAP_FAILED)
dc059294 1071 die_errno(_("mmap failed%s"), mmap_os_err());
1570856b
JK
1072 return ret;
1073}
1074
b04cdea4
ÆAB
1075static int format_object_header_literally(char *str, size_t size,
1076 const char *type, size_t objsize)
1077{
1078 return xsnprintf(str, size, "%s %"PRIuMAX, type, (uintmax_t)objsize) + 1;
1079}
1080
1081int format_object_header(char *str, size_t size, enum object_type type,
1082 size_t objsize)
1083{
1084 const char *name = type_name(type);
1085
1086 if (!name)
1087 BUG("could not get a type name for 'enum object_type' value %d", type);
1088
1089 return format_object_header_literally(str, size, name, objsize);
1090}
1091
b98d1885 1092int check_object_signature(struct repository *r, const struct object_id *oid,
44439c1c
ÆAB
1093 void *buf, unsigned long size,
1094 enum object_type type)
88d0db55 1095{
0f156dbb
ÆAB
1096 struct object_id real_oid;
1097
1098 hash_object_file(r->hash_algo, buf, size, type, &real_oid);
1099
1100 return !oideq(oid, &real_oid) ? -1 : 0;
1101}
1102
1103int stream_object_signature(struct repository *r, const struct object_id *oid)
1104{
1105 struct object_id real_oid;
1106 unsigned long size;
090ea126
NTND
1107 enum object_type obj_type;
1108 struct git_istream *st;
18e2588e 1109 git_hash_ctx c;
1af64f73 1110 char hdr[MAX_HEADER_LEN];
090ea126 1111 int hdrlen;
88d0db55 1112
b98d1885 1113 st = open_istream(r, oid, &obj_type, &size, NULL);
090ea126
NTND
1114 if (!st)
1115 return -1;
88d0db55 1116
090ea126 1117 /* Generate the header */
b04cdea4 1118 hdrlen = format_object_header(hdr, sizeof(hdr), obj_type, size);
88d0db55 1119
090ea126 1120 /* Sha1.. */
b98d1885
MT
1121 r->hash_algo->init_fn(&c);
1122 r->hash_algo->update_fn(&c, hdr, hdrlen);
090ea126
NTND
1123 for (;;) {
1124 char buf[1024 * 16];
1125 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1f688557 1126
f54fac53
JK
1127 if (readlen < 0) {
1128 close_istream(st);
1129 return -1;
1130 }
090ea126
NTND
1131 if (!readlen)
1132 break;
b98d1885 1133 r->hash_algo->update_fn(&c, buf, readlen);
fa5fc15d 1134 }
0f156dbb 1135 r->hash_algo->final_oid_fn(&real_oid, &c);
090ea126 1136 close_istream(st);
0f156dbb 1137 return !oideq(oid, &real_oid) ? -1 : 0;
fa5fc15d
SP
1138}
1139
1b8ac5ea 1140int git_open_cloexec(const char *name, int flags)
a0788266 1141{
1e3001a8
JH
1142 int fd;
1143 static int o_cloexec = O_CLOEXEC;
a0788266 1144
1e3001a8
JH
1145 fd = open(name, flags | o_cloexec);
1146 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
cd66ada0 1147 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1e3001a8
JH
1148 o_cloexec &= ~O_CLOEXEC;
1149 fd = open(name, flags | o_cloexec);
491a8dec 1150 }
491a8dec 1151
9fb9495d 1152#if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
491a8dec 1153 {
1e3001a8 1154 static int fd_cloexec = FD_CLOEXEC;
a0788266 1155
1e3001a8
JH
1156 if (!o_cloexec && 0 <= fd && fd_cloexec) {
1157 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
9fb9495d
EW
1158 int flags = fcntl(fd, F_GETFD);
1159 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
1e3001a8 1160 fd_cloexec = 0;
cd66ada0 1161 }
44d1c19e 1162 }
a0788266 1163#endif
1b8ac5ea 1164 return fd;
a0788266
JS
1165}
1166
3cf8b462 1167/*
514c5fdd 1168 * Find "oid" as a loose object in the local repository or in an alternate.
771e7d57
JK
1169 * Returns 0 on success, negative on failure.
1170 *
1171 * The "path" out-parameter will give the path of the object we found (if any).
1172 * Note that it may point to static storage and is only valid until another
514c5fdd 1173 * call to stat_loose_object().
3cf8b462 1174 */
514c5fdd
JK
1175static int stat_loose_object(struct repository *r, const struct object_id *oid,
1176 struct stat *st, const char **path)
1f688557 1177{
263db403 1178 struct object_directory *odb;
ea657730
CC
1179 static struct strbuf buf = STRBUF_INIT;
1180
d2607fa0 1181 prepare_alt_odb(r);
f0eaf638 1182 for (odb = r->objects->odb; odb; odb = odb->next) {
514c5fdd 1183 *path = odb_loose_path(odb, &buf, oid);
771e7d57 1184 if (!lstat(*path, st))
052fe5ea 1185 return 0;
c7934306
SP
1186 }
1187
3cf8b462
SP
1188 return -1;
1189}
1190
771e7d57 1191/*
514c5fdd 1192 * Like stat_loose_object(), but actually open the object and return the
771e7d57
JK
1193 * descriptor. See the caveats on the "path" parameter above.
1194 */
514c5fdd
JK
1195static int open_loose_object(struct repository *r,
1196 const struct object_id *oid, const char **path)
60bb8b14 1197{
44d1c19e 1198 int fd;
263db403 1199 struct object_directory *odb;
f0eaf638 1200 int most_interesting_errno = ENOENT;
ea657730
CC
1201 static struct strbuf buf = STRBUF_INIT;
1202
ec7283e5 1203 prepare_alt_odb(r);
f0eaf638 1204 for (odb = r->objects->odb; odb; odb = odb->next) {
514c5fdd 1205 *path = odb_loose_path(odb, &buf, oid);
771e7d57 1206 fd = git_open(*path);
44d1c19e
LT
1207 if (fd >= 0)
1208 return fd;
f0eaf638 1209
d6c8a05b
JK
1210 if (most_interesting_errno == ENOENT)
1211 most_interesting_errno = errno;
03e79c88 1212 }
d6c8a05b 1213 errno = most_interesting_errno;
44d1c19e 1214 return -1;
1f688557
JH
1215}
1216
61c7711c 1217static int quick_has_loose(struct repository *r,
d7a24573 1218 const struct object_id *oid)
61c7711c 1219{
61c7711c
JK
1220 struct object_directory *odb;
1221
61c7711c
JK
1222 prepare_alt_odb(r);
1223 for (odb = r->objects->odb; odb; odb = odb->next) {
92d8ed8a 1224 if (oidtree_contains(odb_loose_cache(odb, oid), oid))
61c7711c
JK
1225 return 1;
1226 }
1227 return 0;
1228}
1229
f6371f92 1230/*
ae285ac4
JT
1231 * Map and close the given loose object fd. The path argument is used for
1232 * error reporting.
f6371f92 1233 */
ae285ac4 1234static void *map_fd(int fd, const char *path, unsigned long *size)
27d69a46 1235{
ae285ac4
JT
1236 void *map = NULL;
1237 struct stat st;
1f688557 1238
ae285ac4
JT
1239 if (!fstat(fd, &st)) {
1240 *size = xsize_t(st.st_size);
1241 if (!*size) {
1242 /* mmap() is forbidden on empty files */
1243 error(_("object file %s is empty"), path);
1244 close(fd);
1245 return NULL;
144bde78 1246 }
ae285ac4 1247 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
74e34e1f 1248 }
ae285ac4 1249 close(fd);
0fcfd160 1250 return map;
74e34e1f
NP
1251}
1252
514c5fdd
JK
1253void *map_loose_object(struct repository *r,
1254 const struct object_id *oid,
1255 unsigned long *size)
068f85e3 1256{
ae285ac4
JT
1257 const char *p;
1258 int fd = open_loose_object(r, oid, &p);
1259
1260 if (fd < 0)
1261 return NULL;
1262 return map_fd(fd, p, size);
068f85e3 1263}
1264
3b6a8db3
ÆAB
1265enum unpack_loose_header_result unpack_loose_header(git_zstream *stream,
1266 unsigned char *map,
1267 unsigned long mapsize,
1268 void *buffer,
1269 unsigned long bufsiz,
1270 struct strbuf *header)
47fe3f6e 1271{
01cab976 1272 int status;
31877c9a 1273
c4483576
LT
1274 /* Get the data stream */
1275 memset(stream, 0, sizeof(*stream));
1276 stream->next_in = map;
1277 stream->avail_in = mapsize;
1278 stream->next_out = buffer;
93821bd9 1279 stream->avail_out = bufsiz;
47fe3f6e 1280
39c68542 1281 git_inflate_init(stream);
31877c9a 1282 obj_read_unlock();
01cab976 1283 status = git_inflate(stream, 0);
31877c9a 1284 obj_read_lock();
d21f8426 1285 if (status < Z_OK)
3b6a8db3 1286 return ULHR_BAD;
d131b7af 1287
46f03448
KN
1288 /*
1289 * Check if entire header is unpacked in the first iteration.
d131b7af 1290 */
46f03448 1291 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
3b6a8db3 1292 return ULHR_OK;
d131b7af 1293
01cab976
ÆAB
1294 /*
1295 * We have a header longer than MAX_HEADER_LEN. The "header"
1296 * here is only non-NULL when we run "cat-file
1297 * --allow-unknown-type".
1298 */
1299 if (!header)
5848fb11 1300 return ULHR_TOO_LONG;
d131b7af 1301
46f03448
KN
1302 /*
1303 * buffer[0..bufsiz] was not large enough. Copy the partial
1304 * result out to header, and then append the result of further
1305 * reading the stream.
1306 */
1307 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1308 stream->next_out = buffer;
1309 stream->avail_out = bufsiz;
d131b7af 1310
46f03448 1311 do {
31877c9a 1312 obj_read_unlock();
46f03448 1313 status = git_inflate(stream, 0);
31877c9a 1314 obj_read_lock();
46f03448
KN
1315 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1316 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1317 return 0;
1318 stream->next_out = buffer;
1319 stream->avail_out = bufsiz;
1320 } while (status != Z_STREAM_END);
5848fb11 1321 return ULHR_TOO_LONG;
d131b7af
SP
1322}
1323
00a7760e
JK
1324static void *unpack_loose_rest(git_zstream *stream,
1325 void *buffer, unsigned long size,
1326 const struct object_id *oid)
95099731 1327{
5180cacc 1328 int bytes = strlen(buffer) + 1;
3aee68aa 1329 unsigned char *buf = xmallocz(size);
93821bd9 1330 unsigned long n;
7efbff75 1331 int status = Z_OK;
95099731 1332
93821bd9
LT
1333 n = stream->total_out - bytes;
1334 if (n > size)
1335 n = size;
1336 memcpy(buf, (char *) buffer + bytes, n);
1337 bytes = n;
456cdf6e
LT
1338 if (bytes <= size) {
1339 /*
1340 * The above condition must be (bytes <= size), not
1341 * (bytes < size). In other words, even though we
ccf5ace0 1342 * expect no more output and set avail_out to zero,
456cdf6e
LT
1343 * the input zlib stream may have bytes that express
1344 * "this concludes the stream", and we *do* want to
1345 * eat that input.
1346 *
1347 * Otherwise we would not be able to test that we
1348 * consumed all the input to reach the expected size;
1349 * we also want to check that zlib tells us that all
1350 * went well with status == Z_STREAM_END at the end.
1351 */
5180cacc
LT
1352 stream->next_out = buf + bytes;
1353 stream->avail_out = size - bytes;
31877c9a
MT
1354 while (status == Z_OK) {
1355 obj_read_unlock();
39c68542 1356 status = git_inflate(stream, Z_FINISH);
31877c9a
MT
1357 obj_read_lock();
1358 }
5180cacc 1359 }
456cdf6e 1360 if (status == Z_STREAM_END && !stream->avail_in) {
39c68542 1361 git_inflate_end(stream);
7efbff75 1362 return buf;
95099731
NTND
1363 }
1364
7efbff75 1365 if (status < 0)
00a7760e 1366 error(_("corrupt loose object '%s'"), oid_to_hex(oid));
7efbff75 1367 else if (stream->avail_in)
259328b7 1368 error(_("garbage at end of loose object '%s'"),
00a7760e 1369 oid_to_hex(oid));
7efbff75
JH
1370 free(buf);
1371 return NULL;
95099731
NTND
1372}
1373
d40d535b 1374/*
5180cacc
LT
1375 * We used to just use "sscanf()", but that's actually way
1376 * too permissive for what we want to check. So do an anal
1377 * object header parse by hand.
d40d535b 1378 */
dccb32bf 1379int parse_loose_header(const char *hdr, struct object_info *oi)
1f688557 1380{
46f03448 1381 const char *type_buf = hdr;
d6a09e79 1382 size_t size;
46f03448 1383 int type, type_len = 0;
43057304 1384
5180cacc 1385 /*
46f03448 1386 * The type can be of any size but is followed by
21666f1a 1387 * a space.
5180cacc 1388 */
5180cacc
LT
1389 for (;;) {
1390 char c = *hdr++;
d21f8426
JH
1391 if (!c)
1392 return -1;
5180cacc
LT
1393 if (c == ' ')
1394 break;
46f03448 1395 type_len++;
5180cacc 1396 }
1f688557 1397
46f03448 1398 type = type_from_string_gently(type_buf, type_len, 1);
6ca32f47
BW
1399 if (oi->type_name)
1400 strbuf_add(oi->type_name, type_buf, type_len);
46f03448
KN
1401 if (oi->typep)
1402 *oi->typep = type;
5180cacc
LT
1403
1404 /*
1405 * The length must follow immediately, and be in canonical
1406 * decimal format (ie "010" is not valid).
1407 */
1408 size = *hdr++ - '0';
1409 if (size > 9)
1410 return -1;
1411 if (size) {
1412 for (;;) {
1413 unsigned long c = *hdr - '0';
1414 if (c > 9)
1415 break;
1416 hdr++;
d6a09e79 1417 size = st_add(st_mult(size, 10), c);
1b1005d1 1418 }
c01f51cc 1419 }
46f03448
KN
1420
1421 if (oi->sizep)
d6a09e79 1422 *oi->sizep = cast_size_t_to_ulong(size);
5180cacc
LT
1423
1424 /*
1425 * The length must be followed by a zero byte
1426 */
dccb32bf
ÆAB
1427 if (*hdr)
1428 return -1;
21666f1a 1429
dccb32bf
ÆAB
1430 /*
1431 * The format is valid, but the type may still be bogus. The
1432 * Caller needs to check its oi->typep.
1433 */
1434 return 0;
bf592c50
DB
1435}
1436
514c5fdd
JK
1437static int loose_object_info(struct repository *r,
1438 const struct object_id *oid,
1439 struct object_info *oi, int flags)
65c2e0c3 1440{
46f03448 1441 int status = 0;
9e59b38c 1442 int fd;
46f03448 1443 unsigned long mapsize;
9e59b38c 1444 const char *path;
65c2e0c3 1445 void *map;
ef49a7a0 1446 git_zstream stream;
1af64f73 1447 char hdr[MAX_HEADER_LEN];
46f03448 1448 struct strbuf hdrbuf = STRBUF_INIT;
c84a1f3e 1449 unsigned long size_scratch;
dccb32bf 1450 enum object_type type_scratch;
01cab976 1451 int allow_unknown = flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE;
65c2e0c3 1452
b99b6bcc
JK
1453 if (oi->delta_base_oid)
1454 oidclr(oi->delta_base_oid);
5d642e75 1455
052fe5ea
JK
1456 /*
1457 * If we don't care about type or size, then we don't
4ef8d1dd
JH
1458 * need to look inside the object at all. Note that we
1459 * do not optimize out the stat call, even if the
1460 * caller doesn't care about the disk-size, since our
1461 * return value implicitly indicates whether the
1462 * object even exists.
052fe5ea 1463 */
6ca32f47 1464 if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
4ef8d1dd 1465 struct stat st;
61c7711c 1466 if (!oi->disk_sizep && (flags & OBJECT_INFO_QUICK))
d7a24573 1467 return quick_has_loose(r, oid) ? 0 : -1;
514c5fdd 1468 if (stat_loose_object(r, oid, &st, &path) < 0)
4ef8d1dd
JH
1469 return -1;
1470 if (oi->disk_sizep)
23c339c0 1471 *oi->disk_sizep = st.st_size;
052fe5ea
JK
1472 return 0;
1473 }
1474
9e59b38c
JT
1475 fd = open_loose_object(r, oid, &path);
1476 if (fd < 0) {
1477 if (errno != ENOENT)
1478 error_errno(_("unable to open loose object %s"), oid_to_hex(oid));
1479 return -1;
1480 }
1481 map = map_fd(fd, path, &mapsize);
f0df4ed5 1482 if (!map)
dbea72a8 1483 return -1;
c84a1f3e
JT
1484
1485 if (!oi->sizep)
1486 oi->sizep = &size_scratch;
dccb32bf
ÆAB
1487 if (!oi->typep)
1488 oi->typep = &type_scratch;
c84a1f3e 1489
23c339c0
JK
1490 if (oi->disk_sizep)
1491 *oi->disk_sizep = mapsize;
01cab976 1492
3b6a8db3
ÆAB
1493 switch (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr),
1494 allow_unknown ? &hdrbuf : NULL)) {
1495 case ULHR_OK:
dccb32bf
ÆAB
1496 if (parse_loose_header(hdrbuf.len ? hdrbuf.buf : hdr, oi) < 0)
1497 status = error(_("unable to parse %s header"), oid_to_hex(oid));
1498 else if (!allow_unknown && *oi->typep < 0)
1499 die(_("invalid object type"));
1500
1501 if (!oi->contentp)
1502 break;
1503 *oi->contentp = unpack_loose_rest(&stream, hdr, *oi->sizep, oid);
1504 if (*oi->contentp)
1505 goto cleanup;
1506
1507 status = -1;
3b6a8db3
ÆAB
1508 break;
1509 case ULHR_BAD:
259328b7 1510 status = error(_("unable to unpack %s header"),
514c5fdd 1511 oid_to_hex(oid));
3b6a8db3 1512 break;
5848fb11
ÆAB
1513 case ULHR_TOO_LONG:
1514 status = error(_("header for %s too long, exceeds %d bytes"),
1515 oid_to_hex(oid), MAX_HEADER_LEN);
1516 break;
3b6a8db3 1517 }
c84a1f3e 1518
9e59b38c
JT
1519 if (status && (flags & OBJECT_INFO_DIE_IF_CORRUPT))
1520 die(_("loose object %s (stored in %s) is corrupt"),
1521 oid_to_hex(oid), path);
1522
dccb32bf
ÆAB
1523 git_inflate_end(&stream);
1524cleanup:
65c2e0c3 1525 munmap(map, mapsize);
c84a1f3e
JT
1526 if (oi->sizep == &size_scratch)
1527 oi->sizep = NULL;
46f03448 1528 strbuf_release(&hdrbuf);
dccb32bf
ÆAB
1529 if (oi->typep == &type_scratch)
1530 oi->typep = NULL;
3ab0fb06 1531 oi->whence = OI_LOOSE;
dccb32bf 1532 return status;
65c2e0c3
JH
1533}
1534
31877c9a
MT
1535int obj_read_use_lock = 0;
1536pthread_mutex_t obj_read_mutex;
1537
1538void enable_obj_read_lock(void)
1539{
1540 if (obj_read_use_lock)
1541 return;
1542
1543 obj_read_use_lock = 1;
1544 init_recursive_mutex(&obj_read_mutex);
1545}
1546
1547void disable_obj_read_lock(void)
1548{
1549 if (!obj_read_use_lock)
1550 return;
1551
1552 obj_read_use_lock = 0;
1553 pthread_mutex_destroy(&obj_read_mutex);
1554}
1555
8b4c0103
JT
1556int fetch_if_missing = 1;
1557
31877c9a
MT
1558static int do_oid_object_info_extended(struct repository *r,
1559 const struct object_id *oid,
1560 struct object_info *oi, unsigned flags)
f0df4ed5 1561{
cd585e2a 1562 static struct object_info blank_oi = OBJECT_INFO_INIT;
9c8a294a 1563 struct cached_object *co;
f0df4ed5 1564 struct pack_entry e;
5b086407 1565 int rtype;
b383a13c 1566 const struct object_id *real = oid;
8b4c0103 1567 int already_retried = 0;
f0df4ed5 1568
31877c9a 1569
b383a13c 1570 if (flags & OBJECT_INFO_LOOKUP_REPLACE)
9d98354f 1571 real = lookup_replace_object(r, oid);
f0df4ed5 1572
b383a13c 1573 if (is_null_oid(real))
87b5e236
JK
1574 return -1;
1575
cd585e2a
JT
1576 if (!oi)
1577 oi = &blank_oi;
1578
9c8a294a
JT
1579 co = find_cached_object(real);
1580 if (co) {
1581 if (oi->typep)
1582 *(oi->typep) = co->type;
1583 if (oi->sizep)
1584 *(oi->sizep) = co->size;
1585 if (oi->disk_sizep)
1586 *(oi->disk_sizep) = 0;
b99b6bcc
JK
1587 if (oi->delta_base_oid)
1588 oidclr(oi->delta_base_oid);
9c8a294a
JT
1589 if (oi->type_name)
1590 strbuf_addstr(oi->type_name, type_name(co->type));
1591 if (oi->contentp)
1592 *oi->contentp = xmemdupz(co->buf, co->size);
1593 oi->whence = OI_CACHED;
1594 return 0;
c4d9986f
NTND
1595 }
1596
8b4c0103 1597 while (1) {
42c8ce1c 1598 if (find_pack_entry(r, real, &e))
8b4c0103
JT
1599 break;
1600
ddd63e64 1601 /* Most likely it's a loose object. */
514c5fdd 1602 if (!loose_object_info(r, real, oi, flags))
5b086407 1603 return 0;
ddd63e64
SG
1604
1605 /* Not a loose object; someone else may have just packed it. */
2b7750c9 1606 if (!(flags & OBJECT_INFO_QUICK)) {
9d98354f 1607 reprepare_packed_git(r);
42c8ce1c 1608 if (find_pack_entry(r, real, &e))
2b7750c9
JT
1609 break;
1610 }
8b4c0103 1611
eef71904
JT
1612 /*
1613 * If r is the_repository, this might be an attempt at
1614 * accessing a submodule object as if it were in the_repository
1615 * (having called add_submodule_odb() on that submodule's ODB).
1616 * If any such ODBs exist, register them and try again.
1617 */
1618 if (r == the_repository &&
1619 register_all_submodule_odb_as_alternates())
a35e03de
JT
1620 /* We added some alternates; retry */
1621 continue;
1622
8b4c0103 1623 /* Check if it is a missing object */
ef830cc4
JT
1624 if (fetch_if_missing && repo_has_promisor_remote(r) &&
1625 !already_retried &&
31f5256c 1626 !(flags & OBJECT_INFO_SKIP_FETCH_OBJECT)) {
b14ed5ad 1627 promisor_remote_get_direct(r, real, 1);
8b4c0103
JT
1628 already_retried = 1;
1629 continue;
dfdd4afc 1630 }
8b4c0103 1631
9e59b38c
JT
1632 if (flags & OBJECT_INFO_DIE_IF_CORRUPT) {
1633 const struct packed_git *p;
1634 if ((flags & OBJECT_INFO_LOOKUP_REPLACE) && !oideq(real, oid))
1635 die(_("replacement %s not found for %s"),
1636 oid_to_hex(real), oid_to_hex(oid));
1637 if ((p = has_packed_and_bad(r, real)))
1638 die(_("packed object %s (stored in %s) is corrupt"),
1639 oid_to_hex(real), p->pack_name);
1640 }
8b4c0103 1641 return -1;
f0df4ed5 1642 }
3d77d877 1643
cd585e2a
JT
1644 if (oi == &blank_oi)
1645 /*
1646 * We know that the caller doesn't actually need the
1647 * information below, so return early.
1648 */
1649 return 0;
9d98354f 1650 rtype = packed_object_info(r, e.p, e.offset, oi);
412916ee 1651 if (rtype < 0) {
751530de 1652 mark_bad_packed_object(e.p, real);
31877c9a 1653 return do_oid_object_info_extended(r, real, oi, 0);
3ab0fb06 1654 } else if (oi->whence == OI_PACKED) {
9a490590
JH
1655 oi->u.packed.offset = e.offset;
1656 oi->u.packed.pack = e.p;
1657 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1658 rtype == OBJ_OFS_DELTA);
3d77d877
NP
1659 }
1660
5b086407 1661 return 0;
f0df4ed5
JS
1662}
1663
31877c9a
MT
1664int oid_object_info_extended(struct repository *r, const struct object_id *oid,
1665 struct object_info *oi, unsigned flags)
1666{
1667 int ret;
1668 obj_read_lock();
1669 ret = do_oid_object_info_extended(r, oid, oi, flags);
1670 obj_read_unlock();
1671 return ret;
1672}
1673
1674
3fc0dca9 1675/* returns enum object_type or negative */
9d98354f
SB
1676int oid_object_info(struct repository *r,
1677 const struct object_id *oid,
1678 unsigned long *sizep)
9a490590 1679{
5b086407 1680 enum object_type type;
27b5c1a0 1681 struct object_info oi = OBJECT_INFO_INIT;
9a490590 1682
5b086407 1683 oi.typep = &type;
9a490590 1684 oi.sizep = sizep;
9d98354f
SB
1685 if (oid_object_info_extended(r, oid, &oi,
1686 OBJECT_INFO_LOOKUP_REPLACE) < 0)
5b086407
JK
1687 return -1;
1688 return type;
9a490590
JH
1689}
1690
829e5c3b
PO
1691int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1692 struct object_id *oid)
d66b37bb
JH
1693{
1694 struct cached_object *co;
1695
44439c1c 1696 hash_object_file(the_hash_algo, buf, len, type, oid);
bc726bd0 1697 if (repo_has_object_file_with_flags(the_repository, oid, OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT) ||
a64d2aae 1698 find_cached_object(oid))
d66b37bb 1699 return 0;
c7353967 1700 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
d66b37bb
JH
1701 co = &cached_objects[cached_object_nr++];
1702 co->size = len;
21666f1a 1703 co->type = type;
efa13f7b
JH
1704 co->buf = xmalloc(len);
1705 memcpy(co->buf, buf, len);
62ba93ea 1706 oidcpy(&co->oid, oid);
d66b37bb
JH
1707 return 0;
1708}
1709
b6c4cecc
JH
1710/*
1711 * This function dies on corrupt objects; the callers who want to
b25562e6
JK
1712 * deal with them should arrange to call oid_object_info_extended() and give
1713 * error messages themselves.
b6c4cecc 1714 */
0ba05cf2
JK
1715void *repo_read_object_file(struct repository *r,
1716 const struct object_id *oid,
1717 enum object_type *type,
1718 unsigned long *size)
ac939109 1719{
b25562e6 1720 struct object_info oi = OBJECT_INFO_INIT;
7be13f5f 1721 unsigned flags = OBJECT_INFO_DIE_IF_CORRUPT | OBJECT_INFO_LOOKUP_REPLACE;
3ba7a065 1722 void *data;
b6c4cecc 1723
b25562e6
JK
1724 oi.typep = type;
1725 oi.sizep = size;
1726 oi.contentp = &data;
b25562e6 1727 if (oid_object_info_extended(r, oid, &oi, flags))
15b63689 1728 return NULL;
68095570 1729
b25562e6 1730 return data;
ac939109
NP
1731}
1732
d3b4705a
NTND
1733void *read_object_with_reference(struct repository *r,
1734 const struct object_id *oid,
6aea6bae 1735 enum object_type required_type,
40469ee9 1736 unsigned long *size,
02f0547e 1737 struct object_id *actual_oid_return)
f4913f91 1738{
6aea6bae 1739 enum object_type type;
f4913f91
JH
1740 void *buffer;
1741 unsigned long isize;
02f0547e 1742 struct object_id actual_oid;
f4913f91 1743
02f0547e 1744 oidcpy(&actual_oid, oid);
40469ee9
JH
1745 while (1) {
1746 int ref_length = -1;
1747 const char *ref_type = NULL;
f4913f91 1748
d3b4705a 1749 buffer = repo_read_object_file(r, &actual_oid, &type, &isize);
40469ee9
JH
1750 if (!buffer)
1751 return NULL;
21666f1a 1752 if (type == required_type) {
40469ee9 1753 *size = isize;
02f0547e 1754 if (actual_oid_return)
1755 oidcpy(actual_oid_return, &actual_oid);
40469ee9
JH
1756 return buffer;
1757 }
1758 /* Handle references */
21666f1a 1759 else if (type == OBJ_COMMIT)
40469ee9 1760 ref_type = "tree ";
21666f1a 1761 else if (type == OBJ_TAG)
40469ee9
JH
1762 ref_type = "object ";
1763 else {
1764 free(buffer);
1765 return NULL;
1766 }
1767 ref_length = strlen(ref_type);
f4913f91 1768
94b5e093 1769 if (ref_length + the_hash_algo->hexsz > isize ||
50974ec9 1770 memcmp(buffer, ref_type, ref_length) ||
02f0547e 1771 get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
40469ee9
JH
1772 free(buffer);
1773 return NULL;
1774 }
1cf58e72 1775 free(buffer);
40469ee9 1776 /* Now we have the ID of the referred-to object in
02f0547e 1777 * actual_oid. Check again. */
f4913f91 1778 }
f4913f91
JH
1779}
1780
2bbb28a3
ÆAB
1781static void hash_object_body(const struct git_hash_algo *algo, git_hash_ctx *c,
1782 const void *buf, unsigned long len,
1783 struct object_id *oid,
1784 char *hdr, int *hdrlen)
1785{
1786 algo->init_fn(c);
1787 algo->update_fn(c, hdr, *hdrlen);
1788 algo->update_fn(c, buf, len);
1789 algo->final_oid_fn(oid, c);
1790}
1791
7ad5c44d
MT
1792static void write_object_file_prepare(const struct git_hash_algo *algo,
1793 const void *buf, unsigned long len,
2bbb28a3 1794 enum object_type type, struct object_id *oid,
a09c985e 1795 char *hdr, int *hdrlen)
d410c0f5 1796{
18e2588e 1797 git_hash_ctx c;
d410c0f5
JH
1798
1799 /* Generate the header */
2bbb28a3 1800 *hdrlen = format_object_header(hdr, *hdrlen, type, len);
d410c0f5
JH
1801
1802 /* Sha1.. */
2bbb28a3
ÆAB
1803 hash_object_body(algo, &c, buf, len, oid, hdr, hdrlen);
1804}
1805
1806static void write_object_file_prepare_literally(const struct git_hash_algo *algo,
1807 const void *buf, unsigned long len,
1808 const char *type, struct object_id *oid,
1809 char *hdr, int *hdrlen)
1810{
1811 git_hash_ctx c;
1812
1813 *hdrlen = format_object_header_literally(hdr, *hdrlen, type, len);
1814 hash_object_body(algo, &c, buf, len, oid, hdr, hdrlen);
d410c0f5
JH
1815}
1816
230f1322 1817/*
5a688fe4 1818 * Move the just written object into its final resting place.
230f1322 1819 */
cb5add58 1820int finalize_object_file(const char *tmpfile, const char *filename)
230f1322 1821{
e32c0a9c 1822 int ret = 0;
5a688fe4 1823
348df166 1824 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
be66a6c4
JS
1825 goto try_rename;
1826 else if (link(tmpfile, filename))
e32c0a9c 1827 ret = errno;
7ebb6fca
LT
1828
1829 /*
1830 * Coda hack - coda doesn't like cross-directory links,
1831 * so we fall back to a rename, which will mean that it
1832 * won't be able to check collisions, but that's not a
1833 * big deal.
1834 *
1835 * The same holds for FAT formatted media.
1836 *
3be1f18e 1837 * When this succeeds, we just return. We have nothing
7ebb6fca
LT
1838 * left to unlink.
1839 */
1840 if (ret && ret != EEXIST) {
be66a6c4 1841 try_rename:
7ebb6fca 1842 if (!rename(tmpfile, filename))
3be1f18e 1843 goto out;
9e48b389 1844 ret = errno;
230f1322 1845 }
691f1a28 1846 unlink_or_warn(tmpfile);
230f1322
LT
1847 if (ret) {
1848 if (ret != EEXIST) {
2c319886 1849 return error_errno(_("unable to write file %s"), filename);
230f1322
LT
1850 }
1851 /* FIXME!!! Collision check here ? */
1852 }
1853
3be1f18e 1854out:
5256b006 1855 if (adjust_shared_perm(filename))
259328b7 1856 return error(_("unable to set permission to '%s'"), filename);
230f1322
LT
1857 return 0;
1858}
1859
44439c1c
ÆAB
1860static void hash_object_file_literally(const struct git_hash_algo *algo,
1861 const void *buf, unsigned long len,
1862 const char *type, struct object_id *oid)
abdc3fc8 1863{
1af64f73 1864 char hdr[MAX_HEADER_LEN];
ef1286d3 1865 int hdrlen = sizeof(hdr);
44439c1c 1866
2bbb28a3 1867 write_object_file_prepare_literally(algo, buf, len, type, oid, hdr, &hdrlen);
abdc3fc8
RS
1868}
1869
44439c1c
ÆAB
1870void hash_object_file(const struct git_hash_algo *algo, const void *buf,
1871 unsigned long len, enum object_type type,
1872 struct object_id *oid)
1873{
1874 hash_object_file_literally(algo, buf, len, type_name(type), oid);
abdc3fc8
RS
1875}
1876
e9039dd3 1877/* Finalize a file on disk, and close it. */
c4e707f8 1878static void close_loose_object(int fd, const char *filename)
e9039dd3 1879{
020406ea
NS
1880 if (the_repository->objects->odb->will_destroy)
1881 goto out;
b3cecf49 1882
c0f4752e 1883 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
83937e95 1884 fsync_loose_object_bulk_checkin(fd, filename);
c0f4752e 1885 else if (fsync_object_files > 0)
c4e707f8 1886 fsync_or_die(fd, filename);
020406ea
NS
1887 else
1888 fsync_component_or_die(FSYNC_COMPONENT_LOOSE_OBJECT, fd,
c4e707f8 1889 filename);
020406ea
NS
1890
1891out:
e9039dd3 1892 if (close(fd) != 0)
76011357 1893 die_errno(_("error when closing loose object file"));
e9039dd3
LT
1894}
1895
5723fe7e
LT
1896/* Size of directory component, including the ending '/' */
1897static inline int directory_size(const char *filename)
1898{
1899 const char *s = strrchr(filename, '/');
1900 if (!s)
1901 return 0;
1902 return s - filename + 1;
1903}
1904
1905/*
1906 * This creates a temporary file in the same directory as the final
1907 * 'filename'
1908 *
1909 * We want to avoid cross-directory filename renames, because those
1910 * can have problems on various filesystems (FAT, NFS, Coda).
1911 */
d4b3d11a 1912static int create_tmpfile(struct strbuf *tmp, const char *filename)
5723fe7e
LT
1913{
1914 int fd, dirlen = directory_size(filename);
1915
d4b3d11a
JK
1916 strbuf_reset(tmp);
1917 strbuf_add(tmp, filename, dirlen);
1918 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
1919 fd = git_mkstemp_mode(tmp->buf, 0444);
cbacbf4e 1920 if (fd < 0 && dirlen && errno == ENOENT) {
d4b3d11a
JK
1921 /*
1922 * Make sure the directory exists; note that the contents
1923 * of the buffer are undefined after mkstemp returns an
1924 * error, so we have to rewrite the whole buffer from
1925 * scratch.
1926 */
1927 strbuf_reset(tmp);
1928 strbuf_add(tmp, filename, dirlen - 1);
1929 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
b2476a60 1930 return -1;
d4b3d11a 1931 if (adjust_shared_perm(tmp->buf))
5723fe7e
LT
1932 return -1;
1933
1934 /* Try again */
d4b3d11a
JK
1935 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
1936 fd = git_mkstemp_mode(tmp->buf, 0444);
5723fe7e
LT
1937 }
1938 return fd;
1939}
1940
97a9db6f
HX
1941/**
1942 * Common steps for loose object writers to start writing loose
1943 * objects:
1944 *
1945 * - Create tmpfile for the loose object.
1946 * - Setup zlib stream for compression.
1947 * - Start to feed header to zlib stream.
1948 *
1949 * Returns a "fd", which should later be provided to
1950 * end_loose_object_common().
1951 */
1952static int start_loose_object_common(struct strbuf *tmp_file,
1953 const char *filename, unsigned flags,
1954 git_zstream *stream,
1955 unsigned char *buf, size_t buflen,
1956 git_hash_ctx *c,
1957 char *hdr, int hdrlen)
1958{
1959 int fd;
1960
1961 fd = create_tmpfile(tmp_file, filename);
1962 if (fd < 0) {
1963 if (flags & HASH_SILENT)
1964 return -1;
1965 else if (errno == EACCES)
1966 return error(_("insufficient permission for adding "
1967 "an object to repository database %s"),
1968 get_object_directory());
1969 else
1970 return error_errno(
1971 _("unable to create temporary file"));
1972 }
1973
1974 /* Setup zlib stream for compression */
1975 git_deflate_init(stream, zlib_compression_level);
1976 stream->next_out = buf;
1977 stream->avail_out = buflen;
1978 the_hash_algo->init_fn(c);
1979
1980 /* Start to feed header to zlib stream */
1981 stream->next_in = (unsigned char *)hdr;
1982 stream->avail_in = hdrlen;
1983 while (git_deflate(stream, 0) == Z_OK)
1984 ; /* nothing */
1985 the_hash_algo->update_fn(c, hdr, hdrlen);
1986
1987 return fd;
1988}
1989
21e7d881
ÆAB
1990/**
1991 * Common steps for the inner git_deflate() loop for writing loose
1992 * objects. Returns what git_deflate() returns.
1993 */
1994static int write_loose_object_common(git_hash_ctx *c,
1995 git_zstream *stream, const int flush,
1996 unsigned char *in0, const int fd,
1997 unsigned char *compressed,
1998 const size_t compressed_len)
1999{
2000 int ret;
2001
2002 ret = git_deflate(stream, flush ? Z_FINISH : 0);
2003 the_hash_algo->update_fn(c, in0, stream->next_in - in0);
d422d061
RS
2004 if (write_in_full(fd, compressed, stream->next_out - compressed) < 0)
2005 die_errno(_("unable to write loose object file"));
21e7d881
ÆAB
2006 stream->next_out = compressed;
2007 stream->avail_out = compressed_len;
2008
2009 return ret;
2010}
2011
97a9db6f
HX
2012/**
2013 * Common steps for loose object writers to end writing loose objects:
2014 *
2015 * - End the compression of zlib stream.
2016 * - Get the calculated oid to "oid".
2017 */
2018static int end_loose_object_common(git_hash_ctx *c, git_zstream *stream,
2019 struct object_id *oid)
2020{
2021 int ret;
2022
2023 ret = git_deflate_end_gently(stream);
2024 if (ret != Z_OK)
2025 return ret;
2026 the_hash_algo->final_oid_fn(oid, c);
2027
2028 return Z_OK;
2029}
2030
3fc7281f
PO
2031static int write_loose_object(const struct object_id *oid, char *hdr,
2032 int hdrlen, const void *buf, unsigned long len,
4ef91a2d 2033 time_t mtime, unsigned flags)
0fcfd160 2034{
915308b1 2035 int fd, ret;
9892beba 2036 unsigned char compressed[4096];
ef49a7a0 2037 git_zstream stream;
18e2588e 2038 git_hash_ctx c;
3fc7281f 2039 struct object_id parano_oid;
d4b3d11a 2040 static struct strbuf tmp_file = STRBUF_INIT;
ea657730
CC
2041 static struct strbuf filename = STRBUF_INIT;
2042
c0f4752e
NS
2043 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
2044 prepare_loose_object_bulk_checkin();
2045
514c5fdd 2046 loose_object_path(the_repository, &filename, oid);
a44c9a5e 2047
97a9db6f
HX
2048 fd = start_loose_object_common(&tmp_file, filename.buf, flags,
2049 &stream, compressed, sizeof(compressed),
2050 &c, hdr, hdrlen);
2051 if (fd < 0)
2052 return -1;
a44c9a5e
LT
2053
2054 /* Then the data itself.. */
c00e657d 2055 stream.next_in = (void *)buf;
a44c9a5e 2056 stream.avail_in = len;
9892beba 2057 do {
748af44c 2058 unsigned char *in0 = stream.next_in;
21e7d881
ÆAB
2059
2060 ret = write_loose_object_common(&c, &stream, 1, in0, fd,
2061 compressed, sizeof(compressed));
9892beba
NP
2062 } while (ret == Z_OK);
2063
ac54c277 2064 if (ret != Z_STREAM_END)
259328b7 2065 die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
3fc7281f 2066 ret);
97a9db6f 2067 ret = end_loose_object_common(&c, &stream, &parano_oid);
ac54c277 2068 if (ret != Z_OK)
259328b7 2069 die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
3fc7281f 2070 ret);
9001dc2a 2071 if (!oideq(oid, &parano_oid))
259328b7 2072 die(_("confused by unstable object source data for %s"),
3fc7281f 2073 oid_to_hex(oid));
ac54c277 2074
c4e707f8 2075 close_loose_object(fd, tmp_file.buf);
0fcfd160 2076
bbac7311
NP
2077 if (mtime) {
2078 struct utimbuf utb;
2079 utb.actime = mtime;
2080 utb.modtime = mtime;
4ef91a2d
ÆAB
2081 if (utime(tmp_file.buf, &utb) < 0 &&
2082 !(flags & HASH_SILENT))
259328b7 2083 warning_errno(_("failed utime() on %s"), tmp_file.buf);
bbac7311
NP
2084 }
2085
ea657730 2086 return finalize_object_file(tmp_file.buf, filename.buf);
0fcfd160 2087}
8237b185 2088
6862ebbf 2089static int freshen_loose_object(const struct object_id *oid)
33d4221c 2090{
6862ebbf 2091 return check_and_freshen(oid, 1);
33d4221c
JK
2092}
2093
6862ebbf 2094static int freshen_packed_object(const struct object_id *oid)
33d4221c
JK
2095{
2096 struct pack_entry e;
544443cb 2097 if (!find_pack_entry(the_repository, oid, &e))
ee1c6c34 2098 return 0;
a6131642
TB
2099 if (e.p->is_cruft)
2100 return 0;
ee1c6c34
JK
2101 if (e.p->freshened)
2102 return 1;
2103 if (!freshen_file(e.p->pack_name))
2104 return 0;
2105 e.p->freshened = 1;
2106 return 1;
33d4221c
JK
2107}
2108
2b6070ac
HX
2109int stream_loose_object(struct input_stream *in_stream, size_t len,
2110 struct object_id *oid)
2111{
2112 int fd, ret, err = 0, flush = 0;
2113 unsigned char compressed[4096];
2114 git_zstream stream;
2115 git_hash_ctx c;
2116 struct strbuf tmp_file = STRBUF_INIT;
2117 struct strbuf filename = STRBUF_INIT;
2118 int dirlen;
2119 char hdr[MAX_HEADER_LEN];
2120 int hdrlen;
2121
2122 if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
2123 prepare_loose_object_bulk_checkin();
2124
2125 /* Since oid is not determined, save tmp file to odb path. */
2126 strbuf_addf(&filename, "%s/", get_object_directory());
2127 hdrlen = format_object_header(hdr, sizeof(hdr), OBJ_BLOB, len);
2128
2129 /*
2130 * Common steps for write_loose_object and stream_loose_object to
2131 * start writing loose objects:
2132 *
2133 * - Create tmpfile for the loose object.
2134 * - Setup zlib stream for compression.
2135 * - Start to feed header to zlib stream.
2136 */
2137 fd = start_loose_object_common(&tmp_file, filename.buf, 0,
2138 &stream, compressed, sizeof(compressed),
2139 &c, hdr, hdrlen);
2140 if (fd < 0) {
2141 err = -1;
2142 goto cleanup;
2143 }
2144
2145 /* Then the data itself.. */
2146 do {
2147 unsigned char *in0 = stream.next_in;
2148
2149 if (!stream.avail_in && !in_stream->is_finished) {
2150 const void *in = in_stream->read(in_stream, &stream.avail_in);
2151 stream.next_in = (void *)in;
2152 in0 = (unsigned char *)in;
2153 /* All data has been read. */
2154 if (in_stream->is_finished)
2155 flush = 1;
2156 }
2157 ret = write_loose_object_common(&c, &stream, flush, in0, fd,
2158 compressed, sizeof(compressed));
2159 /*
2160 * Unlike write_loose_object(), we do not have the entire
2161 * buffer. If we get Z_BUF_ERROR due to too few input bytes,
2162 * then we'll replenish them in the next input_stream->read()
2163 * call when we loop.
2164 */
2165 } while (ret == Z_OK || ret == Z_BUF_ERROR);
2166
2167 if (stream.total_in != len + hdrlen)
2168 die(_("write stream object %ld != %"PRIuMAX), stream.total_in,
2169 (uintmax_t)len + hdrlen);
2170
2171 /*
2172 * Common steps for write_loose_object and stream_loose_object to
2173 * end writing loose oject:
2174 *
2175 * - End the compression of zlib stream.
2176 * - Get the calculated oid.
2177 */
2178 if (ret != Z_STREAM_END)
2179 die(_("unable to stream deflate new object (%d)"), ret);
2180 ret = end_loose_object_common(&c, &stream, oid);
2181 if (ret != Z_OK)
2182 die(_("deflateEnd on stream object failed (%d)"), ret);
2183 close_loose_object(fd, tmp_file.buf);
2184
2185 if (freshen_packed_object(oid) || freshen_loose_object(oid)) {
2186 unlink_or_warn(tmp_file.buf);
2187 goto cleanup;
2188 }
2189
2190 loose_object_path(the_repository, &filename, oid);
2191
2192 /* We finally know the object path, and create the missing dir. */
2193 dirlen = directory_size(filename.buf);
2194 if (dirlen) {
2195 struct strbuf dir = STRBUF_INIT;
2196 strbuf_add(&dir, filename.buf, dirlen);
2197
2198 if (mkdir_in_gitdir(dir.buf) && errno != EEXIST) {
2199 err = error_errno(_("unable to create directory %s"), dir.buf);
2200 strbuf_release(&dir);
2201 goto cleanup;
2202 }
2203 strbuf_release(&dir);
2204 }
2205
2206 err = finalize_object_file(tmp_file.buf, filename.buf);
2207cleanup:
2208 strbuf_release(&tmp_file);
2209 strbuf_release(&filename);
2210 return err;
2211}
2212
4ef91a2d 2213int write_object_file_flags(const void *buf, unsigned long len,
c80d226a 2214 enum object_type type, struct object_id *oid,
4ef91a2d 2215 unsigned flags)
bbac7311 2216{
1af64f73 2217 char hdr[MAX_HEADER_LEN];
ef1286d3 2218 int hdrlen = sizeof(hdr);
bbac7311
NP
2219
2220 /* Normally if we have it in the pack then we do not bother writing
2221 * it out into .git/objects/??/?{38} file.
2222 */
7ad5c44d
MT
2223 write_object_file_prepare(the_hash_algo, buf, len, type, oid, hdr,
2224 &hdrlen);
6862ebbf 2225 if (freshen_packed_object(oid) || freshen_loose_object(oid))
bbac7311 2226 return 0;
4ef91a2d 2227 return write_loose_object(oid, hdr, hdrlen, buf, len, 0, flags);
bbac7311
NP
2228}
2229
0ff7b4f9
ÆAB
2230int write_object_file_literally(const void *buf, unsigned long len,
2231 const char *type, struct object_id *oid,
2232 unsigned flags)
0c3db67c
ES
2233{
2234 char *header;
2235 int hdrlen, status = 0;
2236
2237 /* type string, SP, %lu of the length plus NUL must fit this */
1af64f73 2238 hdrlen = strlen(type) + MAX_HEADER_LEN;
ef1286d3 2239 header = xmalloc(hdrlen);
2bbb28a3
ÆAB
2240 write_object_file_prepare_literally(the_hash_algo, buf, len, type,
2241 oid, header, &hdrlen);
0c3db67c
ES
2242
2243 if (!(flags & HASH_WRITE_OBJECT))
2244 goto cleanup;
6862ebbf 2245 if (freshen_packed_object(oid) || freshen_loose_object(oid))
0c3db67c 2246 goto cleanup;
4ef91a2d 2247 status = write_loose_object(oid, header, hdrlen, buf, len, 0, 0);
0c3db67c
ES
2248
2249cleanup:
2250 free(header);
2251 return status;
2252}
2253
4bdb70a4 2254int force_object_loose(const struct object_id *oid, time_t mtime)
bbac7311 2255{
bbac7311
NP
2256 void *buf;
2257 unsigned long len;
b25562e6 2258 struct object_info oi = OBJECT_INFO_INIT;
bbac7311 2259 enum object_type type;
1af64f73 2260 char hdr[MAX_HEADER_LEN];
bbac7311 2261 int hdrlen;
1fb23e65 2262 int ret;
bbac7311 2263
6862ebbf 2264 if (has_loose_object(oid))
bbac7311 2265 return 0;
b25562e6
JK
2266 oi.typep = &type;
2267 oi.sizep = &len;
2268 oi.contentp = &buf;
2269 if (oid_object_info_extended(the_repository, oid, &oi, 0))
2c319886 2270 return error(_("cannot read object for %s"), oid_to_hex(oid));
b04cdea4 2271 hdrlen = format_object_header(hdr, sizeof(hdr), type, len);
4ef91a2d 2272 ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime, 0);
1fb23e65
BS
2273 free(buf);
2274
2275 return ret;
bbac7311
NP
2276}
2277
1d8d9cb6
JT
2278int has_object(struct repository *r, const struct object_id *oid,
2279 unsigned flags)
2280{
2281 int quick = !(flags & HAS_OBJECT_RECHECK_PACKED);
2282 unsigned object_info_flags = OBJECT_INFO_SKIP_FETCH_OBJECT |
2283 (quick ? OBJECT_INFO_QUICK : 0);
2284
2285 if (!startup_info->have_repository)
2286 return 0;
2287 return oid_object_info_extended(r, oid, NULL, object_info_flags) >= 0;
2288}
2289
cba595ab
JH
2290int repo_has_object_file_with_flags(struct repository *r,
2291 const struct object_id *oid, int flags)
8237b185 2292{
3e8b7d3c
JN
2293 if (!startup_info->have_repository)
2294 return 0;
9c8a294a 2295 return oid_object_info_extended(r, oid, NULL, flags) >= 0;
b419aa25 2296}
2297
9b45f499
SB
2298int repo_has_object_file(struct repository *r,
2299 const struct object_id *oid)
b419aa25 2300{
cba595ab 2301 return repo_has_object_file_with_flags(r, oid, 0);
5827a035
JK
2302}
2303
69bbbe48
JK
2304/*
2305 * We can't use the normal fsck_error_function() for index_mem(),
2306 * because we don't yet have a valid oid for it to report. Instead,
2307 * report the minimal fsck error here, and rely on the caller to
2308 * give more context.
2309 */
2310static int hash_format_check_report(struct fsck_options *opts,
2311 const struct object_id *oid,
2312 enum object_type object_type,
2313 enum fsck_msg_type msg_type,
2314 enum fsck_msg_id msg_id,
2315 const char *message)
2316{
2317 error(_("object fails fsck: %s"), message);
2318 return 1;
c879daa2
NTND
2319}
2320
58bf2a4c
NTND
2321static int index_mem(struct index_state *istate,
2322 struct object_id *oid, void *buf, size_t size,
c4ce46fc
JH
2323 enum object_type type,
2324 const char *path, unsigned flags)
e7332f96 2325{
63e05f90 2326 int ret = 0;
bbea0dde 2327 int re_allocated = 0;
c4ce46fc 2328 int write_object = flags & HASH_WRITE_OBJECT;
74400e71 2329
7672db20 2330 if (!type)
edaec3fb 2331 type = OBJ_BLOB;
6c510bee
LT
2332
2333 /*
2334 * Convert blobs to git internal format
2335 */
43df4f86 2336 if ((type == OBJ_BLOB) && path) {
f285a2d7 2337 struct strbuf nbuf = STRBUF_INIT;
58bf2a4c 2338 if (convert_to_git(istate, path, buf, size, &nbuf,
8462ff43 2339 get_conv_flags(flags))) {
b315c5c0 2340 buf = strbuf_detach(&nbuf, &size);
6c510bee
LT
2341 re_allocated = 1;
2342 }
2343 }
c4ce46fc 2344 if (flags & HASH_FORMAT_CHECK) {
69bbbe48
JK
2345 struct fsck_options opts = FSCK_OPTIONS_DEFAULT;
2346
2347 opts.strict = 1;
2348 opts.error_func = hash_format_check_report;
2349 if (fsck_buffer(null_oid(), type, buf, size, &opts))
2350 die(_("refusing to create malformed object"));
2351 fsck_finish(&opts);
c879daa2 2352 }
6c510bee 2353
7672db20 2354 if (write_object)
c80d226a 2355 ret = write_object_file(buf, size, type, oid);
abdc3fc8 2356 else
44439c1c 2357 hash_object_file(the_hash_algo, buf, size, type, oid);
43df4f86 2358 if (re_allocated)
6c510bee 2359 free(buf);
43df4f86
DP
2360 return ret;
2361}
2362
58bf2a4c
NTND
2363static int index_stream_convert_blob(struct index_state *istate,
2364 struct object_id *oid,
2365 int fd,
2366 const char *path,
2367 unsigned flags)
9035d75a 2368{
63e05f90 2369 int ret = 0;
9035d75a
SP
2370 const int write_object = flags & HASH_WRITE_OBJECT;
2371 struct strbuf sbuf = STRBUF_INIT;
2372
2373 assert(path);
58bf2a4c 2374 assert(would_convert_to_git_filter_fd(istate, path));
9035d75a 2375
58bf2a4c 2376 convert_to_git_filter_fd(istate, path, fd, &sbuf,
8462ff43 2377 get_conv_flags(flags));
9035d75a
SP
2378
2379 if (write_object)
c80d226a 2380 ret = write_object_file(sbuf.buf, sbuf.len, OBJ_BLOB,
a09c985e 2381 oid);
9035d75a 2382 else
44439c1c
ÆAB
2383 hash_object_file(the_hash_algo, sbuf.buf, sbuf.len, OBJ_BLOB,
2384 oid);
9035d75a
SP
2385 strbuf_release(&sbuf);
2386 return ret;
2387}
2388
58bf2a4c
NTND
2389static int index_pipe(struct index_state *istate, struct object_id *oid,
2390 int fd, enum object_type type,
7b41e1e1
JH
2391 const char *path, unsigned flags)
2392{
2393 struct strbuf sbuf = STRBUF_INIT;
2394 int ret;
2395
2396 if (strbuf_read(&sbuf, fd, 4096) >= 0)
58bf2a4c 2397 ret = index_mem(istate, oid, sbuf.buf, sbuf.len, type, path, flags);
7b41e1e1
JH
2398 else
2399 ret = -1;
2400 strbuf_release(&sbuf);
2401 return ret;
2402}
2403
ea68b0ce
DP
2404#define SMALL_FILE_SIZE (32*1024)
2405
58bf2a4c
NTND
2406static int index_core(struct index_state *istate,
2407 struct object_id *oid, int fd, size_t size,
7b41e1e1
JH
2408 enum object_type type, const char *path,
2409 unsigned flags)
43df4f86
DP
2410{
2411 int ret;
43df4f86 2412
7b41e1e1 2413 if (!size) {
58bf2a4c 2414 ret = index_mem(istate, oid, "", size, type, path, flags);
ea68b0ce
DP
2415 } else if (size <= SMALL_FILE_SIZE) {
2416 char *buf = xmalloc(size);
90dca671
JK
2417 ssize_t read_result = read_in_full(fd, buf, size);
2418 if (read_result < 0)
259328b7 2419 ret = error_errno(_("read error while indexing %s"),
90dca671
JK
2420 path ? path : "<unknown>");
2421 else if (read_result != size)
259328b7 2422 ret = error(_("short read while indexing %s"),
90dca671 2423 path ? path : "<unknown>");
ea68b0ce 2424 else
58bf2a4c 2425 ret = index_mem(istate, oid, buf, size, type, path, flags);
ea68b0ce 2426 free(buf);
08bda208 2427 } else {
43df4f86 2428 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
58bf2a4c 2429 ret = index_mem(istate, oid, buf, size, type, path, flags);
aac17941 2430 munmap(buf, size);
08bda208 2431 }
7b41e1e1
JH
2432 return ret;
2433}
2434
4dd1fbc7 2435/*
568508e7
JH
2436 * This creates one packfile per large blob unless bulk-checkin
2437 * machinery is "plugged".
4dd1fbc7
JH
2438 *
2439 * This also bypasses the usual "convert-to-git" dance, and that is on
2440 * purpose. We could write a streaming version of the converting
2441 * functions and insert that before feeding the data to fast-import
4f22b101
JK
2442 * (or equivalent in-core API described above). However, that is
2443 * somewhat complicated, as we do not know the size of the filter
2444 * result, which we need to know beforehand when writing a git object.
2445 * Since the primary motivation for trying to stream from the working
2446 * tree file and to avoid mmaping it in core is to deal with large
2447 * binary blobs, they generally do not want to get any conversion, and
2448 * callers should avoid this code path when filters are requested.
4dd1fbc7 2449 */
7d5e1dc3 2450static int index_stream(struct object_id *oid, int fd, size_t size,
4dd1fbc7
JH
2451 enum object_type type, const char *path,
2452 unsigned flags)
2453{
68ee6dfc 2454 return index_bulk_checkin(oid, fd, size, type, path, flags);
4dd1fbc7
JH
2455}
2456
58bf2a4c
NTND
2457int index_fd(struct index_state *istate, struct object_id *oid,
2458 int fd, struct stat *st,
7b41e1e1
JH
2459 enum object_type type, const char *path, unsigned flags)
2460{
2461 int ret;
7b41e1e1 2462
9079ab7c
SP
2463 /*
2464 * Call xsize_t() only when needed to avoid potentially unnecessary
2465 * die() for large files.
2466 */
58bf2a4c
NTND
2467 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path))
2468 ret = index_stream_convert_blob(istate, oid, fd, path, flags);
9035d75a 2469 else if (!S_ISREG(st->st_mode))
58bf2a4c 2470 ret = index_pipe(istate, oid, fd, type, path, flags);
9079ab7c 2471 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
58bf2a4c
NTND
2472 (path && would_convert_to_git(istate, path)))
2473 ret = index_core(istate, oid, fd, xsize_t(st->st_size),
2474 type, path, flags);
4dd1fbc7 2475 else
7d5e1dc3 2476 ret = index_stream(oid, fd, xsize_t(st->st_size), type, path,
9079ab7c 2477 flags);
43df4f86 2478 close(fd);
aac17941 2479 return ret;
74400e71 2480}
ec1fcc16 2481
58bf2a4c
NTND
2482int index_path(struct index_state *istate, struct object_id *oid,
2483 const char *path, struct stat *st, unsigned flags)
ec1fcc16
JH
2484{
2485 int fd;
b760d3aa 2486 struct strbuf sb = STRBUF_INIT;
ea8e0297 2487 int rc = 0;
ec1fcc16
JH
2488
2489 switch (st->st_mode & S_IFMT) {
2490 case S_IFREG:
2491 fd = open(path, O_RDONLY);
2492 if (fd < 0)
7616c6ca 2493 return error_errno("open(\"%s\")", path);
58bf2a4c 2494 if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
259328b7 2495 return error(_("%s: failed to insert into database"),
ec1fcc16
JH
2496 path);
2497 break;
2498 case S_IFLNK:
7616c6ca
NTND
2499 if (strbuf_readlink(&sb, path, st->st_size))
2500 return error_errno("readlink(\"%s\")", path);
c4ce46fc 2501 if (!(flags & HASH_WRITE_OBJECT))
2dcde20e 2502 hash_object_file(the_hash_algo, sb.buf, sb.len,
44439c1c 2503 OBJ_BLOB, oid);
c80d226a 2504 else if (write_object_file(sb.buf, sb.len, OBJ_BLOB, oid))
259328b7 2505 rc = error(_("%s: failed to insert into database"), path);
b760d3aa 2506 strbuf_release(&sb);
ec1fcc16 2507 break;
f35a6d3b 2508 case S_IFDIR:
a98e6101 2509 return resolve_gitlink_ref(path, "HEAD", oid);
ec1fcc16 2510 default:
259328b7 2511 return error(_("%s: unsupported file type"), path);
ec1fcc16 2512 }
ea8e0297 2513 return rc;
ec1fcc16 2514}
a69e5429
JH
2515
2516int read_pack_header(int fd, struct pack_header *header)
2517{
f48ecd38 2518 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
c697ad14
HO
2519 /* "eof before pack header was fully read" */
2520 return PH_ERROR_EOF;
2521
a69e5429
JH
2522 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2523 /* "protocol error (pack signature mismatch detected)" */
2524 return PH_ERROR_PACK_SIGNATURE;
2525 if (!pack_version_ok(header->hdr_version))
2526 /* "protocol error (pack version unsupported)" */
2527 return PH_ERROR_PROTOCOL;
2528 return 0;
2529}
40d52ff7 2530
e816caa0 2531void assert_oid_type(const struct object_id *oid, enum object_type expect)
40d52ff7 2532{
0df8e965 2533 enum object_type type = oid_object_info(the_repository, oid, NULL);
40d52ff7 2534 if (type < 0)
259328b7 2535 die(_("%s is not a valid object"), oid_to_hex(oid));
40d52ff7 2536 if (type != expect)
259328b7 2537 die(_("%s is not a valid '%s' object"), oid_to_hex(oid),
debca9d2 2538 type_name(expect));
40d52ff7 2539}
27e1e22d 2540
70c49050 2541int for_each_file_in_obj_subdir(unsigned int subdir_nr,
cc817ca3
RS
2542 struct strbuf *path,
2543 each_loose_object_fn obj_cb,
2544 each_loose_cruft_fn cruft_cb,
2545 each_loose_subdir_fn subdir_cb,
2546 void *data)
27e1e22d 2547{
0375f472
RS
2548 size_t origlen, baselen;
2549 DIR *dir;
27e1e22d
JK
2550 struct dirent *de;
2551 int r = 0;
62a24c89 2552 struct object_id oid;
27e1e22d 2553
70c49050
RS
2554 if (subdir_nr > 0xff)
2555 BUG("invalid loose object subdirectory: %x", subdir_nr);
2556
0375f472
RS
2557 origlen = path->len;
2558 strbuf_complete(path, '/');
2559 strbuf_addf(path, "%02x", subdir_nr);
0375f472
RS
2560
2561 dir = opendir(path->buf);
27e1e22d 2562 if (!dir) {
0375f472 2563 if (errno != ENOENT)
259328b7 2564 r = error_errno(_("unable to open %s"), path->buf);
0375f472
RS
2565 strbuf_setlen(path, origlen);
2566 return r;
27e1e22d
JK
2567 }
2568
62a24c89 2569 oid.hash[0] = subdir_nr;
163ee5e6
DS
2570 strbuf_addch(path, '/');
2571 baselen = path->len;
62a24c89 2572
b548f0f1 2573 while ((de = readdir_skip_dot_and_dotdot(dir))) {
163ee5e6 2574 size_t namelen;
27e1e22d 2575
163ee5e6 2576 namelen = strlen(de->d_name);
27e1e22d 2577 strbuf_setlen(path, baselen);
163ee5e6 2578 strbuf_add(path, de->d_name, namelen);
94b5e093 2579 if (namelen == the_hash_algo->hexsz - 2 &&
62a24c89 2580 !hex_to_bytes(oid.hash + 1, de->d_name,
94b5e093 2581 the_hash_algo->rawsz - 1)) {
5a6dce70 2582 oid_set_algo(&oid, the_hash_algo);
62a24c89
RS
2583 if (obj_cb) {
2584 r = obj_cb(&oid, path->buf, data);
2585 if (r)
2586 break;
27e1e22d 2587 }
62a24c89 2588 continue;
27e1e22d
JK
2589 }
2590
2591 if (cruft_cb) {
2592 r = cruft_cb(de->d_name, path->buf, data);
2593 if (r)
2594 break;
2595 }
2596 }
094c7e63 2597 closedir(dir);
27e1e22d 2598
163ee5e6 2599 strbuf_setlen(path, baselen - 1);
27e1e22d
JK
2600 if (!r && subdir_cb)
2601 r = subdir_cb(subdir_nr, path->buf, data);
2602
0375f472
RS
2603 strbuf_setlen(path, origlen);
2604
27e1e22d
JK
2605 return r;
2606}
2607
e6f875e0 2608int for_each_loose_file_in_objdir_buf(struct strbuf *path,
27e1e22d
JK
2609 each_loose_object_fn obj_cb,
2610 each_loose_cruft_fn cruft_cb,
2611 each_loose_subdir_fn subdir_cb,
2612 void *data)
2613{
27e1e22d
JK
2614 int r = 0;
2615 int i;
2616
27e1e22d 2617 for (i = 0; i < 256; i++) {
e6f875e0 2618 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
27e1e22d 2619 subdir_cb, data);
27e1e22d
JK
2620 if (r)
2621 break;
2622 }
2623
e6f875e0
JK
2624 return r;
2625}
2626
2627int for_each_loose_file_in_objdir(const char *path,
2628 each_loose_object_fn obj_cb,
2629 each_loose_cruft_fn cruft_cb,
2630 each_loose_subdir_fn subdir_cb,
2631 void *data)
2632{
2633 struct strbuf buf = STRBUF_INIT;
2634 int r;
2635
2636 strbuf_addstr(&buf, path);
2637 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2638 subdir_cb, data);
27e1e22d 2639 strbuf_release(&buf);
e6f875e0 2640
27e1e22d
JK
2641 return r;
2642}
660c889e 2643
a7ff6f5a
JK
2644int for_each_loose_object(each_loose_object_fn cb, void *data,
2645 enum for_each_object_flags flags)
660c889e 2646{
f0eaf638 2647 struct object_directory *odb;
b0a42642 2648
f0eaf638
JK
2649 prepare_alt_odb(the_repository);
2650 for (odb = the_repository->objects->odb; odb; odb = odb->next) {
2651 int r = for_each_loose_file_in_objdir(odb->path, cb, NULL,
2652 NULL, data);
2653 if (r)
2654 return r;
660c889e 2655
f0eaf638
JK
2656 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2657 break;
2658 }
1385bb7b 2659
f0eaf638 2660 return 0;
660c889e
JK
2661}
2662
be252d33
JK
2663static int append_loose_object(const struct object_id *oid,
2664 const char *path UNUSED,
3a2e0824 2665 void *data)
660c889e 2666{
92d8ed8a 2667 oidtree_insert(data, oid);
3a2e0824
JK
2668 return 0;
2669}
660c889e 2670
92d8ed8a 2671struct oidtree *odb_loose_cache(struct object_directory *odb,
0000d654
RS
2672 const struct object_id *oid)
2673{
2674 int subdir_nr = oid->hash[0];
3a2e0824 2675 struct strbuf buf = STRBUF_INIT;
33f379ee
EW
2676 size_t word_bits = bitsizeof(odb->loose_objects_subdir_seen[0]);
2677 size_t word_index = subdir_nr / word_bits;
26de1fc0 2678 size_t mask = (size_t)1u << (subdir_nr % word_bits);
33f379ee 2679 uint32_t *bitmap;
660c889e 2680
3a2e0824 2681 if (subdir_nr < 0 ||
33f379ee 2682 subdir_nr >= bitsizeof(odb->loose_objects_subdir_seen))
3a2e0824 2683 BUG("subdir_nr out of range");
1385bb7b 2684
33f379ee
EW
2685 bitmap = &odb->loose_objects_subdir_seen[word_index];
2686 if (*bitmap & mask)
92d8ed8a
EW
2687 return odb->loose_objects_cache;
2688 if (!odb->loose_objects_cache) {
2689 ALLOC_ARRAY(odb->loose_objects_cache, 1);
2690 oidtree_init(odb->loose_objects_cache);
2691 }
3a2e0824
JK
2692 strbuf_addstr(&buf, odb->path);
2693 for_each_file_in_obj_subdir(subdir_nr, &buf,
2694 append_loose_object,
2695 NULL, NULL,
92d8ed8a 2696 odb->loose_objects_cache);
33f379ee 2697 *bitmap |= mask;
7317aa71 2698 strbuf_release(&buf);
92d8ed8a 2699 return odb->loose_objects_cache;
660c889e
JK
2700}
2701
d4e19e51
RS
2702void odb_clear_loose_cache(struct object_directory *odb)
2703{
92d8ed8a
EW
2704 oidtree_clear(odb->loose_objects_cache);
2705 FREE_AND_NULL(odb->loose_objects_cache);
d4e19e51
RS
2706 memset(&odb->loose_objects_subdir_seen, 0,
2707 sizeof(odb->loose_objects_subdir_seen));
2708}
2709
00a7760e
JK
2710static int check_stream_oid(git_zstream *stream,
2711 const char *hdr,
2712 unsigned long size,
2713 const char *path,
2714 const struct object_id *expected_oid)
f6371f92 2715{
18e2588e 2716 git_hash_ctx c;
00a7760e 2717 struct object_id real_oid;
f6371f92
JK
2718 unsigned char buf[4096];
2719 unsigned long total_read;
2720 int status = Z_OK;
2721
18e2588e 2722 the_hash_algo->init_fn(&c);
2723 the_hash_algo->update_fn(&c, hdr, stream->total_out);
f6371f92
JK
2724
2725 /*
2726 * We already read some bytes into hdr, but the ones up to the NUL
2727 * do not count against the object's content size.
2728 */
2729 total_read = stream->total_out - strlen(hdr) - 1;
2730
2731 /*
2732 * This size comparison must be "<=" to read the final zlib packets;
00a7760e 2733 * see the comment in unpack_loose_rest for details.
f6371f92
JK
2734 */
2735 while (total_read <= size &&
18ad13e5
JH
2736 (status == Z_OK ||
2737 (status == Z_BUF_ERROR && !stream->avail_out))) {
f6371f92
JK
2738 stream->next_out = buf;
2739 stream->avail_out = sizeof(buf);
2740 if (size - total_read < stream->avail_out)
2741 stream->avail_out = size - total_read;
2742 status = git_inflate(stream, Z_FINISH);
18e2588e 2743 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
f6371f92
JK
2744 total_read += stream->next_out - buf;
2745 }
2746 git_inflate_end(stream);
2747
2748 if (status != Z_STREAM_END) {
00a7760e 2749 error(_("corrupt loose object '%s'"), oid_to_hex(expected_oid));
f6371f92
JK
2750 return -1;
2751 }
cce044df 2752 if (stream->avail_in) {
259328b7 2753 error(_("garbage at end of loose object '%s'"),
00a7760e 2754 oid_to_hex(expected_oid));
cce044df
JK
2755 return -1;
2756 }
f6371f92 2757
5951bf46 2758 the_hash_algo->final_oid_fn(&real_oid, &c);
00a7760e 2759 if (!oideq(expected_oid, &real_oid)) {
01f8d594 2760 error(_("hash mismatch for %s (expected %s)"), path,
00a7760e 2761 oid_to_hex(expected_oid));
f6371f92
JK
2762 return -1;
2763 }
2764
2765 return 0;
2766}
2767
2768int read_loose_object(const char *path,
d61d87bd 2769 const struct object_id *expected_oid,
96e41f58 2770 struct object_id *real_oid,
31deb28f
ÆAB
2771 void **contents,
2772 struct object_info *oi)
f6371f92
JK
2773{
2774 int ret = -1;
ae285ac4 2775 int fd;
f6371f92
JK
2776 void *map = NULL;
2777 unsigned long mapsize;
2778 git_zstream stream;
1af64f73 2779 char hdr[MAX_HEADER_LEN];
31deb28f 2780 unsigned long *size = oi->sizep;
f6371f92 2781
ae285ac4
JT
2782 fd = git_open(path);
2783 if (fd >= 0)
2784 map = map_fd(fd, path, &mapsize);
f6371f92 2785 if (!map) {
259328b7 2786 error_errno(_("unable to mmap %s"), path);
f6371f92
JK
2787 goto out;
2788 }
2789
8a50571a
DS
2790 if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr),
2791 NULL) != ULHR_OK) {
259328b7 2792 error(_("unable to unpack header of %s"), path);
f6371f92
JK
2793 goto out;
2794 }
2795
31deb28f 2796 if (parse_loose_header(hdr, oi) < 0) {
259328b7 2797 error(_("unable to parse header of %s"), path);
f6371f92
JK
2798 git_inflate_end(&stream);
2799 goto out;
2800 }
2801
31deb28f 2802 if (*oi->typep == OBJ_BLOB && *size > big_file_threshold) {
00a7760e 2803 if (check_stream_oid(&stream, hdr, *size, path, expected_oid) < 0)
f6371f92
JK
2804 goto out;
2805 } else {
00a7760e 2806 *contents = unpack_loose_rest(&stream, hdr, *size, expected_oid);
f6371f92 2807 if (!*contents) {
259328b7 2808 error(_("unable to unpack contents of %s"), path);
f6371f92
JK
2809 git_inflate_end(&stream);
2810 goto out;
2811 }
44439c1c 2812 hash_object_file_literally(the_repository->hash_algo,
16235e3b 2813 *contents, *size,
44439c1c 2814 oi->type_name->buf, real_oid);
0f156dbb 2815 if (!oideq(expected_oid, real_oid))
f6371f92 2816 goto out;
f6371f92
JK
2817 }
2818
2819 ret = 0; /* everything checks out */
2820
2821out:
2822 if (map)
2823 munmap(map, mapsize);
f6371f92
JK
2824 return ret;
2825}