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