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