]> git.ipfire.org Git - thirdparty/git.git/blob - object-file.c
reftable: generic interface to tables
[thirdparty/git.git] / object-file.c
1 /*
2 * GIT - The information manager from hell
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 *
6 * This handles basic git object files - packing, unpacking,
7 * creation etc.
8 */
9 #include "cache.h"
10 #include "config.h"
11 #include "string-list.h"
12 #include "lockfile.h"
13 #include "delta.h"
14 #include "pack.h"
15 #include "blob.h"
16 #include "commit.h"
17 #include "run-command.h"
18 #include "tag.h"
19 #include "tree.h"
20 #include "tree-walk.h"
21 #include "refs.h"
22 #include "pack-revindex.h"
23 #include "hash-lookup.h"
24 #include "bulk-checkin.h"
25 #include "repository.h"
26 #include "replace-object.h"
27 #include "streaming.h"
28 #include "dir.h"
29 #include "list.h"
30 #include "mergesort.h"
31 #include "quote.h"
32 #include "packfile.h"
33 #include "object-store.h"
34 #include "promisor-remote.h"
35
36 /* The maximum size for an object header. */
37 #define MAX_HEADER_LEN 32
38
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 #define EMPTY_TREE_SHA256_BIN_LITERAL \
44 "\x6e\xf1\x9b\x41\x22\x5c\x53\x69\xf1\xc1" \
45 "\x04\xd4\x5d\x8d\x85\xef\xa9\xb0\x57\xb5" \
46 "\x3b\x14\xb4\xb9\xb9\x39\xdd\x74\xde\xcc" \
47 "\x53\x21"
48
49 #define EMPTY_BLOB_SHA1_BIN_LITERAL \
50 "\xe6\x9d\xe2\x9b\xb2\xd1\xd6\x43\x4b\x8b" \
51 "\x29\xae\x77\x5a\xd8\xc2\xe4\x8c\x53\x91"
52 #define EMPTY_BLOB_SHA256_BIN_LITERAL \
53 "\x47\x3a\x0f\x4c\x3b\xe8\xa9\x36\x81\xa2" \
54 "\x67\xe3\xb1\xe9\xa7\xdc\xda\x11\x85\x43" \
55 "\x6f\xe1\x41\xf7\x74\x91\x20\xa3\x03\x72" \
56 "\x18\x13"
57
58 static const struct object_id empty_tree_oid = {
59 .hash = EMPTY_TREE_SHA1_BIN_LITERAL,
60 .algo = GIT_HASH_SHA1,
61 };
62 static const struct object_id empty_blob_oid = {
63 .hash = EMPTY_BLOB_SHA1_BIN_LITERAL,
64 .algo = GIT_HASH_SHA1,
65 };
66 static const struct object_id null_oid_sha1 = {
67 .hash = {0},
68 .algo = GIT_HASH_SHA1,
69 };
70 static const struct object_id empty_tree_oid_sha256 = {
71 .hash = EMPTY_TREE_SHA256_BIN_LITERAL,
72 .algo = GIT_HASH_SHA256,
73 };
74 static const struct object_id empty_blob_oid_sha256 = {
75 .hash = EMPTY_BLOB_SHA256_BIN_LITERAL,
76 .algo = GIT_HASH_SHA256,
77 };
78 static const struct object_id null_oid_sha256 = {
79 .hash = {0},
80 .algo = GIT_HASH_SHA256,
81 };
82
83 static void git_hash_sha1_init(git_hash_ctx *ctx)
84 {
85 git_SHA1_Init(&ctx->sha1);
86 }
87
88 static void git_hash_sha1_clone(git_hash_ctx *dst, const git_hash_ctx *src)
89 {
90 git_SHA1_Clone(&dst->sha1, &src->sha1);
91 }
92
93 static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
94 {
95 git_SHA1_Update(&ctx->sha1, data, len);
96 }
97
98 static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
99 {
100 git_SHA1_Final(hash, &ctx->sha1);
101 }
102
103 static void git_hash_sha1_final_oid(struct object_id *oid, git_hash_ctx *ctx)
104 {
105 git_SHA1_Final(oid->hash, &ctx->sha1);
106 memset(oid->hash + GIT_SHA1_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA1_RAWSZ);
107 oid->algo = GIT_HASH_SHA1;
108 }
109
110
111 static void git_hash_sha256_init(git_hash_ctx *ctx)
112 {
113 git_SHA256_Init(&ctx->sha256);
114 }
115
116 static void git_hash_sha256_clone(git_hash_ctx *dst, const git_hash_ctx *src)
117 {
118 git_SHA256_Clone(&dst->sha256, &src->sha256);
119 }
120
121 static void git_hash_sha256_update(git_hash_ctx *ctx, const void *data, size_t len)
122 {
123 git_SHA256_Update(&ctx->sha256, data, len);
124 }
125
126 static void git_hash_sha256_final(unsigned char *hash, git_hash_ctx *ctx)
127 {
128 git_SHA256_Final(hash, &ctx->sha256);
129 }
130
131 static void git_hash_sha256_final_oid(struct object_id *oid, git_hash_ctx *ctx)
132 {
133 git_SHA256_Final(oid->hash, &ctx->sha256);
134 /*
135 * This currently does nothing, so the compiler should optimize it out,
136 * but keep it in case we extend the hash size again.
137 */
138 memset(oid->hash + GIT_SHA256_RAWSZ, 0, GIT_MAX_RAWSZ - GIT_SHA256_RAWSZ);
139 oid->algo = GIT_HASH_SHA256;
140 }
141
142 static void git_hash_unknown_init(git_hash_ctx *ctx)
143 {
144 BUG("trying to init unknown hash");
145 }
146
147 static void git_hash_unknown_clone(git_hash_ctx *dst, const git_hash_ctx *src)
148 {
149 BUG("trying to clone unknown hash");
150 }
151
152 static void git_hash_unknown_update(git_hash_ctx *ctx, const void *data, size_t len)
153 {
154 BUG("trying to update unknown hash");
155 }
156
157 static void git_hash_unknown_final(unsigned char *hash, git_hash_ctx *ctx)
158 {
159 BUG("trying to finalize unknown hash");
160 }
161
162 static void git_hash_unknown_final_oid(struct object_id *oid, git_hash_ctx *ctx)
163 {
164 BUG("trying to finalize unknown hash");
165 }
166
167 const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
168 {
169 NULL,
170 0x00000000,
171 0,
172 0,
173 0,
174 git_hash_unknown_init,
175 git_hash_unknown_clone,
176 git_hash_unknown_update,
177 git_hash_unknown_final,
178 git_hash_unknown_final_oid,
179 NULL,
180 NULL,
181 NULL,
182 },
183 {
184 "sha1",
185 GIT_SHA1_FORMAT_ID,
186 GIT_SHA1_RAWSZ,
187 GIT_SHA1_HEXSZ,
188 GIT_SHA1_BLKSZ,
189 git_hash_sha1_init,
190 git_hash_sha1_clone,
191 git_hash_sha1_update,
192 git_hash_sha1_final,
193 git_hash_sha1_final_oid,
194 &empty_tree_oid,
195 &empty_blob_oid,
196 &null_oid_sha1,
197 },
198 {
199 "sha256",
200 GIT_SHA256_FORMAT_ID,
201 GIT_SHA256_RAWSZ,
202 GIT_SHA256_HEXSZ,
203 GIT_SHA256_BLKSZ,
204 git_hash_sha256_init,
205 git_hash_sha256_clone,
206 git_hash_sha256_update,
207 git_hash_sha256_final,
208 git_hash_sha256_final_oid,
209 &empty_tree_oid_sha256,
210 &empty_blob_oid_sha256,
211 &null_oid_sha256,
212 }
213 };
214
215 const struct object_id *null_oid(void)
216 {
217 return the_hash_algo->null_oid;
218 }
219
220 const char *empty_tree_oid_hex(void)
221 {
222 static char buf[GIT_MAX_HEXSZ + 1];
223 return oid_to_hex_r(buf, the_hash_algo->empty_tree);
224 }
225
226 const char *empty_blob_oid_hex(void)
227 {
228 static char buf[GIT_MAX_HEXSZ + 1];
229 return oid_to_hex_r(buf, the_hash_algo->empty_blob);
230 }
231
232 int hash_algo_by_name(const char *name)
233 {
234 int i;
235 if (!name)
236 return GIT_HASH_UNKNOWN;
237 for (i = 1; i < GIT_HASH_NALGOS; i++)
238 if (!strcmp(name, hash_algos[i].name))
239 return i;
240 return GIT_HASH_UNKNOWN;
241 }
242
243 int hash_algo_by_id(uint32_t format_id)
244 {
245 int i;
246 for (i = 1; i < GIT_HASH_NALGOS; i++)
247 if (format_id == hash_algos[i].format_id)
248 return i;
249 return GIT_HASH_UNKNOWN;
250 }
251
252 int hash_algo_by_length(int len)
253 {
254 int i;
255 for (i = 1; i < GIT_HASH_NALGOS; i++)
256 if (len == hash_algos[i].rawsz)
257 return i;
258 return GIT_HASH_UNKNOWN;
259 }
260
261 /*
262 * This is meant to hold a *small* number of objects that you would
263 * want read_object_file() to be able to return, but yet you do not want
264 * to write them into the object store (e.g. a browse-only
265 * application).
266 */
267 static struct cached_object {
268 struct object_id oid;
269 enum object_type type;
270 void *buf;
271 unsigned long size;
272 } *cached_objects;
273 static int cached_object_nr, cached_object_alloc;
274
275 static struct cached_object empty_tree = {
276 { EMPTY_TREE_SHA1_BIN_LITERAL },
277 OBJ_TREE,
278 "",
279 0
280 };
281
282 static struct cached_object *find_cached_object(const struct object_id *oid)
283 {
284 int i;
285 struct cached_object *co = cached_objects;
286
287 for (i = 0; i < cached_object_nr; i++, co++) {
288 if (oideq(&co->oid, oid))
289 return co;
290 }
291 if (oideq(oid, the_hash_algo->empty_tree))
292 return &empty_tree;
293 return NULL;
294 }
295
296
297 static int get_conv_flags(unsigned flags)
298 {
299 if (flags & HASH_RENORMALIZE)
300 return CONV_EOL_RENORMALIZE;
301 else if (flags & HASH_WRITE_OBJECT)
302 return global_conv_flags_eol | CONV_WRITE_OBJECT;
303 else
304 return 0;
305 }
306
307
308 int mkdir_in_gitdir(const char *path)
309 {
310 if (mkdir(path, 0777)) {
311 int saved_errno = errno;
312 struct stat st;
313 struct strbuf sb = STRBUF_INIT;
314
315 if (errno != EEXIST)
316 return -1;
317 /*
318 * Are we looking at a path in a symlinked worktree
319 * whose original repository does not yet have it?
320 * e.g. .git/rr-cache pointing at its original
321 * repository in which the user hasn't performed any
322 * conflict resolution yet?
323 */
324 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
325 strbuf_readlink(&sb, path, st.st_size) ||
326 !is_absolute_path(sb.buf) ||
327 mkdir(sb.buf, 0777)) {
328 strbuf_release(&sb);
329 errno = saved_errno;
330 return -1;
331 }
332 strbuf_release(&sb);
333 }
334 return adjust_shared_perm(path);
335 }
336
337 static enum scld_error safe_create_leading_directories_1(char *path, int share)
338 {
339 char *next_component = path + offset_1st_component(path);
340 enum scld_error ret = SCLD_OK;
341
342 while (ret == SCLD_OK && next_component) {
343 struct stat st;
344 char *slash = next_component, slash_character;
345
346 while (*slash && !is_dir_sep(*slash))
347 slash++;
348
349 if (!*slash)
350 break;
351
352 next_component = slash + 1;
353 while (is_dir_sep(*next_component))
354 next_component++;
355 if (!*next_component)
356 break;
357
358 slash_character = *slash;
359 *slash = '\0';
360 if (!stat(path, &st)) {
361 /* path exists */
362 if (!S_ISDIR(st.st_mode)) {
363 errno = ENOTDIR;
364 ret = SCLD_EXISTS;
365 }
366 } else if (mkdir(path, 0777)) {
367 if (errno == EEXIST &&
368 !stat(path, &st) && S_ISDIR(st.st_mode))
369 ; /* somebody created it since we checked */
370 else if (errno == ENOENT)
371 /*
372 * Either mkdir() failed because
373 * somebody just pruned the containing
374 * directory, or stat() failed because
375 * the file that was in our way was
376 * just removed. Either way, inform
377 * the caller that it might be worth
378 * trying again:
379 */
380 ret = SCLD_VANISHED;
381 else
382 ret = SCLD_FAILED;
383 } else if (share && adjust_shared_perm(path)) {
384 ret = SCLD_PERMS;
385 }
386 *slash = slash_character;
387 }
388 return ret;
389 }
390
391 enum scld_error safe_create_leading_directories(char *path)
392 {
393 return safe_create_leading_directories_1(path, 1);
394 }
395
396 enum scld_error safe_create_leading_directories_no_share(char *path)
397 {
398 return safe_create_leading_directories_1(path, 0);
399 }
400
401 enum scld_error safe_create_leading_directories_const(const char *path)
402 {
403 int save_errno;
404 /* path points to cache entries, so xstrdup before messing with it */
405 char *buf = xstrdup(path);
406 enum scld_error result = safe_create_leading_directories(buf);
407
408 save_errno = errno;
409 free(buf);
410 errno = save_errno;
411 return result;
412 }
413
414 int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
415 {
416 /*
417 * The number of times we will try to remove empty directories
418 * in the way of path. This is only 1 because if another
419 * process is racily creating directories that conflict with
420 * us, we don't want to fight against them.
421 */
422 int remove_directories_remaining = 1;
423
424 /*
425 * The number of times that we will try to create the
426 * directories containing path. We are willing to attempt this
427 * more than once, because another process could be trying to
428 * clean up empty directories at the same time as we are
429 * trying to create them.
430 */
431 int create_directories_remaining = 3;
432
433 /* A scratch copy of path, filled lazily if we need it: */
434 struct strbuf path_copy = STRBUF_INIT;
435
436 int ret, save_errno;
437
438 /* Sanity check: */
439 assert(*path);
440
441 retry_fn:
442 ret = fn(path, cb);
443 save_errno = errno;
444 if (!ret)
445 goto out;
446
447 if (errno == EISDIR && remove_directories_remaining-- > 0) {
448 /*
449 * A directory is in the way. Maybe it is empty; try
450 * to remove it:
451 */
452 if (!path_copy.len)
453 strbuf_addstr(&path_copy, path);
454
455 if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
456 goto retry_fn;
457 } else if (errno == ENOENT && create_directories_remaining-- > 0) {
458 /*
459 * Maybe the containing directory didn't exist, or
460 * maybe it was just deleted by a process that is
461 * racing with us to clean up empty directories. Try
462 * to create it:
463 */
464 enum scld_error scld_result;
465
466 if (!path_copy.len)
467 strbuf_addstr(&path_copy, path);
468
469 do {
470 scld_result = safe_create_leading_directories(path_copy.buf);
471 if (scld_result == SCLD_OK)
472 goto retry_fn;
473 } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
474 }
475
476 out:
477 strbuf_release(&path_copy);
478 errno = save_errno;
479 return ret;
480 }
481
482 static void fill_loose_path(struct strbuf *buf, const struct object_id *oid)
483 {
484 int i;
485 for (i = 0; i < the_hash_algo->rawsz; i++) {
486 static char hex[] = "0123456789abcdef";
487 unsigned int val = oid->hash[i];
488 strbuf_addch(buf, hex[val >> 4]);
489 strbuf_addch(buf, hex[val & 0xf]);
490 if (!i)
491 strbuf_addch(buf, '/');
492 }
493 }
494
495 static const char *odb_loose_path(struct object_directory *odb,
496 struct strbuf *buf,
497 const struct object_id *oid)
498 {
499 strbuf_reset(buf);
500 strbuf_addstr(buf, odb->path);
501 strbuf_addch(buf, '/');
502 fill_loose_path(buf, oid);
503 return buf->buf;
504 }
505
506 const char *loose_object_path(struct repository *r, struct strbuf *buf,
507 const struct object_id *oid)
508 {
509 return odb_loose_path(r->objects->odb, buf, oid);
510 }
511
512 /*
513 * Return non-zero iff the path is usable as an alternate object database.
514 */
515 static int alt_odb_usable(struct raw_object_store *o,
516 struct strbuf *path,
517 const char *normalized_objdir, khiter_t *pos)
518 {
519 int r;
520
521 /* Detect cases where alternate disappeared */
522 if (!is_directory(path->buf)) {
523 error(_("object directory %s does not exist; "
524 "check .git/objects/info/alternates"),
525 path->buf);
526 return 0;
527 }
528
529 /*
530 * Prevent the common mistake of listing the same
531 * thing twice, or object directory itself.
532 */
533 if (!o->odb_by_path) {
534 khiter_t p;
535
536 o->odb_by_path = kh_init_odb_path_map();
537 assert(!o->odb->next);
538 p = kh_put_odb_path_map(o->odb_by_path, o->odb->path, &r);
539 assert(r == 1); /* never used */
540 kh_value(o->odb_by_path, p) = o->odb;
541 }
542 if (fspatheq(path->buf, normalized_objdir))
543 return 0;
544 *pos = kh_put_odb_path_map(o->odb_by_path, path->buf, &r);
545 /* r: 0 = exists, 1 = never used, 2 = deleted */
546 return r == 0 ? 0 : 1;
547 }
548
549 /*
550 * Prepare alternate object database registry.
551 *
552 * The variable alt_odb_list points at the list of struct
553 * object_directory. The elements on this list come from
554 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
555 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
556 * whose contents is similar to that environment variable but can be
557 * LF separated. Its base points at a statically allocated buffer that
558 * contains "/the/directory/corresponding/to/.git/objects/...", while
559 * its name points just after the slash at the end of ".git/objects/"
560 * in the example above, and has enough space to hold all hex characters
561 * of the object ID, an extra slash for the first level indirection, and
562 * the terminating NUL.
563 */
564 static void read_info_alternates(struct repository *r,
565 const char *relative_base,
566 int depth);
567 static int link_alt_odb_entry(struct repository *r, const struct strbuf *entry,
568 const char *relative_base, int depth, const char *normalized_objdir)
569 {
570 struct object_directory *ent;
571 struct strbuf pathbuf = STRBUF_INIT;
572 khiter_t pos;
573
574 if (!is_absolute_path(entry->buf) && relative_base) {
575 strbuf_realpath(&pathbuf, relative_base, 1);
576 strbuf_addch(&pathbuf, '/');
577 }
578 strbuf_addbuf(&pathbuf, entry);
579
580 if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
581 error(_("unable to normalize alternate object path: %s"),
582 pathbuf.buf);
583 strbuf_release(&pathbuf);
584 return -1;
585 }
586
587 /*
588 * The trailing slash after the directory name is given by
589 * this function at the end. Remove duplicates.
590 */
591 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
592 strbuf_setlen(&pathbuf, pathbuf.len - 1);
593
594 if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir, &pos)) {
595 strbuf_release(&pathbuf);
596 return -1;
597 }
598
599 CALLOC_ARRAY(ent, 1);
600 /* pathbuf.buf is already in r->objects->odb_by_path */
601 ent->path = strbuf_detach(&pathbuf, NULL);
602
603 /* add the alternate entry */
604 *r->objects->odb_tail = ent;
605 r->objects->odb_tail = &(ent->next);
606 ent->next = NULL;
607 assert(r->objects->odb_by_path);
608 kh_value(r->objects->odb_by_path, pos) = ent;
609
610 /* recursively add alternates */
611 read_info_alternates(r, ent->path, depth + 1);
612
613 return 0;
614 }
615
616 static const char *parse_alt_odb_entry(const char *string,
617 int sep,
618 struct strbuf *out)
619 {
620 const char *end;
621
622 strbuf_reset(out);
623
624 if (*string == '#') {
625 /* comment; consume up to next separator */
626 end = strchrnul(string, sep);
627 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
628 /*
629 * quoted path; unquote_c_style has copied the
630 * data for us and set "end". Broken quoting (e.g.,
631 * an entry that doesn't end with a quote) falls
632 * back to the unquoted case below.
633 */
634 } else {
635 /* normal, unquoted path */
636 end = strchrnul(string, sep);
637 strbuf_add(out, string, end - string);
638 }
639
640 if (*end)
641 end++;
642 return end;
643 }
644
645 static void link_alt_odb_entries(struct repository *r, const char *alt,
646 int sep, const char *relative_base, int depth)
647 {
648 struct strbuf objdirbuf = STRBUF_INIT;
649 struct strbuf entry = STRBUF_INIT;
650
651 if (!alt || !*alt)
652 return;
653
654 if (depth > 5) {
655 error(_("%s: ignoring alternate object stores, nesting too deep"),
656 relative_base);
657 return;
658 }
659
660 strbuf_add_absolute_path(&objdirbuf, r->objects->odb->path);
661 if (strbuf_normalize_path(&objdirbuf) < 0)
662 die(_("unable to normalize object directory: %s"),
663 objdirbuf.buf);
664
665 while (*alt) {
666 alt = parse_alt_odb_entry(alt, sep, &entry);
667 if (!entry.len)
668 continue;
669 link_alt_odb_entry(r, &entry,
670 relative_base, depth, objdirbuf.buf);
671 }
672 strbuf_release(&entry);
673 strbuf_release(&objdirbuf);
674 }
675
676 static void read_info_alternates(struct repository *r,
677 const char *relative_base,
678 int depth)
679 {
680 char *path;
681 struct strbuf buf = STRBUF_INIT;
682
683 path = xstrfmt("%s/info/alternates", relative_base);
684 if (strbuf_read_file(&buf, path, 1024) < 0) {
685 warn_on_fopen_errors(path);
686 free(path);
687 return;
688 }
689
690 link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
691 strbuf_release(&buf);
692 free(path);
693 }
694
695 void add_to_alternates_file(const char *reference)
696 {
697 struct lock_file lock = LOCK_INIT;
698 char *alts = git_pathdup("objects/info/alternates");
699 FILE *in, *out;
700 int found = 0;
701
702 hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
703 out = fdopen_lock_file(&lock, "w");
704 if (!out)
705 die_errno(_("unable to fdopen alternates lockfile"));
706
707 in = fopen(alts, "r");
708 if (in) {
709 struct strbuf line = STRBUF_INIT;
710
711 while (strbuf_getline(&line, in) != EOF) {
712 if (!strcmp(reference, line.buf)) {
713 found = 1;
714 break;
715 }
716 fprintf_or_die(out, "%s\n", line.buf);
717 }
718
719 strbuf_release(&line);
720 fclose(in);
721 }
722 else if (errno != ENOENT)
723 die_errno(_("unable to read alternates file"));
724
725 if (found) {
726 rollback_lock_file(&lock);
727 } else {
728 fprintf_or_die(out, "%s\n", reference);
729 if (commit_lock_file(&lock))
730 die_errno(_("unable to move new alternates file into place"));
731 if (the_repository->objects->loaded_alternates)
732 link_alt_odb_entries(the_repository, reference,
733 '\n', NULL, 0);
734 }
735 free(alts);
736 }
737
738 void add_to_alternates_memory(const char *reference)
739 {
740 /*
741 * Make sure alternates are initialized, or else our entry may be
742 * overwritten when they are.
743 */
744 prepare_alt_odb(the_repository);
745
746 link_alt_odb_entries(the_repository, reference,
747 '\n', NULL, 0);
748 }
749
750 /*
751 * Compute the exact path an alternate is at and returns it. In case of
752 * error NULL is returned and the human readable error is added to `err`
753 * `path` may be relative and should point to $GIT_DIR.
754 * `err` must not be null.
755 */
756 char *compute_alternate_path(const char *path, struct strbuf *err)
757 {
758 char *ref_git = NULL;
759 const char *repo;
760 int seen_error = 0;
761
762 ref_git = real_pathdup(path, 0);
763 if (!ref_git) {
764 seen_error = 1;
765 strbuf_addf(err, _("path '%s' does not exist"), path);
766 goto out;
767 }
768
769 repo = read_gitfile(ref_git);
770 if (!repo)
771 repo = read_gitfile(mkpath("%s/.git", ref_git));
772 if (repo) {
773 free(ref_git);
774 ref_git = xstrdup(repo);
775 }
776
777 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
778 char *ref_git_git = mkpathdup("%s/.git", ref_git);
779 free(ref_git);
780 ref_git = ref_git_git;
781 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
782 struct strbuf sb = STRBUF_INIT;
783 seen_error = 1;
784 if (get_common_dir(&sb, ref_git)) {
785 strbuf_addf(err,
786 _("reference repository '%s' as a linked "
787 "checkout is not supported yet."),
788 path);
789 goto out;
790 }
791
792 strbuf_addf(err, _("reference repository '%s' is not a "
793 "local repository."), path);
794 goto out;
795 }
796
797 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
798 strbuf_addf(err, _("reference repository '%s' is shallow"),
799 path);
800 seen_error = 1;
801 goto out;
802 }
803
804 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
805 strbuf_addf(err,
806 _("reference repository '%s' is grafted"),
807 path);
808 seen_error = 1;
809 goto out;
810 }
811
812 out:
813 if (seen_error) {
814 FREE_AND_NULL(ref_git);
815 }
816
817 return ref_git;
818 }
819
820 static void fill_alternate_refs_command(struct child_process *cmd,
821 const char *repo_path)
822 {
823 const char *value;
824
825 if (!git_config_get_value("core.alternateRefsCommand", &value)) {
826 cmd->use_shell = 1;
827
828 strvec_push(&cmd->args, value);
829 strvec_push(&cmd->args, repo_path);
830 } else {
831 cmd->git_cmd = 1;
832
833 strvec_pushf(&cmd->args, "--git-dir=%s", repo_path);
834 strvec_push(&cmd->args, "for-each-ref");
835 strvec_push(&cmd->args, "--format=%(objectname)");
836
837 if (!git_config_get_value("core.alternateRefsPrefixes", &value)) {
838 strvec_push(&cmd->args, "--");
839 strvec_split(&cmd->args, value);
840 }
841 }
842
843 cmd->env = local_repo_env;
844 cmd->out = -1;
845 }
846
847 static void read_alternate_refs(const char *path,
848 alternate_ref_fn *cb,
849 void *data)
850 {
851 struct child_process cmd = CHILD_PROCESS_INIT;
852 struct strbuf line = STRBUF_INIT;
853 FILE *fh;
854
855 fill_alternate_refs_command(&cmd, path);
856
857 if (start_command(&cmd))
858 return;
859
860 fh = xfdopen(cmd.out, "r");
861 while (strbuf_getline_lf(&line, fh) != EOF) {
862 struct object_id oid;
863 const char *p;
864
865 if (parse_oid_hex(line.buf, &oid, &p) || *p) {
866 warning(_("invalid line while parsing alternate refs: %s"),
867 line.buf);
868 break;
869 }
870
871 cb(&oid, data);
872 }
873
874 fclose(fh);
875 finish_command(&cmd);
876 strbuf_release(&line);
877 }
878
879 struct alternate_refs_data {
880 alternate_ref_fn *fn;
881 void *data;
882 };
883
884 static int refs_from_alternate_cb(struct object_directory *e,
885 void *data)
886 {
887 struct strbuf path = STRBUF_INIT;
888 size_t base_len;
889 struct alternate_refs_data *cb = data;
890
891 if (!strbuf_realpath(&path, e->path, 0))
892 goto out;
893 if (!strbuf_strip_suffix(&path, "/objects"))
894 goto out;
895 base_len = path.len;
896
897 /* Is this a git repository with refs? */
898 strbuf_addstr(&path, "/refs");
899 if (!is_directory(path.buf))
900 goto out;
901 strbuf_setlen(&path, base_len);
902
903 read_alternate_refs(path.buf, cb->fn, cb->data);
904
905 out:
906 strbuf_release(&path);
907 return 0;
908 }
909
910 void for_each_alternate_ref(alternate_ref_fn fn, void *data)
911 {
912 struct alternate_refs_data cb;
913 cb.fn = fn;
914 cb.data = data;
915 foreach_alt_odb(refs_from_alternate_cb, &cb);
916 }
917
918 int foreach_alt_odb(alt_odb_fn fn, void *cb)
919 {
920 struct object_directory *ent;
921 int r = 0;
922
923 prepare_alt_odb(the_repository);
924 for (ent = the_repository->objects->odb->next; ent; ent = ent->next) {
925 r = fn(ent, cb);
926 if (r)
927 break;
928 }
929 return r;
930 }
931
932 void prepare_alt_odb(struct repository *r)
933 {
934 if (r->objects->loaded_alternates)
935 return;
936
937 link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
938
939 read_info_alternates(r, r->objects->odb->path, 0);
940 r->objects->loaded_alternates = 1;
941 }
942
943 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
944 static int freshen_file(const char *fn)
945 {
946 return !utime(fn, NULL);
947 }
948
949 /*
950 * All of the check_and_freshen functions return 1 if the file exists and was
951 * freshened (if freshening was requested), 0 otherwise. If they return
952 * 0, you should not assume that it is safe to skip a write of the object (it
953 * either does not exist on disk, or has a stale mtime and may be subject to
954 * pruning).
955 */
956 int check_and_freshen_file(const char *fn, int freshen)
957 {
958 if (access(fn, F_OK))
959 return 0;
960 if (freshen && !freshen_file(fn))
961 return 0;
962 return 1;
963 }
964
965 static int check_and_freshen_odb(struct object_directory *odb,
966 const struct object_id *oid,
967 int freshen)
968 {
969 static struct strbuf path = STRBUF_INIT;
970 odb_loose_path(odb, &path, oid);
971 return check_and_freshen_file(path.buf, freshen);
972 }
973
974 static int check_and_freshen_local(const struct object_id *oid, int freshen)
975 {
976 return check_and_freshen_odb(the_repository->objects->odb, oid, freshen);
977 }
978
979 static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
980 {
981 struct object_directory *odb;
982
983 prepare_alt_odb(the_repository);
984 for (odb = the_repository->objects->odb->next; odb; odb = odb->next) {
985 if (check_and_freshen_odb(odb, oid, freshen))
986 return 1;
987 }
988 return 0;
989 }
990
991 static int check_and_freshen(const struct object_id *oid, int freshen)
992 {
993 return check_and_freshen_local(oid, freshen) ||
994 check_and_freshen_nonlocal(oid, freshen);
995 }
996
997 int has_loose_object_nonlocal(const struct object_id *oid)
998 {
999 return check_and_freshen_nonlocal(oid, 0);
1000 }
1001
1002 static int has_loose_object(const struct object_id *oid)
1003 {
1004 return check_and_freshen(oid, 0);
1005 }
1006
1007 static void mmap_limit_check(size_t length)
1008 {
1009 static size_t limit = 0;
1010 if (!limit) {
1011 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
1012 if (!limit)
1013 limit = SIZE_MAX;
1014 }
1015 if (length > limit)
1016 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX),
1017 (uintmax_t)length, (uintmax_t)limit);
1018 }
1019
1020 void *xmmap_gently(void *start, size_t length,
1021 int prot, int flags, int fd, off_t offset)
1022 {
1023 void *ret;
1024
1025 mmap_limit_check(length);
1026 ret = mmap(start, length, prot, flags, fd, offset);
1027 if (ret == MAP_FAILED && !length)
1028 ret = NULL;
1029 return ret;
1030 }
1031
1032 const char *mmap_os_err(void)
1033 {
1034 static const char blank[] = "";
1035 #if defined(__linux__)
1036 if (errno == ENOMEM) {
1037 /* this continues an existing error message: */
1038 static const char enomem[] =
1039 ", check sys.vm.max_map_count and/or RLIMIT_DATA";
1040 return enomem;
1041 }
1042 #endif /* OS-specific bits */
1043 return blank;
1044 }
1045
1046 void *xmmap(void *start, size_t length,
1047 int prot, int flags, int fd, off_t offset)
1048 {
1049 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
1050 if (ret == MAP_FAILED)
1051 die_errno(_("mmap failed%s"), mmap_os_err());
1052 return ret;
1053 }
1054
1055 /*
1056 * With an in-core object data in "map", rehash it to make sure the
1057 * object name actually matches "oid" to detect object corruption.
1058 * With "map" == NULL, try reading the object named with "oid" using
1059 * the streaming interface and rehash it to do the same.
1060 */
1061 int check_object_signature(struct repository *r, const struct object_id *oid,
1062 void *map, unsigned long size, const char *type)
1063 {
1064 struct object_id real_oid;
1065 enum object_type obj_type;
1066 struct git_istream *st;
1067 git_hash_ctx c;
1068 char hdr[MAX_HEADER_LEN];
1069 int hdrlen;
1070
1071 if (map) {
1072 hash_object_file(r->hash_algo, map, size, type, &real_oid);
1073 return !oideq(oid, &real_oid) ? -1 : 0;
1074 }
1075
1076 st = open_istream(r, oid, &obj_type, &size, NULL);
1077 if (!st)
1078 return -1;
1079
1080 /* Generate the header */
1081 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %"PRIuMAX , type_name(obj_type), (uintmax_t)size) + 1;
1082
1083 /* Sha1.. */
1084 r->hash_algo->init_fn(&c);
1085 r->hash_algo->update_fn(&c, hdr, hdrlen);
1086 for (;;) {
1087 char buf[1024 * 16];
1088 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1089
1090 if (readlen < 0) {
1091 close_istream(st);
1092 return -1;
1093 }
1094 if (!readlen)
1095 break;
1096 r->hash_algo->update_fn(&c, buf, readlen);
1097 }
1098 r->hash_algo->final_oid_fn(&real_oid, &c);
1099 close_istream(st);
1100 return !oideq(oid, &real_oid) ? -1 : 0;
1101 }
1102
1103 int git_open_cloexec(const char *name, int flags)
1104 {
1105 int fd;
1106 static int o_cloexec = O_CLOEXEC;
1107
1108 fd = open(name, flags | o_cloexec);
1109 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
1110 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1111 o_cloexec &= ~O_CLOEXEC;
1112 fd = open(name, flags | o_cloexec);
1113 }
1114
1115 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
1116 {
1117 static int fd_cloexec = FD_CLOEXEC;
1118
1119 if (!o_cloexec && 0 <= fd && fd_cloexec) {
1120 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
1121 int flags = fcntl(fd, F_GETFD);
1122 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
1123 fd_cloexec = 0;
1124 }
1125 }
1126 #endif
1127 return fd;
1128 }
1129
1130 /*
1131 * Find "oid" as a loose object in the local repository or in an alternate.
1132 * Returns 0 on success, negative on failure.
1133 *
1134 * The "path" out-parameter will give the path of the object we found (if any).
1135 * Note that it may point to static storage and is only valid until another
1136 * call to stat_loose_object().
1137 */
1138 static int stat_loose_object(struct repository *r, const struct object_id *oid,
1139 struct stat *st, const char **path)
1140 {
1141 struct object_directory *odb;
1142 static struct strbuf buf = STRBUF_INIT;
1143
1144 prepare_alt_odb(r);
1145 for (odb = r->objects->odb; odb; odb = odb->next) {
1146 *path = odb_loose_path(odb, &buf, oid);
1147 if (!lstat(*path, st))
1148 return 0;
1149 }
1150
1151 return -1;
1152 }
1153
1154 /*
1155 * Like stat_loose_object(), but actually open the object and return the
1156 * descriptor. See the caveats on the "path" parameter above.
1157 */
1158 static int open_loose_object(struct repository *r,
1159 const struct object_id *oid, const char **path)
1160 {
1161 int fd;
1162 struct object_directory *odb;
1163 int most_interesting_errno = ENOENT;
1164 static struct strbuf buf = STRBUF_INIT;
1165
1166 prepare_alt_odb(r);
1167 for (odb = r->objects->odb; odb; odb = odb->next) {
1168 *path = odb_loose_path(odb, &buf, oid);
1169 fd = git_open(*path);
1170 if (fd >= 0)
1171 return fd;
1172
1173 if (most_interesting_errno == ENOENT)
1174 most_interesting_errno = errno;
1175 }
1176 errno = most_interesting_errno;
1177 return -1;
1178 }
1179
1180 static int quick_has_loose(struct repository *r,
1181 const struct object_id *oid)
1182 {
1183 struct object_directory *odb;
1184
1185 prepare_alt_odb(r);
1186 for (odb = r->objects->odb; odb; odb = odb->next) {
1187 if (oidtree_contains(odb_loose_cache(odb, oid), oid))
1188 return 1;
1189 }
1190 return 0;
1191 }
1192
1193 /*
1194 * Map the loose object at "path" if it is not NULL, or the path found by
1195 * searching for a loose object named "oid".
1196 */
1197 static void *map_loose_object_1(struct repository *r, const char *path,
1198 const struct object_id *oid, unsigned long *size)
1199 {
1200 void *map;
1201 int fd;
1202
1203 if (path)
1204 fd = git_open(path);
1205 else
1206 fd = open_loose_object(r, oid, &path);
1207 map = NULL;
1208 if (fd >= 0) {
1209 struct stat st;
1210
1211 if (!fstat(fd, &st)) {
1212 *size = xsize_t(st.st_size);
1213 if (!*size) {
1214 /* mmap() is forbidden on empty files */
1215 error(_("object file %s is empty"), path);
1216 close(fd);
1217 return NULL;
1218 }
1219 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1220 }
1221 close(fd);
1222 }
1223 return map;
1224 }
1225
1226 void *map_loose_object(struct repository *r,
1227 const struct object_id *oid,
1228 unsigned long *size)
1229 {
1230 return map_loose_object_1(r, NULL, oid, size);
1231 }
1232
1233 static int unpack_loose_short_header(git_zstream *stream,
1234 unsigned char *map, unsigned long mapsize,
1235 void *buffer, unsigned long bufsiz)
1236 {
1237 int ret;
1238
1239 /* Get the data stream */
1240 memset(stream, 0, sizeof(*stream));
1241 stream->next_in = map;
1242 stream->avail_in = mapsize;
1243 stream->next_out = buffer;
1244 stream->avail_out = bufsiz;
1245
1246 git_inflate_init(stream);
1247 obj_read_unlock();
1248 ret = git_inflate(stream, 0);
1249 obj_read_lock();
1250
1251 return ret;
1252 }
1253
1254 int unpack_loose_header(git_zstream *stream,
1255 unsigned char *map, unsigned long mapsize,
1256 void *buffer, unsigned long bufsiz)
1257 {
1258 int status = unpack_loose_short_header(stream, map, mapsize,
1259 buffer, bufsiz);
1260
1261 if (status < Z_OK)
1262 return status;
1263
1264 /* Make sure we have the terminating NUL */
1265 if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1266 return -1;
1267 return 0;
1268 }
1269
1270 static int unpack_loose_header_to_strbuf(git_zstream *stream, unsigned char *map,
1271 unsigned long mapsize, void *buffer,
1272 unsigned long bufsiz, struct strbuf *header)
1273 {
1274 int status;
1275
1276 status = unpack_loose_short_header(stream, map, mapsize, buffer, bufsiz);
1277 if (status < Z_OK)
1278 return -1;
1279
1280 /*
1281 * Check if entire header is unpacked in the first iteration.
1282 */
1283 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1284 return 0;
1285
1286 /*
1287 * buffer[0..bufsiz] was not large enough. Copy the partial
1288 * result out to header, and then append the result of further
1289 * reading the stream.
1290 */
1291 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1292 stream->next_out = buffer;
1293 stream->avail_out = bufsiz;
1294
1295 do {
1296 obj_read_unlock();
1297 status = git_inflate(stream, 0);
1298 obj_read_lock();
1299 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1300 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1301 return 0;
1302 stream->next_out = buffer;
1303 stream->avail_out = bufsiz;
1304 } while (status != Z_STREAM_END);
1305 return -1;
1306 }
1307
1308 static void *unpack_loose_rest(git_zstream *stream,
1309 void *buffer, unsigned long size,
1310 const struct object_id *oid)
1311 {
1312 int bytes = strlen(buffer) + 1;
1313 unsigned char *buf = xmallocz(size);
1314 unsigned long n;
1315 int status = Z_OK;
1316
1317 n = stream->total_out - bytes;
1318 if (n > size)
1319 n = size;
1320 memcpy(buf, (char *) buffer + bytes, n);
1321 bytes = n;
1322 if (bytes <= size) {
1323 /*
1324 * The above condition must be (bytes <= size), not
1325 * (bytes < size). In other words, even though we
1326 * expect no more output and set avail_out to zero,
1327 * the input zlib stream may have bytes that express
1328 * "this concludes the stream", and we *do* want to
1329 * eat that input.
1330 *
1331 * Otherwise we would not be able to test that we
1332 * consumed all the input to reach the expected size;
1333 * we also want to check that zlib tells us that all
1334 * went well with status == Z_STREAM_END at the end.
1335 */
1336 stream->next_out = buf + bytes;
1337 stream->avail_out = size - bytes;
1338 while (status == Z_OK) {
1339 obj_read_unlock();
1340 status = git_inflate(stream, Z_FINISH);
1341 obj_read_lock();
1342 }
1343 }
1344 if (status == Z_STREAM_END && !stream->avail_in) {
1345 git_inflate_end(stream);
1346 return buf;
1347 }
1348
1349 if (status < 0)
1350 error(_("corrupt loose object '%s'"), oid_to_hex(oid));
1351 else if (stream->avail_in)
1352 error(_("garbage at end of loose object '%s'"),
1353 oid_to_hex(oid));
1354 free(buf);
1355 return NULL;
1356 }
1357
1358 /*
1359 * We used to just use "sscanf()", but that's actually way
1360 * too permissive for what we want to check. So do an anal
1361 * object header parse by hand.
1362 */
1363 static int parse_loose_header_extended(const char *hdr, struct object_info *oi,
1364 unsigned int flags)
1365 {
1366 const char *type_buf = hdr;
1367 unsigned long size;
1368 int type, type_len = 0;
1369
1370 /*
1371 * The type can be of any size but is followed by
1372 * a space.
1373 */
1374 for (;;) {
1375 char c = *hdr++;
1376 if (!c)
1377 return -1;
1378 if (c == ' ')
1379 break;
1380 type_len++;
1381 }
1382
1383 type = type_from_string_gently(type_buf, type_len, 1);
1384 if (oi->type_name)
1385 strbuf_add(oi->type_name, type_buf, type_len);
1386 /*
1387 * Set type to 0 if its an unknown object and
1388 * we're obtaining the type using '--allow-unknown-type'
1389 * option.
1390 */
1391 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1392 type = 0;
1393 else if (type < 0)
1394 die(_("invalid object type"));
1395 if (oi->typep)
1396 *oi->typep = type;
1397
1398 /*
1399 * The length must follow immediately, and be in canonical
1400 * decimal format (ie "010" is not valid).
1401 */
1402 size = *hdr++ - '0';
1403 if (size > 9)
1404 return -1;
1405 if (size) {
1406 for (;;) {
1407 unsigned long c = *hdr - '0';
1408 if (c > 9)
1409 break;
1410 hdr++;
1411 size = size * 10 + c;
1412 }
1413 }
1414
1415 if (oi->sizep)
1416 *oi->sizep = size;
1417
1418 /*
1419 * The length must be followed by a zero byte
1420 */
1421 return *hdr ? -1 : type;
1422 }
1423
1424 int parse_loose_header(const char *hdr, unsigned long *sizep)
1425 {
1426 struct object_info oi = OBJECT_INFO_INIT;
1427
1428 oi.sizep = sizep;
1429 return parse_loose_header_extended(hdr, &oi, 0);
1430 }
1431
1432 static int loose_object_info(struct repository *r,
1433 const struct object_id *oid,
1434 struct object_info *oi, int flags)
1435 {
1436 int status = 0;
1437 unsigned long mapsize;
1438 void *map;
1439 git_zstream stream;
1440 char hdr[MAX_HEADER_LEN];
1441 struct strbuf hdrbuf = STRBUF_INIT;
1442 unsigned long size_scratch;
1443
1444 if (oi->delta_base_oid)
1445 oidclr(oi->delta_base_oid);
1446
1447 /*
1448 * If we don't care about type or size, then we don't
1449 * need to look inside the object at all. Note that we
1450 * do not optimize out the stat call, even if the
1451 * caller doesn't care about the disk-size, since our
1452 * return value implicitly indicates whether the
1453 * object even exists.
1454 */
1455 if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
1456 const char *path;
1457 struct stat st;
1458 if (!oi->disk_sizep && (flags & OBJECT_INFO_QUICK))
1459 return quick_has_loose(r, oid) ? 0 : -1;
1460 if (stat_loose_object(r, oid, &st, &path) < 0)
1461 return -1;
1462 if (oi->disk_sizep)
1463 *oi->disk_sizep = st.st_size;
1464 return 0;
1465 }
1466
1467 map = map_loose_object(r, oid, &mapsize);
1468 if (!map)
1469 return -1;
1470
1471 if (!oi->sizep)
1472 oi->sizep = &size_scratch;
1473
1474 if (oi->disk_sizep)
1475 *oi->disk_sizep = mapsize;
1476 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
1477 if (unpack_loose_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
1478 status = error(_("unable to unpack %s header with --allow-unknown-type"),
1479 oid_to_hex(oid));
1480 } else if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1481 status = error(_("unable to unpack %s header"),
1482 oid_to_hex(oid));
1483 if (status < 0)
1484 ; /* Do nothing */
1485 else if (hdrbuf.len) {
1486 if ((status = parse_loose_header_extended(hdrbuf.buf, oi, flags)) < 0)
1487 status = error(_("unable to parse %s header with --allow-unknown-type"),
1488 oid_to_hex(oid));
1489 } else if ((status = parse_loose_header_extended(hdr, oi, flags)) < 0)
1490 status = error(_("unable to parse %s header"), oid_to_hex(oid));
1491
1492 if (status >= 0 && oi->contentp) {
1493 *oi->contentp = unpack_loose_rest(&stream, hdr,
1494 *oi->sizep, oid);
1495 if (!*oi->contentp) {
1496 git_inflate_end(&stream);
1497 status = -1;
1498 }
1499 } else
1500 git_inflate_end(&stream);
1501
1502 munmap(map, mapsize);
1503 if (status && oi->typep)
1504 *oi->typep = status;
1505 if (oi->sizep == &size_scratch)
1506 oi->sizep = NULL;
1507 strbuf_release(&hdrbuf);
1508 oi->whence = OI_LOOSE;
1509 return (status < 0) ? status : 0;
1510 }
1511
1512 int obj_read_use_lock = 0;
1513 pthread_mutex_t obj_read_mutex;
1514
1515 void enable_obj_read_lock(void)
1516 {
1517 if (obj_read_use_lock)
1518 return;
1519
1520 obj_read_use_lock = 1;
1521 init_recursive_mutex(&obj_read_mutex);
1522 }
1523
1524 void disable_obj_read_lock(void)
1525 {
1526 if (!obj_read_use_lock)
1527 return;
1528
1529 obj_read_use_lock = 0;
1530 pthread_mutex_destroy(&obj_read_mutex);
1531 }
1532
1533 int fetch_if_missing = 1;
1534
1535 static int do_oid_object_info_extended(struct repository *r,
1536 const struct object_id *oid,
1537 struct object_info *oi, unsigned flags)
1538 {
1539 static struct object_info blank_oi = OBJECT_INFO_INIT;
1540 struct cached_object *co;
1541 struct pack_entry e;
1542 int rtype;
1543 const struct object_id *real = oid;
1544 int already_retried = 0;
1545
1546
1547 if (flags & OBJECT_INFO_LOOKUP_REPLACE)
1548 real = lookup_replace_object(r, oid);
1549
1550 if (is_null_oid(real))
1551 return -1;
1552
1553 if (!oi)
1554 oi = &blank_oi;
1555
1556 co = find_cached_object(real);
1557 if (co) {
1558 if (oi->typep)
1559 *(oi->typep) = co->type;
1560 if (oi->sizep)
1561 *(oi->sizep) = co->size;
1562 if (oi->disk_sizep)
1563 *(oi->disk_sizep) = 0;
1564 if (oi->delta_base_oid)
1565 oidclr(oi->delta_base_oid);
1566 if (oi->type_name)
1567 strbuf_addstr(oi->type_name, type_name(co->type));
1568 if (oi->contentp)
1569 *oi->contentp = xmemdupz(co->buf, co->size);
1570 oi->whence = OI_CACHED;
1571 return 0;
1572 }
1573
1574 while (1) {
1575 if (find_pack_entry(r, real, &e))
1576 break;
1577
1578 if (flags & OBJECT_INFO_IGNORE_LOOSE)
1579 return -1;
1580
1581 /* Most likely it's a loose object. */
1582 if (!loose_object_info(r, real, oi, flags))
1583 return 0;
1584
1585 /* Not a loose object; someone else may have just packed it. */
1586 if (!(flags & OBJECT_INFO_QUICK)) {
1587 reprepare_packed_git(r);
1588 if (find_pack_entry(r, real, &e))
1589 break;
1590 }
1591
1592 /* Check if it is a missing object */
1593 if (fetch_if_missing && repo_has_promisor_remote(r) &&
1594 !already_retried &&
1595 !(flags & OBJECT_INFO_SKIP_FETCH_OBJECT)) {
1596 /*
1597 * TODO Investigate checking promisor_remote_get_direct()
1598 * TODO return value and stopping on error here.
1599 */
1600 promisor_remote_get_direct(r, real, 1);
1601 already_retried = 1;
1602 continue;
1603 }
1604
1605 return -1;
1606 }
1607
1608 if (oi == &blank_oi)
1609 /*
1610 * We know that the caller doesn't actually need the
1611 * information below, so return early.
1612 */
1613 return 0;
1614 rtype = packed_object_info(r, e.p, e.offset, oi);
1615 if (rtype < 0) {
1616 mark_bad_packed_object(e.p, real->hash);
1617 return do_oid_object_info_extended(r, real, oi, 0);
1618 } else if (oi->whence == OI_PACKED) {
1619 oi->u.packed.offset = e.offset;
1620 oi->u.packed.pack = e.p;
1621 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1622 rtype == OBJ_OFS_DELTA);
1623 }
1624
1625 return 0;
1626 }
1627
1628 int oid_object_info_extended(struct repository *r, const struct object_id *oid,
1629 struct object_info *oi, unsigned flags)
1630 {
1631 int ret;
1632 obj_read_lock();
1633 ret = do_oid_object_info_extended(r, oid, oi, flags);
1634 obj_read_unlock();
1635 return ret;
1636 }
1637
1638
1639 /* returns enum object_type or negative */
1640 int oid_object_info(struct repository *r,
1641 const struct object_id *oid,
1642 unsigned long *sizep)
1643 {
1644 enum object_type type;
1645 struct object_info oi = OBJECT_INFO_INIT;
1646
1647 oi.typep = &type;
1648 oi.sizep = sizep;
1649 if (oid_object_info_extended(r, oid, &oi,
1650 OBJECT_INFO_LOOKUP_REPLACE) < 0)
1651 return -1;
1652 return type;
1653 }
1654
1655 static void *read_object(struct repository *r,
1656 const struct object_id *oid, enum object_type *type,
1657 unsigned long *size)
1658 {
1659 struct object_info oi = OBJECT_INFO_INIT;
1660 void *content;
1661 oi.typep = type;
1662 oi.sizep = size;
1663 oi.contentp = &content;
1664
1665 if (oid_object_info_extended(r, oid, &oi, 0) < 0)
1666 return NULL;
1667 return content;
1668 }
1669
1670 int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1671 struct object_id *oid)
1672 {
1673 struct cached_object *co;
1674
1675 hash_object_file(the_hash_algo, buf, len, type_name(type), oid);
1676 if (has_object_file_with_flags(oid, OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT) ||
1677 find_cached_object(oid))
1678 return 0;
1679 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1680 co = &cached_objects[cached_object_nr++];
1681 co->size = len;
1682 co->type = type;
1683 co->buf = xmalloc(len);
1684 memcpy(co->buf, buf, len);
1685 oidcpy(&co->oid, oid);
1686 return 0;
1687 }
1688
1689 /*
1690 * This function dies on corrupt objects; the callers who want to
1691 * deal with them should arrange to call read_object() and give error
1692 * messages themselves.
1693 */
1694 void *read_object_file_extended(struct repository *r,
1695 const struct object_id *oid,
1696 enum object_type *type,
1697 unsigned long *size,
1698 int lookup_replace)
1699 {
1700 void *data;
1701 const struct packed_git *p;
1702 const char *path;
1703 struct stat st;
1704 const struct object_id *repl = lookup_replace ?
1705 lookup_replace_object(r, oid) : oid;
1706
1707 errno = 0;
1708 data = read_object(r, repl, type, size);
1709 if (data)
1710 return data;
1711
1712 obj_read_lock();
1713 if (errno && errno != ENOENT)
1714 die_errno(_("failed to read object %s"), oid_to_hex(oid));
1715
1716 /* die if we replaced an object with one that does not exist */
1717 if (repl != oid)
1718 die(_("replacement %s not found for %s"),
1719 oid_to_hex(repl), oid_to_hex(oid));
1720
1721 if (!stat_loose_object(r, repl, &st, &path))
1722 die(_("loose object %s (stored in %s) is corrupt"),
1723 oid_to_hex(repl), path);
1724
1725 if ((p = has_packed_and_bad(r, repl->hash)) != NULL)
1726 die(_("packed object %s (stored in %s) is corrupt"),
1727 oid_to_hex(repl), p->pack_name);
1728 obj_read_unlock();
1729
1730 return NULL;
1731 }
1732
1733 void *read_object_with_reference(struct repository *r,
1734 const struct object_id *oid,
1735 const char *required_type_name,
1736 unsigned long *size,
1737 struct object_id *actual_oid_return)
1738 {
1739 enum object_type type, required_type;
1740 void *buffer;
1741 unsigned long isize;
1742 struct object_id actual_oid;
1743
1744 required_type = type_from_string(required_type_name);
1745 oidcpy(&actual_oid, oid);
1746 while (1) {
1747 int ref_length = -1;
1748 const char *ref_type = NULL;
1749
1750 buffer = repo_read_object_file(r, &actual_oid, &type, &isize);
1751 if (!buffer)
1752 return NULL;
1753 if (type == required_type) {
1754 *size = isize;
1755 if (actual_oid_return)
1756 oidcpy(actual_oid_return, &actual_oid);
1757 return buffer;
1758 }
1759 /* Handle references */
1760 else if (type == OBJ_COMMIT)
1761 ref_type = "tree ";
1762 else if (type == OBJ_TAG)
1763 ref_type = "object ";
1764 else {
1765 free(buffer);
1766 return NULL;
1767 }
1768 ref_length = strlen(ref_type);
1769
1770 if (ref_length + the_hash_algo->hexsz > isize ||
1771 memcmp(buffer, ref_type, ref_length) ||
1772 get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
1773 free(buffer);
1774 return NULL;
1775 }
1776 free(buffer);
1777 /* Now we have the ID of the referred-to object in
1778 * actual_oid. Check again. */
1779 }
1780 }
1781
1782 static void write_object_file_prepare(const struct git_hash_algo *algo,
1783 const void *buf, unsigned long len,
1784 const char *type, struct object_id *oid,
1785 char *hdr, int *hdrlen)
1786 {
1787 git_hash_ctx c;
1788
1789 /* Generate the header */
1790 *hdrlen = xsnprintf(hdr, *hdrlen, "%s %"PRIuMAX , type, (uintmax_t)len)+1;
1791
1792 /* Sha1.. */
1793 algo->init_fn(&c);
1794 algo->update_fn(&c, hdr, *hdrlen);
1795 algo->update_fn(&c, buf, len);
1796 algo->final_oid_fn(oid, &c);
1797 }
1798
1799 /*
1800 * Move the just written object into its final resting place.
1801 */
1802 int finalize_object_file(const char *tmpfile, const char *filename)
1803 {
1804 int ret = 0;
1805
1806 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
1807 goto try_rename;
1808 else if (link(tmpfile, filename))
1809 ret = errno;
1810
1811 /*
1812 * Coda hack - coda doesn't like cross-directory links,
1813 * so we fall back to a rename, which will mean that it
1814 * won't be able to check collisions, but that's not a
1815 * big deal.
1816 *
1817 * The same holds for FAT formatted media.
1818 *
1819 * When this succeeds, we just return. We have nothing
1820 * left to unlink.
1821 */
1822 if (ret && ret != EEXIST) {
1823 try_rename:
1824 if (!rename(tmpfile, filename))
1825 goto out;
1826 ret = errno;
1827 }
1828 unlink_or_warn(tmpfile);
1829 if (ret) {
1830 if (ret != EEXIST) {
1831 return error_errno(_("unable to write file %s"), filename);
1832 }
1833 /* FIXME!!! Collision check here ? */
1834 }
1835
1836 out:
1837 if (adjust_shared_perm(filename))
1838 return error(_("unable to set permission to '%s'"), filename);
1839 return 0;
1840 }
1841
1842 static int write_buffer(int fd, const void *buf, size_t len)
1843 {
1844 if (write_in_full(fd, buf, len) < 0)
1845 return error_errno(_("file write error"));
1846 return 0;
1847 }
1848
1849 int hash_object_file(const struct git_hash_algo *algo, const void *buf,
1850 unsigned long len, const char *type,
1851 struct object_id *oid)
1852 {
1853 char hdr[MAX_HEADER_LEN];
1854 int hdrlen = sizeof(hdr);
1855 write_object_file_prepare(algo, buf, len, type, oid, hdr, &hdrlen);
1856 return 0;
1857 }
1858
1859 /* Finalize a file on disk, and close it. */
1860 static void close_loose_object(int fd)
1861 {
1862 if (fsync_object_files)
1863 fsync_or_die(fd, "loose object file");
1864 if (close(fd) != 0)
1865 die_errno(_("error when closing loose object file"));
1866 }
1867
1868 /* Size of directory component, including the ending '/' */
1869 static inline int directory_size(const char *filename)
1870 {
1871 const char *s = strrchr(filename, '/');
1872 if (!s)
1873 return 0;
1874 return s - filename + 1;
1875 }
1876
1877 /*
1878 * This creates a temporary file in the same directory as the final
1879 * 'filename'
1880 *
1881 * We want to avoid cross-directory filename renames, because those
1882 * can have problems on various filesystems (FAT, NFS, Coda).
1883 */
1884 static int create_tmpfile(struct strbuf *tmp, const char *filename)
1885 {
1886 int fd, dirlen = directory_size(filename);
1887
1888 strbuf_reset(tmp);
1889 strbuf_add(tmp, filename, dirlen);
1890 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
1891 fd = git_mkstemp_mode(tmp->buf, 0444);
1892 if (fd < 0 && dirlen && errno == ENOENT) {
1893 /*
1894 * Make sure the directory exists; note that the contents
1895 * of the buffer are undefined after mkstemp returns an
1896 * error, so we have to rewrite the whole buffer from
1897 * scratch.
1898 */
1899 strbuf_reset(tmp);
1900 strbuf_add(tmp, filename, dirlen - 1);
1901 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
1902 return -1;
1903 if (adjust_shared_perm(tmp->buf))
1904 return -1;
1905
1906 /* Try again */
1907 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
1908 fd = git_mkstemp_mode(tmp->buf, 0444);
1909 }
1910 return fd;
1911 }
1912
1913 static int write_loose_object(const struct object_id *oid, char *hdr,
1914 int hdrlen, const void *buf, unsigned long len,
1915 time_t mtime)
1916 {
1917 int fd, ret;
1918 unsigned char compressed[4096];
1919 git_zstream stream;
1920 git_hash_ctx c;
1921 struct object_id parano_oid;
1922 static struct strbuf tmp_file = STRBUF_INIT;
1923 static struct strbuf filename = STRBUF_INIT;
1924
1925 loose_object_path(the_repository, &filename, oid);
1926
1927 fd = create_tmpfile(&tmp_file, filename.buf);
1928 if (fd < 0) {
1929 if (errno == EACCES)
1930 return error(_("insufficient permission for adding an object to repository database %s"), get_object_directory());
1931 else
1932 return error_errno(_("unable to create temporary file"));
1933 }
1934
1935 /* Set it up */
1936 git_deflate_init(&stream, zlib_compression_level);
1937 stream.next_out = compressed;
1938 stream.avail_out = sizeof(compressed);
1939 the_hash_algo->init_fn(&c);
1940
1941 /* First header.. */
1942 stream.next_in = (unsigned char *)hdr;
1943 stream.avail_in = hdrlen;
1944 while (git_deflate(&stream, 0) == Z_OK)
1945 ; /* nothing */
1946 the_hash_algo->update_fn(&c, hdr, hdrlen);
1947
1948 /* Then the data itself.. */
1949 stream.next_in = (void *)buf;
1950 stream.avail_in = len;
1951 do {
1952 unsigned char *in0 = stream.next_in;
1953 ret = git_deflate(&stream, Z_FINISH);
1954 the_hash_algo->update_fn(&c, in0, stream.next_in - in0);
1955 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
1956 die(_("unable to write loose object file"));
1957 stream.next_out = compressed;
1958 stream.avail_out = sizeof(compressed);
1959 } while (ret == Z_OK);
1960
1961 if (ret != Z_STREAM_END)
1962 die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
1963 ret);
1964 ret = git_deflate_end_gently(&stream);
1965 if (ret != Z_OK)
1966 die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
1967 ret);
1968 the_hash_algo->final_oid_fn(&parano_oid, &c);
1969 if (!oideq(oid, &parano_oid))
1970 die(_("confused by unstable object source data for %s"),
1971 oid_to_hex(oid));
1972
1973 close_loose_object(fd);
1974
1975 if (mtime) {
1976 struct utimbuf utb;
1977 utb.actime = mtime;
1978 utb.modtime = mtime;
1979 if (utime(tmp_file.buf, &utb) < 0)
1980 warning_errno(_("failed utime() on %s"), tmp_file.buf);
1981 }
1982
1983 return finalize_object_file(tmp_file.buf, filename.buf);
1984 }
1985
1986 static int freshen_loose_object(const struct object_id *oid)
1987 {
1988 return check_and_freshen(oid, 1);
1989 }
1990
1991 static int freshen_packed_object(const struct object_id *oid)
1992 {
1993 struct pack_entry e;
1994 if (!find_pack_entry(the_repository, oid, &e))
1995 return 0;
1996 if (e.p->freshened)
1997 return 1;
1998 if (!freshen_file(e.p->pack_name))
1999 return 0;
2000 e.p->freshened = 1;
2001 return 1;
2002 }
2003
2004 int write_object_file(const void *buf, unsigned long len, const char *type,
2005 struct object_id *oid)
2006 {
2007 char hdr[MAX_HEADER_LEN];
2008 int hdrlen = sizeof(hdr);
2009
2010 /* Normally if we have it in the pack then we do not bother writing
2011 * it out into .git/objects/??/?{38} file.
2012 */
2013 write_object_file_prepare(the_hash_algo, buf, len, type, oid, hdr,
2014 &hdrlen);
2015 if (freshen_packed_object(oid) || freshen_loose_object(oid))
2016 return 0;
2017 return write_loose_object(oid, hdr, hdrlen, buf, len, 0);
2018 }
2019
2020 int hash_object_file_literally(const void *buf, unsigned long len,
2021 const char *type, struct object_id *oid,
2022 unsigned flags)
2023 {
2024 char *header;
2025 int hdrlen, status = 0;
2026
2027 /* type string, SP, %lu of the length plus NUL must fit this */
2028 hdrlen = strlen(type) + MAX_HEADER_LEN;
2029 header = xmalloc(hdrlen);
2030 write_object_file_prepare(the_hash_algo, buf, len, type, oid, header,
2031 &hdrlen);
2032
2033 if (!(flags & HASH_WRITE_OBJECT))
2034 goto cleanup;
2035 if (freshen_packed_object(oid) || freshen_loose_object(oid))
2036 goto cleanup;
2037 status = write_loose_object(oid, header, hdrlen, buf, len, 0);
2038
2039 cleanup:
2040 free(header);
2041 return status;
2042 }
2043
2044 int force_object_loose(const struct object_id *oid, time_t mtime)
2045 {
2046 void *buf;
2047 unsigned long len;
2048 enum object_type type;
2049 char hdr[MAX_HEADER_LEN];
2050 int hdrlen;
2051 int ret;
2052
2053 if (has_loose_object(oid))
2054 return 0;
2055 buf = read_object(the_repository, oid, &type, &len);
2056 if (!buf)
2057 return error(_("cannot read object for %s"), oid_to_hex(oid));
2058 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %"PRIuMAX , type_name(type), (uintmax_t)len) + 1;
2059 ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime);
2060 free(buf);
2061
2062 return ret;
2063 }
2064
2065 int has_object(struct repository *r, const struct object_id *oid,
2066 unsigned flags)
2067 {
2068 int quick = !(flags & HAS_OBJECT_RECHECK_PACKED);
2069 unsigned object_info_flags = OBJECT_INFO_SKIP_FETCH_OBJECT |
2070 (quick ? OBJECT_INFO_QUICK : 0);
2071
2072 if (!startup_info->have_repository)
2073 return 0;
2074 return oid_object_info_extended(r, oid, NULL, object_info_flags) >= 0;
2075 }
2076
2077 int repo_has_object_file_with_flags(struct repository *r,
2078 const struct object_id *oid, int flags)
2079 {
2080 if (!startup_info->have_repository)
2081 return 0;
2082 return oid_object_info_extended(r, oid, NULL, flags) >= 0;
2083 }
2084
2085 int repo_has_object_file(struct repository *r,
2086 const struct object_id *oid)
2087 {
2088 return repo_has_object_file_with_flags(r, oid, 0);
2089 }
2090
2091 static void check_tree(const void *buf, size_t size)
2092 {
2093 struct tree_desc desc;
2094 struct name_entry entry;
2095
2096 init_tree_desc(&desc, buf, size);
2097 while (tree_entry(&desc, &entry))
2098 /* do nothing
2099 * tree_entry() will die() on malformed entries */
2100 ;
2101 }
2102
2103 static void check_commit(const void *buf, size_t size)
2104 {
2105 struct commit c;
2106 memset(&c, 0, sizeof(c));
2107 if (parse_commit_buffer(the_repository, &c, buf, size, 0))
2108 die(_("corrupt commit"));
2109 }
2110
2111 static void check_tag(const void *buf, size_t size)
2112 {
2113 struct tag t;
2114 memset(&t, 0, sizeof(t));
2115 if (parse_tag_buffer(the_repository, &t, buf, size))
2116 die(_("corrupt tag"));
2117 }
2118
2119 static int index_mem(struct index_state *istate,
2120 struct object_id *oid, void *buf, size_t size,
2121 enum object_type type,
2122 const char *path, unsigned flags)
2123 {
2124 int ret, re_allocated = 0;
2125 int write_object = flags & HASH_WRITE_OBJECT;
2126
2127 if (!type)
2128 type = OBJ_BLOB;
2129
2130 /*
2131 * Convert blobs to git internal format
2132 */
2133 if ((type == OBJ_BLOB) && path) {
2134 struct strbuf nbuf = STRBUF_INIT;
2135 if (convert_to_git(istate, path, buf, size, &nbuf,
2136 get_conv_flags(flags))) {
2137 buf = strbuf_detach(&nbuf, &size);
2138 re_allocated = 1;
2139 }
2140 }
2141 if (flags & HASH_FORMAT_CHECK) {
2142 if (type == OBJ_TREE)
2143 check_tree(buf, size);
2144 if (type == OBJ_COMMIT)
2145 check_commit(buf, size);
2146 if (type == OBJ_TAG)
2147 check_tag(buf, size);
2148 }
2149
2150 if (write_object)
2151 ret = write_object_file(buf, size, type_name(type), oid);
2152 else
2153 ret = hash_object_file(the_hash_algo, buf, size,
2154 type_name(type), oid);
2155 if (re_allocated)
2156 free(buf);
2157 return ret;
2158 }
2159
2160 static int index_stream_convert_blob(struct index_state *istate,
2161 struct object_id *oid,
2162 int fd,
2163 const char *path,
2164 unsigned flags)
2165 {
2166 int ret;
2167 const int write_object = flags & HASH_WRITE_OBJECT;
2168 struct strbuf sbuf = STRBUF_INIT;
2169
2170 assert(path);
2171 assert(would_convert_to_git_filter_fd(istate, path));
2172
2173 convert_to_git_filter_fd(istate, path, fd, &sbuf,
2174 get_conv_flags(flags));
2175
2176 if (write_object)
2177 ret = write_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
2178 oid);
2179 else
2180 ret = hash_object_file(the_hash_algo, sbuf.buf, sbuf.len,
2181 type_name(OBJ_BLOB), oid);
2182 strbuf_release(&sbuf);
2183 return ret;
2184 }
2185
2186 static int index_pipe(struct index_state *istate, struct object_id *oid,
2187 int fd, enum object_type type,
2188 const char *path, unsigned flags)
2189 {
2190 struct strbuf sbuf = STRBUF_INIT;
2191 int ret;
2192
2193 if (strbuf_read(&sbuf, fd, 4096) >= 0)
2194 ret = index_mem(istate, oid, sbuf.buf, sbuf.len, type, path, flags);
2195 else
2196 ret = -1;
2197 strbuf_release(&sbuf);
2198 return ret;
2199 }
2200
2201 #define SMALL_FILE_SIZE (32*1024)
2202
2203 static int index_core(struct index_state *istate,
2204 struct object_id *oid, int fd, size_t size,
2205 enum object_type type, const char *path,
2206 unsigned flags)
2207 {
2208 int ret;
2209
2210 if (!size) {
2211 ret = index_mem(istate, oid, "", size, type, path, flags);
2212 } else if (size <= SMALL_FILE_SIZE) {
2213 char *buf = xmalloc(size);
2214 ssize_t read_result = read_in_full(fd, buf, size);
2215 if (read_result < 0)
2216 ret = error_errno(_("read error while indexing %s"),
2217 path ? path : "<unknown>");
2218 else if (read_result != size)
2219 ret = error(_("short read while indexing %s"),
2220 path ? path : "<unknown>");
2221 else
2222 ret = index_mem(istate, oid, buf, size, type, path, flags);
2223 free(buf);
2224 } else {
2225 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2226 ret = index_mem(istate, oid, buf, size, type, path, flags);
2227 munmap(buf, size);
2228 }
2229 return ret;
2230 }
2231
2232 /*
2233 * This creates one packfile per large blob unless bulk-checkin
2234 * machinery is "plugged".
2235 *
2236 * This also bypasses the usual "convert-to-git" dance, and that is on
2237 * purpose. We could write a streaming version of the converting
2238 * functions and insert that before feeding the data to fast-import
2239 * (or equivalent in-core API described above). However, that is
2240 * somewhat complicated, as we do not know the size of the filter
2241 * result, which we need to know beforehand when writing a git object.
2242 * Since the primary motivation for trying to stream from the working
2243 * tree file and to avoid mmaping it in core is to deal with large
2244 * binary blobs, they generally do not want to get any conversion, and
2245 * callers should avoid this code path when filters are requested.
2246 */
2247 static int index_stream(struct object_id *oid, int fd, size_t size,
2248 enum object_type type, const char *path,
2249 unsigned flags)
2250 {
2251 return index_bulk_checkin(oid, fd, size, type, path, flags);
2252 }
2253
2254 int index_fd(struct index_state *istate, struct object_id *oid,
2255 int fd, struct stat *st,
2256 enum object_type type, const char *path, unsigned flags)
2257 {
2258 int ret;
2259
2260 /*
2261 * Call xsize_t() only when needed to avoid potentially unnecessary
2262 * die() for large files.
2263 */
2264 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path))
2265 ret = index_stream_convert_blob(istate, oid, fd, path, flags);
2266 else if (!S_ISREG(st->st_mode))
2267 ret = index_pipe(istate, oid, fd, type, path, flags);
2268 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
2269 (path && would_convert_to_git(istate, path)))
2270 ret = index_core(istate, oid, fd, xsize_t(st->st_size),
2271 type, path, flags);
2272 else
2273 ret = index_stream(oid, fd, xsize_t(st->st_size), type, path,
2274 flags);
2275 close(fd);
2276 return ret;
2277 }
2278
2279 int index_path(struct index_state *istate, struct object_id *oid,
2280 const char *path, struct stat *st, unsigned flags)
2281 {
2282 int fd;
2283 struct strbuf sb = STRBUF_INIT;
2284 int rc = 0;
2285
2286 switch (st->st_mode & S_IFMT) {
2287 case S_IFREG:
2288 fd = open(path, O_RDONLY);
2289 if (fd < 0)
2290 return error_errno("open(\"%s\")", path);
2291 if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
2292 return error(_("%s: failed to insert into database"),
2293 path);
2294 break;
2295 case S_IFLNK:
2296 if (strbuf_readlink(&sb, path, st->st_size))
2297 return error_errno("readlink(\"%s\")", path);
2298 if (!(flags & HASH_WRITE_OBJECT))
2299 hash_object_file(the_hash_algo, sb.buf, sb.len,
2300 blob_type, oid);
2301 else if (write_object_file(sb.buf, sb.len, blob_type, oid))
2302 rc = error(_("%s: failed to insert into database"), path);
2303 strbuf_release(&sb);
2304 break;
2305 case S_IFDIR:
2306 return resolve_gitlink_ref(path, "HEAD", oid);
2307 default:
2308 return error(_("%s: unsupported file type"), path);
2309 }
2310 return rc;
2311 }
2312
2313 int read_pack_header(int fd, struct pack_header *header)
2314 {
2315 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
2316 /* "eof before pack header was fully read" */
2317 return PH_ERROR_EOF;
2318
2319 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2320 /* "protocol error (pack signature mismatch detected)" */
2321 return PH_ERROR_PACK_SIGNATURE;
2322 if (!pack_version_ok(header->hdr_version))
2323 /* "protocol error (pack version unsupported)" */
2324 return PH_ERROR_PROTOCOL;
2325 return 0;
2326 }
2327
2328 void assert_oid_type(const struct object_id *oid, enum object_type expect)
2329 {
2330 enum object_type type = oid_object_info(the_repository, oid, NULL);
2331 if (type < 0)
2332 die(_("%s is not a valid object"), oid_to_hex(oid));
2333 if (type != expect)
2334 die(_("%s is not a valid '%s' object"), oid_to_hex(oid),
2335 type_name(expect));
2336 }
2337
2338 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
2339 struct strbuf *path,
2340 each_loose_object_fn obj_cb,
2341 each_loose_cruft_fn cruft_cb,
2342 each_loose_subdir_fn subdir_cb,
2343 void *data)
2344 {
2345 size_t origlen, baselen;
2346 DIR *dir;
2347 struct dirent *de;
2348 int r = 0;
2349 struct object_id oid;
2350
2351 if (subdir_nr > 0xff)
2352 BUG("invalid loose object subdirectory: %x", subdir_nr);
2353
2354 origlen = path->len;
2355 strbuf_complete(path, '/');
2356 strbuf_addf(path, "%02x", subdir_nr);
2357
2358 dir = opendir(path->buf);
2359 if (!dir) {
2360 if (errno != ENOENT)
2361 r = error_errno(_("unable to open %s"), path->buf);
2362 strbuf_setlen(path, origlen);
2363 return r;
2364 }
2365
2366 oid.hash[0] = subdir_nr;
2367 strbuf_addch(path, '/');
2368 baselen = path->len;
2369
2370 while ((de = readdir_skip_dot_and_dotdot(dir))) {
2371 size_t namelen;
2372
2373 namelen = strlen(de->d_name);
2374 strbuf_setlen(path, baselen);
2375 strbuf_add(path, de->d_name, namelen);
2376 if (namelen == the_hash_algo->hexsz - 2 &&
2377 !hex_to_bytes(oid.hash + 1, de->d_name,
2378 the_hash_algo->rawsz - 1)) {
2379 oid_set_algo(&oid, the_hash_algo);
2380 if (obj_cb) {
2381 r = obj_cb(&oid, path->buf, data);
2382 if (r)
2383 break;
2384 }
2385 continue;
2386 }
2387
2388 if (cruft_cb) {
2389 r = cruft_cb(de->d_name, path->buf, data);
2390 if (r)
2391 break;
2392 }
2393 }
2394 closedir(dir);
2395
2396 strbuf_setlen(path, baselen - 1);
2397 if (!r && subdir_cb)
2398 r = subdir_cb(subdir_nr, path->buf, data);
2399
2400 strbuf_setlen(path, origlen);
2401
2402 return r;
2403 }
2404
2405 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2406 each_loose_object_fn obj_cb,
2407 each_loose_cruft_fn cruft_cb,
2408 each_loose_subdir_fn subdir_cb,
2409 void *data)
2410 {
2411 int r = 0;
2412 int i;
2413
2414 for (i = 0; i < 256; i++) {
2415 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2416 subdir_cb, data);
2417 if (r)
2418 break;
2419 }
2420
2421 return r;
2422 }
2423
2424 int for_each_loose_file_in_objdir(const char *path,
2425 each_loose_object_fn obj_cb,
2426 each_loose_cruft_fn cruft_cb,
2427 each_loose_subdir_fn subdir_cb,
2428 void *data)
2429 {
2430 struct strbuf buf = STRBUF_INIT;
2431 int r;
2432
2433 strbuf_addstr(&buf, path);
2434 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2435 subdir_cb, data);
2436 strbuf_release(&buf);
2437
2438 return r;
2439 }
2440
2441 int for_each_loose_object(each_loose_object_fn cb, void *data,
2442 enum for_each_object_flags flags)
2443 {
2444 struct object_directory *odb;
2445
2446 prepare_alt_odb(the_repository);
2447 for (odb = the_repository->objects->odb; odb; odb = odb->next) {
2448 int r = for_each_loose_file_in_objdir(odb->path, cb, NULL,
2449 NULL, data);
2450 if (r)
2451 return r;
2452
2453 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2454 break;
2455 }
2456
2457 return 0;
2458 }
2459
2460 static int append_loose_object(const struct object_id *oid, const char *path,
2461 void *data)
2462 {
2463 oidtree_insert(data, oid);
2464 return 0;
2465 }
2466
2467 struct oidtree *odb_loose_cache(struct object_directory *odb,
2468 const struct object_id *oid)
2469 {
2470 int subdir_nr = oid->hash[0];
2471 struct strbuf buf = STRBUF_INIT;
2472 size_t word_bits = bitsizeof(odb->loose_objects_subdir_seen[0]);
2473 size_t word_index = subdir_nr / word_bits;
2474 size_t mask = 1u << (subdir_nr % word_bits);
2475 uint32_t *bitmap;
2476
2477 if (subdir_nr < 0 ||
2478 subdir_nr >= bitsizeof(odb->loose_objects_subdir_seen))
2479 BUG("subdir_nr out of range");
2480
2481 bitmap = &odb->loose_objects_subdir_seen[word_index];
2482 if (*bitmap & mask)
2483 return odb->loose_objects_cache;
2484 if (!odb->loose_objects_cache) {
2485 ALLOC_ARRAY(odb->loose_objects_cache, 1);
2486 oidtree_init(odb->loose_objects_cache);
2487 }
2488 strbuf_addstr(&buf, odb->path);
2489 for_each_file_in_obj_subdir(subdir_nr, &buf,
2490 append_loose_object,
2491 NULL, NULL,
2492 odb->loose_objects_cache);
2493 *bitmap |= mask;
2494 strbuf_release(&buf);
2495 return odb->loose_objects_cache;
2496 }
2497
2498 void odb_clear_loose_cache(struct object_directory *odb)
2499 {
2500 oidtree_clear(odb->loose_objects_cache);
2501 FREE_AND_NULL(odb->loose_objects_cache);
2502 memset(&odb->loose_objects_subdir_seen, 0,
2503 sizeof(odb->loose_objects_subdir_seen));
2504 }
2505
2506 static int check_stream_oid(git_zstream *stream,
2507 const char *hdr,
2508 unsigned long size,
2509 const char *path,
2510 const struct object_id *expected_oid)
2511 {
2512 git_hash_ctx c;
2513 struct object_id real_oid;
2514 unsigned char buf[4096];
2515 unsigned long total_read;
2516 int status = Z_OK;
2517
2518 the_hash_algo->init_fn(&c);
2519 the_hash_algo->update_fn(&c, hdr, stream->total_out);
2520
2521 /*
2522 * We already read some bytes into hdr, but the ones up to the NUL
2523 * do not count against the object's content size.
2524 */
2525 total_read = stream->total_out - strlen(hdr) - 1;
2526
2527 /*
2528 * This size comparison must be "<=" to read the final zlib packets;
2529 * see the comment in unpack_loose_rest for details.
2530 */
2531 while (total_read <= size &&
2532 (status == Z_OK ||
2533 (status == Z_BUF_ERROR && !stream->avail_out))) {
2534 stream->next_out = buf;
2535 stream->avail_out = sizeof(buf);
2536 if (size - total_read < stream->avail_out)
2537 stream->avail_out = size - total_read;
2538 status = git_inflate(stream, Z_FINISH);
2539 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
2540 total_read += stream->next_out - buf;
2541 }
2542 git_inflate_end(stream);
2543
2544 if (status != Z_STREAM_END) {
2545 error(_("corrupt loose object '%s'"), oid_to_hex(expected_oid));
2546 return -1;
2547 }
2548 if (stream->avail_in) {
2549 error(_("garbage at end of loose object '%s'"),
2550 oid_to_hex(expected_oid));
2551 return -1;
2552 }
2553
2554 the_hash_algo->final_oid_fn(&real_oid, &c);
2555 if (!oideq(expected_oid, &real_oid)) {
2556 error(_("hash mismatch for %s (expected %s)"), path,
2557 oid_to_hex(expected_oid));
2558 return -1;
2559 }
2560
2561 return 0;
2562 }
2563
2564 int read_loose_object(const char *path,
2565 const struct object_id *expected_oid,
2566 enum object_type *type,
2567 unsigned long *size,
2568 void **contents)
2569 {
2570 int ret = -1;
2571 void *map = NULL;
2572 unsigned long mapsize;
2573 git_zstream stream;
2574 char hdr[MAX_HEADER_LEN];
2575
2576 *contents = NULL;
2577
2578 map = map_loose_object_1(the_repository, path, NULL, &mapsize);
2579 if (!map) {
2580 error_errno(_("unable to mmap %s"), path);
2581 goto out;
2582 }
2583
2584 if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
2585 error(_("unable to unpack header of %s"), path);
2586 goto out;
2587 }
2588
2589 *type = parse_loose_header(hdr, size);
2590 if (*type < 0) {
2591 error(_("unable to parse header of %s"), path);
2592 git_inflate_end(&stream);
2593 goto out;
2594 }
2595
2596 if (*type == OBJ_BLOB && *size > big_file_threshold) {
2597 if (check_stream_oid(&stream, hdr, *size, path, expected_oid) < 0)
2598 goto out;
2599 } else {
2600 *contents = unpack_loose_rest(&stream, hdr, *size, expected_oid);
2601 if (!*contents) {
2602 error(_("unable to unpack contents of %s"), path);
2603 git_inflate_end(&stream);
2604 goto out;
2605 }
2606 if (check_object_signature(the_repository, expected_oid,
2607 *contents, *size,
2608 type_name(*type))) {
2609 error(_("hash mismatch for %s (expected %s)"), path,
2610 oid_to_hex(expected_oid));
2611 free(*contents);
2612 goto out;
2613 }
2614 }
2615
2616 ret = 0; /* everything checks out */
2617
2618 out:
2619 if (map)
2620 munmap(map, mapsize);
2621 return ret;
2622 }