]> git.proxmox.com Git - libgit2.git/blame - src/pack.c
Merge pull request #1529 from arrbee/more-packfile-locking
[libgit2.git] / src / pack.c
CommitLineData
7d0cdf82 1/*
359fc2d2 2 * Copyright (C) the libgit2 contributors. All rights reserved.
7d0cdf82 3 *
bb742ede
VM
4 * This file is part of libgit2, distributed under the GNU GPL v2 with
5 * a Linking Exception. For full terms see the included COPYING file.
7d0cdf82
CMN
6 */
7
a15c550d 8#include "common.h"
7d0cdf82
CMN
9#include "odb.h"
10#include "pack.h"
11#include "delta-apply.h"
a070f152 12#include "sha1_lookup.h"
a15c550d
VM
13#include "mwindow.h"
14#include "fileops.h"
b7f167da 15#include "oid.h"
7d0cdf82 16
0c3bae62 17#include <zlib.h>
7d0cdf82 18
a070f152 19static int packfile_open(struct git_pack_file *p);
e1de726c 20static git_off_t nth_packed_object_offset(const struct git_pack_file *p, uint32_t n);
a070f152
CMN
21int packfile_unpack_compressed(
22 git_rawobj *obj,
23 struct git_pack_file *p,
24 git_mwindow **w_curs,
e1de726c 25 git_off_t *curpos,
a070f152
CMN
26 size_t size,
27 git_otype type);
28
29/* Can find the offset of an object given
30 * a prefix of an identifier.
904b67e6 31 * Throws GIT_EAMBIGUOUSOIDPREFIX if short oid
a070f152
CMN
32 * is ambiguous within the pack.
33 * This method assumes that len is between
34 * GIT_OID_MINPREFIXLEN and GIT_OID_HEXSZ.
35 */
36static int pack_entry_find_offset(
e1de726c 37 git_off_t *offset_out,
a070f152
CMN
38 git_oid *found_oid,
39 struct git_pack_file *p,
40 const git_oid *short_oid,
b8457baa 41 size_t len);
a070f152 42
e1de726c
RB
43static int packfile_error(const char *message)
44{
45 giterr_set(GITERR_ODB, "Invalid pack file - %s", message);
46 return -1;
47}
48
c8f79c2b
CMN
49/********************
50 * Delta base cache
51 ********************/
c0f4a011 52
525d961c 53static git_pack_cache_entry *new_cache_object(git_rawobj *source)
c0f4a011 54{
c8f79c2b 55 git_pack_cache_entry *e = git__calloc(1, sizeof(git_pack_cache_entry));
c0f4a011
CMN
56 if (!e)
57 return NULL;
58
c0f4a011
CMN
59 memcpy(&e->raw, source, sizeof(git_rawobj));
60
61 return e;
62}
63
64static void free_cache_object(void *o)
65{
66 git_pack_cache_entry *e = (git_pack_cache_entry *)o;
67
68 if (e != NULL) {
0ed75620 69 assert(e->refcount.val == 0);
c0f4a011
CMN
70 git__free(e->raw.data);
71 git__free(e);
72 }
73}
74
c8f79c2b
CMN
75static void cache_free(git_pack_cache *cache)
76{
77 khiter_t k;
78
79 if (cache->entries) {
80 for (k = kh_begin(cache->entries); k != kh_end(cache->entries); k++) {
81 if (kh_exist(cache->entries, k))
82 free_cache_object(kh_value(cache->entries, k));
83 }
84
85 git_offmap_free(cache->entries);
aa3bf89d 86 git_mutex_free(&cache->lock);
c8f79c2b
CMN
87 }
88}
89
90static int cache_init(git_pack_cache *cache)
91{
92 memset(cache, 0, sizeof(git_pack_cache));
93 cache->entries = git_offmap_alloc();
94 GITERR_CHECK_ALLOC(cache->entries);
95 cache->memory_limit = GIT_PACK_CACHE_MEMORY_LIMIT;
96 git_mutex_init(&cache->lock);
97
98 return 0;
99}
100
09e29e47 101static git_pack_cache_entry *cache_get(git_pack_cache *cache, git_off_t offset)
c8f79c2b
CMN
102{
103 khiter_t k;
104 git_pack_cache_entry *entry = NULL;
105
09e29e47
CMN
106 if (git_mutex_lock(&cache->lock) < 0)
107 return NULL;
108
c8f79c2b
CMN
109 k = kh_get(off, cache->entries, offset);
110 if (k != kh_end(cache->entries)) { /* found it */
111 entry = kh_value(cache->entries, k);
112 git_atomic_inc(&entry->refcount);
0ed75620 113 entry->last_usage = cache->use_ctr++;
c8f79c2b
CMN
114 }
115 git_mutex_unlock(&cache->lock);
116
117 return entry;
118}
119
0ed75620
CMN
120/* Run with the cache lock held */
121static void free_lowest_entry(git_pack_cache *cache)
122{
ed6648ba
CMN
123 git_pack_cache_entry *entry;
124 khiter_t k;
125
0ed75620
CMN
126 for (k = kh_begin(cache->entries); k != kh_end(cache->entries); k++) {
127 if (!kh_exist(cache->entries, k))
128 continue;
129
130 entry = kh_value(cache->entries, k);
ed6648ba 131
9c62aaab
CMN
132 if (entry && entry->refcount.val == 0) {
133 cache->memory_used -= entry->raw.len;
134 kh_del(off, cache->entries, k);
135 free_cache_object(entry);
ed6648ba
CMN
136 }
137 }
0ed75620
CMN
138}
139
c8f79c2b
CMN
140static int cache_add(git_pack_cache *cache, git_rawobj *base, git_off_t offset)
141{
142 git_pack_cache_entry *entry;
143 int error, exists = 0;
144 khiter_t k;
145
0ed75620
CMN
146 if (base->len > GIT_PACK_CACHE_SIZE_LIMIT)
147 return -1;
148
c8f79c2b
CMN
149 entry = new_cache_object(base);
150 if (entry) {
09e29e47
CMN
151 if (git_mutex_lock(&cache->lock) < 0) {
152 giterr_set(GITERR_OS, "failed to lock cache");
153 return -1;
154 }
c8f79c2b
CMN
155 /* Add it to the cache if nobody else has */
156 exists = kh_get(off, cache->entries, offset) != kh_end(cache->entries);
157 if (!exists) {
0ed75620
CMN
158 while (cache->memory_used + base->len > cache->memory_limit)
159 free_lowest_entry(cache);
160
c8f79c2b
CMN
161 k = kh_put(off, cache->entries, offset, &error);
162 assert(error != 0);
163 kh_value(cache->entries, k) = entry;
0ed75620 164 cache->memory_used += entry->raw.len;
c8f79c2b
CMN
165 }
166 git_mutex_unlock(&cache->lock);
167 /* Somebody beat us to adding it into the cache */
168 if (exists) {
169 git__free(entry);
170 return -1;
171 }
172 }
173
174 return 0;
175}
176
a070f152
CMN
177/***********************************************************
178 *
179 * PACK INDEX METHODS
180 *
181 ***********************************************************/
182
183static void pack_index_free(struct git_pack_file *p)
184{
60ecdf59
DMB
185 if (p->oids) {
186 git__free(p->oids);
187 p->oids = NULL;
188 }
a070f152
CMN
189 if (p->index_map.data) {
190 git_futils_mmap_free(&p->index_map);
191 p->index_map.data = NULL;
192 }
193}
194
87d9869f 195static int pack_index_check(const char *path, struct git_pack_file *p)
a070f152
CMN
196{
197 struct git_pack_idx_header *hdr;
198 uint32_t version, nr, i, *index;
a070f152
CMN
199 void *idx_map;
200 size_t idx_size;
a070f152 201 struct stat st;
a070f152 202 int error;
e1de726c
RB
203 /* TODO: properly open the file without access time using O_NOATIME */
204 git_file fd = git_futils_open_ro(path);
a070f152 205 if (fd < 0)
e1de726c 206 return fd;
a070f152 207
9d2f841a
RB
208 if (p_fstat(fd, &st) < 0) {
209 p_close(fd);
210 giterr_set(GITERR_OS, "Unable to stat pack index '%s'", path);
211 return -1;
212 }
213
214 if (!S_ISREG(st.st_mode) ||
e1de726c
RB
215 !git__is_sizet(st.st_size) ||
216 (idx_size = (size_t)st.st_size) < 4 * 256 + 20 + 20)
217 {
a070f152 218 p_close(fd);
9d2f841a 219 giterr_set(GITERR_ODB, "Invalid pack index '%s'", path);
e1de726c 220 return -1;
a070f152
CMN
221 }
222
223 error = git_futils_mmap_ro(&p->index_map, fd, 0, idx_size);
e1de726c 224
a070f152
CMN
225 p_close(fd);
226
e1de726c
RB
227 if (error < 0)
228 return error;
a070f152
CMN
229
230 hdr = idx_map = p->index_map.data;
231
232 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
233 version = ntohl(hdr->idx_version);
234
235 if (version < 2 || version > 2) {
236 git_futils_mmap_free(&p->index_map);
e1de726c 237 return packfile_error("unsupported index version");
a070f152
CMN
238 }
239
240 } else
241 version = 1;
242
243 nr = 0;
244 index = idx_map;
245
246 if (version > 1)
87d9869f 247 index += 2; /* skip index header */
a070f152
CMN
248
249 for (i = 0; i < 256; i++) {
250 uint32_t n = ntohl(index[i]);
251 if (n < nr) {
252 git_futils_mmap_free(&p->index_map);
e1de726c 253 return packfile_error("index is non-monotonic");
a070f152
CMN
254 }
255 nr = n;
256 }
257
258 if (version == 1) {
259 /*
260 * Total size:
87d9869f
VM
261 * - 256 index entries 4 bytes each
262 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
263 * - 20-byte SHA1 of the packfile
264 * - 20-byte SHA1 file checksum
a070f152
CMN
265 */
266 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
267 git_futils_mmap_free(&p->index_map);
e1de726c 268 return packfile_error("index is corrupted");
a070f152
CMN
269 }
270 } else if (version == 2) {
271 /*
272 * Minimum size:
87d9869f
VM
273 * - 8 bytes of header
274 * - 256 index entries 4 bytes each
275 * - 20-byte sha1 entry * nr
276 * - 4-byte crc entry * nr
277 * - 4-byte offset entry * nr
278 * - 20-byte SHA1 of the packfile
279 * - 20-byte SHA1 file checksum
a070f152
CMN
280 * And after the 4-byte offset table might be a
281 * variable sized table containing 8-byte entries
282 * for offsets larger than 2^31.
283 */
284 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
285 unsigned long max_size = min_size;
286
287 if (nr)
288 max_size += (nr - 1)*8;
289
290 if (idx_size < min_size || idx_size > max_size) {
291 git_futils_mmap_free(&p->index_map);
e1de726c 292 return packfile_error("wrong index size");
a070f152 293 }
a070f152
CMN
294 }
295
296 p->index_version = version;
297 p->num_objects = nr;
e1de726c 298 return 0;
a070f152
CMN
299}
300
301static int pack_index_open(struct git_pack_file *p)
302{
303 char *idx_name;
24c70804
RB
304 int error = 0;
305 size_t name_len, base_len;
306
a070f152 307 if (p->index_map.data)
53607868 308 return 0;
a070f152 309
24c70804
RB
310 name_len = strlen(p->pack_name);
311 assert(name_len > strlen(".pack")); /* checked by git_pack_file alloc */
e1de726c 312
53607868
RB
313 if ((idx_name = git__malloc(name_len)) == NULL)
314 return -1;
44ef8b1b 315
24c70804
RB
316 base_len = name_len - strlen(".pack");
317 memcpy(idx_name, p->pack_name, base_len);
318 memcpy(idx_name + base_len, ".idx", sizeof(".idx"));
a070f152 319
53607868
RB
320 if ((error = git_mutex_lock(&p->lock)) < 0)
321 return error;
322
323 if (!p->index_map.data)
324 error = pack_index_check(idx_name, p);
24c70804 325
3286c408 326 git__free(idx_name);
a070f152 327
24c70804
RB
328 git_mutex_unlock(&p->lock);
329
e1de726c 330 return error;
a070f152
CMN
331}
332
333static unsigned char *pack_window_open(
334 struct git_pack_file *p,
7d0cdf82 335 git_mwindow **w_cursor,
e1de726c 336 git_off_t offset,
7d0cdf82
CMN
337 unsigned int *left)
338{
e1de726c 339 if (p->mwf.fd == -1 && packfile_open(p) < 0)
7d0cdf82
CMN
340 return NULL;
341
342 /* Since packfiles end in a hash of their content and it's
343 * pointless to ask for an offset into the middle of that
344 * hash, and the pack_window_contains function above wouldn't match
345 * don't allow an offset too close to the end of the file.
346 */
347 if (offset > (p->mwf.size - 20))
348 return NULL;
349
350 return git_mwindow_open(&p->mwf, w_cursor, offset, 20, left);
351 }
352
45d773ef
CMN
353static int packfile_unpack_header1(
354 unsigned long *usedp,
7d0cdf82
CMN
355 size_t *sizep,
356 git_otype *type,
357 const unsigned char *buf,
358 unsigned long len)
359{
360 unsigned shift;
361 unsigned long size, c;
362 unsigned long used = 0;
2aeadb9c 363
7d0cdf82
CMN
364 c = buf[used++];
365 *type = (c >> 4) & 7;
366 size = c & 15;
367 shift = 4;
368 while (c & 0x80) {
45d773ef 369 if (len <= used)
904b67e6 370 return GIT_EBUFS;
45d773ef
CMN
371
372 if (bitsizeof(long) <= shift) {
373 *usedp = 0;
374 return -1;
375 }
7d0cdf82
CMN
376
377 c = buf[used++];
378 size += (c & 0x7f) << shift;
379 shift += 7;
380 }
381
382 *sizep = (size_t)size;
45d773ef
CMN
383 *usedp = used;
384 return 0;
7d0cdf82
CMN
385}
386
387int git_packfile_unpack_header(
388 size_t *size_p,
389 git_otype *type_p,
390 git_mwindow_file *mwf,
391 git_mwindow **w_curs,
e1de726c 392 git_off_t *curpos)
7d0cdf82
CMN
393{
394 unsigned char *base;
395 unsigned int left;
396 unsigned long used;
45d773ef 397 int ret;
7d0cdf82
CMN
398
399 /* pack_window_open() assures us we have [base, base + 20) available
87d9869f
VM
400 * as a range that we can look at at. (Its actually the hash
401 * size that is assured.) With our object header encoding
7d0cdf82
CMN
402 * the maximum deflated object size is 2^137, which is just
403 * insane, so we know won't exceed what we have been given.
404 */
24c70804 405/* base = pack_window_open(p, w_curs, *curpos, &left); */
7d0cdf82
CMN
406 base = git_mwindow_open(mwf, w_curs, *curpos, 20, &left);
407 if (base == NULL)
904b67e6 408 return GIT_EBUFS;
2aeadb9c 409
9d2f841a 410 ret = packfile_unpack_header1(&used, size_p, type_p, base, left);
45d773ef 411 git_mwindow_close(w_curs);
904b67e6 412 if (ret == GIT_EBUFS)
45d773ef
CMN
413 return ret;
414 else if (ret < 0)
e1de726c 415 return packfile_error("header length is zero");
7d0cdf82
CMN
416
417 *curpos += used;
e1de726c 418 return 0;
7d0cdf82
CMN
419}
420
44f9f547
DMB
421int git_packfile_resolve_header(
422 size_t *size_p,
423 git_otype *type_p,
424 struct git_pack_file *p,
425 git_off_t offset)
426{
427 git_mwindow *w_curs = NULL;
428 git_off_t curpos = offset;
429 size_t size;
430 git_otype type;
431 git_off_t base_offset;
432 int error;
433
434 error = git_packfile_unpack_header(&size, &type, &p->mwf, &w_curs, &curpos);
435 git_mwindow_close(&w_curs);
436 if (error < 0)
437 return error;
438
439 if (type == GIT_OBJ_OFS_DELTA || type == GIT_OBJ_REF_DELTA) {
440 size_t base_size;
441 git_rawobj delta;
442 base_offset = get_delta_base(p, &w_curs, &curpos, type, offset);
443 git_mwindow_close(&w_curs);
444 error = packfile_unpack_compressed(&delta, p, &w_curs, &curpos, size, type);
445 git_mwindow_close(&w_curs);
446 if (error < 0)
447 return error;
448 error = git__delta_read_header(delta.data, delta.len, &base_size, size_p);
449 git__free(delta.data);
450 if (error < 0)
451 return error;
452 } else
453 *size_p = size;
454
455 while (type == GIT_OBJ_OFS_DELTA || type == GIT_OBJ_REF_DELTA) {
456 curpos = base_offset;
457 error = git_packfile_unpack_header(&size, &type, &p->mwf, &w_curs, &curpos);
458 git_mwindow_close(&w_curs);
459 if (error < 0)
460 return error;
461 if (type != GIT_OBJ_OFS_DELTA && type != GIT_OBJ_REF_DELTA)
462 break;
463 base_offset = get_delta_base(p, &w_curs, &curpos, type, base_offset);
464 git_mwindow_close(&w_curs);
465 }
466 *type_p = type;
467
468 return error;
469}
470
a070f152 471static int packfile_unpack_delta(
7d0cdf82 472 git_rawobj *obj,
a070f152 473 struct git_pack_file *p,
7d0cdf82 474 git_mwindow **w_curs,
e1de726c 475 git_off_t *curpos,
7d0cdf82
CMN
476 size_t delta_size,
477 git_otype delta_type,
e1de726c 478 git_off_t obj_offset)
7d0cdf82 479{
c0f4a011 480 git_off_t base_offset, base_key;
7d0cdf82 481 git_rawobj base, delta;
525d961c 482 git_pack_cache_entry *cached = NULL;
c0f4a011 483 int error, found_base = 0;
7d0cdf82 484
b5b474dd 485 base_offset = get_delta_base(p, w_curs, curpos, delta_type, obj_offset);
45d773ef 486 git_mwindow_close(w_curs);
7d0cdf82 487 if (base_offset == 0)
e1de726c
RB
488 return packfile_error("delta offset is zero");
489 if (base_offset < 0) /* must actually be an error code */
490 return (int)base_offset;
7d0cdf82 491
c8f79c2b
CMN
492 if (!p->bases.entries && (cache_init(&p->bases) < 0))
493 return -1;
7d0cdf82 494
c0f4a011 495 base_key = base_offset; /* git_packfile_unpack modifies base_offset */
c8f79c2b 496 if ((cached = cache_get(&p->bases, base_offset)) != NULL) {
c0f4a011 497 memcpy(&base, &cached->raw, sizeof(git_rawobj));
c8f79c2b 498 found_base = 1;
525d961c 499 }
525d961c
CMN
500
501 if (!cached) { /* have to inflate it */
c0f4a011
CMN
502 error = git_packfile_unpack(&base, p, &base_offset);
503
504 /*
505 * TODO: git.git tries to load the base from other packfiles
506 * or loose objects.
507 *
508 * We'll need to do this in order to support thin packs.
509 */
510 if (error < 0)
511 return error;
512 }
7d0cdf82
CMN
513
514 error = packfile_unpack_compressed(&delta, p, w_curs, curpos, delta_size, delta_type);
45d773ef 515 git_mwindow_close(w_curs);
c0f4a011 516
e1de726c 517 if (error < 0) {
c0f4a011
CMN
518 if (!found_base)
519 git__free(base.data);
e1de726c 520 return error;
7d0cdf82
CMN
521 }
522
523 obj->type = base.type;
e1de726c 524 error = git__delta_apply(obj, base.data, base.len, delta.data, delta.len);
c0f4a011
CMN
525 if (error < 0)
526 goto on_error;
527
c8f79c2b 528 if (found_base)
525d961c 529 git_atomic_dec(&cached->refcount);
c8f79c2b
CMN
530 else if (cache_add(&p->bases, &base, base_key) < 0)
531 git__free(base.data);
7d0cdf82 532
c0f4a011 533on_error:
3286c408 534 git__free(delta.data);
7d0cdf82 535
7d0cdf82
CMN
536 return error; /* error set by git__delta_apply */
537}
538
a070f152 539int git_packfile_unpack(
e1de726c
RB
540 git_rawobj *obj,
541 struct git_pack_file *p,
542 git_off_t *obj_offset)
7d0cdf82
CMN
543{
544 git_mwindow *w_curs = NULL;
e1de726c 545 git_off_t curpos = *obj_offset;
7d0cdf82
CMN
546 int error;
547
548 size_t size = 0;
549 git_otype type;
550
551 /*
552 * TODO: optionally check the CRC on the packfile
553 */
554
555 obj->data = NULL;
556 obj->len = 0;
557 obj->type = GIT_OBJ_BAD;
558
559 error = git_packfile_unpack_header(&size, &type, &p->mwf, &w_curs, &curpos);
45d773ef
CMN
560 git_mwindow_close(&w_curs);
561
e1de726c
RB
562 if (error < 0)
563 return error;
7d0cdf82
CMN
564
565 switch (type) {
566 case GIT_OBJ_OFS_DELTA:
567 case GIT_OBJ_REF_DELTA:
568 error = packfile_unpack_delta(
b5b474dd
CMN
569 obj, p, &w_curs, &curpos,
570 size, type, *obj_offset);
7d0cdf82
CMN
571 break;
572
573 case GIT_OBJ_COMMIT:
574 case GIT_OBJ_TREE:
575 case GIT_OBJ_BLOB:
576 case GIT_OBJ_TAG:
577 error = packfile_unpack_compressed(
b5b474dd 578 obj, p, &w_curs, &curpos,
7d0cdf82
CMN
579 size, type);
580 break;
581
582 default:
e1de726c 583 error = packfile_error("invalid packfile type in header");;
7d0cdf82
CMN
584 break;
585 }
586
b5b474dd 587 *obj_offset = curpos;
e1de726c 588 return error;
7d0cdf82
CMN
589}
590
282283ac
RB
591static void *use_git_alloc(void *opaq, unsigned int count, unsigned int size)
592{
593 GIT_UNUSED(opaq);
594 return git__calloc(count, size);
595}
596
597static void use_git_free(void *opaq, void *ptr)
598{
599 GIT_UNUSED(opaq);
600 git__free(ptr);
601}
602
46635339
CMN
603int git_packfile_stream_open(git_packfile_stream *obj, struct git_pack_file *p, git_off_t curpos)
604{
605 int st;
606
607 memset(obj, 0, sizeof(git_packfile_stream));
608 obj->curpos = curpos;
609 obj->p = p;
610 obj->zstream.zalloc = use_git_alloc;
611 obj->zstream.zfree = use_git_free;
612 obj->zstream.next_in = Z_NULL;
613 obj->zstream.next_out = Z_NULL;
614 st = inflateInit(&obj->zstream);
615 if (st != Z_OK) {
616 git__free(obj);
617 giterr_set(GITERR_ZLIB, "Failed to inflate packfile");
618 return -1;
619 }
620
621 return 0;
622}
623
624ssize_t git_packfile_stream_read(git_packfile_stream *obj, void *buffer, size_t len)
625{
626 unsigned char *in;
627 size_t written;
628 int st;
629
630 if (obj->done)
631 return 0;
632
633 in = pack_window_open(obj->p, &obj->mw, obj->curpos, &obj->zstream.avail_in);
634 if (in == NULL)
635 return GIT_EBUFS;
636
637 obj->zstream.next_out = buffer;
090d5e1f 638 obj->zstream.avail_out = (unsigned int)len;
46635339
CMN
639 obj->zstream.next_in = in;
640
641 st = inflate(&obj->zstream, Z_SYNC_FLUSH);
642 git_mwindow_close(&obj->mw);
643
644 obj->curpos += obj->zstream.next_in - in;
645 written = len - obj->zstream.avail_out;
646
647 if (st != Z_OK && st != Z_STREAM_END) {
648 giterr_set(GITERR_ZLIB, "Failed to inflate packfile");
649 return -1;
650 }
651
652 if (st == Z_STREAM_END)
653 obj->done = 1;
654
655
656 /* If we didn't write anything out but we're not done, we need more data */
657 if (!written && st != Z_STREAM_END)
658 return GIT_EBUFS;
659
660 return written;
661
662}
663
664void git_packfile_stream_free(git_packfile_stream *obj)
665{
666 inflateEnd(&obj->zstream);
667}
668
7d0cdf82 669int packfile_unpack_compressed(
e1de726c
RB
670 git_rawobj *obj,
671 struct git_pack_file *p,
672 git_mwindow **w_curs,
673 git_off_t *curpos,
674 size_t size,
675 git_otype type)
7d0cdf82
CMN
676{
677 int st;
678 z_stream stream;
679 unsigned char *buffer, *in;
680
e1de726c
RB
681 buffer = git__calloc(1, size + 1);
682 GITERR_CHECK_ALLOC(buffer);
7d0cdf82
CMN
683
684 memset(&stream, 0, sizeof(stream));
685 stream.next_out = buffer;
1c3fac4d 686 stream.avail_out = (uInt)size + 1;
282283ac
RB
687 stream.zalloc = use_git_alloc;
688 stream.zfree = use_git_free;
7d0cdf82
CMN
689
690 st = inflateInit(&stream);
691 if (st != Z_OK) {
3286c408 692 git__free(buffer);
e1de726c 693 giterr_set(GITERR_ZLIB, "Failed to inflate packfile");
45d773ef 694
e1de726c 695 return -1;
7d0cdf82
CMN
696 }
697
698 do {
b5b474dd 699 in = pack_window_open(p, w_curs, *curpos, &stream.avail_in);
7d0cdf82
CMN
700 stream.next_in = in;
701 st = inflate(&stream, Z_FINISH);
45d773ef 702 git_mwindow_close(w_curs);
7d0cdf82
CMN
703
704 if (!stream.avail_out)
705 break; /* the payload is larger than it should be */
706
45d773ef
CMN
707 if (st == Z_BUF_ERROR && in == NULL) {
708 inflateEnd(&stream);
709 git__free(buffer);
904b67e6 710 return GIT_EBUFS;
45d773ef
CMN
711 }
712
b5b474dd 713 *curpos += stream.next_in - in;
7d0cdf82
CMN
714 } while (st == Z_OK || st == Z_BUF_ERROR);
715
716 inflateEnd(&stream);
717
718 if ((st != Z_STREAM_END) || stream.total_out != size) {
3286c408 719 git__free(buffer);
e1de726c
RB
720 giterr_set(GITERR_ZLIB, "Failed to inflate packfile");
721 return -1;
7d0cdf82
CMN
722 }
723
724 obj->type = type;
725 obj->len = size;
726 obj->data = buffer;
e1de726c 727 return 0;
7d0cdf82
CMN
728}
729
b5b474dd
CMN
730/*
731 * curpos is where the data starts, delta_obj_offset is the where the
732 * header starts
733 */
e1de726c
RB
734git_off_t get_delta_base(
735 struct git_pack_file *p,
736 git_mwindow **w_curs,
737 git_off_t *curpos,
738 git_otype type,
739 git_off_t delta_obj_offset)
7d0cdf82 740{
45d773ef
CMN
741 unsigned int left = 0;
742 unsigned char *base_info;
e1de726c 743 git_off_t base_offset;
7d0cdf82
CMN
744 git_oid unused;
745
45d773ef
CMN
746 base_info = pack_window_open(p, w_curs, *curpos, &left);
747 /* Assumption: the only reason this would fail is because the file is too small */
748 if (base_info == NULL)
904b67e6 749 return GIT_EBUFS;
7d0cdf82
CMN
750 /* pack_window_open() assured us we have [base_info, base_info + 20)
751 * as a range that we can look at without walking off the
87d9869f
VM
752 * end of the mapped window. Its actually the hash size
753 * that is assured. An OFS_DELTA longer than the hash size
7d0cdf82
CMN
754 * is stupid, as then a REF_DELTA would be smaller to store.
755 */
756 if (type == GIT_OBJ_OFS_DELTA) {
757 unsigned used = 0;
758 unsigned char c = base_info[used++];
759 base_offset = c & 127;
760 while (c & 128) {
45d773ef 761 if (left <= used)
904b67e6 762 return GIT_EBUFS;
7d0cdf82
CMN
763 base_offset += 1;
764 if (!base_offset || MSB(base_offset, 7))
87d9869f 765 return 0; /* overflow */
7d0cdf82
CMN
766 c = base_info[used++];
767 base_offset = (base_offset << 7) + (c & 127);
768 }
769 base_offset = delta_obj_offset - base_offset;
770 if (base_offset <= 0 || base_offset >= delta_obj_offset)
87d9869f 771 return 0; /* out of bound */
7d0cdf82
CMN
772 *curpos += used;
773 } else if (type == GIT_OBJ_REF_DELTA) {
c1af5a39
CMN
774 /* If we have the cooperative cache, search in it first */
775 if (p->has_cache) {
0e040c03
CMN
776 khiter_t k;
777 git_oid oid;
c1af5a39 778
0e040c03
CMN
779 git_oid_fromraw(&oid, base_info);
780 k = kh_get(oid, p->idx_cache, &oid);
781 if (k != kh_end(p->idx_cache)) {
c1af5a39 782 *curpos += 20;
0e040c03 783 return ((struct git_pack_entry *)kh_value(p->idx_cache, k))->offset;
c1af5a39
CMN
784 }
785 }
7d0cdf82 786 /* The base entry _must_ be in the same pack */
e1de726c
RB
787 if (pack_entry_find_offset(&base_offset, &unused, p, (git_oid *)base_info, GIT_OID_HEXSZ) < 0)
788 return packfile_error("base entry delta is not in the same pack");
7d0cdf82
CMN
789 *curpos += 20;
790 } else
791 return 0;
792
793 return base_offset;
794}
a070f152
CMN
795
796/***********************************************************
797 *
798 * PACKFILE METHODS
799 *
800 ***********************************************************/
801
96c9b9f0 802void git_packfile_free(struct git_pack_file *p)
a070f152 803{
24c70804
RB
804 if (!p)
805 return;
806
c8f79c2b 807 cache_free(&p->bases);
c0f4a011 808
a070f152
CMN
809 git_mwindow_free_all(&p->mwf);
810
811 if (p->mwf.fd != -1)
812 p_close(p->mwf.fd);
813
814 pack_index_free(p);
815
3286c408 816 git__free(p->bad_object_sha1);
24c70804 817
24c70804 818 git_mutex_free(&p->lock);
3286c408 819 git__free(p);
a070f152
CMN
820}
821
822static int packfile_open(struct git_pack_file *p)
823{
824 struct stat st;
825 struct git_pack_header hdr;
826 git_oid sha1;
827 unsigned char *idx_sha1;
828
0d0fa7c3 829 if (!p->index_map.data && pack_index_open(p) < 0)
282283ac 830 return git_odb__error_notfound("failed to open packfile", NULL);
a070f152 831
9d2f841a
RB
832 /* if mwf opened by another thread, return now */
833 if (git_mutex_lock(&p->lock) < 0)
834 return packfile_error("failed to get lock for open");
835
836 if (p->mwf.fd >= 0) {
837 git_mutex_unlock(&p->lock);
838 return 0;
839 }
840
a070f152 841 /* TODO: open with noatime */
e1de726c 842 p->mwf.fd = git_futils_open_ro(p->pack_name);
9d2f841a
RB
843 if (p->mwf.fd < 0)
844 goto cleanup;
a070f152 845
e1de726c
RB
846 if (p_fstat(p->mwf.fd, &st) < 0 ||
847 git_mwindow_file_register(&p->mwf) < 0)
848 goto cleanup;
a070f152
CMN
849
850 /* If we created the struct before we had the pack we lack size. */
851 if (!p->mwf.size) {
852 if (!S_ISREG(st.st_mode))
853 goto cleanup;
e1de726c 854 p->mwf.size = (git_off_t)st.st_size;
a070f152
CMN
855 } else if (p->mwf.size != st.st_size)
856 goto cleanup;
857
858#if 0
859 /* We leave these file descriptors open with sliding mmap;
860 * there is no point keeping them open across exec(), though.
861 */
862 fd_flag = fcntl(p->mwf.fd, F_GETFD, 0);
863 if (fd_flag < 0)
e1de726c 864 goto cleanup;
a070f152
CMN
865
866 fd_flag |= FD_CLOEXEC;
867 if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
e1de726c 868 goto cleanup;
a070f152
CMN
869#endif
870
871 /* Verify we recognize this pack file format. */
e1de726c
RB
872 if (p_read(p->mwf.fd, &hdr, sizeof(hdr)) < 0 ||
873 hdr.hdr_signature != htonl(PACK_SIGNATURE) ||
874 !pack_version_ok(hdr.hdr_version))
a070f152
CMN
875 goto cleanup;
876
877 /* Verify the pack matches its index. */
e1de726c
RB
878 if (p->num_objects != ntohl(hdr.hdr_entries) ||
879 p_lseek(p->mwf.fd, p->mwf.size - GIT_OID_RAWSZ, SEEK_SET) == -1 ||
880 p_read(p->mwf.fd, sha1.id, GIT_OID_RAWSZ) < 0)
a070f152
CMN
881 goto cleanup;
882
883 idx_sha1 = ((unsigned char *)p->index_map.data) + p->index_map.len - 40;
884
9d2f841a
RB
885 if (git_oid__cmp(&sha1, (git_oid *)idx_sha1) != 0)
886 goto cleanup;
887
888 git_mutex_unlock(&p->lock);
889 return 0;
a070f152
CMN
890
891cleanup:
e1de726c 892 giterr_set(GITERR_OS, "Invalid packfile '%s'", p->pack_name);
9d2f841a 893
a070f152
CMN
894 p_close(p->mwf.fd);
895 p->mwf.fd = -1;
9d2f841a
RB
896
897 git_mutex_unlock(&p->lock);
898
e1de726c 899 return -1;
a070f152
CMN
900}
901
5d2d21e5 902int git_packfile_alloc(struct git_pack_file **pack_out, const char *path)
a070f152
CMN
903{
904 struct stat st;
905 struct git_pack_file *p;
38eef611 906 size_t path_len = path ? strlen(path) : 0;
a070f152
CMN
907
908 *pack_out = NULL;
24c70804 909
38eef611 910 if (path_len < strlen(".idx"))
24c70804
RB
911 return git_odb__error_notfound("invalid packfile path", NULL);
912
38eef611 913 p = git__calloc(1, sizeof(*p) + path_len + 2);
e1de726c 914 GITERR_CHECK_ALLOC(p);
a070f152 915
38eef611
RB
916 memcpy(p->pack_name, path, path_len + 1);
917
a070f152
CMN
918 /*
919 * Make sure a corresponding .pack file exists and that
920 * the index looks sane.
921 */
38eef611
RB
922 if (git__suffixcmp(path, ".idx") == 0) {
923 size_t root_len = path_len - strlen(".idx");
924
925 memcpy(p->pack_name + root_len, ".keep", sizeof(".keep"));
926 if (git_path_exists(p->pack_name) == true)
927 p->pack_keep = 1;
a070f152 928
38eef611
RB
929 memcpy(p->pack_name + root_len, ".pack", sizeof(".pack"));
930 path_len = path_len - strlen(".idx") + strlen(".pack");
931 }
a070f152 932
e1de726c 933 if (p_stat(p->pack_name, &st) < 0 || !S_ISREG(st.st_mode)) {
3286c408 934 git__free(p);
282283ac 935 return git_odb__error_notfound("packfile not found", NULL);
a070f152
CMN
936 }
937
938 /* ok, it looks sane as far as we can check without
939 * actually mapping the pack file.
940 */
38eef611 941 p->mwf.fd = -1;
1af56d7d 942 p->mwf.size = st.st_size;
a070f152
CMN
943 p->pack_local = 1;
944 p->mtime = (git_time_t)st.st_mtime;
945
38eef611
RB
946 git_mutex_init(&p->lock);
947
a070f152
CMN
948 /* see if we can parse the sha1 oid in the packfile name */
949 if (path_len < 40 ||
e1de726c 950 git_oid_fromstr(&p->sha1, path + path_len - GIT_OID_HEXSZ) < 0)
a070f152
CMN
951 memset(&p->sha1, 0x0, GIT_OID_RAWSZ);
952
953 *pack_out = p;
e1de726c
RB
954
955 return 0;
a070f152
CMN
956}
957
958/***********************************************************
959 *
960 * PACKFILE ENTRY SEARCH INTERNALS
961 *
962 ***********************************************************/
963
e1de726c 964static git_off_t nth_packed_object_offset(const struct git_pack_file *p, uint32_t n)
a070f152
CMN
965{
966 const unsigned char *index = p->index_map.data;
967 index += 4 * 256;
968 if (p->index_version == 1) {
969 return ntohl(*((uint32_t *)(index + 24 * n)));
970 } else {
971 uint32_t off;
972 index += 8 + p->num_objects * (20 + 4);
973 off = ntohl(*((uint32_t *)(index + 4 * n)));
974 if (!(off & 0x80000000))
975 return off;
976 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
977 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
87d9869f 978 ntohl(*((uint32_t *)(index + 4)));
a070f152
CMN
979 }
980}
981
60ecdf59
DMB
982static int git__memcmp4(const void *a, const void *b) {
983 return memcmp(a, b, 4);
984}
985
521aedad 986int git_pack_foreach_entry(
5dca2010 987 struct git_pack_file *p,
c3fb7d04 988 git_odb_foreach_cb cb,
5dca2010 989 void *data)
521aedad
CMN
990{
991 const unsigned char *index = p->index_map.data, *current;
521aedad
CMN
992 uint32_t i;
993
994 if (index == NULL) {
995 int error;
996
997 if ((error = pack_index_open(p)) < 0)
998 return error;
999
1000 assert(p->index_map.data);
1001
1002 index = p->index_map.data;
1003 }
1004
1005 if (p->index_version > 1) {
1006 index += 8;
1007 }
1008
1009 index += 4 * 256;
1010
60ecdf59
DMB
1011 if (p->oids == NULL) {
1012 git_vector offsets, oids;
1013 int error;
521aedad 1014
60ecdf59
DMB
1015 if ((error = git_vector_init(&oids, p->num_objects, NULL)))
1016 return error;
1017
1018 if ((error = git_vector_init(&offsets, p->num_objects, git__memcmp4)))
1019 return error;
5dca2010 1020
60ecdf59
DMB
1021 if (p->index_version > 1) {
1022 const unsigned char *off = index + 24 * p->num_objects;
1023 for (i = 0; i < p->num_objects; i++)
1024 git_vector_insert(&offsets, (void*)&off[4 * i]);
1025 git_vector_sort(&offsets);
1026 git_vector_foreach(&offsets, i, current)
1027 git_vector_insert(&oids, (void*)&index[5 * (current - off)]);
1028 } else {
1029 for (i = 0; i < p->num_objects; i++)
1030 git_vector_insert(&offsets, (void*)&index[24 * i]);
1031 git_vector_sort(&offsets);
1032 git_vector_foreach(&offsets, i, current)
1033 git_vector_insert(&oids, (void*)&current[4]);
1034 }
1035 git_vector_free(&offsets);
1036 p->oids = (git_oid **)oids.contents;
521aedad
CMN
1037 }
1038
60ecdf59
DMB
1039 for (i = 0; i < p->num_objects; i++)
1040 if (cb(p->oids[i], data))
1041 return GIT_EUSER;
1042
521aedad
CMN
1043 return 0;
1044}
1045
a070f152 1046static int pack_entry_find_offset(
e1de726c
RB
1047 git_off_t *offset_out,
1048 git_oid *found_oid,
1049 struct git_pack_file *p,
1050 const git_oid *short_oid,
b8457baa 1051 size_t len)
a070f152 1052{
8c535f3f
RB
1053 const uint32_t *level1_ofs;
1054 const unsigned char *index;
a070f152
CMN
1055 unsigned hi, lo, stride;
1056 int pos, found = 0;
1057 const unsigned char *current = 0;
1058
1059 *offset_out = 0;
1060
8c535f3f
RB
1061 if (!p->index_map.data && pack_index_open(p) < 0)
1062 return git_odb__error_notfound("failed to open packfile", NULL);
a070f152 1063
8c535f3f
RB
1064 if (git_mutex_lock(&p->lock) < 0)
1065 return packfile_error("failed to get lock for finding entry offset");
a070f152 1066
8c535f3f
RB
1067 assert(p->index_map.data);
1068
1069 index = p->index_map.data;
1070 level1_ofs = p->index_map.data;
a070f152
CMN
1071
1072 if (p->index_version > 1) {
1073 level1_ofs += 2;
1074 index += 8;
1075 }
1076
1077 index += 4 * 256;
1078 hi = ntohl(level1_ofs[(int)short_oid->id[0]]);
1079 lo = ((short_oid->id[0] == 0x0) ? 0 : ntohl(level1_ofs[(int)short_oid->id[0] - 1]));
1080
1081 if (p->index_version > 1) {
1082 stride = 20;
1083 } else {
1084 stride = 24;
1085 index += 4;
1086 }
1087
1088#ifdef INDEX_DEBUG_LOOKUP
1089 printf("%02x%02x%02x... lo %u hi %u nr %d\n",
1090 short_oid->id[0], short_oid->id[1], short_oid->id[2], lo, hi, p->num_objects);
1091#endif
1092
1093 /* Use git.git lookup code */
87d9869f 1094 pos = sha1_entry_pos(index, stride, 0, lo, hi, p->num_objects, short_oid->id);
a070f152 1095
8c535f3f
RB
1096 git_mutex_unlock(&p->lock);
1097
a070f152
CMN
1098 if (pos >= 0) {
1099 /* An object matching exactly the oid was found */
1100 found = 1;
1101 current = index + pos * stride;
1102 } else {
1103 /* No object was found */
1104 /* pos refers to the object with the "closest" oid to short_oid */
1105 pos = - 1 - pos;
1106 if (pos < (int)p->num_objects) {
1107 current = index + pos * stride;
1108
282283ac 1109 if (!git_oid_ncmp(short_oid, (const git_oid *)current, len))
a070f152 1110 found = 1;
a070f152
CMN
1111 }
1112 }
1113
b2a2702d 1114 if (found && len != GIT_OID_HEXSZ && pos + 1 < (int)p->num_objects) {
a070f152
CMN
1115 /* Check for ambiguousity */
1116 const unsigned char *next = current + stride;
1117
1118 if (!git_oid_ncmp(short_oid, (const git_oid *)next, len)) {
1119 found = 2;
1120 }
1121 }
1122
e1de726c 1123 if (!found)
282283ac 1124 return git_odb__error_notfound("failed to find offset for pack entry", short_oid);
e1de726c
RB
1125 if (found > 1)
1126 return git_odb__error_ambiguous("found multiple offsets for pack entry");
24c70804 1127
e1de726c
RB
1128 *offset_out = nth_packed_object_offset(p, pos);
1129 git_oid_fromraw(found_oid, current);
a070f152
CMN
1130
1131#ifdef INDEX_DEBUG_LOOKUP
e1de726c 1132 {
a070f152
CMN
1133 unsigned char hex_sha1[GIT_OID_HEXSZ + 1];
1134 git_oid_fmt(hex_sha1, found_oid);
1135 hex_sha1[GIT_OID_HEXSZ] = '\0';
1136 printf("found lo=%d %s\n", lo, hex_sha1);
a070f152 1137 }
e1de726c 1138#endif
24c70804 1139
e1de726c 1140 return 0;
a070f152
CMN
1141}
1142
1143int git_pack_entry_find(
1144 struct git_pack_entry *e,
1145 struct git_pack_file *p,
1146 const git_oid *short_oid,
b8457baa 1147 size_t len)
a070f152 1148{
e1de726c 1149 git_off_t offset;
a070f152
CMN
1150 git_oid found_oid;
1151 int error;
1152
1153 assert(p);
1154
1155 if (len == GIT_OID_HEXSZ && p->num_bad_objects) {
1156 unsigned i;
1157 for (i = 0; i < p->num_bad_objects; i++)
b7f167da 1158 if (git_oid__cmp(short_oid, &p->bad_object_sha1[i]) == 0)
e1de726c 1159 return packfile_error("bad object found in packfile");
a070f152
CMN
1160 }
1161
1162 error = pack_entry_find_offset(&offset, &found_oid, p, short_oid, len);
e1de726c
RB
1163 if (error < 0)
1164 return error;
a070f152
CMN
1165
1166 /* we found a unique entry in the index;
1167 * make sure the packfile backing the index
1168 * still exists on disk */
e1de726c
RB
1169 if (p->mwf.fd == -1 && (error = packfile_open(p)) < 0)
1170 return error;
a070f152
CMN
1171
1172 e->offset = offset;
1173 e->p = p;
1174
1175 git_oid_cpy(&e->sha1, &found_oid);
e1de726c 1176 return 0;
a070f152 1177}