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