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