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