pack: move pack_report()
[git/git.git] / sha1_file.c
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 */
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 "sha1-lookup.h"
24 #include "bulk-checkin.h"
25 #include "streaming.h"
26 #include "dir.h"
27 #include "mru.h"
28 #include "list.h"
29 #include "mergesort.h"
30 #include "quote.h"
31 #include "packfile.h"
32
33 const unsigned char null_sha1[20];
34 const struct object_id null_oid;
35 const struct object_id empty_tree_oid = {
36 EMPTY_TREE_SHA1_BIN_LITERAL
37 };
38 const struct object_id empty_blob_oid = {
39 EMPTY_BLOB_SHA1_BIN_LITERAL
40 };
41
42 /*
43 * This is meant to hold a *small* number of objects that you would
44 * want read_sha1_file() to be able to return, but yet you do not want
45 * to write them into the object store (e.g. a browse-only
46 * application).
47 */
48 static struct cached_object {
49 unsigned char sha1[20];
50 enum object_type type;
51 void *buf;
52 unsigned long size;
53 } *cached_objects;
54 static int cached_object_nr, cached_object_alloc;
55
56 static struct cached_object empty_tree = {
57 EMPTY_TREE_SHA1_BIN_LITERAL,
58 OBJ_TREE,
59 "",
60 0
61 };
62
63 static struct cached_object *find_cached_object(const unsigned char *sha1)
64 {
65 int i;
66 struct cached_object *co = cached_objects;
67
68 for (i = 0; i < cached_object_nr; i++, co++) {
69 if (!hashcmp(co->sha1, sha1))
70 return co;
71 }
72 if (!hashcmp(sha1, empty_tree.sha1))
73 return &empty_tree;
74 return NULL;
75 }
76
77 int mkdir_in_gitdir(const char *path)
78 {
79 if (mkdir(path, 0777)) {
80 int saved_errno = errno;
81 struct stat st;
82 struct strbuf sb = STRBUF_INIT;
83
84 if (errno != EEXIST)
85 return -1;
86 /*
87 * Are we looking at a path in a symlinked worktree
88 * whose original repository does not yet have it?
89 * e.g. .git/rr-cache pointing at its original
90 * repository in which the user hasn't performed any
91 * conflict resolution yet?
92 */
93 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
94 strbuf_readlink(&sb, path, st.st_size) ||
95 !is_absolute_path(sb.buf) ||
96 mkdir(sb.buf, 0777)) {
97 strbuf_release(&sb);
98 errno = saved_errno;
99 return -1;
100 }
101 strbuf_release(&sb);
102 }
103 return adjust_shared_perm(path);
104 }
105
106 enum scld_error safe_create_leading_directories(char *path)
107 {
108 char *next_component = path + offset_1st_component(path);
109 enum scld_error ret = SCLD_OK;
110
111 while (ret == SCLD_OK && next_component) {
112 struct stat st;
113 char *slash = next_component, slash_character;
114
115 while (*slash && !is_dir_sep(*slash))
116 slash++;
117
118 if (!*slash)
119 break;
120
121 next_component = slash + 1;
122 while (is_dir_sep(*next_component))
123 next_component++;
124 if (!*next_component)
125 break;
126
127 slash_character = *slash;
128 *slash = '\0';
129 if (!stat(path, &st)) {
130 /* path exists */
131 if (!S_ISDIR(st.st_mode)) {
132 errno = ENOTDIR;
133 ret = SCLD_EXISTS;
134 }
135 } else if (mkdir(path, 0777)) {
136 if (errno == EEXIST &&
137 !stat(path, &st) && S_ISDIR(st.st_mode))
138 ; /* somebody created it since we checked */
139 else if (errno == ENOENT)
140 /*
141 * Either mkdir() failed because
142 * somebody just pruned the containing
143 * directory, or stat() failed because
144 * the file that was in our way was
145 * just removed. Either way, inform
146 * the caller that it might be worth
147 * trying again:
148 */
149 ret = SCLD_VANISHED;
150 else
151 ret = SCLD_FAILED;
152 } else if (adjust_shared_perm(path)) {
153 ret = SCLD_PERMS;
154 }
155 *slash = slash_character;
156 }
157 return ret;
158 }
159
160 enum scld_error safe_create_leading_directories_const(const char *path)
161 {
162 int save_errno;
163 /* path points to cache entries, so xstrdup before messing with it */
164 char *buf = xstrdup(path);
165 enum scld_error result = safe_create_leading_directories(buf);
166
167 save_errno = errno;
168 free(buf);
169 errno = save_errno;
170 return result;
171 }
172
173 int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
174 {
175 /*
176 * The number of times we will try to remove empty directories
177 * in the way of path. This is only 1 because if another
178 * process is racily creating directories that conflict with
179 * us, we don't want to fight against them.
180 */
181 int remove_directories_remaining = 1;
182
183 /*
184 * The number of times that we will try to create the
185 * directories containing path. We are willing to attempt this
186 * more than once, because another process could be trying to
187 * clean up empty directories at the same time as we are
188 * trying to create them.
189 */
190 int create_directories_remaining = 3;
191
192 /* A scratch copy of path, filled lazily if we need it: */
193 struct strbuf path_copy = STRBUF_INIT;
194
195 int ret, save_errno;
196
197 /* Sanity check: */
198 assert(*path);
199
200 retry_fn:
201 ret = fn(path, cb);
202 save_errno = errno;
203 if (!ret)
204 goto out;
205
206 if (errno == EISDIR && remove_directories_remaining-- > 0) {
207 /*
208 * A directory is in the way. Maybe it is empty; try
209 * to remove it:
210 */
211 if (!path_copy.len)
212 strbuf_addstr(&path_copy, path);
213
214 if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
215 goto retry_fn;
216 } else if (errno == ENOENT && create_directories_remaining-- > 0) {
217 /*
218 * Maybe the containing directory didn't exist, or
219 * maybe it was just deleted by a process that is
220 * racing with us to clean up empty directories. Try
221 * to create it:
222 */
223 enum scld_error scld_result;
224
225 if (!path_copy.len)
226 strbuf_addstr(&path_copy, path);
227
228 do {
229 scld_result = safe_create_leading_directories(path_copy.buf);
230 if (scld_result == SCLD_OK)
231 goto retry_fn;
232 } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
233 }
234
235 out:
236 strbuf_release(&path_copy);
237 errno = save_errno;
238 return ret;
239 }
240
241 static void fill_sha1_path(struct strbuf *buf, const unsigned char *sha1)
242 {
243 int i;
244 for (i = 0; i < 20; i++) {
245 static char hex[] = "0123456789abcdef";
246 unsigned int val = sha1[i];
247 strbuf_addch(buf, hex[val >> 4]);
248 strbuf_addch(buf, hex[val & 0xf]);
249 if (!i)
250 strbuf_addch(buf, '/');
251 }
252 }
253
254 const char *sha1_file_name(const unsigned char *sha1)
255 {
256 static struct strbuf buf = STRBUF_INIT;
257
258 strbuf_reset(&buf);
259 strbuf_addf(&buf, "%s/", get_object_directory());
260
261 fill_sha1_path(&buf, sha1);
262 return buf.buf;
263 }
264
265 struct strbuf *alt_scratch_buf(struct alternate_object_database *alt)
266 {
267 strbuf_setlen(&alt->scratch, alt->base_len);
268 return &alt->scratch;
269 }
270
271 static const char *alt_sha1_path(struct alternate_object_database *alt,
272 const unsigned char *sha1)
273 {
274 struct strbuf *buf = alt_scratch_buf(alt);
275 fill_sha1_path(buf, sha1);
276 return buf->buf;
277 }
278
279 struct alternate_object_database *alt_odb_list;
280 static struct alternate_object_database **alt_odb_tail;
281
282 /*
283 * Return non-zero iff the path is usable as an alternate object database.
284 */
285 static int alt_odb_usable(struct strbuf *path, const char *normalized_objdir)
286 {
287 struct alternate_object_database *alt;
288
289 /* Detect cases where alternate disappeared */
290 if (!is_directory(path->buf)) {
291 error("object directory %s does not exist; "
292 "check .git/objects/info/alternates.",
293 path->buf);
294 return 0;
295 }
296
297 /*
298 * Prevent the common mistake of listing the same
299 * thing twice, or object directory itself.
300 */
301 for (alt = alt_odb_list; alt; alt = alt->next) {
302 if (!fspathcmp(path->buf, alt->path))
303 return 0;
304 }
305 if (!fspathcmp(path->buf, normalized_objdir))
306 return 0;
307
308 return 1;
309 }
310
311 /*
312 * Prepare alternate object database registry.
313 *
314 * The variable alt_odb_list points at the list of struct
315 * alternate_object_database. The elements on this list come from
316 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
317 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
318 * whose contents is similar to that environment variable but can be
319 * LF separated. Its base points at a statically allocated buffer that
320 * contains "/the/directory/corresponding/to/.git/objects/...", while
321 * its name points just after the slash at the end of ".git/objects/"
322 * in the example above, and has enough space to hold 40-byte hex
323 * SHA1, an extra slash for the first level indirection, and the
324 * terminating NUL.
325 */
326 static void read_info_alternates(const char * relative_base, int depth);
327 static int link_alt_odb_entry(const char *entry, const char *relative_base,
328 int depth, const char *normalized_objdir)
329 {
330 struct alternate_object_database *ent;
331 struct strbuf pathbuf = STRBUF_INIT;
332
333 if (!is_absolute_path(entry) && relative_base) {
334 strbuf_realpath(&pathbuf, relative_base, 1);
335 strbuf_addch(&pathbuf, '/');
336 }
337 strbuf_addstr(&pathbuf, entry);
338
339 if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
340 error("unable to normalize alternate object path: %s",
341 pathbuf.buf);
342 strbuf_release(&pathbuf);
343 return -1;
344 }
345
346 /*
347 * The trailing slash after the directory name is given by
348 * this function at the end. Remove duplicates.
349 */
350 while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
351 strbuf_setlen(&pathbuf, pathbuf.len - 1);
352
353 if (!alt_odb_usable(&pathbuf, normalized_objdir)) {
354 strbuf_release(&pathbuf);
355 return -1;
356 }
357
358 ent = alloc_alt_odb(pathbuf.buf);
359
360 /* add the alternate entry */
361 *alt_odb_tail = ent;
362 alt_odb_tail = &(ent->next);
363 ent->next = NULL;
364
365 /* recursively add alternates */
366 read_info_alternates(pathbuf.buf, depth + 1);
367
368 strbuf_release(&pathbuf);
369 return 0;
370 }
371
372 static const char *parse_alt_odb_entry(const char *string,
373 int sep,
374 struct strbuf *out)
375 {
376 const char *end;
377
378 strbuf_reset(out);
379
380 if (*string == '#') {
381 /* comment; consume up to next separator */
382 end = strchrnul(string, sep);
383 } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
384 /*
385 * quoted path; unquote_c_style has copied the
386 * data for us and set "end". Broken quoting (e.g.,
387 * an entry that doesn't end with a quote) falls
388 * back to the unquoted case below.
389 */
390 } else {
391 /* normal, unquoted path */
392 end = strchrnul(string, sep);
393 strbuf_add(out, string, end - string);
394 }
395
396 if (*end)
397 end++;
398 return end;
399 }
400
401 static void link_alt_odb_entries(const char *alt, int len, int sep,
402 const char *relative_base, int depth)
403 {
404 struct strbuf objdirbuf = STRBUF_INIT;
405 struct strbuf entry = STRBUF_INIT;
406
407 if (depth > 5) {
408 error("%s: ignoring alternate object stores, nesting too deep.",
409 relative_base);
410 return;
411 }
412
413 strbuf_add_absolute_path(&objdirbuf, get_object_directory());
414 if (strbuf_normalize_path(&objdirbuf) < 0)
415 die("unable to normalize object directory: %s",
416 objdirbuf.buf);
417
418 while (*alt) {
419 alt = parse_alt_odb_entry(alt, sep, &entry);
420 if (!entry.len)
421 continue;
422 link_alt_odb_entry(entry.buf, relative_base, depth, objdirbuf.buf);
423 }
424 strbuf_release(&entry);
425 strbuf_release(&objdirbuf);
426 }
427
428 static void read_info_alternates(const char * relative_base, int depth)
429 {
430 char *map;
431 size_t mapsz;
432 struct stat st;
433 char *path;
434 int fd;
435
436 path = xstrfmt("%s/info/alternates", relative_base);
437 fd = git_open(path);
438 free(path);
439 if (fd < 0)
440 return;
441 if (fstat(fd, &st) || (st.st_size == 0)) {
442 close(fd);
443 return;
444 }
445 mapsz = xsize_t(st.st_size);
446 map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
447 close(fd);
448
449 link_alt_odb_entries(map, mapsz, '\n', relative_base, depth);
450
451 munmap(map, mapsz);
452 }
453
454 struct alternate_object_database *alloc_alt_odb(const char *dir)
455 {
456 struct alternate_object_database *ent;
457
458 FLEX_ALLOC_STR(ent, path, dir);
459 strbuf_init(&ent->scratch, 0);
460 strbuf_addf(&ent->scratch, "%s/", dir);
461 ent->base_len = ent->scratch.len;
462
463 return ent;
464 }
465
466 void add_to_alternates_file(const char *reference)
467 {
468 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
469 char *alts = git_pathdup("objects/info/alternates");
470 FILE *in, *out;
471
472 hold_lock_file_for_update(lock, alts, LOCK_DIE_ON_ERROR);
473 out = fdopen_lock_file(lock, "w");
474 if (!out)
475 die_errno("unable to fdopen alternates lockfile");
476
477 in = fopen(alts, "r");
478 if (in) {
479 struct strbuf line = STRBUF_INIT;
480 int found = 0;
481
482 while (strbuf_getline(&line, in) != EOF) {
483 if (!strcmp(reference, line.buf)) {
484 found = 1;
485 break;
486 }
487 fprintf_or_die(out, "%s\n", line.buf);
488 }
489
490 strbuf_release(&line);
491 fclose(in);
492
493 if (found) {
494 rollback_lock_file(lock);
495 lock = NULL;
496 }
497 }
498 else if (errno != ENOENT)
499 die_errno("unable to read alternates file");
500
501 if (lock) {
502 fprintf_or_die(out, "%s\n", reference);
503 if (commit_lock_file(lock))
504 die_errno("unable to move new alternates file into place");
505 if (alt_odb_tail)
506 link_alt_odb_entries(reference, strlen(reference), '\n', NULL, 0);
507 }
508 free(alts);
509 }
510
511 void add_to_alternates_memory(const char *reference)
512 {
513 /*
514 * Make sure alternates are initialized, or else our entry may be
515 * overwritten when they are.
516 */
517 prepare_alt_odb();
518
519 link_alt_odb_entries(reference, strlen(reference), '\n', NULL, 0);
520 }
521
522 /*
523 * Compute the exact path an alternate is at and returns it. In case of
524 * error NULL is returned and the human readable error is added to `err`
525 * `path` may be relative and should point to $GITDIR.
526 * `err` must not be null.
527 */
528 char *compute_alternate_path(const char *path, struct strbuf *err)
529 {
530 char *ref_git = NULL;
531 const char *repo, *ref_git_s;
532 int seen_error = 0;
533
534 ref_git_s = real_path_if_valid(path);
535 if (!ref_git_s) {
536 seen_error = 1;
537 strbuf_addf(err, _("path '%s' does not exist"), path);
538 goto out;
539 } else
540 /*
541 * Beware: read_gitfile(), real_path() and mkpath()
542 * return static buffer
543 */
544 ref_git = xstrdup(ref_git_s);
545
546 repo = read_gitfile(ref_git);
547 if (!repo)
548 repo = read_gitfile(mkpath("%s/.git", ref_git));
549 if (repo) {
550 free(ref_git);
551 ref_git = xstrdup(repo);
552 }
553
554 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
555 char *ref_git_git = mkpathdup("%s/.git", ref_git);
556 free(ref_git);
557 ref_git = ref_git_git;
558 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
559 struct strbuf sb = STRBUF_INIT;
560 seen_error = 1;
561 if (get_common_dir(&sb, ref_git)) {
562 strbuf_addf(err,
563 _("reference repository '%s' as a linked "
564 "checkout is not supported yet."),
565 path);
566 goto out;
567 }
568
569 strbuf_addf(err, _("reference repository '%s' is not a "
570 "local repository."), path);
571 goto out;
572 }
573
574 if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
575 strbuf_addf(err, _("reference repository '%s' is shallow"),
576 path);
577 seen_error = 1;
578 goto out;
579 }
580
581 if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
582 strbuf_addf(err,
583 _("reference repository '%s' is grafted"),
584 path);
585 seen_error = 1;
586 goto out;
587 }
588
589 out:
590 if (seen_error) {
591 FREE_AND_NULL(ref_git);
592 }
593
594 return ref_git;
595 }
596
597 int foreach_alt_odb(alt_odb_fn fn, void *cb)
598 {
599 struct alternate_object_database *ent;
600 int r = 0;
601
602 prepare_alt_odb();
603 for (ent = alt_odb_list; ent; ent = ent->next) {
604 r = fn(ent, cb);
605 if (r)
606 break;
607 }
608 return r;
609 }
610
611 void prepare_alt_odb(void)
612 {
613 const char *alt;
614
615 if (alt_odb_tail)
616 return;
617
618 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
619 if (!alt) alt = "";
620
621 alt_odb_tail = &alt_odb_list;
622 link_alt_odb_entries(alt, strlen(alt), PATH_SEP, NULL, 0);
623
624 read_info_alternates(get_object_directory(), 0);
625 }
626
627 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
628 static int freshen_file(const char *fn)
629 {
630 struct utimbuf t;
631 t.actime = t.modtime = time(NULL);
632 return !utime(fn, &t);
633 }
634
635 /*
636 * All of the check_and_freshen functions return 1 if the file exists and was
637 * freshened (if freshening was requested), 0 otherwise. If they return
638 * 0, you should not assume that it is safe to skip a write of the object (it
639 * either does not exist on disk, or has a stale mtime and may be subject to
640 * pruning).
641 */
642 int check_and_freshen_file(const char *fn, int freshen)
643 {
644 if (access(fn, F_OK))
645 return 0;
646 if (freshen && !freshen_file(fn))
647 return 0;
648 return 1;
649 }
650
651 static int check_and_freshen_local(const unsigned char *sha1, int freshen)
652 {
653 return check_and_freshen_file(sha1_file_name(sha1), freshen);
654 }
655
656 static int check_and_freshen_nonlocal(const unsigned char *sha1, int freshen)
657 {
658 struct alternate_object_database *alt;
659 prepare_alt_odb();
660 for (alt = alt_odb_list; alt; alt = alt->next) {
661 const char *path = alt_sha1_path(alt, sha1);
662 if (check_and_freshen_file(path, freshen))
663 return 1;
664 }
665 return 0;
666 }
667
668 static int check_and_freshen(const unsigned char *sha1, int freshen)
669 {
670 return check_and_freshen_local(sha1, freshen) ||
671 check_and_freshen_nonlocal(sha1, freshen);
672 }
673
674 int has_loose_object_nonlocal(const unsigned char *sha1)
675 {
676 return check_and_freshen_nonlocal(sha1, 0);
677 }
678
679 static int has_loose_object(const unsigned char *sha1)
680 {
681 return check_and_freshen(sha1, 0);
682 }
683
684 /*
685 * Open and mmap the index file at path, perform a couple of
686 * consistency checks, then record its information to p. Return 0 on
687 * success.
688 */
689 static int check_packed_git_idx(const char *path, struct packed_git *p)
690 {
691 void *idx_map;
692 struct pack_idx_header *hdr;
693 size_t idx_size;
694 uint32_t version, nr, i, *index;
695 int fd = git_open(path);
696 struct stat st;
697
698 if (fd < 0)
699 return -1;
700 if (fstat(fd, &st)) {
701 close(fd);
702 return -1;
703 }
704 idx_size = xsize_t(st.st_size);
705 if (idx_size < 4 * 256 + 20 + 20) {
706 close(fd);
707 return error("index file %s is too small", path);
708 }
709 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
710 close(fd);
711
712 hdr = idx_map;
713 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
714 version = ntohl(hdr->idx_version);
715 if (version < 2 || version > 2) {
716 munmap(idx_map, idx_size);
717 return error("index file %s is version %"PRIu32
718 " and is not supported by this binary"
719 " (try upgrading GIT to a newer version)",
720 path, version);
721 }
722 } else
723 version = 1;
724
725 nr = 0;
726 index = idx_map;
727 if (version > 1)
728 index += 2; /* skip index header */
729 for (i = 0; i < 256; i++) {
730 uint32_t n = ntohl(index[i]);
731 if (n < nr) {
732 munmap(idx_map, idx_size);
733 return error("non-monotonic index %s", path);
734 }
735 nr = n;
736 }
737
738 if (version == 1) {
739 /*
740 * Total size:
741 * - 256 index entries 4 bytes each
742 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
743 * - 20-byte SHA1 of the packfile
744 * - 20-byte SHA1 file checksum
745 */
746 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
747 munmap(idx_map, idx_size);
748 return error("wrong index v1 file size in %s", path);
749 }
750 } else if (version == 2) {
751 /*
752 * Minimum size:
753 * - 8 bytes of header
754 * - 256 index entries 4 bytes each
755 * - 20-byte sha1 entry * nr
756 * - 4-byte crc entry * nr
757 * - 4-byte offset entry * nr
758 * - 20-byte SHA1 of the packfile
759 * - 20-byte SHA1 file checksum
760 * And after the 4-byte offset table might be a
761 * variable sized table containing 8-byte entries
762 * for offsets larger than 2^31.
763 */
764 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
765 unsigned long max_size = min_size;
766 if (nr)
767 max_size += (nr - 1)*8;
768 if (idx_size < min_size || idx_size > max_size) {
769 munmap(idx_map, idx_size);
770 return error("wrong index v2 file size in %s", path);
771 }
772 if (idx_size != min_size &&
773 /*
774 * make sure we can deal with large pack offsets.
775 * 31-bit signed offset won't be enough, neither
776 * 32-bit unsigned one will be.
777 */
778 (sizeof(off_t) <= 4)) {
779 munmap(idx_map, idx_size);
780 return error("pack too large for current definition of off_t in %s", path);
781 }
782 }
783
784 p->index_version = version;
785 p->index_data = idx_map;
786 p->index_size = idx_size;
787 p->num_objects = nr;
788 return 0;
789 }
790
791 int open_pack_index(struct packed_git *p)
792 {
793 char *idx_name;
794 size_t len;
795 int ret;
796
797 if (p->index_data)
798 return 0;
799
800 if (!strip_suffix(p->pack_name, ".pack", &len))
801 die("BUG: pack_name does not end in .pack");
802 idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
803 ret = check_packed_git_idx(idx_name, p);
804 free(idx_name);
805 return ret;
806 }
807
808 static void scan_windows(struct packed_git *p,
809 struct packed_git **lru_p,
810 struct pack_window **lru_w,
811 struct pack_window **lru_l)
812 {
813 struct pack_window *w, *w_l;
814
815 for (w_l = NULL, w = p->windows; w; w = w->next) {
816 if (!w->inuse_cnt) {
817 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
818 *lru_p = p;
819 *lru_w = w;
820 *lru_l = w_l;
821 }
822 }
823 w_l = w;
824 }
825 }
826
827 static int unuse_one_window(struct packed_git *current)
828 {
829 struct packed_git *p, *lru_p = NULL;
830 struct pack_window *lru_w = NULL, *lru_l = NULL;
831
832 if (current)
833 scan_windows(current, &lru_p, &lru_w, &lru_l);
834 for (p = packed_git; p; p = p->next)
835 scan_windows(p, &lru_p, &lru_w, &lru_l);
836 if (lru_p) {
837 munmap(lru_w->base, lru_w->len);
838 pack_mapped -= lru_w->len;
839 if (lru_l)
840 lru_l->next = lru_w->next;
841 else
842 lru_p->windows = lru_w->next;
843 free(lru_w);
844 pack_open_windows--;
845 return 1;
846 }
847 return 0;
848 }
849
850 void release_pack_memory(size_t need)
851 {
852 size_t cur = pack_mapped;
853 while (need >= (cur - pack_mapped) && unuse_one_window(NULL))
854 ; /* nothing */
855 }
856
857 static void mmap_limit_check(size_t length)
858 {
859 static size_t limit = 0;
860 if (!limit) {
861 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
862 if (!limit)
863 limit = SIZE_MAX;
864 }
865 if (length > limit)
866 die("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX,
867 (uintmax_t)length, (uintmax_t)limit);
868 }
869
870 void *xmmap_gently(void *start, size_t length,
871 int prot, int flags, int fd, off_t offset)
872 {
873 void *ret;
874
875 mmap_limit_check(length);
876 ret = mmap(start, length, prot, flags, fd, offset);
877 if (ret == MAP_FAILED) {
878 if (!length)
879 return NULL;
880 release_pack_memory(length);
881 ret = mmap(start, length, prot, flags, fd, offset);
882 }
883 return ret;
884 }
885
886 void *xmmap(void *start, size_t length,
887 int prot, int flags, int fd, off_t offset)
888 {
889 void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
890 if (ret == MAP_FAILED)
891 die_errno("mmap failed");
892 return ret;
893 }
894
895 void close_pack_windows(struct packed_git *p)
896 {
897 while (p->windows) {
898 struct pack_window *w = p->windows;
899
900 if (w->inuse_cnt)
901 die("pack '%s' still has open windows to it",
902 p->pack_name);
903 munmap(w->base, w->len);
904 pack_mapped -= w->len;
905 pack_open_windows--;
906 p->windows = w->next;
907 free(w);
908 }
909 }
910
911 static int close_pack_fd(struct packed_git *p)
912 {
913 if (p->pack_fd < 0)
914 return 0;
915
916 close(p->pack_fd);
917 pack_open_fds--;
918 p->pack_fd = -1;
919
920 return 1;
921 }
922
923 static void close_pack(struct packed_git *p)
924 {
925 close_pack_windows(p);
926 close_pack_fd(p);
927 close_pack_index(p);
928 }
929
930 void close_all_packs(void)
931 {
932 struct packed_git *p;
933
934 for (p = packed_git; p; p = p->next)
935 if (p->do_not_close)
936 die("BUG: want to close pack marked 'do-not-close'");
937 else
938 close_pack(p);
939 }
940
941
942 /*
943 * The LRU pack is the one with the oldest MRU window, preferring packs
944 * with no used windows, or the oldest mtime if it has no windows allocated.
945 */
946 static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
947 {
948 struct pack_window *w, *this_mru_w;
949 int has_windows_inuse = 0;
950
951 /*
952 * Reject this pack if it has windows and the previously selected
953 * one does not. If this pack does not have windows, reject
954 * it if the pack file is newer than the previously selected one.
955 */
956 if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
957 return;
958
959 for (w = this_mru_w = p->windows; w; w = w->next) {
960 /*
961 * Reject this pack if any of its windows are in use,
962 * but the previously selected pack did not have any
963 * inuse windows. Otherwise, record that this pack
964 * has windows in use.
965 */
966 if (w->inuse_cnt) {
967 if (*accept_windows_inuse)
968 has_windows_inuse = 1;
969 else
970 return;
971 }
972
973 if (w->last_used > this_mru_w->last_used)
974 this_mru_w = w;
975
976 /*
977 * Reject this pack if it has windows that have been
978 * used more recently than the previously selected pack.
979 * If the previously selected pack had windows inuse and
980 * we have not encountered a window in this pack that is
981 * inuse, skip this check since we prefer a pack with no
982 * inuse windows to one that has inuse windows.
983 */
984 if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
985 this_mru_w->last_used > (*mru_w)->last_used)
986 return;
987 }
988
989 /*
990 * Select this pack.
991 */
992 *mru_w = this_mru_w;
993 *lru_p = p;
994 *accept_windows_inuse = has_windows_inuse;
995 }
996
997 static int close_one_pack(void)
998 {
999 struct packed_git *p, *lru_p = NULL;
1000 struct pack_window *mru_w = NULL;
1001 int accept_windows_inuse = 1;
1002
1003 for (p = packed_git; p; p = p->next) {
1004 if (p->pack_fd == -1)
1005 continue;
1006 find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
1007 }
1008
1009 if (lru_p)
1010 return close_pack_fd(lru_p);
1011
1012 return 0;
1013 }
1014
1015 void unuse_pack(struct pack_window **w_cursor)
1016 {
1017 struct pack_window *w = *w_cursor;
1018 if (w) {
1019 w->inuse_cnt--;
1020 *w_cursor = NULL;
1021 }
1022 }
1023
1024 void close_pack_index(struct packed_git *p)
1025 {
1026 if (p->index_data) {
1027 munmap((void *)p->index_data, p->index_size);
1028 p->index_data = NULL;
1029 }
1030 }
1031
1032 static unsigned int get_max_fd_limit(void)
1033 {
1034 #ifdef RLIMIT_NOFILE
1035 {
1036 struct rlimit lim;
1037
1038 if (!getrlimit(RLIMIT_NOFILE, &lim))
1039 return lim.rlim_cur;
1040 }
1041 #endif
1042
1043 #ifdef _SC_OPEN_MAX
1044 {
1045 long open_max = sysconf(_SC_OPEN_MAX);
1046 if (0 < open_max)
1047 return open_max;
1048 /*
1049 * Otherwise, we got -1 for one of the two
1050 * reasons:
1051 *
1052 * (1) sysconf() did not understand _SC_OPEN_MAX
1053 * and signaled an error with -1; or
1054 * (2) sysconf() said there is no limit.
1055 *
1056 * We _could_ clear errno before calling sysconf() to
1057 * tell these two cases apart and return a huge number
1058 * in the latter case to let the caller cap it to a
1059 * value that is not so selfish, but letting the
1060 * fallback OPEN_MAX codepath take care of these cases
1061 * is a lot simpler.
1062 */
1063 }
1064 #endif
1065
1066 #ifdef OPEN_MAX
1067 return OPEN_MAX;
1068 #else
1069 return 1; /* see the caller ;-) */
1070 #endif
1071 }
1072
1073 /*
1074 * Do not call this directly as this leaks p->pack_fd on error return;
1075 * call open_packed_git() instead.
1076 */
1077 static int open_packed_git_1(struct packed_git *p)
1078 {
1079 struct stat st;
1080 struct pack_header hdr;
1081 unsigned char sha1[20];
1082 unsigned char *idx_sha1;
1083 long fd_flag;
1084
1085 if (!p->index_data && open_pack_index(p))
1086 return error("packfile %s index unavailable", p->pack_name);
1087
1088 if (!pack_max_fds) {
1089 unsigned int max_fds = get_max_fd_limit();
1090
1091 /* Save 3 for stdin/stdout/stderr, 22 for work */
1092 if (25 < max_fds)
1093 pack_max_fds = max_fds - 25;
1094 else
1095 pack_max_fds = 1;
1096 }
1097
1098 while (pack_max_fds <= pack_open_fds && close_one_pack())
1099 ; /* nothing */
1100
1101 p->pack_fd = git_open(p->pack_name);
1102 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
1103 return -1;
1104 pack_open_fds++;
1105
1106 /* If we created the struct before we had the pack we lack size. */
1107 if (!p->pack_size) {
1108 if (!S_ISREG(st.st_mode))
1109 return error("packfile %s not a regular file", p->pack_name);
1110 p->pack_size = st.st_size;
1111 } else if (p->pack_size != st.st_size)
1112 return error("packfile %s size changed", p->pack_name);
1113
1114 /* We leave these file descriptors open with sliding mmap;
1115 * there is no point keeping them open across exec(), though.
1116 */
1117 fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
1118 if (fd_flag < 0)
1119 return error("cannot determine file descriptor flags");
1120 fd_flag |= FD_CLOEXEC;
1121 if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
1122 return error("cannot set FD_CLOEXEC");
1123
1124 /* Verify we recognize this pack file format. */
1125 if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
1126 return error("file %s is far too short to be a packfile", p->pack_name);
1127 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
1128 return error("file %s is not a GIT packfile", p->pack_name);
1129 if (!pack_version_ok(hdr.hdr_version))
1130 return error("packfile %s is version %"PRIu32" and not"
1131 " supported (try upgrading GIT to a newer version)",
1132 p->pack_name, ntohl(hdr.hdr_version));
1133
1134 /* Verify the pack matches its index. */
1135 if (p->num_objects != ntohl(hdr.hdr_entries))
1136 return error("packfile %s claims to have %"PRIu32" objects"
1137 " while index indicates %"PRIu32" objects",
1138 p->pack_name, ntohl(hdr.hdr_entries),
1139 p->num_objects);
1140 if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
1141 return error("end of packfile %s is unavailable", p->pack_name);
1142 if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
1143 return error("packfile %s signature is unavailable", p->pack_name);
1144 idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
1145 if (hashcmp(sha1, idx_sha1))
1146 return error("packfile %s does not match index", p->pack_name);
1147 return 0;
1148 }
1149
1150 static int open_packed_git(struct packed_git *p)
1151 {
1152 if (!open_packed_git_1(p))
1153 return 0;
1154 close_pack_fd(p);
1155 return -1;
1156 }
1157
1158 static int in_window(struct pack_window *win, off_t offset)
1159 {
1160 /* We must promise at least 20 bytes (one hash) after the
1161 * offset is available from this window, otherwise the offset
1162 * is not actually in this window and a different window (which
1163 * has that one hash excess) must be used. This is to support
1164 * the object header and delta base parsing routines below.
1165 */
1166 off_t win_off = win->offset;
1167 return win_off <= offset
1168 && (offset + 20) <= (win_off + win->len);
1169 }
1170
1171 unsigned char *use_pack(struct packed_git *p,
1172 struct pack_window **w_cursor,
1173 off_t offset,
1174 unsigned long *left)
1175 {
1176 struct pack_window *win = *w_cursor;
1177
1178 /* Since packfiles end in a hash of their content and it's
1179 * pointless to ask for an offset into the middle of that
1180 * hash, and the in_window function above wouldn't match
1181 * don't allow an offset too close to the end of the file.
1182 */
1183 if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
1184 die("packfile %s cannot be accessed", p->pack_name);
1185 if (offset > (p->pack_size - 20))
1186 die("offset beyond end of packfile (truncated pack?)");
1187 if (offset < 0)
1188 die(_("offset before end of packfile (broken .idx?)"));
1189
1190 if (!win || !in_window(win, offset)) {
1191 if (win)
1192 win->inuse_cnt--;
1193 for (win = p->windows; win; win = win->next) {
1194 if (in_window(win, offset))
1195 break;
1196 }
1197 if (!win) {
1198 size_t window_align = packed_git_window_size / 2;
1199 off_t len;
1200
1201 if (p->pack_fd == -1 && open_packed_git(p))
1202 die("packfile %s cannot be accessed", p->pack_name);
1203
1204 win = xcalloc(1, sizeof(*win));
1205 win->offset = (offset / window_align) * window_align;
1206 len = p->pack_size - win->offset;
1207 if (len > packed_git_window_size)
1208 len = packed_git_window_size;
1209 win->len = (size_t)len;
1210 pack_mapped += win->len;
1211 while (packed_git_limit < pack_mapped
1212 && unuse_one_window(p))
1213 ; /* nothing */
1214 win->base = xmmap(NULL, win->len,
1215 PROT_READ, MAP_PRIVATE,
1216 p->pack_fd, win->offset);
1217 if (win->base == MAP_FAILED)
1218 die_errno("packfile %s cannot be mapped",
1219 p->pack_name);
1220 if (!win->offset && win->len == p->pack_size
1221 && !p->do_not_close)
1222 close_pack_fd(p);
1223 pack_mmap_calls++;
1224 pack_open_windows++;
1225 if (pack_mapped > peak_pack_mapped)
1226 peak_pack_mapped = pack_mapped;
1227 if (pack_open_windows > peak_pack_open_windows)
1228 peak_pack_open_windows = pack_open_windows;
1229 win->next = p->windows;
1230 p->windows = win;
1231 }
1232 }
1233 if (win != *w_cursor) {
1234 win->last_used = pack_used_ctr++;
1235 win->inuse_cnt++;
1236 *w_cursor = win;
1237 }
1238 offset -= win->offset;
1239 if (left)
1240 *left = win->len - xsize_t(offset);
1241 return win->base + offset;
1242 }
1243
1244 static struct packed_git *alloc_packed_git(int extra)
1245 {
1246 struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
1247 memset(p, 0, sizeof(*p));
1248 p->pack_fd = -1;
1249 return p;
1250 }
1251
1252 static void try_to_free_pack_memory(size_t size)
1253 {
1254 release_pack_memory(size);
1255 }
1256
1257 struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
1258 {
1259 static int have_set_try_to_free_routine;
1260 struct stat st;
1261 size_t alloc;
1262 struct packed_git *p;
1263
1264 if (!have_set_try_to_free_routine) {
1265 have_set_try_to_free_routine = 1;
1266 set_try_to_free_routine(try_to_free_pack_memory);
1267 }
1268
1269 /*
1270 * Make sure a corresponding .pack file exists and that
1271 * the index looks sane.
1272 */
1273 if (!strip_suffix_mem(path, &path_len, ".idx"))
1274 return NULL;
1275
1276 /*
1277 * ".pack" is long enough to hold any suffix we're adding (and
1278 * the use xsnprintf double-checks that)
1279 */
1280 alloc = st_add3(path_len, strlen(".pack"), 1);
1281 p = alloc_packed_git(alloc);
1282 memcpy(p->pack_name, path, path_len);
1283
1284 xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
1285 if (!access(p->pack_name, F_OK))
1286 p->pack_keep = 1;
1287
1288 xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
1289 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
1290 free(p);
1291 return NULL;
1292 }
1293
1294 /* ok, it looks sane as far as we can check without
1295 * actually mapping the pack file.
1296 */
1297 p->pack_size = st.st_size;
1298 p->pack_local = local;
1299 p->mtime = st.st_mtime;
1300 if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
1301 hashclr(p->sha1);
1302 return p;
1303 }
1304
1305 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
1306 {
1307 const char *path = sha1_pack_name(sha1);
1308 size_t alloc = st_add(strlen(path), 1);
1309 struct packed_git *p = alloc_packed_git(alloc);
1310
1311 memcpy(p->pack_name, path, alloc); /* includes NUL */
1312 hashcpy(p->sha1, sha1);
1313 if (check_packed_git_idx(idx_path, p)) {
1314 free(p);
1315 return NULL;
1316 }
1317
1318 return p;
1319 }
1320
1321 void install_packed_git(struct packed_git *pack)
1322 {
1323 if (pack->pack_fd != -1)
1324 pack_open_fds++;
1325
1326 pack->next = packed_git;
1327 packed_git = pack;
1328 }
1329
1330 void (*report_garbage)(unsigned seen_bits, const char *path);
1331
1332 static void report_helper(const struct string_list *list,
1333 int seen_bits, int first, int last)
1334 {
1335 if (seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))
1336 return;
1337
1338 for (; first < last; first++)
1339 report_garbage(seen_bits, list->items[first].string);
1340 }
1341
1342 static void report_pack_garbage(struct string_list *list)
1343 {
1344 int i, baselen = -1, first = 0, seen_bits = 0;
1345
1346 if (!report_garbage)
1347 return;
1348
1349 string_list_sort(list);
1350
1351 for (i = 0; i < list->nr; i++) {
1352 const char *path = list->items[i].string;
1353 if (baselen != -1 &&
1354 strncmp(path, list->items[first].string, baselen)) {
1355 report_helper(list, seen_bits, first, i);
1356 baselen = -1;
1357 seen_bits = 0;
1358 }
1359 if (baselen == -1) {
1360 const char *dot = strrchr(path, '.');
1361 if (!dot) {
1362 report_garbage(PACKDIR_FILE_GARBAGE, path);
1363 continue;
1364 }
1365 baselen = dot - path + 1;
1366 first = i;
1367 }
1368 if (!strcmp(path + baselen, "pack"))
1369 seen_bits |= 1;
1370 else if (!strcmp(path + baselen, "idx"))
1371 seen_bits |= 2;
1372 }
1373 report_helper(list, seen_bits, first, list->nr);
1374 }
1375
1376 static void prepare_packed_git_one(char *objdir, int local)
1377 {
1378 struct strbuf path = STRBUF_INIT;
1379 size_t dirnamelen;
1380 DIR *dir;
1381 struct dirent *de;
1382 struct string_list garbage = STRING_LIST_INIT_DUP;
1383
1384 strbuf_addstr(&path, objdir);
1385 strbuf_addstr(&path, "/pack");
1386 dir = opendir(path.buf);
1387 if (!dir) {
1388 if (errno != ENOENT)
1389 error_errno("unable to open object pack directory: %s",
1390 path.buf);
1391 strbuf_release(&path);
1392 return;
1393 }
1394 strbuf_addch(&path, '/');
1395 dirnamelen = path.len;
1396 while ((de = readdir(dir)) != NULL) {
1397 struct packed_git *p;
1398 size_t base_len;
1399
1400 if (is_dot_or_dotdot(de->d_name))
1401 continue;
1402
1403 strbuf_setlen(&path, dirnamelen);
1404 strbuf_addstr(&path, de->d_name);
1405
1406 base_len = path.len;
1407 if (strip_suffix_mem(path.buf, &base_len, ".idx")) {
1408 /* Don't reopen a pack we already have. */
1409 for (p = packed_git; p; p = p->next) {
1410 size_t len;
1411 if (strip_suffix(p->pack_name, ".pack", &len) &&
1412 len == base_len &&
1413 !memcmp(p->pack_name, path.buf, len))
1414 break;
1415 }
1416 if (p == NULL &&
1417 /*
1418 * See if it really is a valid .idx file with
1419 * corresponding .pack file that we can map.
1420 */
1421 (p = add_packed_git(path.buf, path.len, local)) != NULL)
1422 install_packed_git(p);
1423 }
1424
1425 if (!report_garbage)
1426 continue;
1427
1428 if (ends_with(de->d_name, ".idx") ||
1429 ends_with(de->d_name, ".pack") ||
1430 ends_with(de->d_name, ".bitmap") ||
1431 ends_with(de->d_name, ".keep"))
1432 string_list_append(&garbage, path.buf);
1433 else
1434 report_garbage(PACKDIR_FILE_GARBAGE, path.buf);
1435 }
1436 closedir(dir);
1437 report_pack_garbage(&garbage);
1438 string_list_clear(&garbage, 0);
1439 strbuf_release(&path);
1440 }
1441
1442 static int approximate_object_count_valid;
1443
1444 /*
1445 * Give a fast, rough count of the number of objects in the repository. This
1446 * ignores loose objects completely. If you have a lot of them, then either
1447 * you should repack because your performance will be awful, or they are
1448 * all unreachable objects about to be pruned, in which case they're not really
1449 * interesting as a measure of repo size in the first place.
1450 */
1451 unsigned long approximate_object_count(void)
1452 {
1453 static unsigned long count;
1454 if (!approximate_object_count_valid) {
1455 struct packed_git *p;
1456
1457 prepare_packed_git();
1458 count = 0;
1459 for (p = packed_git; p; p = p->next) {
1460 if (open_pack_index(p))
1461 continue;
1462 count += p->num_objects;
1463 }
1464 }
1465 return count;
1466 }
1467
1468 static void *get_next_packed_git(const void *p)
1469 {
1470 return ((const struct packed_git *)p)->next;
1471 }
1472
1473 static void set_next_packed_git(void *p, void *next)
1474 {
1475 ((struct packed_git *)p)->next = next;
1476 }
1477
1478 static int sort_pack(const void *a_, const void *b_)
1479 {
1480 const struct packed_git *a = a_;
1481 const struct packed_git *b = b_;
1482 int st;
1483
1484 /*
1485 * Local packs tend to contain objects specific to our
1486 * variant of the project than remote ones. In addition,
1487 * remote ones could be on a network mounted filesystem.
1488 * Favor local ones for these reasons.
1489 */
1490 st = a->pack_local - b->pack_local;
1491 if (st)
1492 return -st;
1493
1494 /*
1495 * Younger packs tend to contain more recent objects,
1496 * and more recent objects tend to get accessed more
1497 * often.
1498 */
1499 if (a->mtime < b->mtime)
1500 return 1;
1501 else if (a->mtime == b->mtime)
1502 return 0;
1503 return -1;
1504 }
1505
1506 static void rearrange_packed_git(void)
1507 {
1508 packed_git = llist_mergesort(packed_git, get_next_packed_git,
1509 set_next_packed_git, sort_pack);
1510 }
1511
1512 static void prepare_packed_git_mru(void)
1513 {
1514 struct packed_git *p;
1515
1516 mru_clear(packed_git_mru);
1517 for (p = packed_git; p; p = p->next)
1518 mru_append(packed_git_mru, p);
1519 }
1520
1521 static int prepare_packed_git_run_once = 0;
1522 void prepare_packed_git(void)
1523 {
1524 struct alternate_object_database *alt;
1525
1526 if (prepare_packed_git_run_once)
1527 return;
1528 prepare_packed_git_one(get_object_directory(), 1);
1529 prepare_alt_odb();
1530 for (alt = alt_odb_list; alt; alt = alt->next)
1531 prepare_packed_git_one(alt->path, 0);
1532 rearrange_packed_git();
1533 prepare_packed_git_mru();
1534 prepare_packed_git_run_once = 1;
1535 }
1536
1537 void reprepare_packed_git(void)
1538 {
1539 approximate_object_count_valid = 0;
1540 prepare_packed_git_run_once = 0;
1541 prepare_packed_git();
1542 }
1543
1544 static void mark_bad_packed_object(struct packed_git *p,
1545 const unsigned char *sha1)
1546 {
1547 unsigned i;
1548 for (i = 0; i < p->num_bad_objects; i++)
1549 if (!hashcmp(sha1, p->bad_object_sha1 + GIT_SHA1_RAWSZ * i))
1550 return;
1551 p->bad_object_sha1 = xrealloc(p->bad_object_sha1,
1552 st_mult(GIT_MAX_RAWSZ,
1553 st_add(p->num_bad_objects, 1)));
1554 hashcpy(p->bad_object_sha1 + GIT_SHA1_RAWSZ * p->num_bad_objects, sha1);
1555 p->num_bad_objects++;
1556 }
1557
1558 static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1559 {
1560 struct packed_git *p;
1561 unsigned i;
1562
1563 for (p = packed_git; p; p = p->next)
1564 for (i = 0; i < p->num_bad_objects; i++)
1565 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1566 return p;
1567 return NULL;
1568 }
1569
1570 /*
1571 * With an in-core object data in "map", rehash it to make sure the
1572 * object name actually matches "sha1" to detect object corruption.
1573 * With "map" == NULL, try reading the object named with "sha1" using
1574 * the streaming interface and rehash it to do the same.
1575 */
1576 int check_sha1_signature(const unsigned char *sha1, void *map,
1577 unsigned long size, const char *type)
1578 {
1579 unsigned char real_sha1[20];
1580 enum object_type obj_type;
1581 struct git_istream *st;
1582 git_SHA_CTX c;
1583 char hdr[32];
1584 int hdrlen;
1585
1586 if (map) {
1587 hash_sha1_file(map, size, type, real_sha1);
1588 return hashcmp(sha1, real_sha1) ? -1 : 0;
1589 }
1590
1591 st = open_istream(sha1, &obj_type, &size, NULL);
1592 if (!st)
1593 return -1;
1594
1595 /* Generate the header */
1596 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(obj_type), size) + 1;
1597
1598 /* Sha1.. */
1599 git_SHA1_Init(&c);
1600 git_SHA1_Update(&c, hdr, hdrlen);
1601 for (;;) {
1602 char buf[1024 * 16];
1603 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1604
1605 if (readlen < 0) {
1606 close_istream(st);
1607 return -1;
1608 }
1609 if (!readlen)
1610 break;
1611 git_SHA1_Update(&c, buf, readlen);
1612 }
1613 git_SHA1_Final(real_sha1, &c);
1614 close_istream(st);
1615 return hashcmp(sha1, real_sha1) ? -1 : 0;
1616 }
1617
1618 int git_open_cloexec(const char *name, int flags)
1619 {
1620 int fd;
1621 static int o_cloexec = O_CLOEXEC;
1622
1623 fd = open(name, flags | o_cloexec);
1624 if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
1625 /* Try again w/o O_CLOEXEC: the kernel might not support it */
1626 o_cloexec &= ~O_CLOEXEC;
1627 fd = open(name, flags | o_cloexec);
1628 }
1629
1630 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
1631 {
1632 static int fd_cloexec = FD_CLOEXEC;
1633
1634 if (!o_cloexec && 0 <= fd && fd_cloexec) {
1635 /* Opened w/o O_CLOEXEC? try with fcntl(2) to add it */
1636 int flags = fcntl(fd, F_GETFD);
1637 if (fcntl(fd, F_SETFD, flags | fd_cloexec))
1638 fd_cloexec = 0;
1639 }
1640 }
1641 #endif
1642 return fd;
1643 }
1644
1645 /*
1646 * Find "sha1" as a loose object in the local repository or in an alternate.
1647 * Returns 0 on success, negative on failure.
1648 *
1649 * The "path" out-parameter will give the path of the object we found (if any).
1650 * Note that it may point to static storage and is only valid until another
1651 * call to sha1_file_name(), etc.
1652 */
1653 static int stat_sha1_file(const unsigned char *sha1, struct stat *st,
1654 const char **path)
1655 {
1656 struct alternate_object_database *alt;
1657
1658 *path = sha1_file_name(sha1);
1659 if (!lstat(*path, st))
1660 return 0;
1661
1662 prepare_alt_odb();
1663 errno = ENOENT;
1664 for (alt = alt_odb_list; alt; alt = alt->next) {
1665 *path = alt_sha1_path(alt, sha1);
1666 if (!lstat(*path, st))
1667 return 0;
1668 }
1669
1670 return -1;
1671 }
1672
1673 /*
1674 * Like stat_sha1_file(), but actually open the object and return the
1675 * descriptor. See the caveats on the "path" parameter above.
1676 */
1677 static int open_sha1_file(const unsigned char *sha1, const char **path)
1678 {
1679 int fd;
1680 struct alternate_object_database *alt;
1681 int most_interesting_errno;
1682
1683 *path = sha1_file_name(sha1);
1684 fd = git_open(*path);
1685 if (fd >= 0)
1686 return fd;
1687 most_interesting_errno = errno;
1688
1689 prepare_alt_odb();
1690 for (alt = alt_odb_list; alt; alt = alt->next) {
1691 *path = alt_sha1_path(alt, sha1);
1692 fd = git_open(*path);
1693 if (fd >= 0)
1694 return fd;
1695 if (most_interesting_errno == ENOENT)
1696 most_interesting_errno = errno;
1697 }
1698 errno = most_interesting_errno;
1699 return -1;
1700 }
1701
1702 /*
1703 * Map the loose object at "path" if it is not NULL, or the path found by
1704 * searching for a loose object named "sha1".
1705 */
1706 static void *map_sha1_file_1(const char *path,
1707 const unsigned char *sha1,
1708 unsigned long *size)
1709 {
1710 void *map;
1711 int fd;
1712
1713 if (path)
1714 fd = git_open(path);
1715 else
1716 fd = open_sha1_file(sha1, &path);
1717 map = NULL;
1718 if (fd >= 0) {
1719 struct stat st;
1720
1721 if (!fstat(fd, &st)) {
1722 *size = xsize_t(st.st_size);
1723 if (!*size) {
1724 /* mmap() is forbidden on empty files */
1725 error("object file %s is empty", path);
1726 return NULL;
1727 }
1728 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1729 }
1730 close(fd);
1731 }
1732 return map;
1733 }
1734
1735 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1736 {
1737 return map_sha1_file_1(NULL, sha1, size);
1738 }
1739
1740 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1741 unsigned long len, enum object_type *type, unsigned long *sizep)
1742 {
1743 unsigned shift;
1744 unsigned long size, c;
1745 unsigned long used = 0;
1746
1747 c = buf[used++];
1748 *type = (c >> 4) & 7;
1749 size = c & 15;
1750 shift = 4;
1751 while (c & 0x80) {
1752 if (len <= used || bitsizeof(long) <= shift) {
1753 error("bad object header");
1754 size = used = 0;
1755 break;
1756 }
1757 c = buf[used++];
1758 size += (c & 0x7f) << shift;
1759 shift += 7;
1760 }
1761 *sizep = size;
1762 return used;
1763 }
1764
1765 static int unpack_sha1_short_header(git_zstream *stream,
1766 unsigned char *map, unsigned long mapsize,
1767 void *buffer, unsigned long bufsiz)
1768 {
1769 /* Get the data stream */
1770 memset(stream, 0, sizeof(*stream));
1771 stream->next_in = map;
1772 stream->avail_in = mapsize;
1773 stream->next_out = buffer;
1774 stream->avail_out = bufsiz;
1775
1776 git_inflate_init(stream);
1777 return git_inflate(stream, 0);
1778 }
1779
1780 int unpack_sha1_header(git_zstream *stream,
1781 unsigned char *map, unsigned long mapsize,
1782 void *buffer, unsigned long bufsiz)
1783 {
1784 int status = unpack_sha1_short_header(stream, map, mapsize,
1785 buffer, bufsiz);
1786
1787 if (status < Z_OK)
1788 return status;
1789
1790 /* Make sure we have the terminating NUL */
1791 if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1792 return -1;
1793 return 0;
1794 }
1795
1796 static int unpack_sha1_header_to_strbuf(git_zstream *stream, unsigned char *map,
1797 unsigned long mapsize, void *buffer,
1798 unsigned long bufsiz, struct strbuf *header)
1799 {
1800 int status;
1801
1802 status = unpack_sha1_short_header(stream, map, mapsize, buffer, bufsiz);
1803 if (status < Z_OK)
1804 return -1;
1805
1806 /*
1807 * Check if entire header is unpacked in the first iteration.
1808 */
1809 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1810 return 0;
1811
1812 /*
1813 * buffer[0..bufsiz] was not large enough. Copy the partial
1814 * result out to header, and then append the result of further
1815 * reading the stream.
1816 */
1817 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1818 stream->next_out = buffer;
1819 stream->avail_out = bufsiz;
1820
1821 do {
1822 status = git_inflate(stream, 0);
1823 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1824 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1825 return 0;
1826 stream->next_out = buffer;
1827 stream->avail_out = bufsiz;
1828 } while (status != Z_STREAM_END);
1829 return -1;
1830 }
1831
1832 static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1833 {
1834 int bytes = strlen(buffer) + 1;
1835 unsigned char *buf = xmallocz(size);
1836 unsigned long n;
1837 int status = Z_OK;
1838
1839 n = stream->total_out - bytes;
1840 if (n > size)
1841 n = size;
1842 memcpy(buf, (char *) buffer + bytes, n);
1843 bytes = n;
1844 if (bytes <= size) {
1845 /*
1846 * The above condition must be (bytes <= size), not
1847 * (bytes < size). In other words, even though we
1848 * expect no more output and set avail_out to zero,
1849 * the input zlib stream may have bytes that express
1850 * "this concludes the stream", and we *do* want to
1851 * eat that input.
1852 *
1853 * Otherwise we would not be able to test that we
1854 * consumed all the input to reach the expected size;
1855 * we also want to check that zlib tells us that all
1856 * went well with status == Z_STREAM_END at the end.
1857 */
1858 stream->next_out = buf + bytes;
1859 stream->avail_out = size - bytes;
1860 while (status == Z_OK)
1861 status = git_inflate(stream, Z_FINISH);
1862 }
1863 if (status == Z_STREAM_END && !stream->avail_in) {
1864 git_inflate_end(stream);
1865 return buf;
1866 }
1867
1868 if (status < 0)
1869 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1870 else if (stream->avail_in)
1871 error("garbage at end of loose object '%s'",
1872 sha1_to_hex(sha1));
1873 free(buf);
1874 return NULL;
1875 }
1876
1877 /*
1878 * We used to just use "sscanf()", but that's actually way
1879 * too permissive for what we want to check. So do an anal
1880 * object header parse by hand.
1881 */
1882 static int parse_sha1_header_extended(const char *hdr, struct object_info *oi,
1883 unsigned int flags)
1884 {
1885 const char *type_buf = hdr;
1886 unsigned long size;
1887 int type, type_len = 0;
1888
1889 /*
1890 * The type can be of any size but is followed by
1891 * a space.
1892 */
1893 for (;;) {
1894 char c = *hdr++;
1895 if (!c)
1896 return -1;
1897 if (c == ' ')
1898 break;
1899 type_len++;
1900 }
1901
1902 type = type_from_string_gently(type_buf, type_len, 1);
1903 if (oi->typename)
1904 strbuf_add(oi->typename, type_buf, type_len);
1905 /*
1906 * Set type to 0 if its an unknown object and
1907 * we're obtaining the type using '--allow-unknown-type'
1908 * option.
1909 */
1910 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1911 type = 0;
1912 else if (type < 0)
1913 die("invalid object type");
1914 if (oi->typep)
1915 *oi->typep = type;
1916
1917 /*
1918 * The length must follow immediately, and be in canonical
1919 * decimal format (ie "010" is not valid).
1920 */
1921 size = *hdr++ - '0';
1922 if (size > 9)
1923 return -1;
1924 if (size) {
1925 for (;;) {
1926 unsigned long c = *hdr - '0';
1927 if (c > 9)
1928 break;
1929 hdr++;
1930 size = size * 10 + c;
1931 }
1932 }
1933
1934 if (oi->sizep)
1935 *oi->sizep = size;
1936
1937 /*
1938 * The length must be followed by a zero byte
1939 */
1940 return *hdr ? -1 : type;
1941 }
1942
1943 int parse_sha1_header(const char *hdr, unsigned long *sizep)
1944 {
1945 struct object_info oi = OBJECT_INFO_INIT;
1946
1947 oi.sizep = sizep;
1948 return parse_sha1_header_extended(hdr, &oi, 0);
1949 }
1950
1951 unsigned long get_size_from_delta(struct packed_git *p,
1952 struct pack_window **w_curs,
1953 off_t curpos)
1954 {
1955 const unsigned char *data;
1956 unsigned char delta_head[20], *in;
1957 git_zstream stream;
1958 int st;
1959
1960 memset(&stream, 0, sizeof(stream));
1961 stream.next_out = delta_head;
1962 stream.avail_out = sizeof(delta_head);
1963
1964 git_inflate_init(&stream);
1965 do {
1966 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1967 stream.next_in = in;
1968 st = git_inflate(&stream, Z_FINISH);
1969 curpos += stream.next_in - in;
1970 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1971 stream.total_out < sizeof(delta_head));
1972 git_inflate_end(&stream);
1973 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1974 error("delta data unpack-initial failed");
1975 return 0;
1976 }
1977
1978 /* Examine the initial part of the delta to figure out
1979 * the result size.
1980 */
1981 data = delta_head;
1982
1983 /* ignore base size */
1984 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1985
1986 /* Read the result size */
1987 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1988 }
1989
1990 static off_t get_delta_base(struct packed_git *p,
1991 struct pack_window **w_curs,
1992 off_t *curpos,
1993 enum object_type type,
1994 off_t delta_obj_offset)
1995 {
1996 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1997 off_t base_offset;
1998
1999 /* use_pack() assured us we have [base_info, base_info + 20)
2000 * as a range that we can look at without walking off the
2001 * end of the mapped window. Its actually the hash size
2002 * that is assured. An OFS_DELTA longer than the hash size
2003 * is stupid, as then a REF_DELTA would be smaller to store.
2004 */
2005 if (type == OBJ_OFS_DELTA) {
2006 unsigned used = 0;
2007 unsigned char c = base_info[used++];
2008 base_offset = c & 127;
2009 while (c & 128) {
2010 base_offset += 1;
2011 if (!base_offset || MSB(base_offset, 7))
2012 return 0; /* overflow */
2013 c = base_info[used++];
2014 base_offset = (base_offset << 7) + (c & 127);
2015 }
2016 base_offset = delta_obj_offset - base_offset;
2017 if (base_offset <= 0 || base_offset >= delta_obj_offset)
2018 return 0; /* out of bound */
2019 *curpos += used;
2020 } else if (type == OBJ_REF_DELTA) {
2021 /* The base entry _must_ be in the same pack */
2022 base_offset = find_pack_entry_one(base_info, p);
2023 *curpos += 20;
2024 } else
2025 die("I am totally screwed");
2026 return base_offset;
2027 }
2028
2029 /*
2030 * Like get_delta_base above, but we return the sha1 instead of the pack
2031 * offset. This means it is cheaper for REF deltas (we do not have to do
2032 * the final object lookup), but more expensive for OFS deltas (we
2033 * have to load the revidx to convert the offset back into a sha1).
2034 */
2035 static const unsigned char *get_delta_base_sha1(struct packed_git *p,
2036 struct pack_window **w_curs,
2037 off_t curpos,
2038 enum object_type type,
2039 off_t delta_obj_offset)
2040 {
2041 if (type == OBJ_REF_DELTA) {
2042 unsigned char *base = use_pack(p, w_curs, curpos, NULL);
2043 return base;
2044 } else if (type == OBJ_OFS_DELTA) {
2045 struct revindex_entry *revidx;
2046 off_t base_offset = get_delta_base(p, w_curs, &curpos,
2047 type, delta_obj_offset);
2048
2049 if (!base_offset)
2050 return NULL;
2051
2052 revidx = find_pack_revindex(p, base_offset);
2053 if (!revidx)
2054 return NULL;
2055
2056 return nth_packed_object_sha1(p, revidx->nr);
2057 } else
2058 return NULL;
2059 }
2060
2061 int unpack_object_header(struct packed_git *p,
2062 struct pack_window **w_curs,
2063 off_t *curpos,
2064 unsigned long *sizep)
2065 {
2066 unsigned char *base;
2067 unsigned long left;
2068 unsigned long used;
2069 enum object_type type;
2070
2071 /* use_pack() assures us we have [base, base + 20) available
2072 * as a range that we can look at. (Its actually the hash
2073 * size that is assured.) With our object header encoding
2074 * the maximum deflated object size is 2^137, which is just
2075 * insane, so we know won't exceed what we have been given.
2076 */
2077 base = use_pack(p, w_curs, *curpos, &left);
2078 used = unpack_object_header_buffer(base, left, &type, sizep);
2079 if (!used) {
2080 type = OBJ_BAD;
2081 } else
2082 *curpos += used;
2083
2084 return type;
2085 }
2086
2087 static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
2088 {
2089 int type;
2090 struct revindex_entry *revidx;
2091 const unsigned char *sha1;
2092 revidx = find_pack_revindex(p, obj_offset);
2093 if (!revidx)
2094 return OBJ_BAD;
2095 sha1 = nth_packed_object_sha1(p, revidx->nr);
2096 mark_bad_packed_object(p, sha1);
2097 type = sha1_object_info(sha1, NULL);
2098 if (type <= OBJ_NONE)
2099 return OBJ_BAD;
2100 return type;
2101 }
2102
2103 #define POI_STACK_PREALLOC 64
2104
2105 static enum object_type packed_to_object_type(struct packed_git *p,
2106 off_t obj_offset,
2107 enum object_type type,
2108 struct pack_window **w_curs,
2109 off_t curpos)
2110 {
2111 off_t small_poi_stack[POI_STACK_PREALLOC];
2112 off_t *poi_stack = small_poi_stack;
2113 int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
2114
2115 while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
2116 off_t base_offset;
2117 unsigned long size;
2118 /* Push the object we're going to leave behind */
2119 if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
2120 poi_stack_alloc = alloc_nr(poi_stack_nr);
2121 ALLOC_ARRAY(poi_stack, poi_stack_alloc);
2122 memcpy(poi_stack, small_poi_stack, sizeof(off_t)*poi_stack_nr);
2123 } else {
2124 ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
2125 }
2126 poi_stack[poi_stack_nr++] = obj_offset;
2127 /* If parsing the base offset fails, just unwind */
2128 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
2129 if (!base_offset)
2130 goto unwind;
2131 curpos = obj_offset = base_offset;
2132 type = unpack_object_header(p, w_curs, &curpos, &size);
2133 if (type <= OBJ_NONE) {
2134 /* If getting the base itself fails, we first
2135 * retry the base, otherwise unwind */
2136 type = retry_bad_packed_offset(p, base_offset);
2137 if (type > OBJ_NONE)
2138 goto out;
2139 goto unwind;
2140 }
2141 }
2142
2143 switch (type) {
2144 case OBJ_BAD:
2145 case OBJ_COMMIT:
2146 case OBJ_TREE:
2147 case OBJ_BLOB:
2148 case OBJ_TAG:
2149 break;
2150 default:
2151 error("unknown object type %i at offset %"PRIuMAX" in %s",
2152 type, (uintmax_t)obj_offset, p->pack_name);
2153 type = OBJ_BAD;
2154 }
2155
2156 out:
2157 if (poi_stack != small_poi_stack)
2158 free(poi_stack);
2159 return type;
2160
2161 unwind:
2162 while (poi_stack_nr) {
2163 obj_offset = poi_stack[--poi_stack_nr];
2164 type = retry_bad_packed_offset(p, obj_offset);
2165 if (type > OBJ_NONE)
2166 goto out;
2167 }
2168 type = OBJ_BAD;
2169 goto out;
2170 }
2171
2172 static struct hashmap delta_base_cache;
2173 static size_t delta_base_cached;
2174
2175 static LIST_HEAD(delta_base_cache_lru);
2176
2177 struct delta_base_cache_key {
2178 struct packed_git *p;
2179 off_t base_offset;
2180 };
2181
2182 struct delta_base_cache_entry {
2183 struct hashmap hash;
2184 struct delta_base_cache_key key;
2185 struct list_head lru;
2186 void *data;
2187 unsigned long size;
2188 enum object_type type;
2189 };
2190
2191 static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
2192 {
2193 unsigned int hash;
2194
2195 hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
2196 hash += (hash >> 8) + (hash >> 16);
2197 return hash;
2198 }
2199
2200 static struct delta_base_cache_entry *
2201 get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
2202 {
2203 struct hashmap_entry entry;
2204 struct delta_base_cache_key key;
2205
2206 if (!delta_base_cache.cmpfn)
2207 return NULL;
2208
2209 hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
2210 key.p = p;
2211 key.base_offset = base_offset;
2212 return hashmap_get(&delta_base_cache, &entry, &key);
2213 }
2214
2215 static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
2216 const struct delta_base_cache_key *b)
2217 {
2218 return a->p == b->p && a->base_offset == b->base_offset;
2219 }
2220
2221 static int delta_base_cache_hash_cmp(const void *unused_cmp_data,
2222 const void *va, const void *vb,
2223 const void *vkey)
2224 {
2225 const struct delta_base_cache_entry *a = va, *b = vb;
2226 const struct delta_base_cache_key *key = vkey;
2227 if (key)
2228 return !delta_base_cache_key_eq(&a->key, key);
2229 else
2230 return !delta_base_cache_key_eq(&a->key, &b->key);
2231 }
2232
2233 static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
2234 {
2235 return !!get_delta_base_cache_entry(p, base_offset);
2236 }
2237
2238 /*
2239 * Remove the entry from the cache, but do _not_ free the associated
2240 * entry data. The caller takes ownership of the "data" buffer, and
2241 * should copy out any fields it wants before detaching.
2242 */
2243 static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
2244 {
2245 hashmap_remove(&delta_base_cache, ent, &ent->key);
2246 list_del(&ent->lru);
2247 delta_base_cached -= ent->size;
2248 free(ent);
2249 }
2250
2251 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
2252 unsigned long *base_size, enum object_type *type)
2253 {
2254 struct delta_base_cache_entry *ent;
2255
2256 ent = get_delta_base_cache_entry(p, base_offset);
2257 if (!ent)
2258 return unpack_entry(p, base_offset, type, base_size);
2259
2260 if (type)
2261 *type = ent->type;
2262 if (base_size)
2263 *base_size = ent->size;
2264 return xmemdupz(ent->data, ent->size);
2265 }
2266
2267 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
2268 {
2269 free(ent->data);
2270 detach_delta_base_cache_entry(ent);
2271 }
2272
2273 void clear_delta_base_cache(void)
2274 {
2275 struct list_head *lru, *tmp;
2276 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
2277 struct delta_base_cache_entry *entry =
2278 list_entry(lru, struct delta_base_cache_entry, lru);
2279 release_delta_base_cache(entry);
2280 }
2281 }
2282
2283 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
2284 void *base, unsigned long base_size, enum object_type type)
2285 {
2286 struct delta_base_cache_entry *ent = xmalloc(sizeof(*ent));
2287 struct list_head *lru, *tmp;
2288
2289 delta_base_cached += base_size;
2290
2291 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
2292 struct delta_base_cache_entry *f =
2293 list_entry(lru, struct delta_base_cache_entry, lru);
2294 if (delta_base_cached <= delta_base_cache_limit)
2295 break;
2296 release_delta_base_cache(f);
2297 }
2298
2299 ent->key.p = p;
2300 ent->key.base_offset = base_offset;
2301 ent->type = type;
2302 ent->data = base;
2303 ent->size = base_size;
2304 list_add_tail(&ent->lru, &delta_base_cache_lru);
2305
2306 if (!delta_base_cache.cmpfn)
2307 hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL, 0);
2308 hashmap_entry_init(ent, pack_entry_hash(p, base_offset));
2309 hashmap_add(&delta_base_cache, ent);
2310 }
2311
2312 int packed_object_info(struct packed_git *p, off_t obj_offset,
2313 struct object_info *oi)
2314 {
2315 struct pack_window *w_curs = NULL;
2316 unsigned long size;
2317 off_t curpos = obj_offset;
2318 enum object_type type;
2319
2320 /*
2321 * We always get the representation type, but only convert it to
2322 * a "real" type later if the caller is interested.
2323 */
2324 if (oi->contentp) {
2325 *oi->contentp = cache_or_unpack_entry(p, obj_offset, oi->sizep,
2326 &type);
2327 if (!*oi->contentp)
2328 type = OBJ_BAD;
2329 } else {
2330 type = unpack_object_header(p, &w_curs, &curpos, &size);
2331 }
2332
2333 if (!oi->contentp && oi->sizep) {
2334 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
2335 off_t tmp_pos = curpos;
2336 off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
2337 type, obj_offset);
2338 if (!base_offset) {
2339 type = OBJ_BAD;
2340 goto out;
2341 }
2342 *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
2343 if (*oi->sizep == 0) {
2344 type = OBJ_BAD;
2345 goto out;
2346 }
2347 } else {
2348 *oi->sizep = size;
2349 }
2350 }
2351
2352 if (oi->disk_sizep) {
2353 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
2354 *oi->disk_sizep = revidx[1].offset - obj_offset;
2355 }
2356
2357 if (oi->typep || oi->typename) {
2358 enum object_type ptot;
2359 ptot = packed_to_object_type(p, obj_offset, type, &w_curs,
2360 curpos);
2361 if (oi->typep)
2362 *oi->typep = ptot;
2363 if (oi->typename) {
2364 const char *tn = typename(ptot);
2365 if (tn)
2366 strbuf_addstr(oi->typename, tn);
2367 }
2368 if (ptot < 0) {
2369 type = OBJ_BAD;
2370 goto out;
2371 }
2372 }
2373
2374 if (oi->delta_base_sha1) {
2375 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
2376 const unsigned char *base;
2377
2378 base = get_delta_base_sha1(p, &w_curs, curpos,
2379 type, obj_offset);
2380 if (!base) {
2381 type = OBJ_BAD;
2382 goto out;
2383 }
2384
2385 hashcpy(oi->delta_base_sha1, base);
2386 } else
2387 hashclr(oi->delta_base_sha1);
2388 }
2389
2390 oi->whence = in_delta_base_cache(p, obj_offset) ? OI_DBCACHED :
2391 OI_PACKED;
2392
2393 out:
2394 unuse_pack(&w_curs);
2395 return type;
2396 }
2397
2398 static void *unpack_compressed_entry(struct packed_git *p,
2399 struct pack_window **w_curs,
2400 off_t curpos,
2401 unsigned long size)
2402 {
2403 int st;
2404 git_zstream stream;
2405 unsigned char *buffer, *in;
2406
2407 buffer = xmallocz_gently(size);
2408 if (!buffer)
2409 return NULL;
2410 memset(&stream, 0, sizeof(stream));
2411 stream.next_out = buffer;
2412 stream.avail_out = size + 1;
2413
2414 git_inflate_init(&stream);
2415 do {
2416 in = use_pack(p, w_curs, curpos, &stream.avail_in);
2417 stream.next_in = in;
2418 st = git_inflate(&stream, Z_FINISH);
2419 if (!stream.avail_out)
2420 break; /* the payload is larger than it should be */
2421 curpos += stream.next_in - in;
2422 } while (st == Z_OK || st == Z_BUF_ERROR);
2423 git_inflate_end(&stream);
2424 if ((st != Z_STREAM_END) || stream.total_out != size) {
2425 free(buffer);
2426 return NULL;
2427 }
2428
2429 return buffer;
2430 }
2431
2432 static void *read_object(const unsigned char *sha1, enum object_type *type,
2433 unsigned long *size);
2434
2435 static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
2436 {
2437 static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
2438 trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
2439 p->pack_name, (uintmax_t)obj_offset);
2440 }
2441
2442 int do_check_packed_object_crc;
2443
2444 #define UNPACK_ENTRY_STACK_PREALLOC 64
2445 struct unpack_entry_stack_ent {
2446 off_t obj_offset;
2447 off_t curpos;
2448 unsigned long size;
2449 };
2450
2451 void *unpack_entry(struct packed_git *p, off_t obj_offset,
2452 enum object_type *final_type, unsigned long *final_size)
2453 {
2454 struct pack_window *w_curs = NULL;
2455 off_t curpos = obj_offset;
2456 void *data = NULL;
2457 unsigned long size;
2458 enum object_type type;
2459 struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
2460 struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
2461 int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
2462 int base_from_cache = 0;
2463
2464 write_pack_access_log(p, obj_offset);
2465
2466 /* PHASE 1: drill down to the innermost base object */
2467 for (;;) {
2468 off_t base_offset;
2469 int i;
2470 struct delta_base_cache_entry *ent;
2471
2472 ent = get_delta_base_cache_entry(p, curpos);
2473 if (ent) {
2474 type = ent->type;
2475 data = ent->data;
2476 size = ent->size;
2477 detach_delta_base_cache_entry(ent);
2478 base_from_cache = 1;
2479 break;
2480 }
2481
2482 if (do_check_packed_object_crc && p->index_version > 1) {
2483 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
2484 off_t len = revidx[1].offset - obj_offset;
2485 if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
2486 const unsigned char *sha1 =
2487 nth_packed_object_sha1(p, revidx->nr);
2488 error("bad packed object CRC for %s",
2489 sha1_to_hex(sha1));
2490 mark_bad_packed_object(p, sha1);
2491 data = NULL;
2492 goto out;
2493 }
2494 }
2495
2496 type = unpack_object_header(p, &w_curs, &curpos, &size);
2497 if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
2498 break;
2499
2500 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
2501 if (!base_offset) {
2502 error("failed to validate delta base reference "
2503 "at offset %"PRIuMAX" from %s",
2504 (uintmax_t)curpos, p->pack_name);
2505 /* bail to phase 2, in hopes of recovery */
2506 data = NULL;
2507 break;
2508 }
2509
2510 /* push object, proceed to base */
2511 if (delta_stack_nr >= delta_stack_alloc
2512 && delta_stack == small_delta_stack) {
2513 delta_stack_alloc = alloc_nr(delta_stack_nr);
2514 ALLOC_ARRAY(delta_stack, delta_stack_alloc);
2515 memcpy(delta_stack, small_delta_stack,
2516 sizeof(*delta_stack)*delta_stack_nr);
2517 } else {
2518 ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
2519 }
2520 i = delta_stack_nr++;
2521 delta_stack[i].obj_offset = obj_offset;
2522 delta_stack[i].curpos = curpos;
2523 delta_stack[i].size = size;
2524
2525 curpos = obj_offset = base_offset;
2526 }
2527
2528 /* PHASE 2: handle the base */
2529 switch (type) {
2530 case OBJ_OFS_DELTA:
2531 case OBJ_REF_DELTA:
2532 if (data)
2533 die("BUG: unpack_entry: left loop at a valid delta");
2534 break;
2535 case OBJ_COMMIT:
2536 case OBJ_TREE:
2537 case OBJ_BLOB:
2538 case OBJ_TAG:
2539 if (!base_from_cache)
2540 data = unpack_compressed_entry(p, &w_curs, curpos, size);
2541 break;
2542 default:
2543 data = NULL;
2544 error("unknown object type %i at offset %"PRIuMAX" in %s",
2545 type, (uintmax_t)obj_offset, p->pack_name);
2546 }
2547
2548 /* PHASE 3: apply deltas in order */
2549
2550 /* invariants:
2551 * 'data' holds the base data, or NULL if there was corruption
2552 */
2553 while (delta_stack_nr) {
2554 void *delta_data;
2555 void *base = data;
2556 void *external_base = NULL;
2557 unsigned long delta_size, base_size = size;
2558 int i;
2559
2560 data = NULL;
2561
2562 if (base)
2563 add_delta_base_cache(p, obj_offset, base, base_size, type);
2564
2565 if (!base) {
2566 /*
2567 * We're probably in deep shit, but let's try to fetch
2568 * the required base anyway from another pack or loose.
2569 * This is costly but should happen only in the presence
2570 * of a corrupted pack, and is better than failing outright.
2571 */
2572 struct revindex_entry *revidx;
2573 const unsigned char *base_sha1;
2574 revidx = find_pack_revindex(p, obj_offset);
2575 if (revidx) {
2576 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
2577 error("failed to read delta base object %s"
2578 " at offset %"PRIuMAX" from %s",
2579 sha1_to_hex(base_sha1), (uintmax_t)obj_offset,
2580 p->pack_name);
2581 mark_bad_packed_object(p, base_sha1);
2582 base = read_object(base_sha1, &type, &base_size);
2583 external_base = base;
2584 }
2585 }
2586
2587 i = --delta_stack_nr;
2588 obj_offset = delta_stack[i].obj_offset;
2589 curpos = delta_stack[i].curpos;
2590 delta_size = delta_stack[i].size;
2591
2592 if (!base)
2593 continue;
2594
2595 delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
2596
2597 if (!delta_data) {
2598 error("failed to unpack compressed delta "
2599 "at offset %"PRIuMAX" from %s",
2600 (uintmax_t)curpos, p->pack_name);
2601 data = NULL;
2602 free(external_base);
2603 continue;
2604 }
2605
2606 data = patch_delta(base, base_size,
2607 delta_data, delta_size,
2608 &size);
2609
2610 /*
2611 * We could not apply the delta; warn the user, but keep going.
2612 * Our failure will be noticed either in the next iteration of
2613 * the loop, or if this is the final delta, in the caller when
2614 * we return NULL. Those code paths will take care of making
2615 * a more explicit warning and retrying with another copy of
2616 * the object.
2617 */
2618 if (!data)
2619 error("failed to apply delta");
2620
2621 free(delta_data);
2622 free(external_base);
2623 }
2624
2625 if (final_type)
2626 *final_type = type;
2627 if (final_size)
2628 *final_size = size;
2629
2630 out:
2631 unuse_pack(&w_curs);
2632
2633 if (delta_stack != small_delta_stack)
2634 free(delta_stack);
2635
2636 return data;
2637 }
2638
2639 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
2640 uint32_t n)
2641 {
2642 const unsigned char *index = p->index_data;
2643 if (!index) {
2644 if (open_pack_index(p))
2645 return NULL;
2646 index = p->index_data;
2647 }
2648 if (n >= p->num_objects)
2649 return NULL;
2650 index += 4 * 256;
2651 if (p->index_version == 1) {
2652 return index + 24 * n + 4;
2653 } else {
2654 index += 8;
2655 return index + 20 * n;
2656 }
2657 }
2658
2659 const struct object_id *nth_packed_object_oid(struct object_id *oid,
2660 struct packed_git *p,
2661 uint32_t n)
2662 {
2663 const unsigned char *hash = nth_packed_object_sha1(p, n);
2664 if (!hash)
2665 return NULL;
2666 hashcpy(oid->hash, hash);
2667 return oid;
2668 }
2669
2670 void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
2671 {
2672 const unsigned char *ptr = vptr;
2673 const unsigned char *start = p->index_data;
2674 const unsigned char *end = start + p->index_size;
2675 if (ptr < start)
2676 die(_("offset before start of pack index for %s (corrupt index?)"),
2677 p->pack_name);
2678 /* No need to check for underflow; .idx files must be at least 8 bytes */
2679 if (ptr >= end - 8)
2680 die(_("offset beyond end of pack index for %s (truncated index?)"),
2681 p->pack_name);
2682 }
2683
2684 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
2685 {
2686 const unsigned char *index = p->index_data;
2687 index += 4 * 256;
2688 if (p->index_version == 1) {
2689 return ntohl(*((uint32_t *)(index + 24 * n)));
2690 } else {
2691 uint32_t off;
2692 index += 8 + p->num_objects * (20 + 4);
2693 off = ntohl(*((uint32_t *)(index + 4 * n)));
2694 if (!(off & 0x80000000))
2695 return off;
2696 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
2697 check_pack_index_ptr(p, index);
2698 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
2699 ntohl(*((uint32_t *)(index + 4)));
2700 }
2701 }
2702
2703 off_t find_pack_entry_one(const unsigned char *sha1,
2704 struct packed_git *p)
2705 {
2706 const uint32_t *level1_ofs = p->index_data;
2707 const unsigned char *index = p->index_data;
2708 unsigned hi, lo, stride;
2709 static int debug_lookup = -1;
2710
2711 if (debug_lookup < 0)
2712 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
2713
2714 if (!index) {
2715 if (open_pack_index(p))
2716 return 0;
2717 level1_ofs = p->index_data;
2718 index = p->index_data;
2719 }
2720 if (p->index_version > 1) {
2721 level1_ofs += 2;
2722 index += 8;
2723 }
2724 index += 4 * 256;
2725 hi = ntohl(level1_ofs[*sha1]);
2726 lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
2727 if (p->index_version > 1) {
2728 stride = 20;
2729 } else {
2730 stride = 24;
2731 index += 4;
2732 }
2733
2734 if (debug_lookup)
2735 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
2736 sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
2737
2738 while (lo < hi) {
2739 unsigned mi = (lo + hi) / 2;
2740 int cmp = hashcmp(index + mi * stride, sha1);
2741
2742 if (debug_lookup)
2743 printf("lo %u hi %u rg %u mi %u\n",
2744 lo, hi, hi - lo, mi);
2745 if (!cmp)
2746 return nth_packed_object_offset(p, mi);
2747 if (cmp > 0)
2748 hi = mi;
2749 else
2750 lo = mi+1;
2751 }
2752 return 0;
2753 }
2754
2755 int is_pack_valid(struct packed_git *p)
2756 {
2757 /* An already open pack is known to be valid. */
2758 if (p->pack_fd != -1)
2759 return 1;
2760
2761 /* If the pack has one window completely covering the
2762 * file size, the pack is known to be valid even if
2763 * the descriptor is not currently open.
2764 */
2765 if (p->windows) {
2766 struct pack_window *w = p->windows;
2767
2768 if (!w->offset && w->len == p->pack_size)
2769 return 1;
2770 }
2771
2772 /* Force the pack to open to prove its valid. */
2773 return !open_packed_git(p);
2774 }
2775
2776 static int fill_pack_entry(const unsigned char *sha1,
2777 struct pack_entry *e,
2778 struct packed_git *p)
2779 {
2780 off_t offset;
2781
2782 if (p->num_bad_objects) {
2783 unsigned i;
2784 for (i = 0; i < p->num_bad_objects; i++)
2785 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
2786 return 0;
2787 }
2788
2789 offset = find_pack_entry_one(sha1, p);
2790 if (!offset)
2791 return 0;
2792
2793 /*
2794 * We are about to tell the caller where they can locate the
2795 * requested object. We better make sure the packfile is
2796 * still here and can be accessed before supplying that
2797 * answer, as it may have been deleted since the index was
2798 * loaded!
2799 */
2800 if (!is_pack_valid(p))
2801 return 0;
2802 e->offset = offset;
2803 e->p = p;
2804 hashcpy(e->sha1, sha1);
2805 return 1;
2806 }
2807
2808 /*
2809 * Iff a pack file contains the object named by sha1, return true and
2810 * store its location to e.
2811 */
2812 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
2813 {
2814 struct mru_entry *p;
2815
2816 prepare_packed_git();
2817 if (!packed_git)
2818 return 0;
2819
2820 for (p = packed_git_mru->head; p; p = p->next) {
2821 if (fill_pack_entry(sha1, e, p->item)) {
2822 mru_mark(packed_git_mru, p);
2823 return 1;
2824 }
2825 }
2826 return 0;
2827 }
2828
2829 struct packed_git *find_sha1_pack(const unsigned char *sha1,
2830 struct packed_git *packs)
2831 {
2832 struct packed_git *p;
2833
2834 for (p = packs; p; p = p->next) {
2835 if (find_pack_entry_one(sha1, p))
2836 return p;
2837 }
2838 return NULL;
2839
2840 }
2841
2842 static int sha1_loose_object_info(const unsigned char *sha1,
2843 struct object_info *oi,
2844 int flags)
2845 {
2846 int status = 0;
2847 unsigned long mapsize;
2848 void *map;
2849 git_zstream stream;
2850 char hdr[32];
2851 struct strbuf hdrbuf = STRBUF_INIT;
2852 unsigned long size_scratch;
2853
2854 if (oi->delta_base_sha1)
2855 hashclr(oi->delta_base_sha1);
2856
2857 /*
2858 * If we don't care about type or size, then we don't
2859 * need to look inside the object at all. Note that we
2860 * do not optimize out the stat call, even if the
2861 * caller doesn't care about the disk-size, since our
2862 * return value implicitly indicates whether the
2863 * object even exists.
2864 */
2865 if (!oi->typep && !oi->typename && !oi->sizep && !oi->contentp) {
2866 const char *path;
2867 struct stat st;
2868 if (stat_sha1_file(sha1, &st, &path) < 0)
2869 return -1;
2870 if (oi->disk_sizep)
2871 *oi->disk_sizep = st.st_size;
2872 return 0;
2873 }
2874
2875 map = map_sha1_file(sha1, &mapsize);
2876 if (!map)
2877 return -1;
2878
2879 if (!oi->sizep)
2880 oi->sizep = &size_scratch;
2881
2882 if (oi->disk_sizep)
2883 *oi->disk_sizep = mapsize;
2884 if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
2885 if (unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
2886 status = error("unable to unpack %s header with --allow-unknown-type",
2887 sha1_to_hex(sha1));
2888 } else if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2889 status = error("unable to unpack %s header",
2890 sha1_to_hex(sha1));
2891 if (status < 0)
2892 ; /* Do nothing */
2893 else if (hdrbuf.len) {
2894 if ((status = parse_sha1_header_extended(hdrbuf.buf, oi, flags)) < 0)
2895 status = error("unable to parse %s header with --allow-unknown-type",
2896 sha1_to_hex(sha1));
2897 } else if ((status = parse_sha1_header_extended(hdr, oi, flags)) < 0)
2898 status = error("unable to parse %s header", sha1_to_hex(sha1));
2899
2900 if (status >= 0 && oi->contentp)
2901 *oi->contentp = unpack_sha1_rest(&stream, hdr,
2902 *oi->sizep, sha1);
2903 else
2904 git_inflate_end(&stream);
2905
2906 munmap(map, mapsize);
2907 if (status && oi->typep)
2908 *oi->typep = status;
2909 if (oi->sizep == &size_scratch)
2910 oi->sizep = NULL;
2911 strbuf_release(&hdrbuf);
2912 oi->whence = OI_LOOSE;
2913 return (status < 0) ? status : 0;
2914 }
2915
2916 int sha1_object_info_extended(const unsigned char *sha1, struct object_info *oi, unsigned flags)
2917 {
2918 static struct object_info blank_oi = OBJECT_INFO_INIT;
2919 struct pack_entry e;
2920 int rtype;
2921 const unsigned char *real = (flags & OBJECT_INFO_LOOKUP_REPLACE) ?
2922 lookup_replace_object(sha1) :
2923 sha1;
2924
2925 if (!oi)
2926 oi = &blank_oi;
2927
2928 if (!(flags & OBJECT_INFO_SKIP_CACHED)) {
2929 struct cached_object *co = find_cached_object(real);
2930 if (co) {
2931 if (oi->typep)
2932 *(oi->typep) = co->type;
2933 if (oi->sizep)
2934 *(oi->sizep) = co->size;
2935 if (oi->disk_sizep)
2936 *(oi->disk_sizep) = 0;
2937 if (oi->delta_base_sha1)
2938 hashclr(oi->delta_base_sha1);
2939 if (oi->typename)
2940 strbuf_addstr(oi->typename, typename(co->type));
2941 if (oi->contentp)
2942 *oi->contentp = xmemdupz(co->buf, co->size);
2943 oi->whence = OI_CACHED;
2944 return 0;
2945 }
2946 }
2947
2948 if (!find_pack_entry(real, &e)) {
2949 /* Most likely it's a loose object. */
2950 if (!sha1_loose_object_info(real, oi, flags))
2951 return 0;
2952
2953 /* Not a loose object; someone else may have just packed it. */
2954 if (flags & OBJECT_INFO_QUICK) {
2955 return -1;
2956 } else {
2957 reprepare_packed_git();
2958 if (!find_pack_entry(real, &e))
2959 return -1;
2960 }
2961 }
2962
2963 if (oi == &blank_oi)
2964 /*
2965 * We know that the caller doesn't actually need the
2966 * information below, so return early.
2967 */
2968 return 0;
2969
2970 rtype = packed_object_info(e.p, e.offset, oi);
2971 if (rtype < 0) {
2972 mark_bad_packed_object(e.p, real);
2973 return sha1_object_info_extended(real, oi, 0);
2974 } else if (oi->whence == OI_PACKED) {
2975 oi->u.packed.offset = e.offset;
2976 oi->u.packed.pack = e.p;
2977 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
2978 rtype == OBJ_OFS_DELTA);
2979 }
2980
2981 return 0;
2982 }
2983
2984 /* returns enum object_type or negative */
2985 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
2986 {
2987 enum object_type type;
2988 struct object_info oi = OBJECT_INFO_INIT;
2989
2990 oi.typep = &type;
2991 oi.sizep = sizep;
2992 if (sha1_object_info_extended(sha1, &oi,
2993 OBJECT_INFO_LOOKUP_REPLACE) < 0)
2994 return -1;
2995 return type;
2996 }
2997
2998 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2999 unsigned char *sha1)
3000 {
3001 struct cached_object *co;
3002
3003 hash_sha1_file(buf, len, typename(type), sha1);
3004 if (has_sha1_file(sha1) || find_cached_object(sha1))
3005 return 0;
3006 ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
3007 co = &cached_objects[cached_object_nr++];
3008 co->size = len;
3009 co->type = type;
3010 co->buf = xmalloc(len);
3011 memcpy(co->buf, buf, len);
3012 hashcpy(co->sha1, sha1);
3013 return 0;
3014 }
3015
3016 static void *read_object(const unsigned char *sha1, enum object_type *type,
3017 unsigned long *size)
3018 {
3019 struct object_info oi = OBJECT_INFO_INIT;
3020 void *content;
3021 oi.typep = type;
3022 oi.sizep = size;
3023 oi.contentp = &content;
3024
3025 if (sha1_object_info_extended(sha1, &oi, 0) < 0)
3026 return NULL;
3027 return content;
3028 }
3029
3030 /*
3031 * This function dies on corrupt objects; the callers who want to
3032 * deal with them should arrange to call read_object() and give error
3033 * messages themselves.
3034 */
3035 void *read_sha1_file_extended(const unsigned char *sha1,
3036 enum object_type *type,
3037 unsigned long *size,
3038 int lookup_replace)
3039 {
3040 void *data;
3041 const struct packed_git *p;
3042 const char *path;
3043 struct stat st;
3044 const unsigned char *repl = lookup_replace ? lookup_replace_object(sha1)
3045 : sha1;
3046
3047 errno = 0;
3048 data = read_object(repl, type, size);
3049 if (data)
3050 return data;
3051
3052 if (errno && errno != ENOENT)
3053 die_errno("failed to read object %s", sha1_to_hex(sha1));
3054
3055 /* die if we replaced an object with one that does not exist */
3056 if (repl != sha1)
3057 die("replacement %s not found for %s",
3058 sha1_to_hex(repl), sha1_to_hex(sha1));
3059
3060 if (!stat_sha1_file(repl, &st, &path))
3061 die("loose object %s (stored in %s) is corrupt",
3062 sha1_to_hex(repl), path);
3063
3064 if ((p = has_packed_and_bad(repl)) != NULL)
3065 die("packed object %s (stored in %s) is corrupt",
3066 sha1_to_hex(repl), p->pack_name);
3067
3068 return NULL;
3069 }
3070
3071 void *read_object_with_reference(const unsigned char *sha1,
3072 const char *required_type_name,
3073 unsigned long *size,
3074 unsigned char *actual_sha1_return)
3075 {
3076 enum object_type type, required_type;
3077 void *buffer;
3078 unsigned long isize;
3079 unsigned char actual_sha1[20];
3080
3081 required_type = type_from_string(required_type_name);
3082 hashcpy(actual_sha1, sha1);
3083 while (1) {
3084 int ref_length = -1;
3085 const char *ref_type = NULL;
3086
3087 buffer = read_sha1_file(actual_sha1, &type, &isize);
3088 if (!buffer)
3089 return NULL;
3090 if (type == required_type) {
3091 *size = isize;
3092 if (actual_sha1_return)
3093 hashcpy(actual_sha1_return, actual_sha1);
3094 return buffer;
3095 }
3096 /* Handle references */
3097 else if (type == OBJ_COMMIT)
3098 ref_type = "tree ";
3099 else if (type == OBJ_TAG)
3100 ref_type = "object ";
3101 else {
3102 free(buffer);
3103 return NULL;
3104 }
3105 ref_length = strlen(ref_type);
3106
3107 if (ref_length + 40 > isize ||
3108 memcmp(buffer, ref_type, ref_length) ||
3109 get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
3110 free(buffer);
3111 return NULL;
3112 }
3113 free(buffer);
3114 /* Now we have the ID of the referred-to object in
3115 * actual_sha1. Check again. */
3116 }
3117 }
3118
3119 static void write_sha1_file_prepare(const void *buf, unsigned long len,
3120 const char *type, unsigned char *sha1,
3121 char *hdr, int *hdrlen)
3122 {
3123 git_SHA_CTX c;
3124
3125 /* Generate the header */
3126 *hdrlen = xsnprintf(hdr, *hdrlen, "%s %lu", type, len)+1;
3127
3128 /* Sha1.. */
3129 git_SHA1_Init(&c);
3130 git_SHA1_Update(&c, hdr, *hdrlen);
3131 git_SHA1_Update(&c, buf, len);
3132 git_SHA1_Final(sha1, &c);
3133 }
3134
3135 /*
3136 * Move the just written object into its final resting place.
3137 */
3138 int finalize_object_file(const char *tmpfile, const char *filename)
3139 {
3140 int ret = 0;
3141
3142 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
3143 goto try_rename;
3144 else if (link(tmpfile, filename))
3145 ret = errno;
3146
3147 /*
3148 * Coda hack - coda doesn't like cross-directory links,
3149 * so we fall back to a rename, which will mean that it
3150 * won't be able to check collisions, but that's not a
3151 * big deal.
3152 *
3153 * The same holds for FAT formatted media.
3154 *
3155 * When this succeeds, we just return. We have nothing
3156 * left to unlink.
3157 */
3158 if (ret && ret != EEXIST) {
3159 try_rename:
3160 if (!rename(tmpfile, filename))
3161 goto out;
3162 ret = errno;
3163 }
3164 unlink_or_warn(tmpfile);
3165 if (ret) {
3166 if (ret != EEXIST) {
3167 return error_errno("unable to write sha1 filename %s", filename);
3168 }
3169 /* FIXME!!! Collision check here ? */
3170 }
3171
3172 out:
3173 if (adjust_shared_perm(filename))
3174 return error("unable to set permission to '%s'", filename);
3175 return 0;
3176 }
3177
3178 static int write_buffer(int fd, const void *buf, size_t len)
3179 {
3180 if (write_in_full(fd, buf, len) < 0)
3181 return error_errno("file write error");
3182 return 0;
3183 }
3184
3185 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
3186 unsigned char *sha1)
3187 {
3188 char hdr[32];
3189 int hdrlen = sizeof(hdr);
3190 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
3191 return 0;
3192 }
3193
3194 /* Finalize a file on disk, and close it. */
3195 static void close_sha1_file(int fd)
3196 {
3197 if (fsync_object_files)
3198 fsync_or_die(fd, "sha1 file");
3199 if (close(fd) != 0)
3200 die_errno("error when closing sha1 file");
3201 }
3202
3203 /* Size of directory component, including the ending '/' */
3204 static inline int directory_size(const char *filename)
3205 {
3206 const char *s = strrchr(filename, '/');
3207 if (!s)
3208 return 0;
3209 return s - filename + 1;
3210 }
3211
3212 /*
3213 * This creates a temporary file in the same directory as the final
3214 * 'filename'
3215 *
3216 * We want to avoid cross-directory filename renames, because those
3217 * can have problems on various filesystems (FAT, NFS, Coda).
3218 */
3219 static int create_tmpfile(struct strbuf *tmp, const char *filename)
3220 {
3221 int fd, dirlen = directory_size(filename);
3222
3223 strbuf_reset(tmp);
3224 strbuf_add(tmp, filename, dirlen);
3225 strbuf_addstr(tmp, "tmp_obj_XXXXXX");
3226 fd = git_mkstemp_mode(tmp->buf, 0444);
3227 if (fd < 0 && dirlen && errno == ENOENT) {
3228 /*
3229 * Make sure the directory exists; note that the contents
3230 * of the buffer are undefined after mkstemp returns an
3231 * error, so we have to rewrite the whole buffer from
3232 * scratch.
3233 */
3234 strbuf_reset(tmp);
3235 strbuf_add(tmp, filename, dirlen - 1);
3236 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
3237 return -1;
3238 if (adjust_shared_perm(tmp->buf))
3239 return -1;
3240
3241 /* Try again */
3242 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
3243 fd = git_mkstemp_mode(tmp->buf, 0444);
3244 }
3245 return fd;
3246 }
3247
3248 static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
3249 const void *buf, unsigned long len, time_t mtime)
3250 {
3251 int fd, ret;
3252 unsigned char compressed[4096];
3253 git_zstream stream;
3254 git_SHA_CTX c;
3255 unsigned char parano_sha1[20];
3256 static struct strbuf tmp_file = STRBUF_INIT;
3257 const char *filename = sha1_file_name(sha1);
3258
3259 fd = create_tmpfile(&tmp_file, filename);
3260 if (fd < 0) {
3261 if (errno == EACCES)
3262 return error("insufficient permission for adding an object to repository database %s", get_object_directory());
3263 else
3264 return error_errno("unable to create temporary file");
3265 }
3266
3267 /* Set it up */
3268 git_deflate_init(&stream, zlib_compression_level);
3269 stream.next_out = compressed;
3270 stream.avail_out = sizeof(compressed);
3271 git_SHA1_Init(&c);
3272
3273 /* First header.. */
3274 stream.next_in = (unsigned char *)hdr;
3275 stream.avail_in = hdrlen;
3276 while (git_deflate(&stream, 0) == Z_OK)
3277 ; /* nothing */
3278 git_SHA1_Update(&c, hdr, hdrlen);
3279
3280 /* Then the data itself.. */
3281 stream.next_in = (void *)buf;
3282 stream.avail_in = len;
3283 do {
3284 unsigned char *in0 = stream.next_in;
3285 ret = git_deflate(&stream, Z_FINISH);
3286 git_SHA1_Update(&c, in0, stream.next_in - in0);
3287 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
3288 die("unable to write sha1 file");
3289 stream.next_out = compressed;
3290 stream.avail_out = sizeof(compressed);
3291 } while (ret == Z_OK);
3292
3293 if (ret != Z_STREAM_END)
3294 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
3295 ret = git_deflate_end_gently(&stream);
3296 if (ret != Z_OK)
3297 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
3298 git_SHA1_Final(parano_sha1, &c);
3299 if (hashcmp(sha1, parano_sha1) != 0)
3300 die("confused by unstable object source data for %s", sha1_to_hex(sha1));
3301
3302 close_sha1_file(fd);
3303
3304 if (mtime) {
3305 struct utimbuf utb;
3306 utb.actime = mtime;
3307 utb.modtime = mtime;
3308 if (utime(tmp_file.buf, &utb) < 0)
3309 warning_errno("failed utime() on %s", tmp_file.buf);
3310 }
3311
3312 return finalize_object_file(tmp_file.buf, filename);
3313 }
3314
3315 static int freshen_loose_object(const unsigned char *sha1)
3316 {
3317 return check_and_freshen(sha1, 1);
3318 }
3319
3320 static int freshen_packed_object(const unsigned char *sha1)
3321 {
3322 struct pack_entry e;
3323 if (!find_pack_entry(sha1, &e))
3324 return 0;
3325 if (e.p->freshened)
3326 return 1;
3327 if (!freshen_file(e.p->pack_name))
3328 return 0;
3329 e.p->freshened = 1;
3330 return 1;
3331 }
3332
3333 int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *sha1)
3334 {
3335 char hdr[32];
3336 int hdrlen = sizeof(hdr);
3337
3338 /* Normally if we have it in the pack then we do not bother writing
3339 * it out into .git/objects/??/?{38} file.
3340 */
3341 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
3342 if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
3343 return 0;
3344 return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
3345 }
3346
3347 int hash_sha1_file_literally(const void *buf, unsigned long len, const char *type,
3348 unsigned char *sha1, unsigned flags)
3349 {
3350 char *header;
3351 int hdrlen, status = 0;
3352
3353 /* type string, SP, %lu of the length plus NUL must fit this */
3354 hdrlen = strlen(type) + 32;
3355 header = xmalloc(hdrlen);
3356 write_sha1_file_prepare(buf, len, type, sha1, header, &hdrlen);
3357
3358 if (!(flags & HASH_WRITE_OBJECT))
3359 goto cleanup;
3360 if (freshen_packed_object(sha1) || freshen_loose_object(sha1))
3361 goto cleanup;
3362 status = write_loose_object(sha1, header, hdrlen, buf, len, 0);
3363
3364 cleanup:
3365 free(header);
3366 return status;
3367 }
3368
3369 int force_object_loose(const unsigned char *sha1, time_t mtime)
3370 {
3371 void *buf;
3372 unsigned long len;
3373 enum object_type type;
3374 char hdr[32];
3375 int hdrlen;
3376 int ret;
3377
3378 if (has_loose_object(sha1))
3379 return 0;
3380 buf = read_object(sha1, &type, &len);
3381 if (!buf)
3382 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
3383 hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", typename(type), len) + 1;
3384 ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
3385 free(buf);
3386
3387 return ret;
3388 }
3389
3390 int has_pack_index(const unsigned char *sha1)
3391 {
3392 struct stat st;
3393 if (stat(sha1_pack_index_name(sha1), &st))
3394 return 0;
3395 return 1;
3396 }
3397
3398 int has_sha1_pack(const unsigned char *sha1)
3399 {
3400 struct pack_entry e;
3401 return find_pack_entry(sha1, &e);
3402 }
3403
3404 int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
3405 {
3406 if (!startup_info->have_repository)
3407 return 0;
3408 return sha1_object_info_extended(sha1, NULL,
3409 flags | OBJECT_INFO_SKIP_CACHED) >= 0;
3410 }
3411
3412 int has_object_file(const struct object_id *oid)
3413 {
3414 return has_sha1_file(oid->hash);
3415 }
3416
3417 int has_object_file_with_flags(const struct object_id *oid, int flags)
3418 {
3419 return has_sha1_file_with_flags(oid->hash, flags);
3420 }
3421
3422 static void check_tree(const void *buf, size_t size)
3423 {
3424 struct tree_desc desc;
3425 struct name_entry entry;
3426
3427 init_tree_desc(&desc, buf, size);
3428 while (tree_entry(&desc, &entry))
3429 /* do nothing
3430 * tree_entry() will die() on malformed entries */
3431 ;
3432 }
3433
3434 static void check_commit(const void *buf, size_t size)
3435 {
3436 struct commit c;
3437 memset(&c, 0, sizeof(c));
3438 if (parse_commit_buffer(&c, buf, size))
3439 die("corrupt commit");
3440 }
3441
3442 static void check_tag(const void *buf, size_t size)
3443 {
3444 struct tag t;
3445 memset(&t, 0, sizeof(t));
3446 if (parse_tag_buffer(&t, buf, size))
3447 die("corrupt tag");
3448 }
3449
3450 static int index_mem(unsigned char *sha1, void *buf, size_t size,
3451 enum object_type type,
3452 const char *path, unsigned flags)
3453 {
3454 int ret, re_allocated = 0;
3455 int write_object = flags & HASH_WRITE_OBJECT;
3456
3457 if (!type)
3458 type = OBJ_BLOB;
3459
3460 /*
3461 * Convert blobs to git internal format
3462 */
3463 if ((type == OBJ_BLOB) && path) {
3464 struct strbuf nbuf = STRBUF_INIT;
3465 if (convert_to_git(&the_index, path, buf, size, &nbuf,
3466 write_object ? safe_crlf : SAFE_CRLF_FALSE)) {
3467 buf = strbuf_detach(&nbuf, &size);
3468 re_allocated = 1;
3469 }
3470 }
3471 if (flags & HASH_FORMAT_CHECK) {
3472 if (type == OBJ_TREE)
3473 check_tree(buf, size);
3474 if (type == OBJ_COMMIT)
3475 check_commit(buf, size);
3476 if (type == OBJ_TAG)
3477 check_tag(buf, size);
3478 }
3479
3480 if (write_object)
3481 ret = write_sha1_file(buf, size, typename(type), sha1);
3482 else
3483 ret = hash_sha1_file(buf, size, typename(type), sha1);
3484 if (re_allocated)
3485 free(buf);
3486 return ret;
3487 }
3488
3489 static int index_stream_convert_blob(unsigned char *sha1, int fd,
3490 const char *path, unsigned flags)
3491 {
3492 int ret;
3493 const int write_object = flags & HASH_WRITE_OBJECT;
3494 struct strbuf sbuf = STRBUF_INIT;
3495
3496 assert(path);
3497 assert(would_convert_to_git_filter_fd(path));
3498
3499 convert_to_git_filter_fd(&the_index, path, fd, &sbuf,
3500 write_object ? safe_crlf : SAFE_CRLF_FALSE);
3501
3502 if (write_object)
3503 ret = write_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
3504 sha1);
3505 else
3506 ret = hash_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
3507 sha1);
3508 strbuf_release(&sbuf);
3509 return ret;
3510 }
3511
3512 static int index_pipe(unsigned char *sha1, int fd, enum object_type type,
3513 const char *path, unsigned flags)
3514 {
3515 struct strbuf sbuf = STRBUF_INIT;
3516 int ret;
3517
3518 if (strbuf_read(&sbuf, fd, 4096) >= 0)
3519 ret = index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);
3520 else
3521 ret = -1;
3522 strbuf_release(&sbuf);
3523 return ret;
3524 }
3525
3526 #define SMALL_FILE_SIZE (32*1024)
3527
3528 static int index_core(unsigned char *sha1, int fd, size_t size,
3529 enum object_type type, const char *path,
3530 unsigned flags)
3531 {
3532 int ret;
3533
3534 if (!size) {
3535 ret = index_mem(sha1, "", size, type, path, flags);
3536 } else if (size <= SMALL_FILE_SIZE) {
3537 char *buf = xmalloc(size);
3538 if (size == read_in_full(fd, buf, size))
3539 ret = index_mem(sha1, buf, size, type, path, flags);
3540 else
3541 ret = error_errno("short read");
3542 free(buf);
3543 } else {
3544 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
3545 ret = index_mem(sha1, buf, size, type, path, flags);
3546 munmap(buf, size);
3547 }
3548 return ret;
3549 }
3550
3551 /*
3552 * This creates one packfile per large blob unless bulk-checkin
3553 * machinery is "plugged".
3554 *
3555 * This also bypasses the usual "convert-to-git" dance, and that is on
3556 * purpose. We could write a streaming version of the converting
3557 * functions and insert that before feeding the data to fast-import
3558 * (or equivalent in-core API described above). However, that is
3559 * somewhat complicated, as we do not know the size of the filter
3560 * result, which we need to know beforehand when writing a git object.
3561 * Since the primary motivation for trying to stream from the working
3562 * tree file and to avoid mmaping it in core is to deal with large
3563 * binary blobs, they generally do not want to get any conversion, and
3564 * callers should avoid this code path when filters are requested.
3565 */
3566 static int index_stream(unsigned char *sha1, int fd, size_t size,
3567 enum object_type type, const char *path,
3568 unsigned flags)
3569 {
3570 return index_bulk_checkin(sha1, fd, size, type, path, flags);
3571 }
3572
3573 int index_fd(unsigned char *sha1, int fd, struct stat *st,
3574 enum object_type type, const char *path, unsigned flags)
3575 {
3576 int ret;
3577
3578 /*
3579 * Call xsize_t() only when needed to avoid potentially unnecessary
3580 * die() for large files.
3581 */
3582 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(path))
3583 ret = index_stream_convert_blob(sha1, fd, path, flags);
3584 else if (!S_ISREG(st->st_mode))
3585 ret = index_pipe(sha1, fd, type, path, flags);
3586 else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
3587 (path && would_convert_to_git(&the_index, path)))
3588 ret = index_core(sha1, fd, xsize_t(st->st_size), type, path,
3589 flags);
3590 else
3591 ret = index_stream(sha1, fd, xsize_t(st->st_size), type, path,
3592 flags);
3593 close(fd);
3594 return ret;
3595 }
3596
3597 int index_path(unsigned char *sha1, const char *path, struct stat *st, unsigned flags)
3598 {
3599 int fd;
3600 struct strbuf sb = STRBUF_INIT;
3601
3602 switch (st->st_mode & S_IFMT) {
3603 case S_IFREG:
3604 fd = open(path, O_RDONLY);
3605 if (fd < 0)
3606 return error_errno("open(\"%s\")", path);
3607 if (index_fd(sha1, fd, st, OBJ_BLOB, path, flags) < 0)
3608 return error("%s: failed to insert into database",
3609 path);
3610 break;
3611 case S_IFLNK:
3612 if (strbuf_readlink(&sb, path, st->st_size))
3613 return error_errno("readlink(\"%s\")", path);
3614 if (!(flags & HASH_WRITE_OBJECT))
3615 hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
3616 else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
3617 return error("%s: failed to insert into database",
3618 path);
3619 strbuf_release(&sb);
3620 break;
3621 case S_IFDIR:
3622 return resolve_gitlink_ref(path, "HEAD", sha1);
3623 default:
3624 return error("%s: unsupported file type", path);
3625 }
3626 return 0;
3627 }
3628
3629 int read_pack_header(int fd, struct pack_header *header)
3630 {
3631 if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
3632 /* "eof before pack header was fully read" */
3633 return PH_ERROR_EOF;
3634
3635 if (header->hdr_signature != htonl(PACK_SIGNATURE))
3636 /* "protocol error (pack signature mismatch detected)" */
3637 return PH_ERROR_PACK_SIGNATURE;
3638 if (!pack_version_ok(header->hdr_version))
3639 /* "protocol error (pack version unsupported)" */
3640 return PH_ERROR_PROTOCOL;
3641 return 0;
3642 }
3643
3644 void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
3645 {
3646 enum object_type type = sha1_object_info(sha1, NULL);
3647 if (type < 0)
3648 die("%s is not a valid object", sha1_to_hex(sha1));
3649 if (type != expect)
3650 die("%s is not a valid '%s' object", sha1_to_hex(sha1),
3651 typename(expect));
3652 }
3653
3654 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
3655 struct strbuf *path,
3656 each_loose_object_fn obj_cb,
3657 each_loose_cruft_fn cruft_cb,
3658 each_loose_subdir_fn subdir_cb,
3659 void *data)
3660 {
3661 size_t origlen, baselen;
3662 DIR *dir;
3663 struct dirent *de;
3664 int r = 0;
3665
3666 if (subdir_nr > 0xff)
3667 BUG("invalid loose object subdirectory: %x", subdir_nr);
3668
3669 origlen = path->len;
3670 strbuf_complete(path, '/');
3671 strbuf_addf(path, "%02x", subdir_nr);
3672 baselen = path->len;
3673
3674 dir = opendir(path->buf);
3675 if (!dir) {
3676 if (errno != ENOENT)
3677 r = error_errno("unable to open %s", path->buf);
3678 strbuf_setlen(path, origlen);
3679 return r;
3680 }
3681
3682 while ((de = readdir(dir))) {
3683 if (is_dot_or_dotdot(de->d_name))
3684 continue;
3685
3686 strbuf_setlen(path, baselen);
3687 strbuf_addf(path, "/%s", de->d_name);
3688
3689 if (strlen(de->d_name) == GIT_SHA1_HEXSZ - 2) {
3690 char hex[GIT_MAX_HEXSZ+1];
3691 struct object_id oid;
3692
3693 xsnprintf(hex, sizeof(hex), "%02x%s",
3694 subdir_nr, de->d_name);
3695 if (!get_oid_hex(hex, &oid)) {
3696 if (obj_cb) {
3697 r = obj_cb(&oid, path->buf, data);
3698 if (r)
3699 break;
3700 }
3701 continue;
3702 }
3703 }
3704
3705 if (cruft_cb) {
3706 r = cruft_cb(de->d_name, path->buf, data);
3707 if (r)
3708 break;
3709 }
3710 }
3711 closedir(dir);
3712
3713 strbuf_setlen(path, baselen);
3714 if (!r && subdir_cb)
3715 r = subdir_cb(subdir_nr, path->buf, data);
3716
3717 strbuf_setlen(path, origlen);
3718
3719 return r;
3720 }
3721
3722 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
3723 each_loose_object_fn obj_cb,
3724 each_loose_cruft_fn cruft_cb,
3725 each_loose_subdir_fn subdir_cb,
3726 void *data)
3727 {
3728 int r = 0;
3729 int i;
3730
3731 for (i = 0; i < 256; i++) {
3732 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
3733 subdir_cb, data);
3734 if (r)
3735 break;
3736 }
3737
3738 return r;
3739 }
3740
3741 int for_each_loose_file_in_objdir(const char *path,
3742 each_loose_object_fn obj_cb,
3743 each_loose_cruft_fn cruft_cb,
3744 each_loose_subdir_fn subdir_cb,
3745 void *data)
3746 {
3747 struct strbuf buf = STRBUF_INIT;
3748 int r;
3749
3750 strbuf_addstr(&buf, path);
3751 r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
3752 subdir_cb, data);
3753 strbuf_release(&buf);
3754
3755 return r;
3756 }
3757
3758 struct loose_alt_odb_data {
3759 each_loose_object_fn *cb;
3760 void *data;
3761 };
3762
3763 static int loose_from_alt_odb(struct alternate_object_database *alt,
3764 void *vdata)
3765 {
3766 struct loose_alt_odb_data *data = vdata;
3767 struct strbuf buf = STRBUF_INIT;
3768 int r;
3769
3770 strbuf_addstr(&buf, alt->path);
3771 r = for_each_loose_file_in_objdir_buf(&buf,
3772 data->cb, NULL, NULL,
3773 data->data);
3774 strbuf_release(&buf);
3775 return r;
3776 }
3777
3778 int for_each_loose_object(each_loose_object_fn cb, void *data, unsigned flags)
3779 {
3780 struct loose_alt_odb_data alt;
3781 int r;
3782
3783 r = for_each_loose_file_in_objdir(get_object_directory(),
3784 cb, NULL, NULL, data);
3785 if (r)
3786 return r;
3787
3788 if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
3789 return 0;
3790
3791 alt.cb = cb;
3792 alt.data = data;
3793 return foreach_alt_odb(loose_from_alt_odb, &alt);
3794 }
3795
3796 static int for_each_object_in_pack(struct packed_git *p, each_packed_object_fn cb, void *data)
3797 {
3798 uint32_t i;
3799 int r = 0;
3800
3801 for (i = 0; i < p->num_objects; i++) {
3802 struct object_id oid;
3803
3804 if (!nth_packed_object_oid(&oid, p, i))
3805 return error("unable to get sha1 of object %u in %s",
3806 i, p->pack_name);
3807
3808 r = cb(&oid, p, i, data);
3809 if (r)
3810 break;
3811 }
3812 return r;
3813 }
3814
3815 int for_each_packed_object(each_packed_object_fn cb, void *data, unsigned flags)
3816 {
3817 struct packed_git *p;
3818 int r = 0;
3819 int pack_errors = 0;
3820
3821 prepare_packed_git();
3822 for (p = packed_git; p; p = p->next) {
3823 if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
3824 continue;
3825 if (open_pack_index(p)) {
3826 pack_errors = 1;
3827 continue;
3828 }
3829 r = for_each_object_in_pack(p, cb, data);
3830 if (r)
3831 break;
3832 }
3833 return r ? r : pack_errors;
3834 }
3835
3836 static int check_stream_sha1(git_zstream *stream,
3837 const char *hdr,
3838 unsigned long size,
3839 const char *path,
3840 const unsigned char *expected_sha1)
3841 {
3842 git_SHA_CTX c;
3843 unsigned char real_sha1[GIT_MAX_RAWSZ];
3844 unsigned char buf[4096];
3845 unsigned long total_read;
3846 int status = Z_OK;
3847
3848 git_SHA1_Init(&c);
3849 git_SHA1_Update(&c, hdr, stream->total_out);
3850
3851 /*
3852 * We already read some bytes into hdr, but the ones up to the NUL
3853 * do not count against the object's content size.
3854 */
3855 total_read = stream->total_out - strlen(hdr) - 1;
3856
3857 /*
3858 * This size comparison must be "<=" to read the final zlib packets;
3859 * see the comment in unpack_sha1_rest for details.
3860 */
3861 while (total_read <= size &&
3862 (status == Z_OK || status == Z_BUF_ERROR)) {
3863 stream->next_out = buf;
3864 stream->avail_out = sizeof(buf);
3865 if (size - total_read < stream->avail_out)
3866 stream->avail_out = size - total_read;
3867 status =