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