safe_create_leading_directories(): add explicit "slash" pointer
[git/git.git] / sha1_file.c
CommitLineData
0fcfd160
LT
1/*
2 * GIT - The information manager from hell
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 *
6 * This handles basic git sha1 object files - packing, unpacking,
7 * creation etc.
8 */
0fcfd160 9#include "cache.h"
6eac50d8 10#include "string-list.h"
1f688557 11#include "delta.h"
a733cb60 12#include "pack.h"
8e440259
PE
13#include "blob.h"
14#include "commit.h"
4dd1fbc7 15#include "run-command.h"
8e440259
PE
16#include "tag.h"
17#include "tree.h"
c879daa2 18#include "tree-walk.h"
f35a6d3b 19#include "refs.h"
70f5d5d3 20#include "pack-revindex.h"
628522ec 21#include "sha1-lookup.h"
568508e7 22#include "bulk-checkin.h"
090ea126 23#include "streaming.h"
543c5caa 24#include "dir.h"
0fcfd160 25
144bde78
LT
26#ifndef O_NOATIME
27#if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
28#define O_NOATIME 01000000
29#else
30#define O_NOATIME 0
31#endif
32#endif
33
28bd70d8
JN
34#define SZ_FMT PRIuMAX
35static inline uintmax_t sz_fmt(size_t s) { return s; }
e05db0fd 36
96f1e58f 37const unsigned char null_sha1[20];
88cd621d 38
b12ca963
NTND
39static const char *no_log_pack_access = "no_log_pack_access";
40static const char *log_pack_access;
41
c597ba80
NTND
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 */
48static struct cached_object {
49 unsigned char sha1[20];
50 enum object_type type;
51 void *buf;
52 unsigned long size;
53} *cached_objects;
54static int cached_object_nr, cached_object_alloc;
55
56static struct cached_object empty_tree = {
dab0d410 57 EMPTY_TREE_SHA1_BIN_LITERAL,
c597ba80
NTND
58 OBJ_TREE,
59 "",
60 0
61};
62
c01f51cc
NTND
63static struct packed_git *last_found_pack;
64
c597ba80
NTND
65static struct cached_object *find_cached_object(const unsigned char *sha1)
66{
67 int i;
68 struct cached_object *co = cached_objects;
69
70 for (i = 0; i < cached_object_nr; i++, co++) {
71 if (!hashcmp(co->sha1, sha1))
72 return co;
73 }
74 if (!hashcmp(sha1, empty_tree.sha1))
75 return &empty_tree;
76 return NULL;
77}
78
90a6464b
JH
79int mkdir_in_gitdir(const char *path)
80{
81 if (mkdir(path, 0777)) {
82 int saved_errno = errno;
83 struct stat st;
84 struct strbuf sb = STRBUF_INIT;
85
86 if (errno != EEXIST)
87 return -1;
88 /*
89 * Are we looking at a path in a symlinked worktree
90 * whose original repository does not yet have it?
91 * e.g. .git/rr-cache pointing at its original
92 * repository in which the user hasn't performed any
93 * conflict resolution yet?
94 */
95 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
96 strbuf_readlink(&sb, path, st.st_size) ||
97 !is_absolute_path(sb.buf) ||
98 mkdir(sb.buf, 0777)) {
99 strbuf_release(&sb);
100 errno = saved_errno;
101 return -1;
102 }
103 strbuf_release(&sb);
104 }
105 return adjust_shared_perm(path);
106}
107
b2cb9425
JH
108int safe_create_leading_directories(char *path)
109{
8385abfd 110 char *pos = path + offset_1st_component(path);
67d42212 111
b2cb9425 112 while (pos) {
f0502332 113 struct stat st;
831651fd 114 char *slash = strchr(pos, '/');
f0502332 115
831651fd 116 if (!slash)
b2cb9425 117 break;
831651fd
MH
118 while (*(slash + 1) == '/')
119 slash++;
120 pos = slash + 1;
5f0bdf50
JH
121 if (!*pos)
122 break;
831651fd
MH
123
124 *slash = '\0';
67d42212
JR
125 if (!stat(path, &st)) {
126 /* path exists */
127 if (!S_ISDIR(st.st_mode)) {
831651fd 128 *slash = '/';
67d42212 129 return -3;
b2cb9425 130 }
53a39721 131 } else if (mkdir(path, 0777)) {
928734d9
SW
132 if (errno == EEXIST &&
133 !stat(path, &st) && S_ISDIR(st.st_mode)) {
134 ; /* somebody created it since we checked */
135 } else {
831651fd 136 *slash = '/';
928734d9
SW
137 return -1;
138 }
53a39721 139 } else if (adjust_shared_perm(path)) {
831651fd 140 *slash = '/';
457f06d6
JS
141 return -2;
142 }
831651fd 143 *slash = '/';
b2cb9425
JH
144 }
145 return 0;
146}
723c31fe 147
8e21d63b
JK
148int safe_create_leading_directories_const(const char *path)
149{
150 /* path points to cache entries, so xstrdup before messing with it */
151 char *buf = xstrdup(path);
152 int result = safe_create_leading_directories(buf);
153 free(buf);
154 return result;
155}
156
ace1534d
JH
157static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
158{
159 int i;
160 for (i = 0; i < 20; i++) {
161 static char hex[] = "0123456789abcdef";
162 unsigned int val = sha1[i];
163 char *pos = pathbuf + i*2 + (i > 0);
164 *pos++ = hex[val >> 4];
165 *pos = hex[val & 0xf];
166 }
167}
168
0fcfd160
LT
169/*
170 * NOTE! This returns a statically allocated buffer, so you have to be
790296fd 171 * careful about using it. Do an "xstrdup()" if you need to save the
0fcfd160 172 * filename.
ace1534d
JH
173 *
174 * Also note that this returns the location for creating. Reading
175 * SHA1 file can happen from any alternate directory listed in the
d19938ab 176 * DB_ENVIRONMENT environment variable if it is not found in
ace1534d 177 * the primary object database.
0fcfd160
LT
178 */
179char *sha1_file_name(const unsigned char *sha1)
180{
560fb6a1
JK
181 static char buf[PATH_MAX];
182 const char *objdir;
183 int len;
0fcfd160 184
560fb6a1
JK
185 objdir = get_object_directory();
186 len = strlen(objdir);
187
188 /* '/' + sha1(2) + '/' + sha1(38) + '\0' */
189 if (len + 43 > PATH_MAX)
190 die("insanely long object directory %s", objdir);
191 memcpy(buf, objdir, len);
192 buf[len] = '/';
193 buf[len+3] = '/';
194 buf[len+42] = '\0';
195 fill_sha1_path(buf + len + 1, sha1);
196 return buf;
0fcfd160
LT
197}
198
633f43e1 199static char *sha1_get_pack_name(const unsigned char *sha1,
6eec46bd 200 char **name, char **base, const char *which)
bf592c50
DB
201{
202 static const char hex[] = "0123456789abcdef";
633f43e1 203 char *buf;
bf592c50
DB
204 int i;
205
633f43e1 206 if (!*base) {
bf592c50
DB
207 const char *sha1_file_directory = get_object_directory();
208 int len = strlen(sha1_file_directory);
633f43e1 209 *base = xmalloc(len + 60);
6eec46bd
JH
210 sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
211 sha1_file_directory, which);
633f43e1 212 *name = *base + len + 11;
bf592c50
DB
213 }
214
633f43e1 215 buf = *name;
bf592c50
DB
216
217 for (i = 0; i < 20; i++) {
218 unsigned int val = *sha1++;
219 *buf++ = hex[val >> 4];
220 *buf++ = hex[val & 0xf];
221 }
a6080a0a 222
633f43e1 223 return *base;
bf592c50
DB
224}
225
633f43e1 226char *sha1_pack_name(const unsigned char *sha1)
bf592c50 227{
633f43e1 228 static char *name, *base;
bf592c50 229
6eec46bd 230 return sha1_get_pack_name(sha1, &name, &base, "pack");
633f43e1 231}
bf592c50 232
633f43e1
HO
233char *sha1_pack_index_name(const unsigned char *sha1)
234{
235 static char *name, *base;
a6080a0a 236
6eec46bd 237 return sha1_get_pack_name(sha1, &name, &base, "idx");
bf592c50
DB
238}
239
d5a63b99
JH
240struct alternate_object_database *alt_odb_list;
241static struct alternate_object_database **alt_odb_tail;
ace1534d 242
f4e51683 243static int git_open_noatime(const char *name);
c2f493a4 244
ddd5d056
JH
245/*
246 * Prepare alternate object database registry.
d5a63b99
JH
247 *
248 * The variable alt_odb_list points at the list of struct
249 * alternate_object_database. The elements on this list come from
250 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
251 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
1494e038
JH
252 * whose contents is similar to that environment variable but can be
253 * LF separated. Its base points at a statically allocated buffer that
d5a63b99
JH
254 * contains "/the/directory/corresponding/to/.git/objects/...", while
255 * its name points just after the slash at the end of ".git/objects/"
256 * in the example above, and has enough space to hold 40-byte hex
257 * SHA1, an extra slash for the first level indirection, and the
258 * terminating NUL.
ddd5d056 259 */
6eac50d8 260static int link_alt_odb_entry(const char *entry, const char *relative_base, int depth)
ace1534d 261{
1494e038 262 const char *objdir = get_object_directory();
c2f493a4
MW
263 struct alternate_object_database *ent;
264 struct alternate_object_database *alt;
5bdf0a84
HW
265 int pfxlen, entlen;
266 struct strbuf pathbuf = STRBUF_INIT;
d5a63b99 267
85dadc38 268 if (!is_absolute_path(entry) && relative_base) {
5bdf0a84
HW
269 strbuf_addstr(&pathbuf, real_path(relative_base));
270 strbuf_addch(&pathbuf, '/');
c2f493a4 271 }
6eac50d8 272 strbuf_addstr(&pathbuf, entry);
c2f493a4 273
5bdf0a84
HW
274 normalize_path_copy(pathbuf.buf, pathbuf.buf);
275
276 pfxlen = strlen(pathbuf.buf);
277
278 /*
279 * The trailing slash after the directory name is given by
280 * this function at the end. Remove duplicates.
281 */
282 while (pfxlen && pathbuf.buf[pfxlen-1] == '/')
283 pfxlen -= 1;
284
285 entlen = pfxlen + 43; /* '/' + 2 hex + '/' + 38 hex + NUL */
286 ent = xmalloc(sizeof(*ent) + entlen);
287 memcpy(ent->base, pathbuf.buf, pfxlen);
288 strbuf_release(&pathbuf);
c2f493a4
MW
289
290 ent->name = ent->base + pfxlen + 1;
291 ent->base[pfxlen + 3] = '/';
292 ent->base[pfxlen] = ent->base[entlen-1] = 0;
293
294 /* Detect cases where alternate disappeared */
90b4a71c 295 if (!is_directory(ent->base)) {
c2f493a4
MW
296 error("object directory %s does not exist; "
297 "check .git/objects/info/alternates.",
298 ent->base);
299 free(ent);
300 return -1;
301 }
302
303 /* Prevent the common mistake of listing the same
304 * thing twice, or object directory itself.
305 */
306 for (alt = alt_odb_list; alt; alt = alt->next) {
307 if (!memcmp(ent->base, alt->base, pfxlen)) {
308 free(ent);
309 return -1;
310 }
311 }
cb2912c3 312 if (!strcmp(ent->base, objdir)) {
c2f493a4
MW
313 free(ent);
314 return -1;
315 }
316
317 /* add the alternate entry */
318 *alt_odb_tail = ent;
319 alt_odb_tail = &(ent->next);
320 ent->next = NULL;
321
322 /* recursively add alternates */
323 read_info_alternates(ent->base, depth + 1);
324
325 ent->base[pfxlen] = '/';
326
327 return 0;
328}
329
c5950164 330static void link_alt_odb_entries(const char *alt, int len, int sep,
c2f493a4
MW
331 const char *relative_base, int depth)
332{
6eac50d8
MH
333 struct string_list entries = STRING_LIST_INIT_NODUP;
334 char *alt_copy;
335 int i;
c2f493a4
MW
336
337 if (depth > 5) {
338 error("%s: ignoring alternate object stores, nesting too deep.",
339 relative_base);
340 return;
341 }
342
c5950164 343 alt_copy = xmemdupz(alt, len);
6eac50d8
MH
344 string_list_split_in_place(&entries, alt_copy, sep, -1);
345 for (i = 0; i < entries.nr; i++) {
346 const char *entry = entries.items[i].string;
347 if (entry[0] == '\0' || entry[0] == '#')
9577e7e3 348 continue;
6eac50d8
MH
349 if (!is_absolute_path(entry) && depth) {
350 error("%s: ignoring relative alternate object store %s",
351 relative_base, entry);
352 } else {
353 link_alt_odb_entry(entry, relative_base, depth);
9577e7e3 354 }
9577e7e3 355 }
6eac50d8
MH
356 string_list_clear(&entries, 0);
357 free(alt_copy);
d5a63b99
JH
358}
359
5e73633d 360void read_info_alternates(const char * relative_base, int depth)
d5a63b99 361{
9577e7e3 362 char *map;
dc49cd76 363 size_t mapsz;
d5a63b99 364 struct stat st;
9cb18f56
JM
365 const char alt_file_name[] = "info/alternates";
366 /* Given that relative_base is no longer than PATH_MAX,
367 ensure that "path" has enough space to append "/", the
368 file name, "info/alternates", and a trailing NUL. */
369 char path[PATH_MAX + 1 + sizeof alt_file_name];
c2f493a4 370 int fd;
d5a63b99 371
9cb18f56 372 sprintf(path, "%s/%s", relative_base, alt_file_name);
f4e51683 373 fd = git_open_noatime(path);
d5a63b99
JH
374 if (fd < 0)
375 return;
376 if (fstat(fd, &st) || (st.st_size == 0)) {
377 close(fd);
9a217f2a 378 return;
ace1534d 379 }
dc49cd76
SP
380 mapsz = xsize_t(st.st_size);
381 map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
d5a63b99 382 close(fd);
d5a63b99 383
c5950164 384 link_alt_odb_entries(map, mapsz, '\n', relative_base, depth);
c2f493a4 385
dc49cd76 386 munmap(map, mapsz);
ace1534d
JH
387}
388
bef70b22
DB
389void add_to_alternates_file(const char *reference)
390{
391 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
acd3b9ec 392 int fd = hold_lock_file_for_append(lock, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR);
e6baf4a1 393 char *alt = mkpath("%s\n", reference);
bef70b22
DB
394 write_or_die(fd, alt, strlen(alt));
395 if (commit_lock_file(lock))
396 die("could not close alternates file");
397 if (alt_odb_tail)
c5950164 398 link_alt_odb_entries(alt, strlen(alt), '\n', NULL, 0);
bef70b22
DB
399}
400
d79796bc
JH
401void foreach_alt_odb(alt_odb_fn fn, void *cb)
402{
403 struct alternate_object_database *ent;
404
405 prepare_alt_odb();
406 for (ent = alt_odb_list; ent; ent = ent->next)
407 if (fn(ent, cb))
408 return;
409}
410
c2f493a4
MW
411void prepare_alt_odb(void)
412{
554fe20d 413 const char *alt;
c2f493a4 414
7dc24aa5
SP
415 if (alt_odb_tail)
416 return;
417
c2f493a4
MW
418 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
419 if (!alt) alt = "";
420
c2f493a4 421 alt_odb_tail = &alt_odb_list;
c5950164 422 link_alt_odb_entries(alt, strlen(alt), PATH_SEP, NULL, 0);
c2f493a4
MW
423
424 read_info_alternates(get_object_directory(), 0);
425}
426
0f4dc14a 427static int has_loose_object_local(const unsigned char *sha1)
ace1534d 428{
ace1534d 429 char *name = sha1_file_name(sha1);
0f4dc14a
BC
430 return !access(name, F_OK);
431}
ace1534d 432
0f4dc14a
BC
433int has_loose_object_nonlocal(const unsigned char *sha1)
434{
435 struct alternate_object_database *alt;
9a217f2a 436 prepare_alt_odb();
d5a63b99 437 for (alt = alt_odb_list; alt; alt = alt->next) {
0f4dc14a 438 fill_sha1_path(alt->name, sha1);
c529d75a
LT
439 if (!access(alt->base, F_OK))
440 return 1;
ace1534d 441 }
c529d75a 442 return 0;
ace1534d
JH
443}
444
0f4dc14a
BC
445static int has_loose_object(const unsigned char *sha1)
446{
447 return has_loose_object_local(sha1) ||
448 has_loose_object_nonlocal(sha1);
449}
450
60bb8b14 451static unsigned int pack_used_ctr;
a53128b6
SP
452static unsigned int pack_mmap_calls;
453static unsigned int peak_pack_open_windows;
454static unsigned int pack_open_windows;
c7934306
SP
455static unsigned int pack_open_fds;
456static unsigned int pack_max_fds;
a53128b6 457static size_t peak_pack_mapped;
60bb8b14 458static size_t pack_mapped;
9a217f2a 459struct packed_git *packed_git;
1f688557 460
b79d18c9 461void pack_report(void)
a53128b6
SP
462{
463 fprintf(stderr,
e05db0fd
PR
464 "pack_report: getpagesize() = %10" SZ_FMT "\n"
465 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
466 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
9e42d6a1
SP
467 sz_fmt(getpagesize()),
468 sz_fmt(packed_git_window_size),
469 sz_fmt(packed_git_limit));
a53128b6
SP
470 fprintf(stderr,
471 "pack_report: pack_used_ctr = %10u\n"
472 "pack_report: pack_mmap_calls = %10u\n"
473 "pack_report: pack_open_windows = %10u / %10u\n"
e05db0fd
PR
474 "pack_report: pack_mapped = "
475 "%10" SZ_FMT " / %10" SZ_FMT "\n",
a53128b6
SP
476 pack_used_ctr,
477 pack_mmap_calls,
478 pack_open_windows, peak_pack_open_windows,
9e42d6a1 479 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
a53128b6
SP
480}
481
42873078 482static int check_packed_git_idx(const char *path, struct packed_git *p)
1f688557
JH
483{
484 void *idx_map;
42873078 485 struct pack_idx_header *hdr;
dc49cd76 486 size_t idx_size;
74e34e1f 487 uint32_t version, nr, i, *index;
f4e51683 488 int fd = git_open_noatime(path);
1f688557 489 struct stat st;
42873078 490
1f688557
JH
491 if (fd < 0)
492 return -1;
493 if (fstat(fd, &st)) {
494 close(fd);
495 return -1;
496 }
dc49cd76 497 idx_size = xsize_t(st.st_size);
2d88451b
SP
498 if (idx_size < 4 * 256 + 20 + 20) {
499 close(fd);
500 return error("index file %s is too small", path);
501 }
c4712e45 502 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
1f688557 503 close(fd);
1f688557 504
42873078
NP
505 hdr = idx_map;
506 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
74e34e1f
NP
507 version = ntohl(hdr->idx_version);
508 if (version < 2 || version > 2) {
509 munmap(idx_map, idx_size);
6e1c2344 510 return error("index file %s is version %"PRIu32
74e34e1f
NP
511 " and is not supported by this binary"
512 " (try upgrading GIT to a newer version)",
513 path, version);
514 }
515 } else
516 version = 1;
df1b059d 517
1f688557 518 nr = 0;
42873078 519 index = idx_map;
74e34e1f
NP
520 if (version > 1)
521 index += 2; /* skip index header */
1f688557 522 for (i = 0; i < 256; i++) {
326bf396 523 uint32_t n = ntohl(index[i]);
2d88451b
SP
524 if (n < nr) {
525 munmap(idx_map, idx_size);
df1b059d 526 return error("non-monotonic index %s", path);
2d88451b 527 }
1f688557
JH
528 nr = n;
529 }
530
74e34e1f
NP
531 if (version == 1) {
532 /*
533 * Total size:
534 * - 256 index entries 4 bytes each
535 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
536 * - 20-byte SHA1 of the packfile
537 * - 20-byte SHA1 file checksum
538 */
539 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
540 munmap(idx_map, idx_size);
eef427a0 541 return error("wrong index v1 file size in %s", path);
74e34e1f
NP
542 }
543 } else if (version == 2) {
544 /*
545 * Minimum size:
546 * - 8 bytes of header
547 * - 256 index entries 4 bytes each
548 * - 20-byte sha1 entry * nr
549 * - 4-byte crc entry * nr
550 * - 4-byte offset entry * nr
551 * - 20-byte SHA1 of the packfile
552 * - 20-byte SHA1 file checksum
553 * And after the 4-byte offset table might be a
554 * variable sized table containing 8-byte entries
555 * for offsets larger than 2^31.
556 */
557 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
1164f1e4
LT
558 unsigned long max_size = min_size;
559 if (nr)
560 max_size += (nr - 1)*8;
561 if (idx_size < min_size || idx_size > max_size) {
74e34e1f 562 munmap(idx_map, idx_size);
eef427a0 563 return error("wrong index v2 file size in %s", path);
74e34e1f 564 }
7109c889
JH
565 if (idx_size != min_size &&
566 /*
567 * make sure we can deal with large pack offsets.
568 * 31-bit signed offset won't be enough, neither
569 * 32-bit unsigned one will be.
570 */
571 (sizeof(off_t) <= 4)) {
572 munmap(idx_map, idx_size);
573 return error("pack too large for current definition of off_t in %s", path);
74e34e1f 574 }
2d88451b 575 }
1f688557 576
74e34e1f 577 p->index_version = version;
42873078
NP
578 p->index_data = idx_map;
579 p->index_size = idx_size;
57059091 580 p->num_objects = nr;
1f688557
JH
581 return 0;
582}
583
bc8e478a 584int open_pack_index(struct packed_git *p)
d079837e
SP
585{
586 char *idx_name;
587 int ret;
588
589 if (p->index_data)
590 return 0;
591
592 idx_name = xstrdup(p->pack_name);
593 strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
594 ret = check_packed_git_idx(idx_name, p);
595 free(idx_name);
596 return ret;
597}
598
11daf39b
SP
599static void scan_windows(struct packed_git *p,
600 struct packed_git **lru_p,
601 struct pack_window **lru_w,
602 struct pack_window **lru_l)
1f688557 603{
11daf39b
SP
604 struct pack_window *w, *w_l;
605
606 for (w_l = NULL, w = p->windows; w; w = w->next) {
607 if (!w->inuse_cnt) {
608 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
609 *lru_p = p;
610 *lru_w = w;
611 *lru_l = w_l;
54044bf8 612 }
54044bf8 613 }
11daf39b 614 w_l = w;
f9253394 615 }
11daf39b
SP
616}
617
7c3ecb32 618static int unuse_one_window(struct packed_git *current)
11daf39b
SP
619{
620 struct packed_git *p, *lru_p = NULL;
621 struct pack_window *lru_w = NULL, *lru_l = NULL;
622
623 if (current)
624 scan_windows(current, &lru_p, &lru_w, &lru_l);
625 for (p = packed_git; p; p = p->next)
626 scan_windows(p, &lru_p, &lru_w, &lru_l);
54044bf8
SP
627 if (lru_p) {
628 munmap(lru_w->base, lru_w->len);
629 pack_mapped -= lru_w->len;
630 if (lru_l)
631 lru_l->next = lru_w->next;
7c3ecb32 632 else
54044bf8 633 lru_p->windows = lru_w->next;
54044bf8 634 free(lru_w);
a53128b6 635 pack_open_windows--;
54044bf8
SP
636 return 1;
637 }
638 return 0;
f9253394
JH
639}
640
7c3ecb32 641void release_pack_memory(size_t need)
97bfeb34
SP
642{
643 size_t cur = pack_mapped;
7c3ecb32 644 while (need >= (cur - pack_mapped) && unuse_one_window(NULL))
97bfeb34
SP
645 ; /* nothing */
646}
647
58ecbd5e
JN
648void *xmmap(void *start, size_t length,
649 int prot, int flags, int fd, off_t offset)
650{
651 void *ret = mmap(start, length, prot, flags, fd, offset);
652 if (ret == MAP_FAILED) {
653 if (!length)
654 return NULL;
7c3ecb32 655 release_pack_memory(length);
58ecbd5e
JN
656 ret = mmap(start, length, prot, flags, fd, offset);
657 if (ret == MAP_FAILED)
658 die_errno("Out of memory? mmap failed");
659 }
660 return ret;
661}
662
c9ced051
SP
663void close_pack_windows(struct packed_git *p)
664{
665 while (p->windows) {
666 struct pack_window *w = p->windows;
667
668 if (w->inuse_cnt)
669 die("pack '%s' still has open windows to it",
670 p->pack_name);
671 munmap(w->base, w->len);
672 pack_mapped -= w->len;
673 pack_open_windows--;
674 p->windows = w->next;
675 free(w);
676 }
677}
678
88d0db55
BC
679/*
680 * The LRU pack is the one with the oldest MRU window, preferring packs
681 * with no used windows, or the oldest mtime if it has no windows allocated.
682 */
683static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
684{
685 struct pack_window *w, *this_mru_w;
686 int has_windows_inuse = 0;
687
688 /*
689 * Reject this pack if it has windows and the previously selected
690 * one does not. If this pack does not have windows, reject
691 * it if the pack file is newer than the previously selected one.
692 */
693 if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
694 return;
695
696 for (w = this_mru_w = p->windows; w; w = w->next) {
697 /*
698 * Reject this pack if any of its windows are in use,
699 * but the previously selected pack did not have any
700 * inuse windows. Otherwise, record that this pack
701 * has windows in use.
702 */
703 if (w->inuse_cnt) {
704 if (*accept_windows_inuse)
705 has_windows_inuse = 1;
706 else
707 return;
708 }
709
710 if (w->last_used > this_mru_w->last_used)
711 this_mru_w = w;
712
713 /*
714 * Reject this pack if it has windows that have been
715 * used more recently than the previously selected pack.
716 * If the previously selected pack had windows inuse and
717 * we have not encountered a window in this pack that is
718 * inuse, skip this check since we prefer a pack with no
719 * inuse windows to one that has inuse windows.
720 */
721 if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
722 this_mru_w->last_used > (*mru_w)->last_used)
723 return;
724 }
725
726 /*
727 * Select this pack.
728 */
729 *mru_w = this_mru_w;
730 *lru_p = p;
731 *accept_windows_inuse = has_windows_inuse;
732}
733
734static int close_one_pack(void)
735{
736 struct packed_git *p, *lru_p = NULL;
737 struct pack_window *mru_w = NULL;
738 int accept_windows_inuse = 1;
739
740 for (p = packed_git; p; p = p->next) {
741 if (p->pack_fd == -1)
742 continue;
743 find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
744 }
745
746 if (lru_p) {
747 close(lru_p->pack_fd);
748 pack_open_fds--;
749 lru_p->pack_fd = -1;
750 return 1;
751 }
752
753 return 0;
754}
755
03e79c88 756void unuse_pack(struct pack_window **w_cursor)
f9253394 757{
03e79c88
SP
758 struct pack_window *w = *w_cursor;
759 if (w) {
760 w->inuse_cnt--;
761 *w_cursor = NULL;
762 }
1f688557
JH
763}
764
fa5fc15d
SP
765void close_pack_index(struct packed_git *p)
766{
767 if (p->index_data) {
768 munmap((void *)p->index_data, p->index_size);
769 p->index_data = NULL;
770 }
771}
772
c74faea1
NP
773/*
774 * This is used by git-repack in case a newly created pack happens to
775 * contain the same set of objects as an existing one. In that case
776 * the resulting file might be different even if its name would be the
777 * same. It is best to close any reference to the old pack before it is
778 * replaced on disk. Of course no index pointers nor windows for given pack
779 * must subsist at this point. If ever objects from this pack are requested
780 * again, the new version of the pack will be reinitialized through
781 * reprepare_packed_git().
782 */
783void free_pack_by_name(const char *pack_name)
784{
785 struct packed_git *p, **pp = &packed_git;
786
787 while (*pp) {
788 p = *pp;
789 if (strcmp(pack_name, p->pack_name) == 0) {
fa3a0c94 790 clear_delta_base_cache();
c74faea1 791 close_pack_windows(p);
c7934306 792 if (p->pack_fd != -1) {
c74faea1 793 close(p->pack_fd);
c7934306
SP
794 pack_open_fds--;
795 }
fa5fc15d 796 close_pack_index(p);
c74faea1
NP
797 free(p->bad_object_sha1);
798 *pp = p->next;
c01f51cc
NTND
799 if (last_found_pack == p)
800 last_found_pack = NULL;
c74faea1
NP
801 free(p);
802 return;
803 }
804 pp = &p->next;
805 }
806}
807
a0788266
JS
808static unsigned int get_max_fd_limit(void)
809{
810#ifdef RLIMIT_NOFILE
811 struct rlimit lim;
812
813 if (getrlimit(RLIMIT_NOFILE, &lim))
814 die_errno("cannot get RLIMIT_NOFILE");
815
816 return lim.rlim_cur;
817#elif defined(_SC_OPEN_MAX)
818 return sysconf(_SC_OPEN_MAX);
819#elif defined(OPEN_MAX)
820 return OPEN_MAX;
821#else
822 return 1; /* see the caller ;-) */
823#endif
824}
825
3cf8b462
SP
826/*
827 * Do not call this directly as this leaks p->pack_fd on error return;
828 * call open_packed_git() instead.
829 */
830static int open_packed_git_1(struct packed_git *p)
1f688557 831{
9bc879c1
SP
832 struct stat st;
833 struct pack_header hdr;
834 unsigned char sha1[20];
835 unsigned char *idx_sha1;
2c039da8 836 long fd_flag;
9bc879c1 837
d079837e
SP
838 if (!p->index_data && open_pack_index(p))
839 return error("packfile %s index unavailable", p->pack_name);
840
c7934306 841 if (!pack_max_fds) {
a0788266 842 unsigned int max_fds = get_max_fd_limit();
c7934306
SP
843
844 /* Save 3 for stdin/stdout/stderr, 22 for work */
845 if (25 < max_fds)
846 pack_max_fds = max_fds - 25;
847 else
848 pack_max_fds = 1;
849 }
850
88d0db55 851 while (pack_max_fds <= pack_open_fds && close_one_pack())
c7934306
SP
852 ; /* nothing */
853
f4e51683 854 p->pack_fd = git_open_noatime(p->pack_name);
9bc879c1 855 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
072db278 856 return -1;
c7934306 857 pack_open_fds++;
9bc879c1
SP
858
859 /* If we created the struct before we had the pack we lack size. */
bf592c50 860 if (!p->pack_size) {
bf592c50 861 if (!S_ISREG(st.st_mode))
072db278 862 return error("packfile %s not a regular file", p->pack_name);
bf592c50 863 p->pack_size = st.st_size;
9bc879c1 864 } else if (p->pack_size != st.st_size)
072db278 865 return error("packfile %s size changed", p->pack_name);
9bc879c1 866
2c039da8
JH
867 /* We leave these file descriptors open with sliding mmap;
868 * there is no point keeping them open across exec(), though.
869 */
870 fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
871 if (fd_flag < 0)
072db278 872 return error("cannot determine file descriptor flags");
2c039da8
JH
873 fd_flag |= FD_CLOEXEC;
874 if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
072db278 875 return error("cannot set FD_CLOEXEC");
2c039da8 876
9bc879c1 877 /* Verify we recognize this pack file format. */
e6e2bd62 878 if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
072db278 879 return error("file %s is far too short to be a packfile", p->pack_name);
9bc879c1 880 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
072db278 881 return error("file %s is not a GIT packfile", p->pack_name);
9bc879c1 882 if (!pack_version_ok(hdr.hdr_version))
6e1c2344
RJ
883 return error("packfile %s is version %"PRIu32" and not"
884 " supported (try upgrading GIT to a newer version)",
9bc879c1
SP
885 p->pack_name, ntohl(hdr.hdr_version));
886
887 /* Verify the pack matches its index. */
57059091 888 if (p->num_objects != ntohl(hdr.hdr_entries))
6e1c2344
RJ
889 return error("packfile %s claims to have %"PRIu32" objects"
890 " while index indicates %"PRIu32" objects",
57059091
NP
891 p->pack_name, ntohl(hdr.hdr_entries),
892 p->num_objects);
9bc879c1 893 if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
072db278 894 return error("end of packfile %s is unavailable", p->pack_name);
e6e2bd62 895 if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
072db278 896 return error("packfile %s signature is unavailable", p->pack_name);
42873078 897 idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
9bc879c1 898 if (hashcmp(sha1, idx_sha1))
072db278
SP
899 return error("packfile %s does not match index", p->pack_name);
900 return 0;
9bc879c1
SP
901}
902
3cf8b462
SP
903static int open_packed_git(struct packed_git *p)
904{
905 if (!open_packed_git_1(p))
906 return 0;
907 if (p->pack_fd != -1) {
908 close(p->pack_fd);
c7934306 909 pack_open_fds--;
3cf8b462
SP
910 p->pack_fd = -1;
911 }
912 return -1;
913}
914
c4001d92 915static int in_window(struct pack_window *win, off_t offset)
60bb8b14
SP
916{
917 /* We must promise at least 20 bytes (one hash) after the
918 * offset is available from this window, otherwise the offset
919 * is not actually in this window and a different window (which
920 * has that one hash excess) must be used. This is to support
921 * the object header and delta base parsing routines below.
922 */
923 off_t win_off = win->offset;
924 return win_off <= offset
925 && (offset + 20) <= (win_off + win->len);
926}
927
4b25d091 928unsigned char *use_pack(struct packed_git *p,
03e79c88 929 struct pack_window **w_cursor,
c4001d92 930 off_t offset,
ef49a7a0 931 unsigned long *left)
9bc879c1 932{
60bb8b14 933 struct pack_window *win = *w_cursor;
03e79c88 934
a9d98a14 935 /* Since packfiles end in a hash of their content and it's
60bb8b14
SP
936 * pointless to ask for an offset into the middle of that
937 * hash, and the in_window function above wouldn't match
938 * don't allow an offset too close to the end of the file.
939 */
d131b7af
SP
940 if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
941 die("packfile %s cannot be accessed", p->pack_name);
60bb8b14
SP
942 if (offset > (p->pack_size - 20))
943 die("offset beyond end of packfile (truncated pack?)");
944
945 if (!win || !in_window(win, offset)) {
946 if (win)
947 win->inuse_cnt--;
948 for (win = p->windows; win; win = win->next) {
949 if (in_window(win, offset))
950 break;
951 }
952 if (!win) {
78a28df9 953 size_t window_align = packed_git_window_size / 2;
dc49cd76 954 off_t len;
d131b7af
SP
955
956 if (p->pack_fd == -1 && open_packed_git(p))
957 die("packfile %s cannot be accessed", p->pack_name);
958
60bb8b14 959 win = xcalloc(1, sizeof(*win));
78a28df9 960 win->offset = (offset / window_align) * window_align;
dc49cd76
SP
961 len = p->pack_size - win->offset;
962 if (len > packed_git_window_size)
963 len = packed_git_window_size;
964 win->len = (size_t)len;
60bb8b14 965 pack_mapped += win->len;
11daf39b 966 while (packed_git_limit < pack_mapped
7c3ecb32 967 && unuse_one_window(p))
60bb8b14 968 ; /* nothing */
c4712e45 969 win->base = xmmap(NULL, win->len,
60bb8b14
SP
970 PROT_READ, MAP_PRIVATE,
971 p->pack_fd, win->offset);
972 if (win->base == MAP_FAILED)
73b4e4be
SP
973 die("packfile %s cannot be mapped: %s",
974 p->pack_name,
975 strerror(errno));
d131b7af
SP
976 if (!win->offset && win->len == p->pack_size
977 && !p->do_not_close) {
978 close(p->pack_fd);
979 pack_open_fds--;
980 p->pack_fd = -1;
981 }
a53128b6
SP
982 pack_mmap_calls++;
983 pack_open_windows++;
984 if (pack_mapped > peak_pack_mapped)
985 peak_pack_mapped = pack_mapped;
986 if (pack_open_windows > peak_pack_open_windows)
987 peak_pack_open_windows = pack_open_windows;
60bb8b14
SP
988 win->next = p->windows;
989 p->windows = win;
990 }
1f688557 991 }
03e79c88
SP
992 if (win != *w_cursor) {
993 win->last_used = pack_used_ctr++;
994 win->inuse_cnt++;
995 *w_cursor = win;
996 }
60bb8b14 997 offset -= win->offset;
03e79c88 998 if (left)
dc49cd76 999 *left = win->len - xsize_t(offset);
03e79c88 1000 return win->base + offset;
1f688557
JH
1001}
1002
27d69a46
NP
1003static struct packed_git *alloc_packed_git(int extra)
1004{
1005 struct packed_git *p = xmalloc(sizeof(*p) + extra);
1006 memset(p, 0, sizeof(*p));
1007 p->pack_fd = -1;
1008 return p;
1009}
1010
e0500293
JN
1011static void try_to_free_pack_memory(size_t size)
1012{
7c3ecb32 1013 release_pack_memory(size);
e0500293
JN
1014}
1015
42873078 1016struct packed_git *add_packed_git(const char *path, int path_len, int local)
1f688557 1017{
e0500293 1018 static int have_set_try_to_free_routine;
1f688557 1019 struct stat st;
27d69a46 1020 struct packed_git *p = alloc_packed_git(path_len + 2);
1f688557 1021
e0500293
JN
1022 if (!have_set_try_to_free_routine) {
1023 have_set_try_to_free_routine = 1;
1024 set_try_to_free_routine(try_to_free_pack_memory);
1025 }
1026
42873078
NP
1027 /*
1028 * Make sure a corresponding .pack file exists and that
1029 * the index looks sane.
1030 */
1031 path_len -= strlen(".idx");
27d69a46
NP
1032 if (path_len < 1) {
1033 free(p);
1f688557 1034 return NULL;
27d69a46 1035 }
42873078 1036 memcpy(p->pack_name, path, path_len);
8d25931d
BC
1037
1038 strcpy(p->pack_name + path_len, ".keep");
1039 if (!access(p->pack_name, F_OK))
1040 p->pack_keep = 1;
1041
42873078 1042 strcpy(p->pack_name + path_len, ".pack");
d079837e 1043 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
42873078 1044 free(p);
1f688557
JH
1045 return NULL;
1046 }
42873078 1047
1f688557
JH
1048 /* ok, it looks sane as far as we can check without
1049 * actually mapping the pack file.
1050 */
1f688557 1051 p->pack_size = st.st_size;
9d835df2 1052 p->pack_local = local;
b867092f 1053 p->mtime = st.st_mtime;
42873078
NP
1054 if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
1055 hashclr(p->sha1);
1f688557
JH
1056 return p;
1057}
1058
7b64469a 1059struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
c508df5e 1060{
42873078 1061 const char *path = sha1_pack_name(sha1);
27d69a46 1062 struct packed_git *p = alloc_packed_git(strlen(path) + 1);
bf592c50 1063
27d69a46
NP
1064 strcpy(p->pack_name, path);
1065 hashcpy(p->sha1, sha1);
42873078
NP
1066 if (check_packed_git_idx(idx_path, p)) {
1067 free(p);
bf592c50 1068 return NULL;
42873078 1069 }
bf592c50 1070
bf592c50
DB
1071 return p;
1072}
1073
1074void install_packed_git(struct packed_git *pack)
1075{
c7934306
SP
1076 if (pack->pack_fd != -1)
1077 pack_open_fds++;
1078
bf592c50
DB
1079 pack->next = packed_git;
1080 packed_git = pack;
1081}
1082
543c5caa
NTND
1083void (*report_garbage)(const char *desc, const char *path);
1084
1085static void report_helper(const struct string_list *list,
1086 int seen_bits, int first, int last)
1087{
1088 const char *msg;
1089 switch (seen_bits) {
1090 case 0:
1091 msg = "no corresponding .idx nor .pack";
1092 break;
1093 case 1:
1094 msg = "no corresponding .idx";
1095 break;
1096 case 2:
1097 msg = "no corresponding .pack";
1098 break;
1099 default:
1100 return;
1101 }
1102 for (; first < last; first++)
1103 report_garbage(msg, list->items[first].string);
1104}
1105
1106static void report_pack_garbage(struct string_list *list)
1107{
1108 int i, baselen = -1, first = 0, seen_bits = 0;
1109
1110 if (!report_garbage)
1111 return;
1112
1113 sort_string_list(list);
1114
1115 for (i = 0; i < list->nr; i++) {
1116 const char *path = list->items[i].string;
1117 if (baselen != -1 &&
1118 strncmp(path, list->items[first].string, baselen)) {
1119 report_helper(list, seen_bits, first, i);
1120 baselen = -1;
1121 seen_bits = 0;
1122 }
1123 if (baselen == -1) {
1124 const char *dot = strrchr(path, '.');
1125 if (!dot) {
1126 report_garbage("garbage found", path);
1127 continue;
1128 }
1129 baselen = dot - path + 1;
1130 first = i;
1131 }
1132 if (!strcmp(path + baselen, "pack"))
1133 seen_bits |= 1;
1134 else if (!strcmp(path + baselen, "idx"))
1135 seen_bits |= 2;
1136 }
1137 report_helper(list, seen_bits, first, list->nr);
1138}
1139
9d835df2 1140static void prepare_packed_git_one(char *objdir, int local)
1f688557 1141{
9cb18f56
JM
1142 /* Ensure that this buffer is large enough so that we can
1143 append "/pack/" without clobbering the stack even if
1144 strlen(objdir) were PATH_MAX. */
1145 char path[PATH_MAX + 1 + 4 + 1 + 1];
1f688557
JH
1146 int len;
1147 DIR *dir;
1148 struct dirent *de;
543c5caa 1149 struct string_list garbage = STRING_LIST_INIT_DUP;
1f688557
JH
1150
1151 sprintf(path, "%s/pack", objdir);
1152 len = strlen(path);
1153 dir = opendir(path);
b5b16990 1154 if (!dir) {
26125f6b 1155 if (errno != ENOENT)
bd2afde8 1156 error("unable to open object pack directory: %s: %s",
26125f6b 1157 path, strerror(errno));
1f688557 1158 return;
b5b16990 1159 }
1f688557
JH
1160 path[len++] = '/';
1161 while ((de = readdir(dir)) != NULL) {
1162 int namelen = strlen(de->d_name);
1163 struct packed_git *p;
1164
543c5caa
NTND
1165 if (len + namelen + 1 > sizeof(path)) {
1166 if (report_garbage) {
1167 struct strbuf sb = STRBUF_INIT;
1168 strbuf_addf(&sb, "%.*s/%s", len - 1, path, de->d_name);
1169 report_garbage("path too long", sb.buf);
1170 strbuf_release(&sb);
1171 }
1172 continue;
1173 }
1174
1175 if (is_dot_or_dotdot(de->d_name))
9cb18f56
JM
1176 continue;
1177
1f688557 1178 strcpy(path + len, de->d_name);
d90906a9
NTND
1179
1180 if (has_extension(de->d_name, ".idx")) {
1181 /* Don't reopen a pack we already have. */
1182 for (p = packed_git; p; p = p->next) {
1183 if (!memcmp(path, p->pack_name, len + namelen - 4))
1184 break;
1185 }
1186 if (p == NULL &&
1187 /*
1188 * See if it really is a valid .idx file with
1189 * corresponding .pack file that we can map.
1190 */
1191 (p = add_packed_git(path, len + namelen, local)) != NULL)
1192 install_packed_git(p);
86f7780c 1193 }
543c5caa
NTND
1194
1195 if (!report_garbage)
1196 continue;
1197
1198 if (has_extension(de->d_name, ".idx") ||
1199 has_extension(de->d_name, ".pack") ||
1200 has_extension(de->d_name, ".keep"))
1201 string_list_append(&garbage, path);
1202 else
1203 report_garbage("garbage found", path);
1f688557 1204 }
5b35bcd5 1205 closedir(dir);
543c5caa
NTND
1206 report_pack_garbage(&garbage);
1207 string_list_clear(&garbage, 0);
1f688557
JH
1208}
1209
b867092f
JH
1210static int sort_pack(const void *a_, const void *b_)
1211{
1212 struct packed_git *a = *((struct packed_git **)a_);
1213 struct packed_git *b = *((struct packed_git **)b_);
1214 int st;
1215
1216 /*
1217 * Local packs tend to contain objects specific to our
1218 * variant of the project than remote ones. In addition,
1219 * remote ones could be on a network mounted filesystem.
1220 * Favor local ones for these reasons.
1221 */
1222 st = a->pack_local - b->pack_local;
1223 if (st)
1224 return -st;
1225
1226 /*
1227 * Younger packs tend to contain more recent objects,
1228 * and more recent objects tend to get accessed more
1229 * often.
1230 */
1231 if (a->mtime < b->mtime)
1232 return 1;
1233 else if (a->mtime == b->mtime)
1234 return 0;
1235 return -1;
1236}
1237
1238static void rearrange_packed_git(void)
1239{
1240 struct packed_git **ary, *p;
1241 int i, n;
1242
1243 for (n = 0, p = packed_git; p; p = p->next)
1244 n++;
1245 if (n < 2)
1246 return;
1247
1248 /* prepare an array of packed_git for easier sorting */
1249 ary = xcalloc(n, sizeof(struct packed_git *));
1250 for (n = 0, p = packed_git; p; p = p->next)
1251 ary[n++] = p;
1252
1253 qsort(ary, n, sizeof(struct packed_git *), sort_pack);
1254
1255 /* link them back again */
1256 for (i = 0; i < n - 1; i++)
1257 ary[i]->next = ary[i + 1];
1258 ary[n - 1]->next = NULL;
1259 packed_git = ary[0];
1260
1261 free(ary);
1262}
1263
637cdd9d 1264static int prepare_packed_git_run_once = 0;
9a217f2a 1265void prepare_packed_git(void)
1f688557 1266{
d5a63b99 1267 struct alternate_object_database *alt;
1f688557 1268
637cdd9d 1269 if (prepare_packed_git_run_once)
1f688557 1270 return;
9d835df2 1271 prepare_packed_git_one(get_object_directory(), 1);
9a217f2a 1272 prepare_alt_odb();
d5a63b99 1273 for (alt = alt_odb_list; alt; alt = alt->next) {
1494e038 1274 alt->name[-1] = 0;
9d835df2 1275 prepare_packed_git_one(alt->base, 0);
1494e038 1276 alt->name[-1] = '/';
1f688557 1277 }
b867092f 1278 rearrange_packed_git();
637cdd9d
JK
1279 prepare_packed_git_run_once = 1;
1280}
1281
fc04c412 1282void reprepare_packed_git(void)
637cdd9d 1283{
4b480c67 1284 discard_revindex();
637cdd9d
JK
1285 prepare_packed_git_run_once = 0;
1286 prepare_packed_git();
1f688557
JH
1287}
1288
8eca0b47
NP
1289static void mark_bad_packed_object(struct packed_git *p,
1290 const unsigned char *sha1)
1291{
1292 unsigned i;
1293 for (i = 0; i < p->num_bad_objects; i++)
1294 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1295 return;
1296 p->bad_object_sha1 = xrealloc(p->bad_object_sha1, 20 * (p->num_bad_objects + 1));
1297 hashcpy(p->bad_object_sha1 + 20 * p->num_bad_objects, sha1);
1298 p->num_bad_objects++;
1299}
1300
b6c4cecc 1301static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
ac939109
NP
1302{
1303 struct packed_git *p;
1304 unsigned i;
1305
1306 for (p = packed_git; p; p = p->next)
1307 for (i = 0; i < p->num_bad_objects; i++)
1308 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
b6c4cecc
JH
1309 return p;
1310 return NULL;
ac939109
NP
1311}
1312
090ea126
NTND
1313/*
1314 * With an in-core object data in "map", rehash it to make sure the
1315 * object name actually matches "sha1" to detect object corruption.
1316 * With "map" == NULL, try reading the object named with "sha1" using
1317 * the streaming interface and rehash it to do the same.
1318 */
1319int check_sha1_signature(const unsigned char *sha1, void *map,
1320 unsigned long size, const char *type)
0fcfd160
LT
1321{
1322 unsigned char real_sha1[20];
090ea126
NTND
1323 enum object_type obj_type;
1324 struct git_istream *st;
1325 git_SHA_CTX c;
1326 char hdr[32];
1327 int hdrlen;
1328
1329 if (map) {
1330 hash_sha1_file(map, size, type, real_sha1);
1331 return hashcmp(sha1, real_sha1) ? -1 : 0;
1332 }
1333
1334 st = open_istream(sha1, &obj_type, &size, NULL);
1335 if (!st)
1336 return -1;
1337
1338 /* Generate the header */
1339 hdrlen = sprintf(hdr, "%s %lu", typename(obj_type), size) + 1;
1340
1341 /* Sha1.. */
1342 git_SHA1_Init(&c);
1343 git_SHA1_Update(&c, hdr, hdrlen);
1344 for (;;) {
1345 char buf[1024 * 16];
1346 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1347
f54fac53
JK
1348 if (readlen < 0) {
1349 close_istream(st);
1350 return -1;
1351 }
090ea126
NTND
1352 if (!readlen)
1353 break;
1354 git_SHA1_Update(&c, buf, readlen);
1355 }
1356 git_SHA1_Final(real_sha1, &c);
1357 close_istream(st);
a89fccd2 1358 return hashcmp(sha1, real_sha1) ? -1 : 0;
0fcfd160
LT
1359}
1360
f4e51683 1361static int git_open_noatime(const char *name)
44d1c19e
LT
1362{
1363 static int sha1_file_open_flag = O_NOATIME;
44d1c19e 1364
f2e872aa
SP
1365 for (;;) {
1366 int fd = open(name, O_RDONLY | sha1_file_open_flag);
44d1c19e 1367 if (fd >= 0)
f2e872aa
SP
1368 return fd;
1369
f2e872aa
SP
1370 /* Might the failure be due to O_NOATIME? */
1371 if (errno != ENOENT && sha1_file_open_flag) {
44d1c19e 1372 sha1_file_open_flag = 0;
f2e872aa
SP
1373 continue;
1374 }
1375
1376 return -1;
44d1c19e 1377 }
44d1c19e
LT
1378}
1379
052fe5ea
JK
1380static int stat_sha1_file(const unsigned char *sha1, struct stat *st)
1381{
1382 char *name = sha1_file_name(sha1);
1383 struct alternate_object_database *alt;
1384
1385 if (!lstat(name, st))
1386 return 0;
1387
1388 prepare_alt_odb();
1389 errno = ENOENT;
1390 for (alt = alt_odb_list; alt; alt = alt->next) {
1391 name = alt->name;
1392 fill_sha1_path(name, sha1);
1393 if (!lstat(alt->base, st))
1394 return 0;
1395 }
1396
1397 return -1;
1398}
1399
44d1c19e
LT
1400static int open_sha1_file(const unsigned char *sha1)
1401{
1402 int fd;
1403 char *name = sha1_file_name(sha1);
1404 struct alternate_object_database *alt;
1405
f4e51683 1406 fd = git_open_noatime(name);
44d1c19e
LT
1407 if (fd >= 0)
1408 return fd;
1409
1410 prepare_alt_odb();
1411 errno = ENOENT;
1412 for (alt = alt_odb_list; alt; alt = alt->next) {
1413 name = alt->name;
1414 fill_sha1_path(name, sha1);
f4e51683 1415 fd = git_open_noatime(alt->base);
44d1c19e
LT
1416 if (fd >= 0)
1417 return fd;
1418 }
1419 return -1;
1420}
1421
f0270efd 1422void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
0fcfd160 1423{
0fcfd160 1424 void *map;
144bde78 1425 int fd;
ace1534d 1426
44d1c19e
LT
1427 fd = open_sha1_file(sha1);
1428 map = NULL;
1429 if (fd >= 0) {
1430 struct stat st;
0fcfd160 1431
44d1c19e
LT
1432 if (!fstat(fd, &st)) {
1433 *size = xsize_t(st.st_size);
33e42de0
MM
1434 if (!*size) {
1435 /* mmap() is forbidden on empty files */
1436 error("object file %s is empty", sha1_file_name(sha1));
1437 return NULL;
1438 }
44d1c19e 1439 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
144bde78 1440 }
44d1c19e 1441 close(fd);
0fcfd160 1442 }
0fcfd160
LT
1443 return map;
1444}
1445
cc5c54e7
JH
1446/*
1447 * There used to be a second loose object header format which
1448 * was meant to mimic the in-pack format, allowing for direct
1449 * copy of the object data. This format turned up not to be
1450 * really worth it and we no longer write loose objects in that
1451 * format.
1452 */
1453static int experimental_loose_object(unsigned char *map)
bb6b8e4f
JH
1454{
1455 unsigned int word;
1456
1457 /*
7f684a2a
RT
1458 * We must determine if the buffer contains the standard
1459 * zlib-deflated stream or the experimental format based
1460 * on the in-pack object format. Compare the header byte
1461 * for each format:
1462 *
1463 * RFC1950 zlib w/ deflate : 0www1000 : 0 <= www <= 7
1464 * Experimental pack-based : Stttssss : ttt = 1,2,3,4
1465 *
1466 * If bit 7 is clear and bits 0-3 equal 8, the buffer MUST be
1467 * in standard loose-object format, UNLESS it is a Git-pack
1468 * format object *exactly* 8 bytes in size when inflated.
1469 *
1470 * However, RFC1950 also specifies that the 1st 16-bit word
1471 * must be divisible by 31 - this checksum tells us our buffer
1472 * is in the standard format, giving a false positive only if
1473 * the 1st word of the Git-pack format object happens to be
1474 * divisible by 31, ie:
1475 * ((byte0 * 256) + byte1) % 31 = 0
1476 * => 0ttt10000www1000 % 31 = 0
1477 *
1478 * As it happens, this case can only arise for www=3 & ttt=1
1479 * - ie, a Commit object, which would have to be 8 bytes in
1480 * size. As no Commit can be that small, we find that the
1481 * combination of these two criteria (bitmask & checksum)
1482 * can always correctly determine the buffer format.
bb6b8e4f
JH
1483 */
1484 word = (map[0] << 8) + map[1];
7f684a2a 1485 if ((map[0] & 0x8F) == 0x08 && !(word % 31))
bb6b8e4f 1486 return 0;
cc5c54e7
JH
1487 else
1488 return 1;
bb6b8e4f
JH
1489}
1490
09ded04b
NP
1491unsigned long unpack_object_header_buffer(const unsigned char *buf,
1492 unsigned long len, enum object_type *type, unsigned long *sizep)
c4483576 1493{
ad1ed5ee 1494 unsigned shift;
48fb7deb 1495 unsigned long size, c;
ad1ed5ee
JH
1496 unsigned long used = 0;
1497
1498 c = buf[used++];
1499 *type = (c >> 4) & 7;
1500 size = c & 15;
1501 shift = 4;
1502 while (c & 0x80) {
f630cfda 1503 if (len <= used || bitsizeof(long) <= shift) {
09ded04b 1504 error("bad object header");
ea4f9685
JH
1505 size = used = 0;
1506 break;
09ded04b 1507 }
ad1ed5ee
JH
1508 c = buf[used++];
1509 size += (c & 0x7f) << shift;
1510 shift += 7;
1511 }
1512 *sizep = size;
1513 return used;
1514}
1515
eb4f4076 1516int unpack_sha1_header(git_zstream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
ad1ed5ee
JH
1517{
1518 unsigned long size, used;
1519 static const char valid_loose_object_type[8] = {
1520 0, /* OBJ_EXT */
1521 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1522 0, /* "delta" and others are invalid in a loose object */
93821bd9 1523 };
ad1ed5ee 1524 enum object_type type;
93821bd9 1525
c4483576
LT
1526 /* Get the data stream */
1527 memset(stream, 0, sizeof(*stream));
1528 stream->next_in = map;
1529 stream->avail_in = mapsize;
1530 stream->next_out = buffer;
93821bd9
LT
1531 stream->avail_out = bufsiz;
1532
cc5c54e7
JH
1533 if (experimental_loose_object(map)) {
1534 /*
1535 * The old experimental format we no longer produce;
1536 * we can still read it.
1537 */
1538 used = unpack_object_header_buffer(map, mapsize, &type, &size);
1539 if (!used || !valid_loose_object_type[type])
1540 return -1;
1541 map += used;
1542 mapsize -= used;
726f852b 1543
cc5c54e7
JH
1544 /* Set up the stream for the rest.. */
1545 stream->next_in = map;
1546 stream->avail_in = mapsize;
1547 git_inflate_init(stream);
93821bd9 1548
cc5c54e7
JH
1549 /* And generate the fake traditional header */
1550 stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1551 typename(type), size);
1552 return 0;
1553 }
39c68542 1554 git_inflate_init(stream);
cc5c54e7 1555 return git_inflate(stream, 0);
c4483576
LT
1556}
1557
ef49a7a0 1558static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
5180cacc
LT
1559{
1560 int bytes = strlen(buffer) + 1;
3aee68aa 1561 unsigned char *buf = xmallocz(size);
93821bd9 1562 unsigned long n;
7efbff75 1563 int status = Z_OK;
5180cacc 1564
93821bd9
LT
1565 n = stream->total_out - bytes;
1566 if (n > size)
1567 n = size;
1568 memcpy(buf, (char *) buffer + bytes, n);
1569 bytes = n;
456cdf6e
LT
1570 if (bytes <= size) {
1571 /*
1572 * The above condition must be (bytes <= size), not
1573 * (bytes < size). In other words, even though we
ccf5ace0 1574 * expect no more output and set avail_out to zero,
456cdf6e
LT
1575 * the input zlib stream may have bytes that express
1576 * "this concludes the stream", and we *do* want to
1577 * eat that input.
1578 *
1579 * Otherwise we would not be able to test that we
1580 * consumed all the input to reach the expected size;
1581 * we also want to check that zlib tells us that all
1582 * went well with status == Z_STREAM_END at the end.
1583 */
5180cacc
LT
1584 stream->next_out = buf + bytes;
1585 stream->avail_out = size - bytes;
7efbff75 1586 while (status == Z_OK)
39c68542 1587 status = git_inflate(stream, Z_FINISH);
5180cacc 1588 }
456cdf6e 1589 if (status == Z_STREAM_END && !stream->avail_in) {
39c68542 1590 git_inflate_end(stream);
7efbff75
JH
1591 return buf;
1592 }
1593
1594 if (status < 0)
1595 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1596 else if (stream->avail_in)
1597 error("garbage at end of loose object '%s'",
1598 sha1_to_hex(sha1));
1599 free(buf);
1600 return NULL;
5180cacc
LT
1601}
1602
1603/*
1604 * We used to just use "sscanf()", but that's actually way
1605 * too permissive for what we want to check. So do an anal
1606 * object header parse by hand.
1607 */
f0270efd 1608int parse_sha1_header(const char *hdr, unsigned long *sizep)
5180cacc 1609{
21666f1a 1610 char type[10];
5180cacc
LT
1611 int i;
1612 unsigned long size;
1613
1614 /*
a6080a0a 1615 * The type can be at most ten bytes (including the
5180cacc 1616 * terminating '\0' that we add), and is followed by
21666f1a 1617 * a space.
5180cacc 1618 */
21666f1a 1619 i = 0;
5180cacc
LT
1620 for (;;) {
1621 char c = *hdr++;
1622 if (c == ' ')
1623 break;
21666f1a
NP
1624 type[i++] = c;
1625 if (i >= sizeof(type))
5180cacc 1626 return -1;
5180cacc 1627 }
21666f1a 1628 type[i] = 0;
5180cacc
LT
1629
1630 /*
1631 * The length must follow immediately, and be in canonical
1632 * decimal format (ie "010" is not valid).
1633 */
1634 size = *hdr++ - '0';
1635 if (size > 9)
1636 return -1;
1637 if (size) {
1638 for (;;) {
1639 unsigned long c = *hdr - '0';
1640 if (c > 9)
1641 break;
1642 hdr++;
1643 size = size * 10 + c;
1644 }
1645 }
1646 *sizep = size;
1647
1648 /*
1649 * The length must be followed by a zero byte
1650 */
21666f1a 1651 return *hdr ? -1 : type_from_string(type);
5180cacc
LT
1652}
1653
7efbff75 1654static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
0fcfd160 1655{
5180cacc 1656 int ret;
ef49a7a0 1657 git_zstream stream;
5180cacc 1658 char hdr[8192];
0fcfd160 1659
5180cacc 1660 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
21666f1a 1661 if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
0fcfd160
LT
1662 return NULL;
1663
7efbff75 1664 return unpack_sha1_rest(&stream, hdr, *size, sha1);
0fcfd160
LT
1665}
1666
54dab52a
NP
1667unsigned long get_size_from_delta(struct packed_git *p,
1668 struct pack_window **w_curs,
1669 off_t curpos)
1670{
1671 const unsigned char *data;
1672 unsigned char delta_head[20], *in;
ef49a7a0 1673 git_zstream stream;
54dab52a
NP
1674 int st;
1675
1676 memset(&stream, 0, sizeof(stream));
1677 stream.next_out = delta_head;
1678 stream.avail_out = sizeof(delta_head);
1679
39c68542 1680 git_inflate_init(&stream);
54dab52a
NP
1681 do {
1682 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1683 stream.next_in = in;
39c68542 1684 st = git_inflate(&stream, Z_FINISH);
54dab52a
NP
1685 curpos += stream.next_in - in;
1686 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1687 stream.total_out < sizeof(delta_head));
39c68542 1688 git_inflate_end(&stream);
3d77d877
NP
1689 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1690 error("delta data unpack-initial failed");
1691 return 0;
1692 }
54dab52a
NP
1693
1694 /* Examine the initial part of the delta to figure out
1695 * the result size.
1696 */
1697 data = delta_head;
1698
1699 /* ignore base size */
1700 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1701
1702 /* Read the result size */
1703 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1704}
1705
c4001d92 1706static off_t get_delta_base(struct packed_git *p,
03e79c88 1707 struct pack_window **w_curs,
c4001d92 1708 off_t *curpos,
21666f1a 1709 enum object_type type,
c4001d92 1710 off_t delta_obj_offset)
eb32d236 1711{
2b87c45b 1712 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
c4001d92 1713 off_t base_offset;
eb32d236 1714
8d8a4ea5
SP
1715 /* use_pack() assured us we have [base_info, base_info + 20)
1716 * as a range that we can look at without walking off the
1717 * end of the mapped window. Its actually the hash size
1718 * that is assured. An OFS_DELTA longer than the hash size
1719 * is stupid, as then a REF_DELTA would be smaller to store.
1720 */
21666f1a 1721 if (type == OBJ_OFS_DELTA) {
eb32d236
NP
1722 unsigned used = 0;
1723 unsigned char c = base_info[used++];
1724 base_offset = c & 127;
1725 while (c & 128) {
1726 base_offset += 1;
8723f216 1727 if (!base_offset || MSB(base_offset, 7))
8eca0b47 1728 return 0; /* overflow */
eb32d236
NP
1729 c = base_info[used++];
1730 base_offset = (base_offset << 7) + (c & 127);
1731 }
1732 base_offset = delta_obj_offset - base_offset;
d8f32556 1733 if (base_offset <= 0 || base_offset >= delta_obj_offset)
8eca0b47 1734 return 0; /* out of bound */
2b87c45b 1735 *curpos += used;
21666f1a 1736 } else if (type == OBJ_REF_DELTA) {
eb32d236
NP
1737 /* The base entry _must_ be in the same pack */
1738 base_offset = find_pack_entry_one(base_info, p);
2b87c45b 1739 *curpos += 20;
eb32d236
NP
1740 } else
1741 die("I am totally screwed");
2b87c45b 1742 return base_offset;
eb32d236
NP
1743}
1744
f8c8abc5
JH
1745int unpack_object_header(struct packed_git *p,
1746 struct pack_window **w_curs,
1747 off_t *curpos,
1748 unsigned long *sizep)
a733cb60 1749{
03e79c88 1750 unsigned char *base;
ef49a7a0 1751 unsigned long left;
ad1ed5ee 1752 unsigned long used;
2b87c45b 1753 enum object_type type;
a733cb60 1754
8d8a4ea5 1755 /* use_pack() assures us we have [base, base + 20) available
0353a0c4 1756 * as a range that we can look at. (Its actually the hash
3dff5379 1757 * size that is assured.) With our object header encoding
8d8a4ea5
SP
1758 * the maximum deflated object size is 2^137, which is just
1759 * insane, so we know won't exceed what we have been given.
1760 */
2b87c45b 1761 base = use_pack(p, w_curs, *curpos, &left);
09ded04b
NP
1762 used = unpack_object_header_buffer(base, left, &type, sizep);
1763 if (!used) {
1764 type = OBJ_BAD;
1765 } else
1766 *curpos += used;
ad1ed5ee 1767
2b87c45b 1768 return type;
a733cb60
LT
1769}
1770
790d96c0
TR
1771static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
1772{
1773 int type;
1774 struct revindex_entry *revidx;
1775 const unsigned char *sha1;
1776 revidx = find_pack_revindex(p, obj_offset);
1777 if (!revidx)
1778 return OBJ_BAD;
1779 sha1 = nth_packed_object_sha1(p, revidx->nr);
1780 mark_bad_packed_object(p, sha1);
1781 type = sha1_object_info(sha1, NULL);
1782 if (type <= OBJ_NONE)
1783 return OBJ_BAD;
1784 return type;
1785}
1786
790d96c0
TR
1787#define POI_STACK_PREALLOC 64
1788
90191d37
JK
1789static enum object_type packed_to_object_type(struct packed_git *p,
1790 off_t obj_offset,
1791 enum object_type type,
1792 struct pack_window **w_curs,
1793 off_t curpos)
1f688557 1794{
790d96c0
TR
1795 off_t small_poi_stack[POI_STACK_PREALLOC];
1796 off_t *poi_stack = small_poi_stack;
1797 int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
5db47c2b 1798
790d96c0
TR
1799 while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1800 off_t base_offset;
90191d37 1801 unsigned long size;
790d96c0
TR
1802 /* Push the object we're going to leave behind */
1803 if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1804 poi_stack_alloc = alloc_nr(poi_stack_nr);
1805 poi_stack = xmalloc(sizeof(off_t)*poi_stack_alloc);
1806 memcpy(poi_stack, small_poi_stack, sizeof(off_t)*poi_stack_nr);
1807 } else {
1808 ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1809 }
1810 poi_stack[poi_stack_nr++] = obj_offset;
1811 /* If parsing the base offset fails, just unwind */
90191d37 1812 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
790d96c0
TR
1813 if (!base_offset)
1814 goto unwind;
1815 curpos = obj_offset = base_offset;
90191d37 1816 type = unpack_object_header(p, w_curs, &curpos, &size);
790d96c0
TR
1817 if (type <= OBJ_NONE) {
1818 /* If getting the base itself fails, we first
1819 * retry the base, otherwise unwind */
1820 type = retry_bad_packed_offset(p, base_offset);
1821 if (type > OBJ_NONE)
1822 goto out;
1823 goto unwind;
1824 }
1825 }
1826
21666f1a 1827 switch (type) {
790d96c0 1828 case OBJ_BAD:
a733cb60 1829 case OBJ_COMMIT:
a733cb60 1830 case OBJ_TREE:
a733cb60 1831 case OBJ_BLOB:
a733cb60 1832 case OBJ_TAG:
a69d0943 1833 break;
1f688557 1834 default:
3d77d877
NP
1835 error("unknown object type %i at offset %"PRIuMAX" in %s",
1836 type, (uintmax_t)obj_offset, p->pack_name);
1837 type = OBJ_BAD;
1f688557 1838 }
790d96c0
TR
1839
1840out:
1841 if (poi_stack != small_poi_stack)
1842 free(poi_stack);
21666f1a 1843 return type;
790d96c0
TR
1844
1845unwind:
1846 while (poi_stack_nr) {
1847 obj_offset = poi_stack[--poi_stack_nr];
1848 type = retry_bad_packed_offset(p, obj_offset);
1849 if (type > OBJ_NONE)
1850 goto out;
1851 }
1852 type = OBJ_BAD;
1853 goto out;
1f688557
JH
1854}
1855
90191d37 1856static int packed_object_info(struct packed_git *p, off_t obj_offset,
23c339c0 1857 struct object_info *oi)
90191d37
JK
1858{
1859 struct pack_window *w_curs = NULL;
1860 unsigned long size;
1861 off_t curpos = obj_offset;
1862 enum object_type type;
1863
412916ee
JK
1864 /*
1865 * We always get the representation type, but only convert it to
1866 * a "real" type later if the caller is interested.
1867 */
90191d37
JK
1868 type = unpack_object_header(p, &w_curs, &curpos, &size);
1869
23c339c0 1870 if (oi->sizep) {
90191d37
JK
1871 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1872 off_t tmp_pos = curpos;
1873 off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1874 type, obj_offset);
1875 if (!base_offset) {
1876 type = OBJ_BAD;
1877 goto out;
1878 }
23c339c0
JK
1879 *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
1880 if (*oi->sizep == 0) {
90191d37
JK
1881 type = OBJ_BAD;
1882 goto out;
1883 }
1884 } else {
23c339c0 1885 *oi->sizep = size;
90191d37
JK
1886 }
1887 }
1888
23c339c0 1889 if (oi->disk_sizep) {
90191d37 1890 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
23c339c0 1891 *oi->disk_sizep = revidx[1].offset - obj_offset;
90191d37
JK
1892 }
1893
23c339c0
JK
1894 if (oi->typep) {
1895 *oi->typep = packed_to_object_type(p, obj_offset, type, &w_curs, curpos);
1896 if (*oi->typep < 0) {
412916ee
JK
1897 type = OBJ_BAD;
1898 goto out;
1899 }
1900 }
90191d37
JK
1901
1902out:
1903 unuse_pack(&w_curs);
1904 return type;
1905}
1906
eb950c19 1907static void *unpack_compressed_entry(struct packed_git *p,
03e79c88 1908 struct pack_window **w_curs,
c4001d92 1909 off_t curpos,
eb950c19 1910 unsigned long size)
de530aaa
SP
1911{
1912 int st;
ef49a7a0 1913 git_zstream stream;
079afb18 1914 unsigned char *buffer, *in;
de530aaa 1915
4ab07e4d 1916 buffer = xmallocz(size);
de530aaa 1917 memset(&stream, 0, sizeof(stream));
de530aaa 1918 stream.next_out = buffer;
39eea7bd 1919 stream.avail_out = size + 1;
de530aaa 1920
39c68542 1921 git_inflate_init(&stream);
079afb18 1922 do {
2b87c45b 1923 in = use_pack(p, w_curs, curpos, &stream.avail_in);
079afb18 1924 stream.next_in = in;
39c68542 1925 st = git_inflate(&stream, Z_FINISH);
39eea7bd
JH
1926 if (!stream.avail_out)
1927 break; /* the payload is larger than it should be */
2b87c45b 1928 curpos += stream.next_in - in;
079afb18 1929 } while (st == Z_OK || st == Z_BUF_ERROR);
39c68542 1930 git_inflate_end(&stream);
de530aaa
SP
1931 if ((st != Z_STREAM_END) || stream.total_out != size) {
1932 free(buffer);
1933 return NULL;
1934 }
1935
1936 return buffer;
1937}
1938
e5e01619
LT
1939#define MAX_DELTA_CACHE (256)
1940
18bdec11 1941static size_t delta_base_cached;
5e08ecbf
NP
1942
1943static struct delta_base_cache_lru_list {
1944 struct delta_base_cache_lru_list *prev;
1945 struct delta_base_cache_lru_list *next;
1946} delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1947
e5e01619 1948static struct delta_base_cache_entry {
5e08ecbf
NP
1949 struct delta_base_cache_lru_list lru;
1950 void *data;
e5e01619
LT
1951 struct packed_git *p;
1952 off_t base_offset;
1953 unsigned long size;
e5e01619
LT
1954 enum object_type type;
1955} delta_base_cache[MAX_DELTA_CACHE];
1956
1957static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1958{
1959 unsigned long hash;
1960
1961 hash = (unsigned long)p + (unsigned long)base_offset;
1962 hash += (hash >> 8) + (hash >> 16);
3358004a 1963 return hash % MAX_DELTA_CACHE;
e5e01619
LT
1964}
1965
84dd81c1
TR
1966static struct delta_base_cache_entry *
1967get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
5266d369
JH
1968{
1969 unsigned long hash = pack_entry_hash(p, base_offset);
84dd81c1
TR
1970 return delta_base_cache + hash;
1971}
1972
1973static int eq_delta_base_cache_entry(struct delta_base_cache_entry *ent,
1974 struct packed_git *p, off_t base_offset)
1975{
5266d369
JH
1976 return (ent->data && ent->p == p && ent->base_offset == base_offset);
1977}
1978
84dd81c1
TR
1979static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
1980{
1981 struct delta_base_cache_entry *ent;
1982 ent = get_delta_base_cache_entry(p, base_offset);
1983 return eq_delta_base_cache_entry(ent, p, base_offset);
1984}
1985
1986static void clear_delta_base_cache_entry(struct delta_base_cache_entry *ent)
1987{
1988 ent->data = NULL;
1989 ent->lru.next->prev = ent->lru.prev;
1990 ent->lru.prev->next = ent->lru.next;
1991 delta_base_cached -= ent->size;
1992}
1993
62f255ad 1994static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
a0cba108 1995 unsigned long *base_size, enum object_type *type, int keep_cache)
62f255ad 1996{
84dd81c1 1997 struct delta_base_cache_entry *ent;
e5e01619 1998 void *ret;
e5e01619 1999
84dd81c1
TR
2000 ent = get_delta_base_cache_entry(p, base_offset);
2001
2002 if (!eq_delta_base_cache_entry(ent, p, base_offset))
749bc58c 2003 return unpack_entry(p, base_offset, type, base_size);
e5e01619 2004
84dd81c1
TR
2005 ret = ent->data;
2006
2007 if (!keep_cache)
2008 clear_delta_base_cache_entry(ent);
2009 else
182af834 2010 ret = xmemdupz(ent->data, ent->size);
e5e01619
LT
2011 *type = ent->type;
2012 *base_size = ent->size;
2013 return ret;
62f255ad
LT
2014}
2015
18bdec11
SP
2016static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
2017{
2018 if (ent->data) {
2019 free(ent->data);
2020 ent->data = NULL;
5e08ecbf
NP
2021 ent->lru.next->prev = ent->lru.prev;
2022 ent->lru.prev->next = ent->lru.next;
18bdec11
SP
2023 delta_base_cached -= ent->size;
2024 }
2025}
2026
3d20c636
SP
2027void clear_delta_base_cache(void)
2028{
2029 unsigned long p;
2030 for (p = 0; p < MAX_DELTA_CACHE; p++)
2031 release_delta_base_cache(&delta_base_cache[p]);
2032}
2033
62f255ad
LT
2034static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
2035 void *base, unsigned long base_size, enum object_type type)
2036{
5e08ecbf 2037 unsigned long hash = pack_entry_hash(p, base_offset);
e5e01619 2038 struct delta_base_cache_entry *ent = delta_base_cache + hash;
5e08ecbf 2039 struct delta_base_cache_lru_list *lru;
e5e01619 2040
18bdec11
SP
2041 release_delta_base_cache(ent);
2042 delta_base_cached += base_size;
5e08ecbf
NP
2043
2044 for (lru = delta_base_cache_lru.next;
2045 delta_base_cached > delta_base_cache_limit
2046 && lru != &delta_base_cache_lru;
2047 lru = lru->next) {
2048 struct delta_base_cache_entry *f = (void *)lru;
18bdec11
SP
2049 if (f->type == OBJ_BLOB)
2050 release_delta_base_cache(f);
2051 }
5e08ecbf
NP
2052 for (lru = delta_base_cache_lru.next;
2053 delta_base_cached > delta_base_cache_limit
2054 && lru != &delta_base_cache_lru;
2055 lru = lru->next) {
2056 struct delta_base_cache_entry *f = (void *)lru;
2057 release_delta_base_cache(f);
2058 }
18bdec11 2059
e5e01619
LT
2060 ent->p = p;
2061 ent->base_offset = base_offset;
2062 ent->type = type;
2063 ent->data = base;
2064 ent->size = base_size;
5e08ecbf
NP
2065 ent->lru.next = &delta_base_cache_lru;
2066 ent->lru.prev = delta_base_cache_lru.prev;
2067 delta_base_cache_lru.prev->next = &ent->lru;
2068 delta_base_cache_lru.prev = &ent->lru;
62f255ad
LT
2069}
2070
c2c5b270
CC
2071static void *read_object(const unsigned char *sha1, enum object_type *type,
2072 unsigned long *size);
2073
5f44324d
JH
2074static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
2075{
2076 static FILE *log_file;
2077
b12ca963
NTND
2078 if (!log_pack_access)
2079 log_pack_access = getenv("GIT_TRACE_PACK_ACCESS");
2080 if (!log_pack_access)
2081 log_pack_access = no_log_pack_access;
2082 if (log_pack_access == no_log_pack_access)
2083 return;
2084
5f44324d
JH
2085 if (!log_file) {
2086 log_file = fopen(log_pack_access, "w");
2087 if (!log_file) {
2088 error("cannot open pack access log '%s' for writing: %s",
2089 log_pack_access, strerror(errno));
b12ca963 2090 log_pack_access = no_log_pack_access;
5f44324d
JH
2091 return;
2092 }
2093 }
2094 fprintf(log_file, "%s %"PRIuMAX"\n",
2095 p->pack_name, (uintmax_t)obj_offset);
2096 fflush(log_file);
2097}
2098
0e8189e2
NP
2099int do_check_packed_object_crc;
2100
abe601bb
TR
2101#define UNPACK_ENTRY_STACK_PREALLOC 64
2102struct unpack_entry_stack_ent {
2103 off_t obj_offset;
2104 off_t curpos;
2105 unsigned long size;
2106};
2107
c4001d92 2108void *unpack_entry(struct packed_git *p, off_t obj_offset,
abe601bb 2109 enum object_type *final_type, unsigned long *final_size)
1f688557 2110{
03e79c88 2111 struct pack_window *w_curs = NULL;
c4001d92 2112 off_t curpos = obj_offset;
abe601bb
TR
2113 void *data = NULL;
2114 unsigned long size;
2115 enum object_type type;
2116 struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
2117 struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
2118 int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
2119 int base_from_cache = 0;
1f688557 2120
b12ca963 2121 if (log_pack_access != no_log_pack_access)
5f44324d
JH
2122 write_pack_access_log(p, obj_offset);
2123
abe601bb
TR
2124 /* PHASE 1: drill down to the innermost base object */
2125 for (;;) {
2126 off_t base_offset;
2127 int i;
2128 struct delta_base_cache_entry *ent;
2129
77965f8b
NTND
2130 ent = get_delta_base_cache_entry(p, curpos);
2131 if (eq_delta_base_cache_entry(ent, p, curpos)) {
2132 type = ent->type;
2133 data = ent->data;
2134 size = ent->size;
2135 clear_delta_base_cache_entry(ent);
2136 base_from_cache = 1;
2137 break;
2138 }
2139
abe601bb
TR
2140 if (do_check_packed_object_crc && p->index_version > 1) {
2141 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
2142 unsigned long len = revidx[1].offset - obj_offset;
2143 if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
2144 const unsigned char *sha1 =
2145 nth_packed_object_sha1(p, revidx->nr);
2146 error("bad packed object CRC for %s",
2147 sha1_to_hex(sha1));
2148 mark_bad_packed_object(p, sha1);
2149 unuse_pack(&w_curs);
2150 return NULL;
2151 }
2152 }
2153
abe601bb
TR
2154 type = unpack_object_header(p, &w_curs, &curpos, &size);
2155 if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
2156 break;
2157
2158 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
2159 if (!base_offset) {
2160 error("failed to validate delta base reference "
2161 "at offset %"PRIuMAX" from %s",
2162 (uintmax_t)curpos, p->pack_name);
2163 /* bail to phase 2, in hopes of recovery */
2164 data = NULL;
2165 break;
2166 }
2167
2168 /* push object, proceed to base */
2169 if (delta_stack_nr >= delta_stack_alloc
2170 && delta_stack == small_delta_stack) {
2171 delta_stack_alloc = alloc_nr(delta_stack_nr);
2172 delta_stack = xmalloc(sizeof(*delta_stack)*delta_stack_alloc);
2173 memcpy(delta_stack, small_delta_stack,
2174 sizeof(*delta_stack)*delta_stack_nr);
2175 } else {
2176 ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
2177 }
2178 i = delta_stack_nr++;
2179 delta_stack[i].obj_offset = obj_offset;
2180 delta_stack[i].curpos = curpos;
2181 delta_stack[i].size = size;
2182
2183 curpos = obj_offset = base_offset;
0e8189e2
NP
2184 }
2185
abe601bb
TR
2186 /* PHASE 2: handle the base */
2187 switch (type) {
eb32d236
NP
2188 case OBJ_OFS_DELTA:
2189 case OBJ_REF_DELTA:
abe601bb
TR
2190 if (data)
2191 die("BUG in unpack_entry: left loop at a valid delta");
4d703a1a 2192 break;
a733cb60 2193 case OBJ_COMMIT:
a733cb60 2194 case OBJ_TREE:
a733cb60 2195 case OBJ_BLOB:
a733cb60 2196 case OBJ_TAG:
abe601bb
TR
2197 if (!base_from_cache)
2198 data = unpack_compressed_entry(p, &w_curs, curpos, size);
4d703a1a 2199 break;
1f688557 2200 default:
8eca0b47
NP
2201 data = NULL;
2202 error("unknown object type %i at offset %"PRIuMAX" in %s",
abe601bb
TR
2203 type, (uintmax_t)obj_offset, p->pack_name);
2204 }
2205
2206 /* PHASE 3: apply deltas in order */
2207
2208 /* invariants:
2209 * 'data' holds the base data, or NULL if there was corruption
2210 */
2211 while (delta_stack_nr) {
2212 void *delta_data;
2213 void *base = data;
2214 unsigned long delta_size, base_size = size;
2215 int i;
2216
2217 data = NULL;
2218
2219 if (base)
2220 add_delta_base_cache(p, obj_offset, base, base_size, type);
2221
2222 if (!base) {
2223 /*
2224 * We're probably in deep shit, but let's try to fetch
2225 * the required base anyway from another pack or loose.
2226 * This is costly but should happen only in the presence
2227 * of a corrupted pack, and is better than failing outright.
2228 */
2229 struct revindex_entry *revidx;
2230 const unsigned char *base_sha1;
2231 revidx = find_pack_revindex(p, obj_offset);
2232 if (revidx) {
2233 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
2234 error("failed to read delta base object %s"
2235 " at offset %"PRIuMAX" from %s",
2236 sha1_to_hex(base_sha1), (uintmax_t)obj_offset,
2237 p->pack_name);
2238 mark_bad_packed_object(p, base_sha1);
2239 base = read_object(base_sha1, &type, &base_size);
2240 }
2241 }
2242
2243 i = --delta_stack_nr;
2244 obj_offset = delta_stack[i].obj_offset;
2245 curpos = delta_stack[i].curpos;
2246 delta_size = delta_stack[i].size;
2247
2248 if (!base)
2249 continue;
2250
2251 delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
2252
2253 if (!delta_data) {
2254 error("failed to unpack compressed delta "
2255 "at offset %"PRIuMAX" from %s",
2256 (uintmax_t)curpos, p->pack_name);
abe601bb
TR
2257 data = NULL;
2258 continue;
2259 }
2260
2261 data = patch_delta(base, base_size,
2262 delta_data, delta_size,
2263 &size);
1ee886c1
JK
2264
2265 /*
2266 * We could not apply the delta; warn the user, but keep going.
2267 * Our failure will be noticed either in the next iteration of
2268 * the loop, or if this is the final delta, in the caller when
2269 * we return NULL. Those code paths will take care of making
2270 * a more explicit warning and retrying with another copy of
2271 * the object.
2272 */
abe601bb 2273 if (!data)
1ee886c1 2274 error("failed to apply delta");
abe601bb 2275
4b8f772c 2276 free(delta_data);
1f688557 2277 }
abe601bb
TR
2278
2279 *final_type = type;
2280 *final_size = size;
2281
03e79c88 2282 unuse_pack(&w_curs);
21666f1a 2283 return data;
1f688557
JH
2284}
2285
d079837e 2286const unsigned char *nth_packed_object_sha1(struct packed_git *p,
d72308e0 2287 uint32_t n)
9a217f2a 2288{
42873078 2289 const unsigned char *index = p->index_data;
d079837e
SP
2290 if (!index) {
2291 if (open_pack_index(p))
2292 return NULL;
2293 index = p->index_data;
2294 }
57059091 2295 if (n >= p->num_objects)
d72308e0 2296 return NULL;
74e34e1f
NP
2297 index += 4 * 256;
2298 if (p->index_version == 1) {
2299 return index + 24 * n + 4;
2300 } else {
2301 index += 8;
2302 return index + 20 * n;
2303 }
2304}
2305
99093238 2306off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
74e34e1f
NP
2307{
2308 const unsigned char *index = p->index_data;
2309 index += 4 * 256;
2310 if (p->index_version == 1) {
2311 return ntohl(*((uint32_t *)(index + 24 * n)));
2312 } else {
2313 uint32_t off;
2314 index += 8 + p->num_objects * (20 + 4);
2315 off = ntohl(*((uint32_t *)(index + 4 * n)));
2316 if (!(off & 0x80000000))
2317 return off;
2318 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
2319 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
2320 ntohl(*((uint32_t *)(index + 4)));
2321 }
9a217f2a
JH
2322}
2323
c4001d92 2324off_t find_pack_entry_one(const unsigned char *sha1,
43057304 2325 struct packed_git *p)
1f688557 2326{
42873078 2327 const uint32_t *level1_ofs = p->index_data;
42873078 2328 const unsigned char *index = p->index_data;
628522ec
JH
2329 unsigned hi, lo, stride;
2330 static int use_lookup = -1;
2331 static int debug_lookup = -1;
2332
2333 if (debug_lookup < 0)
2334 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
42873078 2335
d079837e
SP
2336 if (!index) {
2337 if (open_pack_index(p))
2338 return 0;
2339 level1_ofs = p->index_data;
2340 index = p->index_data;
2341 }
74e34e1f
NP
2342 if (p->index_version > 1) {
2343 level1_ofs += 2;
2344 index += 8;
2345 }
42873078 2346 index += 4 * 256;
74e34e1f
NP
2347 hi = ntohl(level1_ofs[*sha1]);
2348 lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
628522ec
JH
2349 if (p->index_version > 1) {
2350 stride = 20;
2351 } else {
2352 stride = 24;
2353 index += 4;
2354 }
2355
2356 if (debug_lookup)
6e1c2344 2357 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
628522ec
JH
2358 sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
2359
2360 if (use_lookup < 0)
2361 use_lookup = !!getenv("GIT_USE_LOOKUP");
2362 if (use_lookup) {
2363 int pos = sha1_entry_pos(index, stride, 0,
2364 lo, hi, p->num_objects, sha1);
2365 if (pos < 0)
2366 return 0;
2367 return nth_packed_object_offset(p, pos);
2368 }
1f688557
JH
2369
2370 do {
74e34e1f 2371 unsigned mi = (lo + hi) / 2;
628522ec
JH
2372 int cmp = hashcmp(index + mi * stride, sha1);
2373
2374 if (debug_lookup)
2375 printf("lo %u hi %u rg %u mi %u\n",
2376 lo, hi, hi - lo, mi);
43057304 2377 if (!cmp)
74e34e1f 2378 return nth_packed_object_offset(p, mi);
1f688557
JH
2379 if (cmp > 0)
2380 hi = mi;
2381 else
2382 lo = mi+1;
2383 } while (lo < hi);
2384 return 0;
2385}
2386
4c080182 2387int is_pack_valid(struct packed_git *p)
d131b7af
SP
2388{
2389 /* An already open pack is known to be valid. */
2390 if (p->pack_fd != -1)
2391 return 1;
2392
2393 /* If the pack has one window completely covering the
2394 * file size, the pack is known to be valid even if
2395 * the descriptor is not currently open.
2396 */
2397 if (p->windows) {
2398 struct pack_window *w = p->windows;
2399
2400 if (!w->offset && w->len == p->pack_size)
2401 return 1;
2402 }
2403
2404 /* Force the pack to open to prove its valid. */
2405 return !open_packed_git(p);
2406}
2407
95099731
NTND
2408static int fill_pack_entry(const unsigned char *sha1,
2409 struct pack_entry *e,
2410 struct packed_git *p)
2411{
2412 off_t offset;
2413
2414 if (p->num_bad_objects) {
2415 unsigned i;
2416 for (i = 0; i < p->num_bad_objects; i++)
2417 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
2418 return 0;
2419 }
2420
2421 offset = find_pack_entry_one(sha1, p);
2422 if (!offset)
2423 return 0;
2424
2425 /*
2426 * We are about to tell the caller where they can locate the
2427 * requested object. We better make sure the packfile is
2428 * still here and can be accessed before supplying that
2429 * answer, as it may have been deleted since the index was
2430 * loaded!
2431 */
2432 if (!is_pack_valid(p)) {
2433 warning("packfile %s cannot be accessed", p->pack_name);
2434 return 0;
2435 }
2436 e->offset = offset;
2437 e->p = p;
2438 hashcpy(e->sha1, sha1);
2439 return 1;
2440}
2441
4d6acb70 2442static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1f688557
JH
2443{
2444 struct packed_git *p;
43057304 2445
1f688557 2446 prepare_packed_git();
f7c22cc6
NP
2447 if (!packed_git)
2448 return 0;
1f688557 2449
c01f51cc
NTND
2450 if (last_found_pack && fill_pack_entry(sha1, e, last_found_pack))
2451 return 1;
8eca0b47 2452
c01f51cc
NTND
2453 for (p = packed_git; p; p = p->next) {
2454 if (p == last_found_pack || !fill_pack_entry(sha1, e, p))
2455 continue;
f7c22cc6 2456
c01f51cc
NTND
2457 last_found_pack = p;
2458 return 1;
2459 }
1f688557
JH
2460 return 0;
2461}
2462
a6080a0a 2463struct packed_git *find_sha1_pack(const unsigned char *sha1,
bf592c50
DB
2464 struct packed_git *packs)
2465{
2466 struct packed_git *p;
bf592c50
DB
2467
2468 for (p = packs; p; p = p->next) {
43057304 2469 if (find_pack_entry_one(sha1, p))
bf592c50
DB
2470 return p;
2471 }
2472 return NULL;
21666f1a 2473
bf592c50
DB
2474}
2475
052fe5ea 2476static int sha1_loose_object_info(const unsigned char *sha1,
23c339c0 2477 struct object_info *oi)
65c2e0c3 2478{
36e4d74a 2479 int status;
65c2e0c3
JH
2480 unsigned long mapsize, size;
2481 void *map;
ef49a7a0 2482 git_zstream stream;
d65a16f6 2483 char hdr[32];
65c2e0c3 2484
052fe5ea
JK
2485 /*
2486 * If we don't care about type or size, then we don't
4ef8d1dd
JH
2487 * need to look inside the object at all. Note that we
2488 * do not optimize out the stat call, even if the
2489 * caller doesn't care about the disk-size, since our
2490 * return value implicitly indicates whether the
2491 * object even exists.
052fe5ea 2492 */
23c339c0 2493 if (!oi->typep && !oi->sizep) {
4ef8d1dd
JH
2494 struct stat st;
2495 if (stat_sha1_file(sha1, &st) < 0)
2496 return -1;
2497 if (oi->disk_sizep)
23c339c0 2498 *oi->disk_sizep = st.st_size;
052fe5ea
JK
2499 return 0;
2500 }
2501
bb6b8e4f 2502 map = map_sha1_file(sha1, &mapsize);
f0df4ed5 2503 if (!map)
dbea72a8 2504 return -1;
23c339c0
JK
2505 if (oi->disk_sizep)
2506 *oi->disk_sizep = mapsize;
36e4d74a
JH
2507 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2508 status = error("unable to unpack %s header",
2509 sha1_to_hex(sha1));
21666f1a 2510 else if ((status = parse_sha1_header(hdr, &size)) < 0)
36e4d74a 2511 status = error("unable to parse %s header", sha1_to_hex(sha1));
23c339c0
JK
2512 else if (oi->sizep)
2513 *oi->sizep = size;
39c68542 2514 git_inflate_end(&stream);
65c2e0c3 2515 munmap(map, mapsize);
23c339c0
JK
2516 if (oi->typep)
2517 *oi->typep = status;
052fe5ea 2518 return 0;
65c2e0c3
JH
2519}
2520
9a490590 2521int sha1_object_info_extended(const unsigned char *sha1, struct object_info *oi)
f0df4ed5 2522{
c4d9986f 2523 struct cached_object *co;
f0df4ed5 2524 struct pack_entry e;
5b086407 2525 int rtype;
f0df4ed5 2526
c4d9986f
NTND
2527 co = find_cached_object(sha1);
2528 if (co) {
5b086407
JK
2529 if (oi->typep)
2530 *(oi->typep) = co->type;
9a490590
JH
2531 if (oi->sizep)
2532 *(oi->sizep) = co->size;
161f00e7
JK
2533 if (oi->disk_sizep)
2534 *(oi->disk_sizep) = 0;
9a490590 2535 oi->whence = OI_CACHED;
5b086407 2536 return 0;
c4d9986f
NTND
2537 }
2538
cd673c1f 2539 if (!find_pack_entry(sha1, &e)) {
ddd63e64 2540 /* Most likely it's a loose object. */
23c339c0 2541 if (!sha1_loose_object_info(sha1, oi)) {
9a490590 2542 oi->whence = OI_LOOSE;
5b086407 2543 return 0;
9a490590 2544 }
ddd63e64
SG
2545
2546 /* Not a loose object; someone else may have just packed it. */
f0df4ed5 2547 reprepare_packed_git();
cd673c1f 2548 if (!find_pack_entry(sha1, &e))
052fe5ea 2549 return -1;
f0df4ed5 2550 }
3d77d877 2551
23c339c0 2552 rtype = packed_object_info(e.p, e.offset, oi);
412916ee 2553 if (rtype < 0) {
3d77d877 2554 mark_bad_packed_object(e.p, sha1);
412916ee 2555 return sha1_object_info_extended(sha1, oi);
5266d369
JH
2556 } else if (in_delta_base_cache(e.p, e.offset)) {
2557 oi->whence = OI_DBCACHED;
9a490590
JH
2558 } else {
2559 oi->whence = OI_PACKED;
2560 oi->u.packed.offset = e.offset;
2561 oi->u.packed.pack = e.p;
2562 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
2563 rtype == OBJ_OFS_DELTA);
3d77d877
NP
2564 }
2565
5b086407 2566 return 0;
f0df4ed5
JS
2567}
2568
3fc0dca9 2569/* returns enum object_type or negative */
9a490590
JH
2570int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
2571{
5b086407 2572 enum object_type type;
d099b717 2573 struct object_info oi = {NULL};
9a490590 2574
5b086407 2575 oi.typep = &type;
9a490590 2576 oi.sizep = sizep;
5b086407
JK
2577 if (sha1_object_info_extended(sha1, &oi) < 0)
2578 return -1;
2579 return type;
9a490590
JH
2580}
2581
21666f1a
NP
2582static void *read_packed_sha1(const unsigned char *sha1,
2583 enum object_type *type, unsigned long *size)
1f688557
JH
2584{
2585 struct pack_entry e;
8eca0b47 2586 void *data;
1f688557 2587
cd673c1f 2588 if (!find_pack_entry(sha1, &e))
1f688557 2589 return NULL;
8eca0b47
NP
2590 data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
2591 if (!data) {
2592 /*
2593 * We're probably in deep shit, but let's try to fetch
2594 * the required object anyway from another pack or loose.
2595 * This should happen only in the presence of a corrupted
2596 * pack, and is better than failing outright.
2597 */
2598 error("failed to read object %s at offset %"PRIuMAX" from %s",
2599 sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
2600 mark_bad_packed_object(e.p, sha1);
ac939109 2601 data = read_object(sha1, type, size);
8eca0b47
NP
2602 }
2603 return data;
1f688557
JH
2604}
2605
21666f1a
NP
2606int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2607 unsigned char *sha1)
d66b37bb
JH
2608{
2609 struct cached_object *co;
2610
21666f1a 2611 hash_sha1_file(buf, len, typename(type), sha1);
d66b37bb
JH
2612 if (has_sha1_file(sha1) || find_cached_object(sha1))
2613 return 0;
2614 if (cached_object_alloc <= cached_object_nr) {
2615 cached_object_alloc = alloc_nr(cached_object_alloc);
2616 cached_objects = xrealloc(cached_objects,
2617 sizeof(*cached_objects) *
2618 cached_object_alloc);
2619 }
2620 co = &cached_objects[cached_object_nr++];
2621 co->size = len;
21666f1a 2622 co->type = type;
efa13f7b
JH
2623 co->buf = xmalloc(len);
2624 memcpy(co->buf, buf, len);
d66b37bb
JH
2625 hashcpy(co->sha1, sha1);
2626 return 0;
2627}
2628
c2c5b270
CC
2629static void *read_object(const unsigned char *sha1, enum object_type *type,
2630 unsigned long *size)
0fcfd160
LT
2631{
2632 unsigned long mapsize;
2633 void *map, *buf;
d66b37bb
JH
2634 struct cached_object *co;
2635
2636 co = find_cached_object(sha1);
2637 if (co) {
21666f1a 2638 *type = co->type;
d66b37bb 2639 *size = co->size;
182af834 2640 return xmemdupz(co->buf, co->size);
d66b37bb 2641 }
0fcfd160 2642
8276c007
PE
2643 buf = read_packed_sha1(sha1, type, size);
2644 if (buf)
2645 return buf;
bb6b8e4f 2646 map = map_sha1_file(sha1, &mapsize);
0fcfd160 2647 if (map) {
7efbff75 2648 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
0fcfd160
LT
2649 munmap(map, mapsize);
2650 return buf;
2651 }
637cdd9d 2652 reprepare_packed_git();
8276c007 2653 return read_packed_sha1(sha1, type, size);
0fcfd160
LT
2654}
2655
b6c4cecc
JH
2656/*
2657 * This function dies on corrupt objects; the callers who want to
2658 * deal with them should arrange to call read_object() and give error
2659 * messages themselves.
2660 */
5bf29b95
JH
2661void *read_sha1_file_extended(const unsigned char *sha1,
2662 enum object_type *type,
2663 unsigned long *size,
2664 unsigned flag)
ac939109 2665{
3ba7a065 2666 void *data;
e8b15e61 2667 char *path;
b6c4cecc 2668 const struct packed_git *p;
5bf29b95
JH
2669 const unsigned char *repl = (flag & READ_SHA1_FILE_REPLACE)
2670 ? lookup_replace_object(sha1) : sha1;
b6c4cecc 2671
3ba7a065
JH
2672 errno = 0;
2673 data = read_object(repl, type, size);
4bbf5a26 2674 if (data)
b6c4cecc 2675 return data;
68095570 2676
25f3af3f 2677 if (errno && errno != ENOENT)
3ba7a065
JH
2678 die_errno("failed to read object %s", sha1_to_hex(sha1));
2679
68095570 2680 /* die if we replaced an object with one that does not exist */
b6c4cecc 2681 if (repl != sha1)
68095570
CC
2682 die("replacement %s not found for %s",
2683 sha1_to_hex(repl), sha1_to_hex(sha1));
2684
b6c4cecc
JH
2685 if (has_loose_object(repl)) {
2686 path = sha1_file_name(sha1);
2687 die("loose object %s (stored in %s) is corrupt",
2688 sha1_to_hex(repl), path);
e8b15e61 2689 }
68095570 2690
b6c4cecc
JH
2691 if ((p = has_packed_and_bad(repl)) != NULL)
2692 die("packed object %s (stored in %s) is corrupt",
2693 sha1_to_hex(repl), p->pack_name);
f5552aee 2694
b6c4cecc 2695 return NULL;
ac939109
NP
2696}
2697
40469ee9 2698void *read_object_with_reference(const unsigned char *sha1,
21666f1a 2699 const char *required_type_name,
40469ee9
JH
2700 unsigned long *size,
2701 unsigned char *actual_sha1_return)
f4913f91 2702{
21666f1a 2703 enum object_type type, required_type;
f4913f91
JH
2704 void *buffer;
2705 unsigned long isize;
40469ee9 2706 unsigned char actual_sha1[20];
f4913f91 2707
21666f1a 2708 required_type = type_from_string(required_type_name);
e702496e 2709 hashcpy(actual_sha1, sha1);
40469ee9
JH
2710 while (1) {
2711 int ref_length = -1;
2712 const char *ref_type = NULL;
f4913f91 2713
21666f1a 2714 buffer = read_sha1_file(actual_sha1, &type, &isize);
40469ee9
JH
2715 if (!buffer)
2716 return NULL;
21666f1a 2717 if (type == required_type) {
40469ee9
JH
2718 *size = isize;
2719 if (actual_sha1_return)
e702496e 2720 hashcpy(actual_sha1_return, actual_sha1);
40469ee9
JH
2721 return buffer;
2722 }
2723 /* Handle references */
21666f1a 2724 else if (type == OBJ_COMMIT)
40469ee9 2725 ref_type = "tree ";
21666f1a 2726 else if (type == OBJ_TAG)
40469ee9
JH
2727 ref_type = "object ";
2728 else {
2729 free(buffer);
2730 return NULL;
2731 }
2732 ref_length = strlen(ref_type);
f4913f91 2733
50974ec9
MK
2734 if (ref_length + 40 > isize ||
2735 memcmp(buffer, ref_type, ref_length) ||
1d7f171c 2736 get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
40469ee9
JH
2737 free(buffer);
2738 return NULL;
2739 }
1cf58e72 2740 free(buffer);
40469ee9
JH
2741 /* Now we have the ID of the referred-to object in
2742 * actual_sha1. Check again. */
f4913f91 2743 }
f4913f91
JH
2744}
2745
ce9fbf16 2746static void write_sha1_file_prepare(const void *buf, unsigned long len,
972a9155 2747 const char *type, unsigned char *sha1,
d65a16f6 2748 char *hdr, int *hdrlen)
d410c0f5 2749{
9126f009 2750 git_SHA_CTX c;
d410c0f5
JH
2751
2752 /* Generate the header */
d65a16f6 2753 *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
d410c0f5
JH
2754
2755 /* Sha1.. */
9126f009
NP
2756 git_SHA1_Init(&c);
2757 git_SHA1_Update(&c, hdr, *hdrlen);
2758 git_SHA1_Update(&c, buf, len);
2759 git_SHA1_Final(sha1, &c);
d410c0f5
JH
2760}
2761
230f1322 2762/*
5a688fe4
JH
2763 * Move the just written object into its final resting place.
2764 * NEEDSWORK: this should be renamed to finalize_temp_file() as
2765 * "moving" is only a part of what it does, when no patch between
2766 * master to pu changes the call sites of this function.
230f1322 2767 */
839837b9 2768int move_temp_to_file(const char *tmpfile, const char *filename)
230f1322 2769{
e32c0a9c 2770 int ret = 0;
5a688fe4 2771
348df166 2772 if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
be66a6c4
JS
2773 goto try_rename;
2774 else if (link(tmpfile, filename))
e32c0a9c 2775 ret = errno;
7ebb6fca
LT
2776
2777 /*
2778 * Coda hack - coda doesn't like cross-directory links,
2779 * so we fall back to a rename, which will mean that it
2780 * won't be able to check collisions, but that's not a
2781 * big deal.
2782 *
2783 * The same holds for FAT formatted media.
2784 *
3be1f18e 2785 * When this succeeds, we just return. We have nothing
7ebb6fca
LT
2786 * left to unlink.
2787 */
2788 if (ret && ret != EEXIST) {
be66a6c4 2789 try_rename:
7ebb6fca 2790 if (!rename(tmpfile, filename))
3be1f18e 2791 goto out;
9e48b389 2792 ret = errno;
230f1322 2793 }
691f1a28 2794 unlink_or_warn(tmpfile);
230f1322
LT
2795 if (ret) {
2796 if (ret != EEXIST) {
82247e9b 2797 return error("unable to write sha1 filename %s: %s", filename, strerror(ret));
230f1322
LT
2798 }
2799 /* FIXME!!! Collision check here ? */
2800 }
2801
3be1f18e 2802out:
5256b006 2803 if (adjust_shared_perm(filename))
5a688fe4 2804 return error("unable to set permission to '%s'", filename);
230f1322
LT
2805 return 0;
2806}
2807
4d548150
LT
2808static int write_buffer(int fd, const void *buf, size_t len)
2809{
d34cf19b 2810 if (write_in_full(fd, buf, len) < 0)
93822c22 2811 return error("file write error (%s)", strerror(errno));
4d548150
LT
2812 return 0;
2813}
2814
ce9fbf16 2815int hash_sha1_file(const void *buf, unsigned long len, const char *type,
abdc3fc8
RS
2816 unsigned char *sha1)
2817{
d65a16f6 2818 char hdr[32];
abdc3fc8
RS
2819 int hdrlen;
2820 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2821 return 0;
2822}
2823
e9039dd3
LT
2824/* Finalize a file on disk, and close it. */
2825static void close_sha1_file(int fd)
2826{
aafe9fba
LT
2827 if (fsync_object_files)
2828 fsync_or_die(fd, "sha1 file");
e9039dd3 2829 if (close(fd) != 0)
d824cbba 2830 die_errno("error when closing sha1 file");
e9039dd3
LT
2831}
2832
5723fe7e
LT
2833/* Size of directory component, including the ending '/' */
2834static inline int directory_size(const char *filename)
2835{
2836 const char *s = strrchr(filename, '/');
2837 if (!s)
2838 return 0;
2839 return s - filename + 1;
2840}
2841
2842/*
2843 * This creates a temporary file in the same directory as the final
2844 * 'filename'
2845 *
2846 * We want to avoid cross-directory filename renames, because those
2847 * can have problems on various filesystems (FAT, NFS, Coda).
2848 */
2849static int create_tmpfile(char *buffer, size_t bufsiz, const char *filename)
2850{
2851 int fd, dirlen = directory_size(filename);
2852
2853 if (dirlen + 20 > bufsiz) {
2854 errno = ENAMETOOLONG;
2855 return -1;
2856 }
2857 memcpy(buffer, filename, dirlen);
2858 strcpy(buffer + dirlen, "tmp_obj_XXXXXX");
5256b006 2859 fd = git_mkstemp_mode(buffer, 0444);
cbacbf4e 2860 if (fd < 0 && dirlen && errno == ENOENT) {
5723fe7e 2861 /* Make sure the directory exists */
6ff6af62 2862 memcpy(buffer, filename, dirlen);
5723fe7e 2863 buffer[dirlen-1] = 0;
b2476a60
JH
2864 if (mkdir(buffer, 0777) && errno != EEXIST)
2865 return -1;
2866 if (adjust_shared_perm(buffer))
5723fe7e
LT
2867 return -1;
2868
2869 /* Try again */
2870 strcpy(buffer + dirlen - 1, "/tmp_obj_XXXXXX");
5256b006 2871 fd = git_mkstemp_mode(buffer, 0444);
5723fe7e
LT
2872 }
2873 return fd;
2874}
2875
bbac7311 2876static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
c00e657d 2877 const void *buf, unsigned long len, time_t mtime)
0fcfd160 2878{
915308b1 2879 int fd, ret;
9892beba 2880 unsigned char compressed[4096];
ef49a7a0 2881 git_zstream stream;
748af44c
NP
2882 git_SHA_CTX c;
2883 unsigned char parano_sha1[20];
706bc531 2884 char *filename;
ab1900a3 2885 static char tmp_file[PATH_MAX];
a44c9a5e 2886
972a9155 2887 filename = sha1_file_name(sha1);
ab1900a3 2888 fd = create_tmpfile(tmp_file, sizeof(tmp_file), filename);
aac17941 2889 if (fd < 0) {
35243577 2890 if (errno == EACCES)
82247e9b 2891 return error("insufficient permission for adding an object to repository database %s", get_object_directory());
916d081b 2892 else
5eaeda70 2893 return error("unable to create temporary file: %s", strerror(errno));
aac17941
LT
2894 }
2895
0fcfd160
LT
2896 /* Set it up */
2897 memset(&stream, 0, sizeof(stream));
55bb5c91 2898 git_deflate_init(&stream, zlib_compression_level);
0fcfd160 2899 stream.next_out = compressed;
9892beba 2900 stream.avail_out = sizeof(compressed);
748af44c 2901 git_SHA1_Init(&c);
a44c9a5e
LT
2902
2903 /* First header.. */
d65a16f6 2904 stream.next_in = (unsigned char *)hdr;
a44c9a5e 2905 stream.avail_in = hdrlen;
55bb5c91
JH
2906 while (git_deflate(&stream, 0) == Z_OK)
2907 ; /* nothing */
748af44c 2908 git_SHA1_Update(&c, hdr, hdrlen);
a44c9a5e
LT
2909
2910 /* Then the data itself.. */
c00e657d 2911 stream.next_in = (void *)buf;
a44c9a5e 2912 stream.avail_in = len;
9892beba 2913 do {
748af44c 2914 unsigned char *in0 = stream.next_in;
55bb5c91 2915 ret = git_deflate(&stream, Z_FINISH);
748af44c 2916 git_SHA1_Update(&c, in0, stream.next_in - in0);
9892beba
NP
2917 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
2918 die("unable to write sha1 file");
2919 stream.next_out = compressed;
2920 stream.avail_out = sizeof(compressed);
2921 } while (ret == Z_OK);
2922
ac54c277
LT
2923 if (ret != Z_STREAM_END)
2924 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
55bb5c91 2925 ret = git_deflate_end_gently(&stream);
ac54c277
LT
2926 if (ret != Z_OK)
2927 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
748af44c
NP
2928 git_SHA1_Final(parano_sha1, &c);
2929 if (hashcmp(sha1, parano_sha1) != 0)
2930 die("confused by unstable object source data for %s", sha1_to_hex(sha1));
ac54c277 2931
e9039dd3 2932 close_sha1_file(fd);
0fcfd160 2933
bbac7311
NP
2934 if (mtime) {
2935 struct utimbuf utb;
2936 utb.actime = mtime;
2937 utb.modtime = mtime;
ab1900a3 2938 if (utime(tmp_file, &utb) < 0)
bbac7311 2939 warning("failed utime() on %s: %s",
ab1900a3 2940 tmp_file, strerror(errno));
bbac7311
NP
2941 }
2942
ab1900a3 2943 return move_temp_to_file(tmp_file, filename);
0fcfd160 2944}
8237b185 2945
c00e657d 2946int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
bbac7311
NP
2947{
2948 unsigned char sha1[20];
2949 char hdr[32];
2950 int hdrlen;
2951
2952 /* Normally if we have it in the pack then we do not bother writing
2953 * it out into .git/objects/??/?{38} file.
2954 */
2955 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2956 if (returnsha1)
2957 hashcpy(returnsha1, sha1);
2958 if (has_sha1_file(sha1))
2959 return 0;
2960 return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
2961}
2962
2963int force_object_loose(const unsigned char *sha1, time_t mtime)
2964{
bbac7311
NP
2965 void *buf;
2966 unsigned long len;
2967 enum object_type type;
2968 char hdr[32];
2969 int hdrlen;
1fb23e65 2970 int ret;
bbac7311 2971
c529d75a 2972 if (has_loose_object(sha1))
bbac7311
NP
2973 return 0;
2974 buf = read_packed_sha1(sha1, &type, &len);
2975 if (!buf)
2976 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2977 hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
1fb23e65
BS
2978 ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
2979 free(buf);
2980
2981 return ret;
bbac7311
NP
2982}
2983
bf592c50
DB
2984int has_pack_index(const unsigned char *sha1)
2985{
2986 struct stat st;
2987 if (stat(sha1_pack_index_name(sha1), &st))
2988 return 0;
2989 return 1;
bf592c50
DB
2990}
2991
cd673c1f
JH
2992int has_sha1_pack(const unsigned char *sha1)
2993{
2994 struct pack_entry e;
2995 return find_pack_entry(sha1, &e);
2996}
2997
8237b185
DB
2998int has_sha1_file(const unsigned char *sha1)
2999{
1f688557
JH
3000 struct pack_entry e;
3001
cd673c1f 3002 if (find_pack_entry(sha1, &e))
1f688557 3003 return 1;
45e8a748
JK
3004 if (has_loose_object(sha1))
3005 return 1;
3006 reprepare_packed_git();
3007 return find_pack_entry(sha1, &e);
8237b185 3008}
74400e71 3009
c879daa2
NTND
3010static void check_tree(const void *buf, size_t size)
3011{
3012 struct tree_desc desc;
3013 struct name_entry entry;
3014
3015 init_tree_desc(&desc, buf, size);
3016 while (tree_entry(&desc, &entry))
3017 /* do nothing
3018 * tree_entry() will die() on malformed entries */
3019 ;
3020}
3021
3022static void check_commit(const void *buf, size_t size)
3023{
3024 struct commit c;
3025 memset(&c, 0, sizeof(c));
3026 if (parse_commit_buffer(&c, buf, size))
3027 die("corrupt commit");
3028}
3029
3030static void check_tag(const void *buf, size_t size)
3031{
3032 struct tag t;
3033 memset(&t, 0, sizeof(t));
3034 if (parse_tag_buffer(&t, buf, size))
3035 die("corrupt tag");
3036}
3037
43df4f86 3038static int index_mem(unsigned char *sha1, void *buf, size_t size,
c4ce46fc
JH
3039 enum object_type type,
3040 const char *path, unsigned flags)
e7332f96 3041{
6c510bee 3042 int ret, re_allocated = 0;
c4ce46fc 3043 int write_object = flags & HASH_WRITE_OBJECT;
74400e71 3044
7672db20 3045 if (!type)
edaec3fb 3046 type = OBJ_BLOB;
6c510bee
LT
3047
3048 /*
3049 * Convert blobs to git internal format
3050 */
43df4f86 3051 if ((type == OBJ_BLOB) && path) {
f285a2d7 3052 struct strbuf nbuf = STRBUF_INIT;
21e5ad50 3053 if (convert_to_git(path, buf, size, &nbuf,
5e12e78e 3054 write_object ? safe_crlf : SAFE_CRLF_FALSE)) {
b315c5c0 3055 buf = strbuf_detach(&nbuf, &size);
6c510bee
LT
3056 re_allocated = 1;
3057 }
3058 }
c4ce46fc 3059 if (flags & HASH_FORMAT_CHECK) {
c879daa2
NTND
3060 if (type == OBJ_TREE)
3061 check_tree(buf, size);
3062 if (type == OBJ_COMMIT)
3063 check_commit(buf, size);
3064 if (type == OBJ_TAG)
3065 check_tag(buf, size);
3066 }
6c510bee 3067
7672db20 3068 if (write_object)
edaec3fb 3069 ret = write_sha1_file(buf, size, typename(type), sha1);
abdc3fc8 3070 else
edaec3fb 3071 ret = hash_sha1_file(buf, size, typename(type), sha1);
43df4f86 3072 if (re_allocated)
6c510bee 3073 free(buf);
43df4f86
DP
3074 return ret;
3075}
3076
7b41e1e1
JH
3077static int index_pipe(unsigned char *sha1, int fd, enum object_type type,
3078 const char *path, unsigned flags)
3079{
3080 struct strbuf sbuf = STRBUF_INIT;
3081 int ret;
3082
3083 if (strbuf_read(&sbuf, fd, 4096) >= 0)
3084 ret = index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);
3085 else
3086 ret = -1;
3087 strbuf_release(&sbuf);
3088 return ret;
3089}
3090
ea68b0ce
DP
3091#define SMALL_FILE_SIZE (32*1024)
3092
7b41e1e1
JH
3093static int index_core(unsigned char *sha1, int fd, size_t size,
3094 enum object_type type, const char *path,
3095 unsigned flags)
43df4f86
DP
3096{
3097 int ret;
43df4f86 3098
7b41e1e1 3099 if (!size) {
c4ce46fc 3100 ret = index_mem(sha1, NULL, size, type, path, flags);
ea68b0ce
DP
3101 } else if (size <= SMALL_FILE_SIZE) {
3102 char *buf = xmalloc(size);
3103 if (size == read_in_full(fd, buf, size))
c4ce46fc 3104 ret = index_mem(sha1, buf, size, type, path, flags);
ea68b0ce
DP
3105 else
3106 ret = error("short read %s", strerror(errno));
3107 free(buf);
08bda208 3108 } else {
43df4f86 3109 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
c4ce46fc 3110 ret = index_mem(sha1, buf, size, type, path, flags);
aac17941 3111 munmap(buf, size);
08bda208 3112 }
7b41e1e1
JH
3113 return ret;
3114}
3115
4dd1fbc7 3116/*
568508e7
JH
3117 * This creates one packfile per large blob unless bulk-checkin
3118 * machinery is "plugged".
4dd1fbc7
JH
3119 *
3120 * This also bypasses the usual "convert-to-git" dance, and that is on
3121 * purpose. We could write a streaming version of the converting
3122 * functions and insert that before feeding the data to fast-import
4f22b101
JK
3123 * (or equivalent in-core API described above). However, that is
3124 * somewhat complicated, as we do not know the size of the filter
3125 * result, which we need to know beforehand when writing a git object.
3126 * Since the primary motivation for trying to stream from the working
3127 * tree file and to avoid mmaping it in core is to deal with large
3128 * binary blobs, they generally do not want to get any conversion, and
3129 * callers should avoid this code path when filters are requested.
4dd1fbc7
JH
3130 */
3131static int index_stream(unsigned char *sha1, int fd, size_t size,
3132 enum object_type type, const char *path,
3133 unsigned flags)
3134{
568508e7 3135 return index_bulk_checkin(sha1, fd, size, type, path, flags);
4dd1fbc7
JH
3136}
3137
7b41e1e1
JH
3138int index_fd(unsigned char *sha1, int fd, struct stat *st,
3139 enum object_type type, const char *path, unsigned flags)
3140{
3141 int ret;
3142 size_t size = xsize_t(st->st_size);
3143
3144 if (!S_ISREG(st->st_mode))
3145 ret = index_pipe(sha1, fd, type, path, flags);
4f22b101
JK
3146 else if (size <= big_file_threshold || type != OBJ_BLOB ||
3147 (path && would_convert_to_git(path, NULL, 0, 0)))
7b41e1e1 3148 ret = index_core(sha1, fd, size, type, path, flags);
4dd1fbc7
JH
3149 else
3150 ret = index_stream(sha1, fd, size, type, path, flags);
43df4f86 3151 close(fd);
aac17941 3152 return ret;
74400e71 3153}
ec1fcc16 3154
c4ce46fc 3155int index_path(unsigned char *sha1, const char *path, struct stat *st, unsigned flags)
ec1fcc16
JH
3156{
3157 int fd;
b760d3aa 3158 struct strbuf sb = STRBUF_INIT;
ec1fcc16
JH
3159
3160 switch (st->st_mode & S_IFMT) {
3161 case S_IFREG:
3162 fd = open(path, O_RDONLY);
3163 if (fd < 0)
3164 return error("open(\"%s\"): %s", path,
3165 strerror(errno));
c4ce46fc 3166 if (index_fd(sha1, fd, st, OBJ_BLOB, path, flags) < 0)
ec1fcc16
JH
3167 return error("%s: failed to insert into database",
3168 path);
3169 break;
3170 case S_IFLNK:
b760d3aa 3171 if (strbuf_readlink(&sb, path, st->st_size)) {
ec1fcc16 3172 char *errstr = strerror(errno);
ec1fcc16
JH
3173 return error("readlink(\"%s\"): %s", path,
3174 errstr);
3175 }
c4ce46fc 3176 if (!(flags & HASH_WRITE_OBJECT))
b760d3aa
LT
3177 hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
3178 else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
ec1fcc16
JH
3179 return error("%s: failed to insert into database",
3180 path);
b760d3aa 3181 strbuf_release(&sb);
ec1fcc16 3182 break;
f35a6d3b
LT
3183 case S_IFDIR:
3184 return resolve_gitlink_ref(path, "HEAD", sha1);
ec1fcc16
JH
3185 default:
3186 return error("%s: unsupported file type", path);
3187 }
3188 return 0;
3189}
a69e5429
JH
3190
3191int read_pack_header(int fd, struct pack_header *header)
3192{
c697ad14
HO
3193 if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
3194 /* "eof before pack header was fully read" */
3195 return PH_ERROR_EOF;
3196
a69e5429
JH
3197 if (header->hdr_signature != htonl(PACK_SIGNATURE))
3198 /* "protocol error (pack signature mismatch detected)" */
3199 return PH_ERROR_PACK_SIGNATURE;
3200 if (!pack_version_ok(header->hdr_version))
3201 /* "protocol error (pack version unsupported)" */
3202 return PH_ERROR_PROTOCOL;
3203 return 0;
3204}
40d52ff7
JK
3205
3206void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
3207{
3208 enum object_type type = sha1_object_info(sha1, NULL);
3209 if (type < 0)
3210 die("%s is not a valid object", sha1_to_hex(sha1));
3211 if (type != expect)
3212 die("%s is not a valid '%s' object", sha1_to_hex(sha1),
3213 typename(expect));
3214}