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