t7700: demonstrate mishandling of loose objects in an alternate ODB
[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"
1f688557 10#include "delta.h"
a733cb60 11#include "pack.h"
8e440259
PE
12#include "blob.h"
13#include "commit.h"
14#include "tag.h"
15#include "tree.h"
f35a6d3b 16#include "refs.h"
70f5d5d3 17#include "pack-revindex.h"
628522ec 18#include "sha1-lookup.h"
0fcfd160 19
144bde78
LT
20#ifndef O_NOATIME
21#if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
22#define O_NOATIME 01000000
23#else
24#define O_NOATIME 0
25#endif
26#endif
27
e05db0fd
PR
28#ifdef NO_C99_FORMAT
29#define SZ_FMT "lu"
9e42d6a1 30static unsigned long sz_fmt(size_t s) { return (unsigned long)s; }
e05db0fd
PR
31#else
32#define SZ_FMT "zu"
9e42d6a1 33static size_t sz_fmt(size_t s) { return s; }
e05db0fd
PR
34#endif
35
96f1e58f 36const unsigned char null_sha1[20];
88cd621d 37
192a6be2 38const signed char hexval_table[256] = {
e49521b5
JH
39 -1, -1, -1, -1, -1, -1, -1, -1, /* 00-07 */
40 -1, -1, -1, -1, -1, -1, -1, -1, /* 08-0f */
41 -1, -1, -1, -1, -1, -1, -1, -1, /* 10-17 */
42 -1, -1, -1, -1, -1, -1, -1, -1, /* 18-1f */
43 -1, -1, -1, -1, -1, -1, -1, -1, /* 20-27 */
44 -1, -1, -1, -1, -1, -1, -1, -1, /* 28-2f */
45 0, 1, 2, 3, 4, 5, 6, 7, /* 30-37 */
46 8, 9, -1, -1, -1, -1, -1, -1, /* 38-3f */
47 -1, 10, 11, 12, 13, 14, 15, -1, /* 40-47 */
48 -1, -1, -1, -1, -1, -1, -1, -1, /* 48-4f */
49 -1, -1, -1, -1, -1, -1, -1, -1, /* 50-57 */
50 -1, -1, -1, -1, -1, -1, -1, -1, /* 58-5f */
51 -1, 10, 11, 12, 13, 14, 15, -1, /* 60-67 */
52 -1, -1, -1, -1, -1, -1, -1, -1, /* 68-67 */
53 -1, -1, -1, -1, -1, -1, -1, -1, /* 70-77 */
54 -1, -1, -1, -1, -1, -1, -1, -1, /* 78-7f */
55 -1, -1, -1, -1, -1, -1, -1, -1, /* 80-87 */
56 -1, -1, -1, -1, -1, -1, -1, -1, /* 88-8f */
57 -1, -1, -1, -1, -1, -1, -1, -1, /* 90-97 */
58 -1, -1, -1, -1, -1, -1, -1, -1, /* 98-9f */
59 -1, -1, -1, -1, -1, -1, -1, -1, /* a0-a7 */
60 -1, -1, -1, -1, -1, -1, -1, -1, /* a8-af */
61 -1, -1, -1, -1, -1, -1, -1, -1, /* b0-b7 */
62 -1, -1, -1, -1, -1, -1, -1, -1, /* b8-bf */
63 -1, -1, -1, -1, -1, -1, -1, -1, /* c0-c7 */
64 -1, -1, -1, -1, -1, -1, -1, -1, /* c8-cf */
65 -1, -1, -1, -1, -1, -1, -1, -1, /* d0-d7 */
66 -1, -1, -1, -1, -1, -1, -1, -1, /* d8-df */
67 -1, -1, -1, -1, -1, -1, -1, -1, /* e0-e7 */
68 -1, -1, -1, -1, -1, -1, -1, -1, /* e8-ef */
69 -1, -1, -1, -1, -1, -1, -1, -1, /* f0-f7 */
70 -1, -1, -1, -1, -1, -1, -1, -1, /* f8-ff */
71};
0fcfd160
LT
72
73int get_sha1_hex(const char *hex, unsigned char *sha1)
74{
75 int i;
76 for (i = 0; i < 20; i++) {
77 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
78 if (val & ~0xff)
79 return -1;
80 *sha1++ = val;
81 hex += 2;
82 }
83 return 0;
84}
85
8385abfd
JS
86static inline int offset_1st_component(const char *path)
87{
88 if (has_dos_drive_prefix(path))
89 return 2 + (path[2] == '/');
90 return *path == '/';
91}
92
b2cb9425
JH
93int safe_create_leading_directories(char *path)
94{
8385abfd 95 char *pos = path + offset_1st_component(path);
67d42212
JR
96 struct stat st;
97
b2cb9425
JH
98 while (pos) {
99 pos = strchr(pos, '/');
100 if (!pos)
101 break;
102 *pos = 0;
67d42212
JR
103 if (!stat(path, &st)) {
104 /* path exists */
105 if (!S_ISDIR(st.st_mode)) {
b2cb9425 106 *pos = '/';
67d42212 107 return -3;
b2cb9425 108 }
457f06d6 109 }
67d42212
JR
110 else if (mkdir(path, 0777)) {
111 *pos = '/';
112 return -1;
113 }
457f06d6
JS
114 else if (adjust_shared_perm(path)) {
115 *pos = '/';
116 return -2;
117 }
b2cb9425
JH
118 *pos++ = '/';
119 }
120 return 0;
121}
723c31fe 122
8e21d63b
JK
123int safe_create_leading_directories_const(const char *path)
124{
125 /* path points to cache entries, so xstrdup before messing with it */
126 char *buf = xstrdup(path);
127 int result = safe_create_leading_directories(buf);
128 free(buf);
129 return result;
130}
131
3bfaf018 132char *sha1_to_hex(const unsigned char *sha1)
0fcfd160 133{
dcb3450f
LT
134 static int bufno;
135 static char hexbuffer[4][50];
0fcfd160 136 static const char hex[] = "0123456789abcdef";
dcb3450f 137 char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
0fcfd160
LT
138 int i;
139
140 for (i = 0; i < 20; i++) {
141 unsigned int val = *sha1++;
142 *buf++ = hex[val >> 4];
143 *buf++ = hex[val & 0xf];
144 }
1e80e044
JS
145 *buf = '\0';
146
0fcfd160
LT
147 return buffer;
148}
149
ace1534d
JH
150static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
151{
152 int i;
153 for (i = 0; i < 20; i++) {
154 static char hex[] = "0123456789abcdef";
155 unsigned int val = sha1[i];
156 char *pos = pathbuf + i*2 + (i > 0);
157 *pos++ = hex[val >> 4];
158 *pos = hex[val & 0xf];
159 }
160}
161
0fcfd160
LT
162/*
163 * NOTE! This returns a statically allocated buffer, so you have to be
790296fd 164 * careful about using it. Do an "xstrdup()" if you need to save the
0fcfd160 165 * filename.
ace1534d
JH
166 *
167 * Also note that this returns the location for creating. Reading
168 * SHA1 file can happen from any alternate directory listed in the
d19938ab 169 * DB_ENVIRONMENT environment variable if it is not found in
ace1534d 170 * the primary object database.
0fcfd160
LT
171 */
172char *sha1_file_name(const unsigned char *sha1)
173{
0fcfd160
LT
174 static char *name, *base;
175
176 if (!base) {
d19938ab 177 const char *sha1_file_directory = get_object_directory();
0fcfd160 178 int len = strlen(sha1_file_directory);
812666c8 179 base = xmalloc(len + 60);
0fcfd160
LT
180 memcpy(base, sha1_file_directory, len);
181 memset(base+len, 0, 60);
182 base[len] = '/';
183 base[len+3] = '/';
184 name = base + len + 1;
185 }
ace1534d 186 fill_sha1_path(name, sha1);
0fcfd160
LT
187 return base;
188}
189
633f43e1 190static char *sha1_get_pack_name(const unsigned char *sha1,
6eec46bd 191 char **name, char **base, const char *which)
bf592c50
DB
192{
193 static const char hex[] = "0123456789abcdef";
633f43e1 194 char *buf;
bf592c50
DB
195 int i;
196
633f43e1 197 if (!*base) {
bf592c50
DB
198 const char *sha1_file_directory = get_object_directory();
199 int len = strlen(sha1_file_directory);
633f43e1 200 *base = xmalloc(len + 60);
6eec46bd
JH
201 sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
202 sha1_file_directory, which);
633f43e1 203 *name = *base + len + 11;
bf592c50
DB
204 }
205
633f43e1 206 buf = *name;
bf592c50
DB
207
208 for (i = 0; i < 20; i++) {
209 unsigned int val = *sha1++;
210 *buf++ = hex[val >> 4];
211 *buf++ = hex[val & 0xf];
212 }
a6080a0a 213
633f43e1 214 return *base;
bf592c50
DB
215}
216
633f43e1 217char *sha1_pack_name(const unsigned char *sha1)
bf592c50 218{
633f43e1 219 static char *name, *base;
bf592c50 220
6eec46bd 221 return sha1_get_pack_name(sha1, &name, &base, "pack");
633f43e1 222}
bf592c50 223
633f43e1
HO
224char *sha1_pack_index_name(const unsigned char *sha1)
225{
226 static char *name, *base;
a6080a0a 227
6eec46bd 228 return sha1_get_pack_name(sha1, &name, &base, "idx");
bf592c50
DB
229}
230
d5a63b99
JH
231struct alternate_object_database *alt_odb_list;
232static struct alternate_object_database **alt_odb_tail;
ace1534d 233
c2f493a4
MW
234static void read_info_alternates(const char * alternates, int depth);
235
ddd5d056
JH
236/*
237 * Prepare alternate object database registry.
d5a63b99
JH
238 *
239 * The variable alt_odb_list points at the list of struct
240 * alternate_object_database. The elements on this list come from
241 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
242 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
1494e038
JH
243 * whose contents is similar to that environment variable but can be
244 * LF separated. Its base points at a statically allocated buffer that
d5a63b99
JH
245 * contains "/the/directory/corresponding/to/.git/objects/...", while
246 * its name points just after the slash at the end of ".git/objects/"
247 * in the example above, and has enough space to hold 40-byte hex
248 * SHA1, an extra slash for the first level indirection, and the
249 * terminating NUL.
ddd5d056 250 */
c2f493a4 251static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
ace1534d 252{
c2f493a4 253 struct stat st;
1494e038 254 const char *objdir = get_object_directory();
c2f493a4
MW
255 struct alternate_object_database *ent;
256 struct alternate_object_database *alt;
257 /* 43 = 40-byte + 2 '/' + terminating NUL */
258 int pfxlen = len;
259 int entlen = pfxlen + 43;
ccfd3e99 260 int base_len = -1;
d5a63b99 261
85dadc38 262 if (!is_absolute_path(entry) && relative_base) {
c2f493a4
MW
263 /* Relative alt-odb */
264 if (base_len < 0)
265 base_len = strlen(relative_base) + 1;
266 entlen += base_len;
267 pfxlen += base_len;
268 }
269 ent = xmalloc(sizeof(*ent) + entlen);
270
85dadc38 271 if (!is_absolute_path(entry) && relative_base) {
c2f493a4
MW
272 memcpy(ent->base, relative_base, base_len - 1);
273 ent->base[base_len - 1] = '/';
274 memcpy(ent->base + base_len, entry, len);
275 }
276 else
277 memcpy(ent->base, entry, pfxlen);
278
279 ent->name = ent->base + pfxlen + 1;
280 ent->base[pfxlen + 3] = '/';
281 ent->base[pfxlen] = ent->base[entlen-1] = 0;
282
283 /* Detect cases where alternate disappeared */
284 if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
285 error("object directory %s does not exist; "
286 "check .git/objects/info/alternates.",
287 ent->base);
288 free(ent);
289 return -1;
290 }
291
292 /* Prevent the common mistake of listing the same
293 * thing twice, or object directory itself.
294 */
295 for (alt = alt_odb_list; alt; alt = alt->next) {
296 if (!memcmp(ent->base, alt->base, pfxlen)) {
297 free(ent);
298 return -1;
299 }
300 }
301 if (!memcmp(ent->base, objdir, pfxlen)) {
302 free(ent);
303 return -1;
304 }
305
306 /* add the alternate entry */
307 *alt_odb_tail = ent;
308 alt_odb_tail = &(ent->next);
309 ent->next = NULL;
310
311 /* recursively add alternates */
312 read_info_alternates(ent->base, depth + 1);
313
314 ent->base[pfxlen] = '/';
315
316 return 0;
317}
318
319static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
320 const char *relative_base, int depth)
321{
322 const char *cp, *last;
323
324 if (depth > 5) {
325 error("%s: ignoring alternate object stores, nesting too deep.",
326 relative_base);
327 return;
328 }
329
d5a63b99 330 last = alt;
9577e7e3
JH
331 while (last < ep) {
332 cp = last;
333 if (cp < ep && *cp == '#') {
334 while (cp < ep && *cp != sep)
335 cp++;
336 last = cp + 1;
337 continue;
338 }
c2f493a4
MW
339 while (cp < ep && *cp != sep)
340 cp++;
d5a63b99 341 if (last != cp) {
85dadc38 342 if (!is_absolute_path(last) && depth) {
c2f493a4
MW
343 error("%s: ignoring relative alternate object store %s",
344 relative_base, last);
345 } else {
346 link_alt_odb_entry(last, cp - last,
347 relative_base, depth);
1494e038 348 }
d5a63b99 349 }
9577e7e3 350 while (cp < ep && *cp == sep)
d5a63b99
JH
351 cp++;
352 last = cp;
9577e7e3 353 }
d5a63b99
JH
354}
355
c2f493a4 356static void read_info_alternates(const char * relative_base, int depth)
d5a63b99 357{
9577e7e3 358 char *map;
dc49cd76 359 size_t mapsz;
d5a63b99 360 struct stat st;
9cb18f56
JM
361 const char alt_file_name[] = "info/alternates";
362 /* Given that relative_base is no longer than PATH_MAX,
363 ensure that "path" has enough space to append "/", the
364 file name, "info/alternates", and a trailing NUL. */
365 char path[PATH_MAX + 1 + sizeof alt_file_name];
c2f493a4 366 int fd;
d5a63b99 367
9cb18f56 368 sprintf(path, "%s/%s", relative_base, alt_file_name);
d5a63b99
JH
369 fd = open(path, O_RDONLY);
370 if (fd < 0)
371 return;
372 if (fstat(fd, &st) || (st.st_size == 0)) {
373 close(fd);
9a217f2a 374 return;
ace1534d 375 }
dc49cd76
SP
376 mapsz = xsize_t(st.st_size);
377 map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
d5a63b99 378 close(fd);
d5a63b99 379
dc49cd76 380 link_alt_odb_entries(map, map + mapsz, '\n', relative_base, depth);
c2f493a4 381
dc49cd76 382 munmap(map, mapsz);
ace1534d
JH
383}
384
bef70b22
DB
385void add_to_alternates_file(const char *reference)
386{
387 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
acd3b9ec 388 int fd = hold_lock_file_for_append(lock, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR);
bef70b22
DB
389 char *alt = mkpath("%s/objects\n", reference);
390 write_or_die(fd, alt, strlen(alt));
391 if (commit_lock_file(lock))
392 die("could not close alternates file");
393 if (alt_odb_tail)
394 link_alt_odb_entries(alt, alt + strlen(alt), '\n', NULL, 0);
395}
396
c2f493a4
MW
397void prepare_alt_odb(void)
398{
554fe20d 399 const char *alt;
c2f493a4 400
7dc24aa5
SP
401 if (alt_odb_tail)
402 return;
403
c2f493a4
MW
404 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
405 if (!alt) alt = "";
406
c2f493a4 407 alt_odb_tail = &alt_odb_list;
80ba074f 408 link_alt_odb_entries(alt, alt + strlen(alt), PATH_SEP, NULL, 0);
c2f493a4
MW
409
410 read_info_alternates(get_object_directory(), 0);
411}
412
c529d75a 413static int has_loose_object(const unsigned char *sha1)
ace1534d 414{
ace1534d 415 char *name = sha1_file_name(sha1);
d5a63b99 416 struct alternate_object_database *alt;
ace1534d 417
c529d75a
LT
418 if (!access(name, F_OK))
419 return 1;
9a217f2a 420 prepare_alt_odb();
d5a63b99
JH
421 for (alt = alt_odb_list; alt; alt = alt->next) {
422 name = alt->name;
ace1534d 423 fill_sha1_path(name, sha1);
c529d75a
LT
424 if (!access(alt->base, F_OK))
425 return 1;
ace1534d 426 }
c529d75a 427 return 0;
ace1534d
JH
428}
429
60bb8b14 430static unsigned int pack_used_ctr;
a53128b6
SP
431static unsigned int pack_mmap_calls;
432static unsigned int peak_pack_open_windows;
433static unsigned int pack_open_windows;
434static size_t peak_pack_mapped;
60bb8b14 435static size_t pack_mapped;
9a217f2a 436struct packed_git *packed_git;
1f688557 437
b79d18c9 438void pack_report(void)
a53128b6
SP
439{
440 fprintf(stderr,
e05db0fd
PR
441 "pack_report: getpagesize() = %10" SZ_FMT "\n"
442 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
443 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
9e42d6a1
SP
444 sz_fmt(getpagesize()),
445 sz_fmt(packed_git_window_size),
446 sz_fmt(packed_git_limit));
a53128b6
SP
447 fprintf(stderr,
448 "pack_report: pack_used_ctr = %10u\n"
449 "pack_report: pack_mmap_calls = %10u\n"
450 "pack_report: pack_open_windows = %10u / %10u\n"
e05db0fd
PR
451 "pack_report: pack_mapped = "
452 "%10" SZ_FMT " / %10" SZ_FMT "\n",
a53128b6
SP
453 pack_used_ctr,
454 pack_mmap_calls,
455 pack_open_windows, peak_pack_open_windows,
9e42d6a1 456 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
a53128b6
SP
457}
458
42873078 459static int check_packed_git_idx(const char *path, struct packed_git *p)
1f688557
JH
460{
461 void *idx_map;
42873078 462 struct pack_idx_header *hdr;
dc49cd76 463 size_t idx_size;
74e34e1f 464 uint32_t version, nr, i, *index;
e93ec6f9 465 int fd = open(path, O_RDONLY);
1f688557 466 struct stat st;
42873078 467
1f688557
JH
468 if (fd < 0)
469 return -1;
470 if (fstat(fd, &st)) {
471 close(fd);
472 return -1;
473 }
dc49cd76 474 idx_size = xsize_t(st.st_size);
2d88451b
SP
475 if (idx_size < 4 * 256 + 20 + 20) {
476 close(fd);
477 return error("index file %s is too small", path);
478 }
c4712e45 479 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
1f688557 480 close(fd);
1f688557 481
42873078
NP
482 hdr = idx_map;
483 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
74e34e1f
NP
484 version = ntohl(hdr->idx_version);
485 if (version < 2 || version > 2) {
486 munmap(idx_map, idx_size);
6e1c2344 487 return error("index file %s is version %"PRIu32
74e34e1f
NP
488 " and is not supported by this binary"
489 " (try upgrading GIT to a newer version)",
490 path, version);
491 }
492 } else
493 version = 1;
df1b059d 494
1f688557 495 nr = 0;
42873078 496 index = idx_map;
74e34e1f
NP
497 if (version > 1)
498 index += 2; /* skip index header */
1f688557 499 for (i = 0; i < 256; i++) {
326bf396 500 uint32_t n = ntohl(index[i]);
2d88451b
SP
501 if (n < nr) {
502 munmap(idx_map, idx_size);
df1b059d 503 return error("non-monotonic index %s", path);
2d88451b 504 }
1f688557
JH
505 nr = n;
506 }
507
74e34e1f
NP
508 if (version == 1) {
509 /*
510 * Total size:
511 * - 256 index entries 4 bytes each
512 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
513 * - 20-byte SHA1 of the packfile
514 * - 20-byte SHA1 file checksum
515 */
516 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
517 munmap(idx_map, idx_size);
eef427a0 518 return error("wrong index v1 file size in %s", path);
74e34e1f
NP
519 }
520 } else if (version == 2) {
521 /*
522 * Minimum size:
523 * - 8 bytes of header
524 * - 256 index entries 4 bytes each
525 * - 20-byte sha1 entry * nr
526 * - 4-byte crc entry * nr
527 * - 4-byte offset entry * nr
528 * - 20-byte SHA1 of the packfile
529 * - 20-byte SHA1 file checksum
530 * And after the 4-byte offset table might be a
531 * variable sized table containing 8-byte entries
532 * for offsets larger than 2^31.
533 */
534 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
1164f1e4
LT
535 unsigned long max_size = min_size;
536 if (nr)
537 max_size += (nr - 1)*8;
538 if (idx_size < min_size || idx_size > max_size) {
74e34e1f 539 munmap(idx_map, idx_size);
eef427a0 540 return error("wrong index v2 file size in %s", path);
74e34e1f 541 }
7109c889
JH
542 if (idx_size != min_size &&
543 /*
544 * make sure we can deal with large pack offsets.
545 * 31-bit signed offset won't be enough, neither
546 * 32-bit unsigned one will be.
547 */
548 (sizeof(off_t) <= 4)) {
549 munmap(idx_map, idx_size);
550 return error("pack too large for current definition of off_t in %s", path);
74e34e1f 551 }
2d88451b 552 }
1f688557 553
74e34e1f 554 p->index_version = version;
42873078
NP
555 p->index_data = idx_map;
556 p->index_size = idx_size;
57059091 557 p->num_objects = nr;
1f688557
JH
558 return 0;
559}
560
bc8e478a 561int open_pack_index(struct packed_git *p)
d079837e
SP
562{
563 char *idx_name;
564 int ret;
565
566 if (p->index_data)
567 return 0;
568
569 idx_name = xstrdup(p->pack_name);
570 strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
571 ret = check_packed_git_idx(idx_name, p);
572 free(idx_name);
573 return ret;
574}
575
11daf39b
SP
576static void scan_windows(struct packed_git *p,
577 struct packed_git **lru_p,
578 struct pack_window **lru_w,
579 struct pack_window **lru_l)
1f688557 580{
11daf39b
SP
581 struct pack_window *w, *w_l;
582
583 for (w_l = NULL, w = p->windows; w; w = w->next) {
584 if (!w->inuse_cnt) {
585 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
586 *lru_p = p;
587 *lru_w = w;
588 *lru_l = w_l;
54044bf8 589 }
54044bf8 590 }
11daf39b 591 w_l = w;
f9253394 592 }
11daf39b
SP
593}
594
d1efefa4 595static int unuse_one_window(struct packed_git *current, int keep_fd)
11daf39b
SP
596{
597 struct packed_git *p, *lru_p = NULL;
598 struct pack_window *lru_w = NULL, *lru_l = NULL;
599
600 if (current)
601 scan_windows(current, &lru_p, &lru_w, &lru_l);
602 for (p = packed_git; p; p = p->next)
603 scan_windows(p, &lru_p, &lru_w, &lru_l);
54044bf8
SP
604 if (lru_p) {
605 munmap(lru_w->base, lru_w->len);
606 pack_mapped -= lru_w->len;
607 if (lru_l)
608 lru_l->next = lru_w->next;
609 else {
610 lru_p->windows = lru_w->next;
d1efefa4 611 if (!lru_p->windows && lru_p->pack_fd != keep_fd) {
54044bf8
SP
612 close(lru_p->pack_fd);
613 lru_p->pack_fd = -1;
614 }
615 }
616 free(lru_w);
a53128b6 617 pack_open_windows--;
54044bf8
SP
618 return 1;
619 }
620 return 0;
f9253394
JH
621}
622
d1efefa4 623void release_pack_memory(size_t need, int fd)
97bfeb34
SP
624{
625 size_t cur = pack_mapped;
d1efefa4 626 while (need >= (cur - pack_mapped) && unuse_one_window(NULL, fd))
97bfeb34
SP
627 ; /* nothing */
628}
629
c9ced051
SP
630void close_pack_windows(struct packed_git *p)
631{
632 while (p->windows) {
633 struct pack_window *w = p->windows;
634
635 if (w->inuse_cnt)
636 die("pack '%s' still has open windows to it",
637 p->pack_name);
638 munmap(w->base, w->len);
639 pack_mapped -= w->len;
640 pack_open_windows--;
641 p->windows = w->next;
642 free(w);
643 }
644}
645
03e79c88 646void unuse_pack(struct pack_window **w_cursor)
f9253394 647{
03e79c88
SP
648 struct pack_window *w = *w_cursor;
649 if (w) {
650 w->inuse_cnt--;
651 *w_cursor = NULL;
652 }
1f688557
JH
653}
654
3cf8b462
SP
655/*
656 * Do not call this directly as this leaks p->pack_fd on error return;
657 * call open_packed_git() instead.
658 */
659static int open_packed_git_1(struct packed_git *p)
1f688557 660{
9bc879c1
SP
661 struct stat st;
662 struct pack_header hdr;
663 unsigned char sha1[20];
664 unsigned char *idx_sha1;
2c039da8 665 long fd_flag;
9bc879c1 666
d079837e
SP
667 if (!p->index_data && open_pack_index(p))
668 return error("packfile %s index unavailable", p->pack_name);
669
9bc879c1
SP
670 p->pack_fd = open(p->pack_name, O_RDONLY);
671 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
072db278 672 return -1;
9bc879c1
SP
673
674 /* If we created the struct before we had the pack we lack size. */
bf592c50 675 if (!p->pack_size) {
bf592c50 676 if (!S_ISREG(st.st_mode))
072db278 677 return error("packfile %s not a regular file", p->pack_name);
bf592c50 678 p->pack_size = st.st_size;
9bc879c1 679 } else if (p->pack_size != st.st_size)
072db278 680 return error("packfile %s size changed", p->pack_name);
9bc879c1 681
2c039da8
JH
682 /* We leave these file descriptors open with sliding mmap;
683 * there is no point keeping them open across exec(), though.
684 */
685 fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
686 if (fd_flag < 0)
072db278 687 return error("cannot determine file descriptor flags");
2c039da8
JH
688 fd_flag |= FD_CLOEXEC;
689 if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
072db278 690 return error("cannot set FD_CLOEXEC");
2c039da8 691
9bc879c1 692 /* Verify we recognize this pack file format. */
e6e2bd62 693 if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
072db278 694 return error("file %s is far too short to be a packfile", p->pack_name);
9bc879c1 695 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
072db278 696 return error("file %s is not a GIT packfile", p->pack_name);
9bc879c1 697 if (!pack_version_ok(hdr.hdr_version))
6e1c2344
RJ
698 return error("packfile %s is version %"PRIu32" and not"
699 " supported (try upgrading GIT to a newer version)",
9bc879c1
SP
700 p->pack_name, ntohl(hdr.hdr_version));
701
702 /* Verify the pack matches its index. */
57059091 703 if (p->num_objects != ntohl(hdr.hdr_entries))
6e1c2344
RJ
704 return error("packfile %s claims to have %"PRIu32" objects"
705 " while index indicates %"PRIu32" objects",
57059091
NP
706 p->pack_name, ntohl(hdr.hdr_entries),
707 p->num_objects);
9bc879c1 708 if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
072db278 709 return error("end of packfile %s is unavailable", p->pack_name);
e6e2bd62 710 if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
072db278 711 return error("packfile %s signature is unavailable", p->pack_name);
42873078 712 idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
9bc879c1 713 if (hashcmp(sha1, idx_sha1))
072db278
SP
714 return error("packfile %s does not match index", p->pack_name);
715 return 0;
9bc879c1
SP
716}
717
3cf8b462
SP
718static int open_packed_git(struct packed_git *p)
719{
720 if (!open_packed_git_1(p))
721 return 0;
722 if (p->pack_fd != -1) {
723 close(p->pack_fd);
724 p->pack_fd = -1;
725 }
726 return -1;
727}
728
c4001d92 729static int in_window(struct pack_window *win, off_t offset)
60bb8b14
SP
730{
731 /* We must promise at least 20 bytes (one hash) after the
732 * offset is available from this window, otherwise the offset
733 * is not actually in this window and a different window (which
734 * has that one hash excess) must be used. This is to support
735 * the object header and delta base parsing routines below.
736 */
737 off_t win_off = win->offset;
738 return win_off <= offset
739 && (offset + 20) <= (win_off + win->len);
740}
741
03e79c88
SP
742unsigned char* use_pack(struct packed_git *p,
743 struct pack_window **w_cursor,
c4001d92 744 off_t offset,
03e79c88 745 unsigned int *left)
9bc879c1 746{
60bb8b14 747 struct pack_window *win = *w_cursor;
03e79c88 748
072db278
SP
749 if (p->pack_fd == -1 && open_packed_git(p))
750 die("packfile %s cannot be accessed", p->pack_name);
60bb8b14
SP
751
752 /* Since packfiles end in a hash of their content and its
753 * pointless to ask for an offset into the middle of that
754 * hash, and the in_window function above wouldn't match
755 * don't allow an offset too close to the end of the file.
756 */
757 if (offset > (p->pack_size - 20))
758 die("offset beyond end of packfile (truncated pack?)");
759
760 if (!win || !in_window(win, offset)) {
761 if (win)
762 win->inuse_cnt--;
763 for (win = p->windows; win; win = win->next) {
764 if (in_window(win, offset))
765 break;
766 }
767 if (!win) {
78a28df9 768 size_t window_align = packed_git_window_size / 2;
dc49cd76 769 off_t len;
60bb8b14 770 win = xcalloc(1, sizeof(*win));
78a28df9 771 win->offset = (offset / window_align) * window_align;
dc49cd76
SP
772 len = p->pack_size - win->offset;
773 if (len > packed_git_window_size)
774 len = packed_git_window_size;
775 win->len = (size_t)len;
60bb8b14 776 pack_mapped += win->len;
11daf39b 777 while (packed_git_limit < pack_mapped
d1efefa4 778 && unuse_one_window(p, p->pack_fd))
60bb8b14 779 ; /* nothing */
c4712e45 780 win->base = xmmap(NULL, win->len,
60bb8b14
SP
781 PROT_READ, MAP_PRIVATE,
782 p->pack_fd, win->offset);
783 if (win->base == MAP_FAILED)
73b4e4be
SP
784 die("packfile %s cannot be mapped: %s",
785 p->pack_name,
786 strerror(errno));
a53128b6
SP
787 pack_mmap_calls++;
788 pack_open_windows++;
789 if (pack_mapped > peak_pack_mapped)
790 peak_pack_mapped = pack_mapped;
791 if (pack_open_windows > peak_pack_open_windows)
792 peak_pack_open_windows = pack_open_windows;
60bb8b14
SP
793 win->next = p->windows;
794 p->windows = win;
795 }
1f688557 796 }
03e79c88
SP
797 if (win != *w_cursor) {
798 win->last_used = pack_used_ctr++;
799 win->inuse_cnt++;
800 *w_cursor = win;
801 }
60bb8b14 802 offset -= win->offset;
03e79c88 803 if (left)
dc49cd76 804 *left = win->len - xsize_t(offset);
03e79c88 805 return win->base + offset;
1f688557
JH
806}
807
27d69a46
NP
808static struct packed_git *alloc_packed_git(int extra)
809{
810 struct packed_git *p = xmalloc(sizeof(*p) + extra);
811 memset(p, 0, sizeof(*p));
812 p->pack_fd = -1;
813 return p;
814}
815
42873078 816struct packed_git *add_packed_git(const char *path, int path_len, int local)
1f688557
JH
817{
818 struct stat st;
27d69a46 819 struct packed_git *p = alloc_packed_git(path_len + 2);
1f688557 820
42873078
NP
821 /*
822 * Make sure a corresponding .pack file exists and that
823 * the index looks sane.
824 */
825 path_len -= strlen(".idx");
27d69a46
NP
826 if (path_len < 1) {
827 free(p);
1f688557 828 return NULL;
27d69a46 829 }
42873078 830 memcpy(p->pack_name, path, path_len);
8d25931d
BC
831
832 strcpy(p->pack_name + path_len, ".keep");
833 if (!access(p->pack_name, F_OK))
834 p->pack_keep = 1;
835
42873078 836 strcpy(p->pack_name + path_len, ".pack");
d079837e 837 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
42873078 838 free(p);
1f688557
JH
839 return NULL;
840 }
42873078 841
1f688557
JH
842 /* ok, it looks sane as far as we can check without
843 * actually mapping the pack file.
844 */
1f688557 845 p->pack_size = st.st_size;
9d835df2 846 p->pack_local = local;
b867092f 847 p->mtime = st.st_mtime;
42873078
NP
848 if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
849 hashclr(p->sha1);
1f688557
JH
850 return p;
851}
852
bf592c50 853struct packed_git *parse_pack_index(unsigned char *sha1)
c508df5e 854{
79c6dca4 855 const char *idx_path = sha1_pack_index_name(sha1);
42873078 856 const char *path = sha1_pack_name(sha1);
27d69a46 857 struct packed_git *p = alloc_packed_git(strlen(path) + 1);
bf592c50 858
27d69a46
NP
859 strcpy(p->pack_name, path);
860 hashcpy(p->sha1, sha1);
42873078
NP
861 if (check_packed_git_idx(idx_path, p)) {
862 free(p);
bf592c50 863 return NULL;
42873078 864 }
bf592c50 865
bf592c50
DB
866 return p;
867}
868
869void install_packed_git(struct packed_git *pack)
870{
871 pack->next = packed_git;
872 packed_git = pack;
873}
874
9d835df2 875static void prepare_packed_git_one(char *objdir, int local)
1f688557 876{
9cb18f56
JM
877 /* Ensure that this buffer is large enough so that we can
878 append "/pack/" without clobbering the stack even if
879 strlen(objdir) were PATH_MAX. */
880 char path[PATH_MAX + 1 + 4 + 1 + 1];
1f688557
JH
881 int len;
882 DIR *dir;
883 struct dirent *de;
884
885 sprintf(path, "%s/pack", objdir);
886 len = strlen(path);
887 dir = opendir(path);
b5b16990 888 if (!dir) {
26125f6b 889 if (errno != ENOENT)
bd2afde8 890 error("unable to open object pack directory: %s: %s",
26125f6b 891 path, strerror(errno));
1f688557 892 return;
b5b16990 893 }
1f688557
JH
894 path[len++] = '/';
895 while ((de = readdir(dir)) != NULL) {
896 int namelen = strlen(de->d_name);
897 struct packed_git *p;
898
5bb1cda5 899 if (!has_extension(de->d_name, ".idx"))
1f688557
JH
900 continue;
901
9cb18f56
JM
902 if (len + namelen + 1 > sizeof(path))
903 continue;
904
54a15a8d 905 /* Don't reopen a pack we already have. */
1f688557 906 strcpy(path + len, de->d_name);
86f7780c
JK
907 for (p = packed_git; p; p = p->next) {
908 if (!memcmp(path, p->pack_name, len + namelen - 4))
909 break;
910 }
911 if (p)
912 continue;
54a15a8d
SP
913 /* See if it really is a valid .idx file with corresponding
914 * .pack file that we can map.
915 */
9d835df2 916 p = add_packed_git(path, len + namelen, local);
1f688557
JH
917 if (!p)
918 continue;
625e9421 919 install_packed_git(p);
1f688557 920 }
5b35bcd5 921 closedir(dir);
1f688557
JH
922}
923
b867092f
JH
924static int sort_pack(const void *a_, const void *b_)
925{
926 struct packed_git *a = *((struct packed_git **)a_);
927 struct packed_git *b = *((struct packed_git **)b_);
928 int st;
929
930 /*
931 * Local packs tend to contain objects specific to our
932 * variant of the project than remote ones. In addition,
933 * remote ones could be on a network mounted filesystem.
934 * Favor local ones for these reasons.
935 */
936 st = a->pack_local - b->pack_local;
937 if (st)
938 return -st;
939
940 /*
941 * Younger packs tend to contain more recent objects,
942 * and more recent objects tend to get accessed more
943 * often.
944 */
945 if (a->mtime < b->mtime)
946 return 1;
947 else if (a->mtime == b->mtime)
948 return 0;
949 return -1;
950}
951
952static void rearrange_packed_git(void)
953{
954 struct packed_git **ary, *p;
955 int i, n;
956
957 for (n = 0, p = packed_git; p; p = p->next)
958 n++;
959 if (n < 2)
960 return;
961
962 /* prepare an array of packed_git for easier sorting */
963 ary = xcalloc(n, sizeof(struct packed_git *));
964 for (n = 0, p = packed_git; p; p = p->next)
965 ary[n++] = p;
966
967 qsort(ary, n, sizeof(struct packed_git *), sort_pack);
968
969 /* link them back again */
970 for (i = 0; i < n - 1; i++)
971 ary[i]->next = ary[i + 1];
972 ary[n - 1]->next = NULL;
973 packed_git = ary[0];
974
975 free(ary);
976}
977
637cdd9d 978static int prepare_packed_git_run_once = 0;
9a217f2a 979void prepare_packed_git(void)
1f688557 980{
d5a63b99 981 struct alternate_object_database *alt;
1f688557 982
637cdd9d 983 if (prepare_packed_git_run_once)
1f688557 984 return;
9d835df2 985 prepare_packed_git_one(get_object_directory(), 1);
9a217f2a 986 prepare_alt_odb();
d5a63b99 987 for (alt = alt_odb_list; alt; alt = alt->next) {
1494e038 988 alt->name[-1] = 0;
9d835df2 989 prepare_packed_git_one(alt->base, 0);
1494e038 990 alt->name[-1] = '/';
1f688557 991 }
b867092f 992 rearrange_packed_git();
637cdd9d
JK
993 prepare_packed_git_run_once = 1;
994}
995
fc04c412 996void reprepare_packed_git(void)
637cdd9d 997{
4b480c67 998 discard_revindex();
637cdd9d
JK
999 prepare_packed_git_run_once = 0;
1000 prepare_packed_git();
1f688557
JH
1001}
1002
8eca0b47
NP
1003static void mark_bad_packed_object(struct packed_git *p,
1004 const unsigned char *sha1)
1005{
1006 unsigned i;
1007 for (i = 0; i < p->num_bad_objects; i++)
1008 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1009 return;
1010 p->bad_object_sha1 = xrealloc(p->bad_object_sha1, 20 * (p->num_bad_objects + 1));
1011 hashcpy(p->bad_object_sha1 + 20 * p->num_bad_objects, sha1);
1012 p->num_bad_objects++;
1013}
1014
ac939109
NP
1015static int has_packed_and_bad(const unsigned char *sha1)
1016{
1017 struct packed_git *p;
1018 unsigned i;
1019
1020 for (p = packed_git; p; p = p->next)
1021 for (i = 0; i < p->num_bad_objects; i++)
1022 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1023 return 1;
1024 return 0;
1025}
1026
5d6ccf5c 1027int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
0fcfd160
LT
1028{
1029 unsigned char real_sha1[20];
7cfb5f36 1030 hash_sha1_file(map, size, type, real_sha1);
a89fccd2 1031 return hashcmp(sha1, real_sha1) ? -1 : 0;
0fcfd160
LT
1032}
1033
44d1c19e
LT
1034static int git_open_noatime(const char *name)
1035{
1036 static int sha1_file_open_flag = O_NOATIME;
1037 int fd = open(name, O_RDONLY | sha1_file_open_flag);
1038
1039 /* Might the failure be due to O_NOATIME? */
1040 if (fd < 0 && errno != ENOENT && sha1_file_open_flag) {
1041 fd = open(name, O_RDONLY);
1042 if (fd >= 0)
1043 sha1_file_open_flag = 0;
1044 }
1045 return fd;
1046}
1047
1048static int open_sha1_file(const unsigned char *sha1)
1049{
1050 int fd;
1051 char *name = sha1_file_name(sha1);
1052 struct alternate_object_database *alt;
1053
1054 fd = git_open_noatime(name);
1055 if (fd >= 0)
1056 return fd;
1057
1058 prepare_alt_odb();
1059 errno = ENOENT;
1060 for (alt = alt_odb_list; alt; alt = alt->next) {
1061 name = alt->name;
1062 fill_sha1_path(name, sha1);
1063 fd = git_open_noatime(alt->base);
1064 if (fd >= 0)
1065 return fd;
1066 }
1067 return -1;
1068}
1069
4175e9e3 1070static void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
0fcfd160 1071{
0fcfd160 1072 void *map;
144bde78 1073 int fd;
ace1534d 1074
44d1c19e
LT
1075 fd = open_sha1_file(sha1);
1076 map = NULL;
1077 if (fd >= 0) {
1078 struct stat st;
0fcfd160 1079
44d1c19e
LT
1080 if (!fstat(fd, &st)) {
1081 *size = xsize_t(st.st_size);
1082 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
144bde78 1083 }
44d1c19e 1084 close(fd);
0fcfd160 1085 }
0fcfd160
LT
1086 return map;
1087}
1088
726f852b 1089static int legacy_loose_object(unsigned char *map)
bb6b8e4f
JH
1090{
1091 unsigned int word;
1092
1093 /*
1094 * Is it a zlib-compressed buffer? If so, the first byte
1095 * must be 0x78 (15-bit window size, deflated), and the
1096 * first 16-bit word is evenly divisible by 31
1097 */
1098 word = (map[0] << 8) + map[1];
1099 if (map[0] == 0x78 && !(word % 31))
1100 return 1;
1101 else
1102 return 0;
1103}
1104
72518e9c 1105unsigned long unpack_object_header_gently(const unsigned char *buf, unsigned long len, enum object_type *type, unsigned long *sizep)
c4483576 1106{
ad1ed5ee 1107 unsigned shift;
93821bd9 1108 unsigned char c;
93821bd9 1109 unsigned long size;
ad1ed5ee
JH
1110 unsigned long used = 0;
1111
1112 c = buf[used++];
1113 *type = (c >> 4) & 7;
1114 size = c & 15;
1115 shift = 4;
1116 while (c & 0x80) {
1117 if (len <= used)
1118 return 0;
1119 if (sizeof(long) * 8 <= shift)
1120 return 0;
1121 c = buf[used++];
1122 size += (c & 0x7f) << shift;
1123 shift += 7;
1124 }
1125 *sizep = size;
1126 return used;
1127}
1128
1129static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1130{
1131 unsigned long size, used;
1132 static const char valid_loose_object_type[8] = {
1133 0, /* OBJ_EXT */
1134 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1135 0, /* "delta" and others are invalid in a loose object */
93821bd9 1136 };
ad1ed5ee 1137 enum object_type type;
93821bd9 1138
c4483576
LT
1139 /* Get the data stream */
1140 memset(stream, 0, sizeof(*stream));
1141 stream->next_in = map;
1142 stream->avail_in = mapsize;
1143 stream->next_out = buffer;
93821bd9
LT
1144 stream->avail_out = bufsiz;
1145
bb6b8e4f 1146 if (legacy_loose_object(map)) {
93821bd9
LT
1147 inflateInit(stream);
1148 return inflate(stream, 0);
1149 }
1150
726f852b
NP
1151
1152 /*
1153 * There used to be a second loose object header format which
1154 * was meant to mimic the in-pack format, allowing for direct
1155 * copy of the object data. This format turned up not to be
1156 * really worth it and we don't write it any longer. But we
1157 * can still read it.
1158 */
ad1ed5ee
JH
1159 used = unpack_object_header_gently(map, mapsize, &type, &size);
1160 if (!used || !valid_loose_object_type[type])
93821bd9 1161 return -1;
ad1ed5ee
JH
1162 map += used;
1163 mapsize -= used;
93821bd9
LT
1164
1165 /* Set up the stream for the rest.. */
1166 stream->next_in = map;
1167 stream->avail_in = mapsize;
c4483576 1168 inflateInit(stream);
93821bd9
LT
1169
1170 /* And generate the fake traditional header */
ad1ed5ee 1171 stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
df843662 1172 typename(type), size);
93821bd9 1173 return 0;
c4483576
LT
1174}
1175
7efbff75 1176static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
5180cacc
LT
1177{
1178 int bytes = strlen(buffer) + 1;
d565b341 1179 unsigned char *buf = xmalloc(1+size);
93821bd9 1180 unsigned long n;
7efbff75 1181 int status = Z_OK;
5180cacc 1182
93821bd9
LT
1183 n = stream->total_out - bytes;
1184 if (n > size)
1185 n = size;
1186 memcpy(buf, (char *) buffer + bytes, n);
1187 bytes = n;
456cdf6e
LT
1188 if (bytes <= size) {
1189 /*
1190 * The above condition must be (bytes <= size), not
1191 * (bytes < size). In other words, even though we
1192 * expect no more output and set avail_out to zer0,
1193 * the input zlib stream may have bytes that express
1194 * "this concludes the stream", and we *do* want to
1195 * eat that input.
1196 *
1197 * Otherwise we would not be able to test that we
1198 * consumed all the input to reach the expected size;
1199 * we also want to check that zlib tells us that all
1200 * went well with status == Z_STREAM_END at the end.
1201 */
5180cacc
LT
1202 stream->next_out = buf + bytes;
1203 stream->avail_out = size - bytes;
7efbff75
JH
1204 while (status == Z_OK)
1205 status = inflate(stream, Z_FINISH);
5180cacc
LT
1206 }
1207 buf[size] = 0;
456cdf6e 1208 if (status == Z_STREAM_END && !stream->avail_in) {
7efbff75
JH
1209 inflateEnd(stream);
1210 return buf;
1211 }
1212
1213 if (status < 0)
1214 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1215 else if (stream->avail_in)
1216 error("garbage at end of loose object '%s'",
1217 sha1_to_hex(sha1));
1218 free(buf);
1219 return NULL;
5180cacc
LT
1220}
1221
1222/*
1223 * We used to just use "sscanf()", but that's actually way
1224 * too permissive for what we want to check. So do an anal
1225 * object header parse by hand.
1226 */
21666f1a 1227static int parse_sha1_header(const char *hdr, unsigned long *sizep)
5180cacc 1228{
21666f1a 1229 char type[10];
5180cacc
LT
1230 int i;
1231 unsigned long size;
1232
1233 /*
a6080a0a 1234 * The type can be at most ten bytes (including the
5180cacc 1235 * terminating '\0' that we add), and is followed by
21666f1a 1236 * a space.
5180cacc 1237 */
21666f1a 1238 i = 0;
5180cacc
LT
1239 for (;;) {
1240 char c = *hdr++;
1241 if (c == ' ')
1242 break;
21666f1a
NP
1243 type[i++] = c;
1244 if (i >= sizeof(type))
5180cacc 1245 return -1;
5180cacc 1246 }
21666f1a 1247 type[i] = 0;
5180cacc
LT
1248
1249 /*
1250 * The length must follow immediately, and be in canonical
1251 * decimal format (ie "010" is not valid).
1252 */
1253 size = *hdr++ - '0';
1254 if (size > 9)
1255 return -1;
1256 if (size) {
1257 for (;;) {
1258 unsigned long c = *hdr - '0';
1259 if (c > 9)
1260 break;
1261 hdr++;
1262 size = size * 10 + c;
1263 }
1264 }
1265 *sizep = size;
1266
1267 /*
1268 * The length must be followed by a zero byte
1269 */
21666f1a 1270 return *hdr ? -1 : type_from_string(type);
5180cacc
LT
1271}
1272
7efbff75 1273static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
0fcfd160 1274{
5180cacc 1275 int ret;
0fcfd160 1276 z_stream stream;
5180cacc 1277 char hdr[8192];
0fcfd160 1278
5180cacc 1279 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
21666f1a 1280 if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
0fcfd160
LT
1281 return NULL;
1282
7efbff75 1283 return unpack_sha1_rest(&stream, hdr, *size, sha1);
0fcfd160
LT
1284}
1285
54dab52a
NP
1286unsigned long get_size_from_delta(struct packed_git *p,
1287 struct pack_window **w_curs,
1288 off_t curpos)
1289{
1290 const unsigned char *data;
1291 unsigned char delta_head[20], *in;
1292 z_stream stream;
1293 int st;
1294
1295 memset(&stream, 0, sizeof(stream));
1296 stream.next_out = delta_head;
1297 stream.avail_out = sizeof(delta_head);
1298
1299 inflateInit(&stream);
1300 do {
1301 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1302 stream.next_in = in;
1303 st = inflate(&stream, Z_FINISH);
1304 curpos += stream.next_in - in;
1305 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1306 stream.total_out < sizeof(delta_head));
1307 inflateEnd(&stream);
1308 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head))
1309 die("delta data unpack-initial failed");
1310
1311 /* Examine the initial part of the delta to figure out
1312 * the result size.
1313 */
1314 data = delta_head;
1315
1316 /* ignore base size */
1317 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1318
1319 /* Read the result size */
1320 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1321}
1322
c4001d92 1323static off_t get_delta_base(struct packed_git *p,
03e79c88 1324 struct pack_window **w_curs,
c4001d92 1325 off_t *curpos,
21666f1a 1326 enum object_type type,
c4001d92 1327 off_t delta_obj_offset)
eb32d236 1328{
2b87c45b 1329 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
c4001d92 1330 off_t base_offset;
eb32d236 1331
8d8a4ea5
SP
1332 /* use_pack() assured us we have [base_info, base_info + 20)
1333 * as a range that we can look at without walking off the
1334 * end of the mapped window. Its actually the hash size
1335 * that is assured. An OFS_DELTA longer than the hash size
1336 * is stupid, as then a REF_DELTA would be smaller to store.
1337 */
21666f1a 1338 if (type == OBJ_OFS_DELTA) {
eb32d236
NP
1339 unsigned used = 0;
1340 unsigned char c = base_info[used++];
1341 base_offset = c & 127;
1342 while (c & 128) {
1343 base_offset += 1;
8723f216 1344 if (!base_offset || MSB(base_offset, 7))
8eca0b47 1345 return 0; /* overflow */
eb32d236
NP
1346 c = base_info[used++];
1347 base_offset = (base_offset << 7) + (c & 127);
1348 }
1349 base_offset = delta_obj_offset - base_offset;
1350 if (base_offset >= delta_obj_offset)
8eca0b47 1351 return 0; /* out of bound */
2b87c45b 1352 *curpos += used;
21666f1a 1353 } else if (type == OBJ_REF_DELTA) {
eb32d236
NP
1354 /* The base entry _must_ be in the same pack */
1355 base_offset = find_pack_entry_one(base_info, p);
2b87c45b 1356 *curpos += 20;
eb32d236
NP
1357 } else
1358 die("I am totally screwed");
2b87c45b 1359 return base_offset;
eb32d236
NP
1360}
1361
f3bf9224 1362/* forward declaration for a mutually recursive function */
c4001d92 1363static int packed_object_info(struct packed_git *p, off_t offset,
21666f1a 1364 unsigned long *sizep);
f3bf9224 1365
43057304 1366static int packed_delta_info(struct packed_git *p,
03e79c88 1367 struct pack_window **w_curs,
c4001d92 1368 off_t curpos,
21666f1a 1369 enum object_type type,
c4001d92 1370 off_t obj_offset,
43057304 1371 unsigned long *sizep)
5db47c2b 1372{
c4001d92 1373 off_t base_offset;
f3bf9224 1374
21666f1a
NP
1375 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1376 type = packed_object_info(p, base_offset, NULL);
f3bf9224 1377
c62266f3
JH
1378 /* We choose to only get the type of the base object and
1379 * ignore potentially corrupt pack file that expects the delta
1380 * based on a base with a wrong size. This saves tons of
1381 * inflate() calls.
1382 */
54dab52a
NP
1383 if (sizep)
1384 *sizep = get_size_from_delta(p, w_curs, curpos);
21666f1a
NP
1385
1386 return type;
5db47c2b
JH
1387}
1388
2b87c45b
NP
1389static int unpack_object_header(struct packed_git *p,
1390 struct pack_window **w_curs,
c4001d92 1391 off_t *curpos,
2b87c45b 1392 unsigned long *sizep)
a733cb60 1393{
03e79c88
SP
1394 unsigned char *base;
1395 unsigned int left;
ad1ed5ee 1396 unsigned long used;
2b87c45b 1397 enum object_type type;
a733cb60 1398
8d8a4ea5
SP
1399 /* use_pack() assures us we have [base, base + 20) available
1400 * as a range that we can look at at. (Its actually the hash
3dff5379 1401 * size that is assured.) With our object header encoding
8d8a4ea5
SP
1402 * the maximum deflated object size is 2^137, which is just
1403 * insane, so we know won't exceed what we have been given.
1404 */
2b87c45b
NP
1405 base = use_pack(p, w_curs, *curpos, &left);
1406 used = unpack_object_header_gently(base, left, &type, sizep);
ad1ed5ee
JH
1407 if (!used)
1408 die("object offset outside of pack file");
2b87c45b 1409 *curpos += used;
ad1ed5ee 1410
2b87c45b 1411 return type;
a733cb60
LT
1412}
1413
21666f1a 1414const char *packed_object_info_detail(struct packed_git *p,
c4001d92 1415 off_t obj_offset,
21666f1a
NP
1416 unsigned long *size,
1417 unsigned long *store_size,
1418 unsigned int *delta_chain_length,
1419 unsigned char *base_sha1)
ad8c80a5 1420{
03e79c88 1421 struct pack_window *w_curs = NULL;
c4001d92
SP
1422 off_t curpos;
1423 unsigned long dummy;
43057304 1424 unsigned char *next_sha1;
21666f1a 1425 enum object_type type;
70f5d5d3 1426 struct revindex_entry *revidx;
ad8c80a5 1427
43057304 1428 *delta_chain_length = 0;
2b87c45b 1429 curpos = obj_offset;
21666f1a 1430 type = unpack_object_header(p, &w_curs, &curpos, size);
43057304 1431
70f5d5d3
NP
1432 revidx = find_pack_revindex(p, obj_offset);
1433 *store_size = revidx[1].offset - obj_offset;
1434
43057304 1435 for (;;) {
21666f1a 1436 switch (type) {
43057304 1437 default:
08a19d87 1438 die("pack %s contains unknown object type %d",
21666f1a 1439 p->pack_name, type);
43057304
NP
1440 case OBJ_COMMIT:
1441 case OBJ_TREE:
1442 case OBJ_BLOB:
1443 case OBJ_TAG:
03e79c88 1444 unuse_pack(&w_curs);
21666f1a 1445 return typename(type);
eb32d236 1446 case OBJ_OFS_DELTA:
21666f1a 1447 obj_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
8eca0b47
NP
1448 if (!obj_offset)
1449 die("pack %s contains bad delta base reference of type %s",
1450 p->pack_name, typename(type));
eb32d236 1451 if (*delta_chain_length == 0) {
70f5d5d3
NP
1452 revidx = find_pack_revindex(p, obj_offset);
1453 hashcpy(base_sha1, nth_packed_object_sha1(p, revidx->nr));
eb32d236
NP
1454 }
1455 break;
1456 case OBJ_REF_DELTA:
2b87c45b 1457 next_sha1 = use_pack(p, &w_curs, curpos, NULL);
43057304
NP
1458 if (*delta_chain_length == 0)
1459 hashcpy(base_sha1, next_sha1);
2b87c45b 1460 obj_offset = find_pack_entry_one(next_sha1, p);
43057304
NP
1461 break;
1462 }
43057304 1463 (*delta_chain_length)++;
2b87c45b 1464 curpos = obj_offset;
21666f1a 1465 type = unpack_object_header(p, &w_curs, &curpos, &dummy);
ad8c80a5 1466 }
ad8c80a5
JH
1467}
1468
c4001d92 1469static int packed_object_info(struct packed_git *p, off_t obj_offset,
21666f1a 1470 unsigned long *sizep)
1f688557 1471{
03e79c88 1472 struct pack_window *w_curs = NULL;
c4001d92
SP
1473 unsigned long size;
1474 off_t curpos = obj_offset;
21666f1a 1475 enum object_type type;
5db47c2b 1476
21666f1a 1477 type = unpack_object_header(p, &w_curs, &curpos, &size);
5db47c2b 1478
21666f1a 1479 switch (type) {
eb32d236
NP
1480 case OBJ_OFS_DELTA:
1481 case OBJ_REF_DELTA:
21666f1a
NP
1482 type = packed_delta_info(p, &w_curs, curpos,
1483 type, obj_offset, sizep);
2b87c45b 1484 break;
a733cb60 1485 case OBJ_COMMIT:
a733cb60 1486 case OBJ_TREE:
a733cb60 1487 case OBJ_BLOB:
a733cb60 1488 case OBJ_TAG:
2b87c45b
NP
1489 if (sizep)
1490 *sizep = size;
a69d0943 1491 break;
1f688557 1492 default:
08a19d87 1493 die("pack %s contains unknown object type %d",
21666f1a 1494 p->pack_name, type);
1f688557 1495 }
2b87c45b 1496 unuse_pack(&w_curs);
21666f1a 1497 return type;
1f688557
JH
1498}
1499
eb950c19 1500static void *unpack_compressed_entry(struct packed_git *p,
03e79c88 1501 struct pack_window **w_curs,
c4001d92 1502 off_t curpos,
eb950c19 1503 unsigned long size)
de530aaa
SP
1504{
1505 int st;
1506 z_stream stream;
079afb18 1507 unsigned char *buffer, *in;
de530aaa
SP
1508
1509 buffer = xmalloc(size + 1);
1510 buffer[size] = 0;
1511 memset(&stream, 0, sizeof(stream));
de530aaa
SP
1512 stream.next_out = buffer;
1513 stream.avail_out = size;
1514
1515 inflateInit(&stream);
079afb18 1516 do {
2b87c45b 1517 in = use_pack(p, w_curs, curpos, &stream.avail_in);
079afb18
SP
1518 stream.next_in = in;
1519 st = inflate(&stream, Z_FINISH);
2b87c45b 1520 curpos += stream.next_in - in;
079afb18 1521 } while (st == Z_OK || st == Z_BUF_ERROR);
de530aaa
SP
1522 inflateEnd(&stream);
1523 if ((st != Z_STREAM_END) || stream.total_out != size) {
1524 free(buffer);
1525 return NULL;
1526 }
1527
1528 return buffer;
1529}
1530
e5e01619
LT
1531#define MAX_DELTA_CACHE (256)
1532
18bdec11 1533static size_t delta_base_cached;
5e08ecbf
NP
1534
1535static struct delta_base_cache_lru_list {
1536 struct delta_base_cache_lru_list *prev;
1537 struct delta_base_cache_lru_list *next;
1538} delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1539
e5e01619 1540static struct delta_base_cache_entry {
5e08ecbf
NP
1541 struct delta_base_cache_lru_list lru;
1542 void *data;
e5e01619
LT
1543 struct packed_git *p;
1544 off_t base_offset;
1545 unsigned long size;
e5e01619
LT
1546 enum object_type type;
1547} delta_base_cache[MAX_DELTA_CACHE];
1548
1549static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1550{
1551 unsigned long hash;
1552
1553 hash = (unsigned long)p + (unsigned long)base_offset;
1554 hash += (hash >> 8) + (hash >> 16);
3358004a 1555 return hash % MAX_DELTA_CACHE;
e5e01619
LT
1556}
1557
62f255ad 1558static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
a0cba108 1559 unsigned long *base_size, enum object_type *type, int keep_cache)
62f255ad 1560{
e5e01619
LT
1561 void *ret;
1562 unsigned long hash = pack_entry_hash(p, base_offset);
1563 struct delta_base_cache_entry *ent = delta_base_cache + hash;
1564
1565 ret = ent->data;
1566 if (ret && ent->p == p && ent->base_offset == base_offset)
1567 goto found_cache_entry;
62f255ad 1568 return unpack_entry(p, base_offset, type, base_size);
e5e01619
LT
1569
1570found_cache_entry:
18bdec11 1571 if (!keep_cache) {
a0cba108 1572 ent->data = NULL;
5e08ecbf
NP
1573 ent->lru.next->prev = ent->lru.prev;
1574 ent->lru.prev->next = ent->lru.next;
18bdec11 1575 delta_base_cached -= ent->size;
182af834
PH
1576 } else {
1577 ret = xmemdupz(ent->data, ent->size);
a0cba108 1578 }
e5e01619
LT
1579 *type = ent->type;
1580 *base_size = ent->size;
1581 return ret;
62f255ad
LT
1582}
1583
18bdec11
SP
1584static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1585{
1586 if (ent->data) {
1587 free(ent->data);
1588 ent->data = NULL;
5e08ecbf
NP
1589 ent->lru.next->prev = ent->lru.prev;
1590 ent->lru.prev->next = ent->lru.next;
18bdec11
SP
1591 delta_base_cached -= ent->size;
1592 }
1593}
1594
62f255ad
LT
1595static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1596 void *base, unsigned long base_size, enum object_type type)
1597{
5e08ecbf 1598 unsigned long hash = pack_entry_hash(p, base_offset);
e5e01619 1599 struct delta_base_cache_entry *ent = delta_base_cache + hash;
5e08ecbf 1600 struct delta_base_cache_lru_list *lru;
e5e01619 1601
18bdec11
SP
1602 release_delta_base_cache(ent);
1603 delta_base_cached += base_size;
5e08ecbf
NP
1604
1605 for (lru = delta_base_cache_lru.next;
1606 delta_base_cached > delta_base_cache_limit
1607 && lru != &delta_base_cache_lru;
1608 lru = lru->next) {
1609 struct delta_base_cache_entry *f = (void *)lru;
18bdec11
SP
1610 if (f->type == OBJ_BLOB)
1611 release_delta_base_cache(f);
1612 }
5e08ecbf
NP
1613 for (lru = delta_base_cache_lru.next;
1614 delta_base_cached > delta_base_cache_limit
1615 && lru != &delta_base_cache_lru;
1616 lru = lru->next) {
1617 struct delta_base_cache_entry *f = (void *)lru;
1618 release_delta_base_cache(f);
1619 }
18bdec11 1620
e5e01619
LT
1621 ent->p = p;
1622 ent->base_offset = base_offset;
1623 ent->type = type;
1624 ent->data = base;
1625 ent->size = base_size;
5e08ecbf
NP
1626 ent->lru.next = &delta_base_cache_lru;
1627 ent->lru.prev = delta_base_cache_lru.prev;
1628 delta_base_cache_lru.prev->next = &ent->lru;
1629 delta_base_cache_lru.prev = &ent->lru;
62f255ad
LT
1630}
1631
eb950c19 1632static void *unpack_delta_entry(struct packed_git *p,
03e79c88 1633 struct pack_window **w_curs,
c4001d92 1634 off_t curpos,
1f688557 1635 unsigned long delta_size,
c4001d92 1636 off_t obj_offset,
21666f1a 1637 enum object_type *type,
eb950c19 1638 unsigned long *sizep)
1f688557 1639{
7c3e8be3 1640 void *delta_data, *result, *base;
c4001d92
SP
1641 unsigned long base_size;
1642 off_t base_offset;
43057304 1643
21666f1a 1644 base_offset = get_delta_base(p, w_curs, &curpos, *type, obj_offset);
8eca0b47
NP
1645 if (!base_offset) {
1646 error("failed to validate delta base reference "
1647 "at offset %"PRIuMAX" from %s",
1648 (uintmax_t)curpos, p->pack_name);
1649 return NULL;
1650 }
eac12e2d 1651 unuse_pack(w_curs);
a0cba108 1652 base = cache_or_unpack_entry(p, base_offset, &base_size, type, 0);
8eca0b47
NP
1653 if (!base) {
1654 /*
1655 * We're probably in deep shit, but let's try to fetch
1656 * the required base anyway from another pack or loose.
1657 * This is costly but should happen only in the presence
1658 * of a corrupted pack, and is better than failing outright.
1659 */
1660 struct revindex_entry *revidx = find_pack_revindex(p, base_offset);
1661 const unsigned char *base_sha1 =
1662 nth_packed_object_sha1(p, revidx->nr);
1663 error("failed to read delta base object %s"
1664 " at offset %"PRIuMAX" from %s",
1665 sha1_to_hex(base_sha1), (uintmax_t)base_offset,
1666 p->pack_name);
1667 mark_bad_packed_object(p, base_sha1);
ac939109 1668 base = read_object(base_sha1, type, &base_size);
8eca0b47
NP
1669 if (!base)
1670 return NULL;
1671 }
67686d95 1672
2b87c45b 1673 delta_data = unpack_compressed_entry(p, w_curs, curpos, delta_size);
8eca0b47
NP
1674 if (!delta_data) {
1675 error("failed to unpack compressed delta "
1676 "at offset %"PRIuMAX" from %s",
1677 (uintmax_t)curpos, p->pack_name);
1678 free(base);
1679 return NULL;
1680 }
1f688557
JH
1681 result = patch_delta(base, base_size,
1682 delta_data, delta_size,
21666f1a 1683 sizep);
1f688557
JH
1684 if (!result)
1685 die("failed to apply delta");
1686 free(delta_data);
62f255ad 1687 add_delta_base_cache(p, base_offset, base, base_size, *type);
1f688557
JH
1688 return result;
1689}
1690
c4001d92 1691void *unpack_entry(struct packed_git *p, off_t obj_offset,
21666f1a 1692 enum object_type *type, unsigned long *sizep)
1f688557 1693{
03e79c88 1694 struct pack_window *w_curs = NULL;
c4001d92 1695 off_t curpos = obj_offset;
21666f1a 1696 void *data;
1f688557 1697
21666f1a
NP
1698 *type = unpack_object_header(p, &w_curs, &curpos, sizep);
1699 switch (*type) {
eb32d236
NP
1700 case OBJ_OFS_DELTA:
1701 case OBJ_REF_DELTA:
21666f1a
NP
1702 data = unpack_delta_entry(p, &w_curs, curpos, *sizep,
1703 obj_offset, type, sizep);
4d703a1a 1704 break;
a733cb60 1705 case OBJ_COMMIT:
a733cb60 1706 case OBJ_TREE:
a733cb60 1707 case OBJ_BLOB:
a733cb60 1708 case OBJ_TAG:
21666f1a 1709 data = unpack_compressed_entry(p, &w_curs, curpos, *sizep);
4d703a1a 1710 break;
1f688557 1711 default:
8eca0b47
NP
1712 data = NULL;
1713 error("unknown object type %i at offset %"PRIuMAX" in %s",
1714 *type, (uintmax_t)obj_offset, p->pack_name);
1f688557 1715 }
03e79c88 1716 unuse_pack(&w_curs);
21666f1a 1717 return data;
1f688557
JH
1718}
1719
d079837e 1720const unsigned char *nth_packed_object_sha1(struct packed_git *p,
d72308e0 1721 uint32_t n)
9a217f2a 1722{
42873078 1723 const unsigned char *index = p->index_data;
d079837e
SP
1724 if (!index) {
1725 if (open_pack_index(p))
1726 return NULL;
1727 index = p->index_data;
1728 }
57059091 1729 if (n >= p->num_objects)
d72308e0 1730 return NULL;
74e34e1f
NP
1731 index += 4 * 256;
1732 if (p->index_version == 1) {
1733 return index + 24 * n + 4;
1734 } else {
1735 index += 8;
1736 return index + 20 * n;
1737 }
1738}
1739
99093238 1740off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
74e34e1f
NP
1741{
1742 const unsigned char *index = p->index_data;
1743 index += 4 * 256;
1744 if (p->index_version == 1) {
1745 return ntohl(*((uint32_t *)(index + 24 * n)));
1746 } else {
1747 uint32_t off;
1748 index += 8 + p->num_objects * (20 + 4);
1749 off = ntohl(*((uint32_t *)(index + 4 * n)));
1750 if (!(off & 0x80000000))
1751 return off;
1752 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1753 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
1754 ntohl(*((uint32_t *)(index + 4)));
1755 }
9a217f2a
JH
1756}
1757
c4001d92 1758off_t find_pack_entry_one(const unsigned char *sha1,
43057304 1759 struct packed_git *p)
1f688557 1760{
42873078 1761 const uint32_t *level1_ofs = p->index_data;
42873078 1762 const unsigned char *index = p->index_data;
628522ec
JH
1763 unsigned hi, lo, stride;
1764 static int use_lookup = -1;
1765 static int debug_lookup = -1;
1766
1767 if (debug_lookup < 0)
1768 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
42873078 1769
d079837e
SP
1770 if (!index) {
1771 if (open_pack_index(p))
1772 return 0;
1773 level1_ofs = p->index_data;
1774 index = p->index_data;
1775 }
74e34e1f
NP
1776 if (p->index_version > 1) {
1777 level1_ofs += 2;
1778 index += 8;
1779 }
42873078 1780 index += 4 * 256;
74e34e1f
NP
1781 hi = ntohl(level1_ofs[*sha1]);
1782 lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
628522ec
JH
1783 if (p->index_version > 1) {
1784 stride = 20;
1785 } else {
1786 stride = 24;
1787 index += 4;
1788 }
1789
1790 if (debug_lookup)
6e1c2344 1791 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
628522ec
JH
1792 sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
1793
1794 if (use_lookup < 0)
1795 use_lookup = !!getenv("GIT_USE_LOOKUP");
1796 if (use_lookup) {
1797 int pos = sha1_entry_pos(index, stride, 0,
1798 lo, hi, p->num_objects, sha1);
1799 if (pos < 0)
1800 return 0;
1801 return nth_packed_object_offset(p, pos);
1802 }
1f688557
JH
1803
1804 do {
74e34e1f 1805 unsigned mi = (lo + hi) / 2;
628522ec
JH
1806 int cmp = hashcmp(index + mi * stride, sha1);
1807
1808 if (debug_lookup)
1809 printf("lo %u hi %u rg %u mi %u\n",
1810 lo, hi, hi - lo, mi);
43057304 1811 if (!cmp)
74e34e1f 1812 return nth_packed_object_offset(p, mi);
1f688557
JH
1813 if (cmp > 0)
1814 hi = mi;
1815 else
1816 lo = mi+1;
1817 } while (lo < hi);
1818 return 0;
1819}
1820
000dfd3f 1821int matches_pack_name(struct packed_git *p, const char *name)
d4ff6d92
SP
1822{
1823 const char *last_c, *c;
1824
000dfd3f
JH
1825 if (!strcmp(p->pack_name, name))
1826 return 1;
d4ff6d92
SP
1827
1828 for (c = p->pack_name, last_c = c; *c;)
1829 if (*c == '/')
1830 last_c = ++c;
1831 else
1832 ++c;
000dfd3f
JH
1833 if (!strcmp(last_c, name))
1834 return 1;
d4ff6d92 1835
000dfd3f 1836 return 0;
d4ff6d92
SP
1837}
1838
106d710b 1839static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e, const char **ignore_packed)
1f688557 1840{
f7c22cc6 1841 static struct packed_git *last_found = (void *)1;
1f688557 1842 struct packed_git *p;
c4001d92 1843 off_t offset;
43057304 1844
1f688557 1845 prepare_packed_git();
f7c22cc6
NP
1846 if (!packed_git)
1847 return 0;
1848 p = (last_found == (void *)1) ? packed_git : last_found;
1f688557 1849
f7c22cc6 1850 do {
106d710b
JH
1851 if (ignore_packed) {
1852 const char **ig;
1853 for (ig = ignore_packed; *ig; ig++)
000dfd3f 1854 if (matches_pack_name(p, *ig))
106d710b
JH
1855 break;
1856 if (*ig)
f7c22cc6 1857 goto next;
106d710b 1858 }
f7c22cc6 1859
8eca0b47
NP
1860 if (p->num_bad_objects) {
1861 unsigned i;
1862 for (i = 0; i < p->num_bad_objects; i++)
1863 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1864 goto next;
1865 }
1866
43057304
NP
1867 offset = find_pack_entry_one(sha1, p);
1868 if (offset) {
c715f783
SP
1869 /*
1870 * We are about to tell the caller where they can
1871 * locate the requested object. We better make
1872 * sure the packfile is still here and can be
1873 * accessed before supplying that answer, as
1874 * it may have been deleted since the index
1875 * was loaded!
1876 */
1877 if (p->pack_fd == -1 && open_packed_git(p)) {
1878 error("packfile %s cannot be accessed", p->pack_name);
f7c22cc6 1879 goto next;
c715f783 1880 }
43057304
NP
1881 e->offset = offset;
1882 e->p = p;
1883 hashcpy(e->sha1, sha1);
f7c22cc6 1884 last_found = p;
1f688557 1885 return 1;
43057304 1886 }
f7c22cc6
NP
1887
1888 next:
1889 if (p == last_found)
1890 p = packed_git;
1891 else
1892 p = p->next;
1893 if (p == last_found)
1894 p = p->next;
1895 } while (p);
1f688557
JH
1896 return 0;
1897}
1898
a6080a0a 1899struct packed_git *find_sha1_pack(const unsigned char *sha1,
bf592c50
DB
1900 struct packed_git *packs)
1901{
1902 struct packed_git *p;
bf592c50
DB
1903
1904 for (p = packs; p; p = p->next) {
43057304 1905 if (find_pack_entry_one(sha1, p))
bf592c50
DB
1906 return p;
1907 }
1908 return NULL;
21666f1a 1909
bf592c50
DB
1910}
1911
21666f1a 1912static int sha1_loose_object_info(const unsigned char *sha1, unsigned long *sizep)
65c2e0c3 1913{
36e4d74a 1914 int status;
65c2e0c3
JH
1915 unsigned long mapsize, size;
1916 void *map;
1917 z_stream stream;
d65a16f6 1918 char hdr[32];
65c2e0c3 1919
bb6b8e4f 1920 map = map_sha1_file(sha1, &mapsize);
f0df4ed5
JS
1921 if (!map)
1922 return error("unable to find %s", sha1_to_hex(sha1));
36e4d74a
JH
1923 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1924 status = error("unable to unpack %s header",
1925 sha1_to_hex(sha1));
21666f1a 1926 else if ((status = parse_sha1_header(hdr, &size)) < 0)
36e4d74a 1927 status = error("unable to parse %s header", sha1_to_hex(sha1));
21666f1a
NP
1928 else if (sizep)
1929 *sizep = size;
65c2e0c3
JH
1930 inflateEnd(&stream);
1931 munmap(map, mapsize);
1932 return status;
1933}
1934
21666f1a 1935int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
f0df4ed5 1936{
f0df4ed5 1937 struct pack_entry e;
ddd63e64 1938 int status;
f0df4ed5
JS
1939
1940 if (!find_pack_entry(sha1, &e, NULL)) {
ddd63e64
SG
1941 /* Most likely it's a loose object. */
1942 status = sha1_loose_object_info(sha1, sizep);
1943 if (status >= 0)
1944 return status;
1945
1946 /* Not a loose object; someone else may have just packed it. */
f0df4ed5
JS
1947 reprepare_packed_git();
1948 if (!find_pack_entry(sha1, &e, NULL))
ddd63e64 1949 return status;
f0df4ed5 1950 }
21666f1a 1951 return packed_object_info(e.p, e.offset, sizep);
f0df4ed5
JS
1952}
1953
21666f1a
NP
1954static void *read_packed_sha1(const unsigned char *sha1,
1955 enum object_type *type, unsigned long *size)
1f688557
JH
1956{
1957 struct pack_entry e;
8eca0b47 1958 void *data;
1f688557 1959
8276c007 1960 if (!find_pack_entry(sha1, &e, NULL))
1f688557 1961 return NULL;
8eca0b47
NP
1962 data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
1963 if (!data) {
1964 /*
1965 * We're probably in deep shit, but let's try to fetch
1966 * the required object anyway from another pack or loose.
1967 * This should happen only in the presence of a corrupted
1968 * pack, and is better than failing outright.
1969 */
1970 error("failed to read object %s at offset %"PRIuMAX" from %s",
1971 sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
1972 mark_bad_packed_object(e.p, sha1);
ac939109 1973 data = read_object(sha1, type, size);
8eca0b47
NP
1974 }
1975 return data;
1f688557
JH
1976}
1977
d66b37bb
JH
1978/*
1979 * This is meant to hold a *small* number of objects that you would
1980 * want read_sha1_file() to be able to return, but yet you do not want
1981 * to write them into the object store (e.g. a browse-only
1982 * application).
1983 */
1984static struct cached_object {
1985 unsigned char sha1[20];
21666f1a 1986 enum object_type type;
d66b37bb
JH
1987 void *buf;
1988 unsigned long size;
1989} *cached_objects;
1990static int cached_object_nr, cached_object_alloc;
1991
346245a1
JK
1992static struct cached_object empty_tree = {
1993 /* empty tree sha1: 4b825dc642cb6eb9a060e54bf8d69288fbee4904 */
1994 "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60"
1995 "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04",
1996 OBJ_TREE,
1997 "",
1998 0
1999};
2000
d66b37bb
JH
2001static struct cached_object *find_cached_object(const unsigned char *sha1)
2002{
2003 int i;
2004 struct cached_object *co = cached_objects;
2005
2006 for (i = 0; i < cached_object_nr; i++, co++) {
2007 if (!hashcmp(co->sha1, sha1))
2008 return co;
2009 }
346245a1
JK
2010 if (!hashcmp(sha1, empty_tree.sha1))
2011 return &empty_tree;
d66b37bb
JH
2012 return NULL;
2013}
2014
21666f1a
NP
2015int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2016 unsigned char *sha1)
d66b37bb
JH
2017{
2018 struct cached_object *co;
2019
21666f1a 2020 hash_sha1_file(buf, len, typename(type), sha1);
d66b37bb
JH
2021 if (has_sha1_file(sha1) || find_cached_object(sha1))
2022 return 0;
2023 if (cached_object_alloc <= cached_object_nr) {
2024 cached_object_alloc = alloc_nr(cached_object_alloc);
2025 cached_objects = xrealloc(cached_objects,
2026 sizeof(*cached_objects) *
2027 cached_object_alloc);
2028 }
2029 co = &cached_objects[cached_object_nr++];
2030 co->size = len;
21666f1a 2031 co->type = type;
efa13f7b
JH
2032 co->buf = xmalloc(len);
2033 memcpy(co->buf, buf, len);
d66b37bb
JH
2034 hashcpy(co->sha1, sha1);
2035 return 0;
2036}
2037
ac939109
NP
2038void *read_object(const unsigned char *sha1, enum object_type *type,
2039 unsigned long *size)
0fcfd160
LT
2040{
2041 unsigned long mapsize;
2042 void *map, *buf;
d66b37bb
JH
2043 struct cached_object *co;
2044
2045 co = find_cached_object(sha1);
2046 if (co) {
21666f1a 2047 *type = co->type;
d66b37bb 2048 *size = co->size;
182af834 2049 return xmemdupz(co->buf, co->size);
d66b37bb 2050 }
0fcfd160 2051
8276c007
PE
2052 buf = read_packed_sha1(sha1, type, size);
2053 if (buf)
2054 return buf;
bb6b8e4f 2055 map = map_sha1_file(sha1, &mapsize);
0fcfd160 2056 if (map) {
7efbff75 2057 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
0fcfd160
LT
2058 munmap(map, mapsize);
2059 return buf;
2060 }
637cdd9d 2061 reprepare_packed_git();
8276c007 2062 return read_packed_sha1(sha1, type, size);
0fcfd160
LT
2063}
2064
ac939109
NP
2065void *read_sha1_file(const unsigned char *sha1, enum object_type *type,
2066 unsigned long *size)
2067{
2068 void *data = read_object(sha1, type, size);
2069 /* legacy behavior is to die on corrupted objects */
2070 if (!data && (has_loose_object(sha1) || has_packed_and_bad(sha1)))
2071 die("object %s is corrupted", sha1_to_hex(sha1));
2072 return data;
2073}
2074
40469ee9 2075void *read_object_with_reference(const unsigned char *sha1,
21666f1a 2076 const char *required_type_name,
40469ee9
JH
2077 unsigned long *size,
2078 unsigned char *actual_sha1_return)
f4913f91 2079{
21666f1a 2080 enum object_type type, required_type;
f4913f91
JH
2081 void *buffer;
2082 unsigned long isize;
40469ee9 2083 unsigned char actual_sha1[20];
f4913f91 2084
21666f1a 2085 required_type = type_from_string(required_type_name);
e702496e 2086 hashcpy(actual_sha1, sha1);
40469ee9
JH
2087 while (1) {
2088 int ref_length = -1;
2089 const char *ref_type = NULL;
f4913f91 2090
21666f1a 2091 buffer = read_sha1_file(actual_sha1, &type, &isize);
40469ee9
JH
2092 if (!buffer)
2093 return NULL;
21666f1a 2094 if (type == required_type) {
40469ee9
JH
2095 *size = isize;
2096 if (actual_sha1_return)
e702496e 2097 hashcpy(actual_sha1_return, actual_sha1);
40469ee9
JH
2098 return buffer;
2099 }
2100 /* Handle references */
21666f1a 2101 else if (type == OBJ_COMMIT)
40469ee9 2102 ref_type = "tree ";
21666f1a 2103 else if (type == OBJ_TAG)
40469ee9
JH
2104 ref_type = "object ";
2105 else {
2106 free(buffer);
2107 return NULL;
2108 }
2109 ref_length = strlen(ref_type);
f4913f91 2110
50974ec9
MK
2111 if (ref_length + 40 > isize ||
2112 memcmp(buffer, ref_type, ref_length) ||
1d7f171c 2113 get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
40469ee9
JH
2114 free(buffer);
2115 return NULL;
2116 }
1cf58e72 2117 free(buffer);
40469ee9
JH
2118 /* Now we have the ID of the referred-to object in
2119 * actual_sha1. Check again. */
f4913f91 2120 }
f4913f91
JH
2121}
2122
ce9fbf16 2123static void write_sha1_file_prepare(const void *buf, unsigned long len,
972a9155 2124 const char *type, unsigned char *sha1,
d65a16f6 2125 char *hdr, int *hdrlen)
d410c0f5
JH
2126{
2127 SHA_CTX c;
2128
2129 /* Generate the header */
d65a16f6 2130 *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
d410c0f5
JH
2131
2132 /* Sha1.. */
2133 SHA1_Init(&c);
2134 SHA1_Update(&c, hdr, *hdrlen);
2135 SHA1_Update(&c, buf, len);
2136 SHA1_Final(sha1, &c);
d410c0f5
JH
2137}
2138
230f1322
LT
2139/*
2140 * Move the just written object into its final resting place
2141 */
839837b9 2142int move_temp_to_file(const char *tmpfile, const char *filename)
230f1322 2143{
e32c0a9c
TR
2144 int ret = 0;
2145 if (link(tmpfile, filename))
2146 ret = errno;
7ebb6fca
LT
2147
2148 /*
2149 * Coda hack - coda doesn't like cross-directory links,
2150 * so we fall back to a rename, which will mean that it
2151 * won't be able to check collisions, but that's not a
2152 * big deal.
2153 *
2154 * The same holds for FAT formatted media.
2155 *
2156 * When this succeeds, we just return 0. We have nothing
2157 * left to unlink.
2158 */
2159 if (ret && ret != EEXIST) {
2160 if (!rename(tmpfile, filename))
230f1322 2161 return 0;
9e48b389 2162 ret = errno;
230f1322
LT
2163 }
2164 unlink(tmpfile);
2165 if (ret) {
2166 if (ret != EEXIST) {
916d081b 2167 return error("unable to write sha1 filename %s: %s\n", filename, strerror(ret));
230f1322
LT
2168 }
2169 /* FIXME!!! Collision check here ? */
2170 }
2171
2172 return 0;
2173}
2174
4d548150
LT
2175static int write_buffer(int fd, const void *buf, size_t len)
2176{
d34cf19b 2177 if (write_in_full(fd, buf, len) < 0)
93822c22 2178 return error("file write error (%s)", strerror(errno));
4d548150
LT
2179 return 0;
2180}
2181
ce9fbf16 2182int hash_sha1_file(const void *buf, unsigned long len, const char *type,
abdc3fc8
RS
2183 unsigned char *sha1)
2184{
d65a16f6 2185 char hdr[32];
abdc3fc8
RS
2186 int hdrlen;
2187 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2188 return 0;
2189}
2190
e9039dd3
LT
2191/* Finalize a file on disk, and close it. */
2192static void close_sha1_file(int fd)
2193{
aafe9fba
LT
2194 if (fsync_object_files)
2195 fsync_or_die(fd, "sha1 file");
e9039dd3
LT
2196 fchmod(fd, 0444);
2197 if (close(fd) != 0)
2198 die("unable to write sha1 file");
2199}
2200
5723fe7e
LT
2201/* Size of directory component, including the ending '/' */
2202static inline int directory_size(const char *filename)
2203{
2204 const char *s = strrchr(filename, '/');
2205 if (!s)
2206 return 0;
2207 return s - filename + 1;
2208}
2209
2210/*
2211 * This creates a temporary file in the same directory as the final
2212 * 'filename'
2213 *
2214 * We want to avoid cross-directory filename renames, because those
2215 * can have problems on various filesystems (FAT, NFS, Coda).
2216 */
2217static int create_tmpfile(char *buffer, size_t bufsiz, const char *filename)
2218{
2219 int fd, dirlen = directory_size(filename);
2220
2221 if (dirlen + 20 > bufsiz) {
2222 errno = ENAMETOOLONG;
2223 return -1;
2224 }
2225 memcpy(buffer, filename, dirlen);
2226 strcpy(buffer + dirlen, "tmp_obj_XXXXXX");
2227 fd = mkstemp(buffer);
2228 if (fd < 0 && dirlen) {
2229 /* Make sure the directory exists */
6ff6af62 2230 memcpy(buffer, filename, dirlen);
5723fe7e 2231 buffer[dirlen-1] = 0;
3bfaf018 2232 if (mkdir(buffer, 0777) || adjust_shared_perm(buffer))
5723fe7e
LT
2233 return -1;
2234
2235 /* Try again */
2236 strcpy(buffer + dirlen - 1, "/tmp_obj_XXXXXX");
2237 fd = mkstemp(buffer);
2238 }
2239 return fd;
2240}
2241
bbac7311
NP
2242static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2243 void *buf, unsigned long len, time_t mtime)
0fcfd160 2244{
bbac7311 2245 int fd, size, ret;
bf0f910d 2246 unsigned char *compressed;
0fcfd160 2247 z_stream stream;
706bc531 2248 char *filename;
aac17941 2249 static char tmpfile[PATH_MAX];
a44c9a5e 2250
972a9155 2251 filename = sha1_file_name(sha1);
5723fe7e 2252 fd = create_tmpfile(tmpfile, sizeof(tmpfile), filename);
aac17941 2253 if (fd < 0) {
916d081b
PB
2254 if (errno == EPERM)
2255 return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2256 else
2257 return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
aac17941
LT
2258 }
2259
0fcfd160
LT
2260 /* Set it up */
2261 memset(&stream, 0, sizeof(stream));
12f6c308 2262 deflateInit(&stream, zlib_compression_level);
93821bd9 2263 size = 8 + deflateBound(&stream, len+hdrlen);
812666c8 2264 compressed = xmalloc(size);
0fcfd160
LT
2265
2266 /* Compress it */
0fcfd160
LT
2267 stream.next_out = compressed;
2268 stream.avail_out = size;
a44c9a5e
LT
2269
2270 /* First header.. */
d65a16f6 2271 stream.next_in = (unsigned char *)hdr;
a44c9a5e 2272 stream.avail_in = hdrlen;
726f852b
NP
2273 while (deflate(&stream, 0) == Z_OK)
2274 /* nothing */;
a44c9a5e
LT
2275
2276 /* Then the data itself.. */
2277 stream.next_in = buf;
2278 stream.avail_in = len;
ac54c277
LT
2279 ret = deflate(&stream, Z_FINISH);
2280 if (ret != Z_STREAM_END)
2281 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2282
2283 ret = deflateEnd(&stream);
2284 if (ret != Z_OK)
2285 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2286
0fcfd160
LT
2287 size = stream.total_out;
2288
4d548150
LT
2289 if (write_buffer(fd, compressed, size) < 0)
2290 die("unable to write sha1 file");
e9039dd3 2291 close_sha1_file(fd);
383f85b7 2292 free(compressed);
0fcfd160 2293
bbac7311
NP
2294 if (mtime) {
2295 struct utimbuf utb;
2296 utb.actime = mtime;
2297 utb.modtime = mtime;
2298 if (utime(tmpfile, &utb) < 0)
2299 warning("failed utime() on %s: %s",
2300 tmpfile, strerror(errno));
2301 }
2302
230f1322 2303 return move_temp_to_file(tmpfile, filename);
0fcfd160 2304}
8237b185 2305
bbac7311
NP
2306int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
2307{
2308 unsigned char sha1[20];
2309 char hdr[32];
2310 int hdrlen;
2311
2312 /* Normally if we have it in the pack then we do not bother writing
2313 * it out into .git/objects/??/?{38} file.
2314 */
2315 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2316 if (returnsha1)
2317 hashcpy(returnsha1, sha1);
2318 if (has_sha1_file(sha1))
2319 return 0;
2320 return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
2321}
2322
2323int force_object_loose(const unsigned char *sha1, time_t mtime)
2324{
bbac7311
NP
2325 void *buf;
2326 unsigned long len;
2327 enum object_type type;
2328 char hdr[32];
2329 int hdrlen;
1fb23e65 2330 int ret;
bbac7311 2331
c529d75a 2332 if (has_loose_object(sha1))
bbac7311
NP
2333 return 0;
2334 buf = read_packed_sha1(sha1, &type, &len);
2335 if (!buf)
2336 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2337 hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
1fb23e65
BS
2338 ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
2339 free(buf);
2340
2341 return ret;
bbac7311
NP
2342}
2343
bf592c50
DB
2344int has_pack_index(const unsigned char *sha1)
2345{
2346 struct stat st;
2347 if (stat(sha1_pack_index_name(sha1), &st))
2348 return 0;
2349 return 1;
2350}
2351
2352int has_pack_file(const unsigned char *sha1)
2353{
2354 struct stat st;
2355 if (stat(sha1_pack_name(sha1), &st))
2356 return 0;
2357 return 1;
2358}
2359
106d710b 2360int has_sha1_pack(const unsigned char *sha1, const char **ignore_packed)
dade09c2
LT
2361{
2362 struct pack_entry e;
106d710b 2363 return find_pack_entry(sha1, &e, ignore_packed);
dade09c2
LT
2364}
2365
8237b185
DB
2366int has_sha1_file(const unsigned char *sha1)
2367{
1f688557
JH
2368 struct pack_entry e;
2369
106d710b 2370 if (find_pack_entry(sha1, &e, NULL))
1f688557 2371 return 1;
c529d75a 2372 return has_loose_object(sha1);
8237b185 2373}
74400e71 2374
e7332f96
BE
2375int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
2376{
fd17f5b5 2377 struct strbuf buf;
e7332f96 2378 int ret;
e7332f96 2379
fd17f5b5
PH
2380 strbuf_init(&buf, 0);
2381 if (strbuf_read(&buf, fd, 4096) < 0) {
2382 strbuf_release(&buf);
024510c8
DB
2383 return -1;
2384 }
e7332f96 2385
024510c8 2386 if (!type)
8e440259 2387 type = blob_type;
024510c8 2388 if (write_object)
fd17f5b5 2389 ret = write_sha1_file(buf.buf, buf.len, type, sha1);
abdc3fc8 2390 else
fd17f5b5
PH
2391 ret = hash_sha1_file(buf.buf, buf.len, type, sha1);
2392 strbuf_release(&buf);
2393
024510c8
DB
2394 return ret;
2395}
2396
edaec3fb 2397int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object,
53bca91a 2398 enum object_type type, const char *path)
74400e71 2399{
dc49cd76 2400 size_t size = xsize_t(st->st_size);
3a55602e 2401 void *buf = NULL;
6c510bee 2402 int ret, re_allocated = 0;
74400e71 2403
74400e71 2404 if (size)
c4712e45 2405 buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
74400e71 2406 close(fd);
74400e71 2407
7672db20 2408 if (!type)
edaec3fb 2409 type = OBJ_BLOB;
6c510bee
LT
2410
2411 /*
2412 * Convert blobs to git internal format
2413 */
d0d8e14d 2414 if ((type == OBJ_BLOB) && S_ISREG(st->st_mode)) {
5ecd293d
PH
2415 struct strbuf nbuf;
2416 strbuf_init(&nbuf, 0);
21e5ad50
SP
2417 if (convert_to_git(path, buf, size, &nbuf,
2418 write_object ? safe_crlf : 0)) {
ac78e548 2419 munmap(buf, size);
b315c5c0 2420 buf = strbuf_detach(&nbuf, &size);
6c510bee
LT
2421 re_allocated = 1;
2422 }
2423 }
2424
7672db20 2425 if (write_object)
edaec3fb 2426 ret = write_sha1_file(buf, size, typename(type), sha1);
abdc3fc8 2427 else
edaec3fb 2428 ret = hash_sha1_file(buf, size, typename(type), sha1);
6c510bee
LT
2429 if (re_allocated) {
2430 free(buf);
2431 return ret;
2432 }
aac17941
LT
2433 if (size)
2434 munmap(buf, size);
2435 return ret;
74400e71 2436}
ec1fcc16
JH
2437
2438int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
2439{
2440 int fd;
2441 char *target;
dc49cd76 2442 size_t len;
ec1fcc16
JH
2443
2444 switch (st->st_mode & S_IFMT) {
2445 case S_IFREG:
2446 fd = open(path, O_RDONLY);
2447 if (fd < 0)
2448 return error("open(\"%s\"): %s", path,
2449 strerror(errno));
53bca91a 2450 if (index_fd(sha1, fd, st, write_object, OBJ_BLOB, path) < 0)
ec1fcc16
JH
2451 return error("%s: failed to insert into database",
2452 path);
2453 break;
2454 case S_IFLNK:
dc49cd76
SP
2455 len = xsize_t(st->st_size);
2456 target = xmalloc(len + 1);
2457 if (readlink(path, target, len + 1) != st->st_size) {
ec1fcc16
JH
2458 char *errstr = strerror(errno);
2459 free(target);
2460 return error("readlink(\"%s\"): %s", path,
2461 errstr);
2462 }
abdc3fc8 2463 if (!write_object)
dc49cd76
SP
2464 hash_sha1_file(target, len, blob_type, sha1);
2465 else if (write_sha1_file(target, len, blob_type, sha1))
ec1fcc16
JH
2466 return error("%s: failed to insert into database",
2467 path);
2468 free(target);
2469 break;
f35a6d3b
LT
2470 case S_IFDIR:
2471 return resolve_gitlink_ref(path, "HEAD", sha1);
ec1fcc16
JH
2472 default:
2473 return error("%s: unsupported file type", path);
2474 }
2475 return 0;
2476}
a69e5429
JH
2477
2478int read_pack_header(int fd, struct pack_header *header)
2479{
c697ad14
HO
2480 if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
2481 /* "eof before pack header was fully read" */
2482 return PH_ERROR_EOF;
2483
a69e5429
JH
2484 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2485 /* "protocol error (pack signature mismatch detected)" */
2486 return PH_ERROR_PACK_SIGNATURE;
2487 if (!pack_version_ok(header->hdr_version))
2488 /* "protocol error (pack version unsupported)" */
2489 return PH_ERROR_PROTOCOL;
2490 return 0;
2491}