[PATCH] verify-pack updates.
[git/git.git] / sha1_file.c
CommitLineData
0fcfd160
LT
1/*
2 * GIT - The information manager from hell
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 *
6 * This handles basic git sha1 object files - packing, unpacking,
7 * creation etc.
8 */
1f688557
JH
9#include <sys/types.h>
10#include <dirent.h>
0fcfd160 11#include "cache.h"
1f688557 12#include "delta.h"
a733cb60 13#include "pack.h"
0fcfd160 14
144bde78
LT
15#ifndef O_NOATIME
16#if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
17#define O_NOATIME 01000000
18#else
19#define O_NOATIME 0
20#endif
21#endif
22
23static unsigned int sha1_file_open_flag = O_NOATIME;
24
0fcfd160
LT
25static unsigned hexval(char c)
26{
27 if (c >= '0' && c <= '9')
28 return c - '0';
29 if (c >= 'a' && c <= 'f')
30 return c - 'a' + 10;
31 if (c >= 'A' && c <= 'F')
32 return c - 'A' + 10;
33 return ~0;
34}
35
36int get_sha1_hex(const char *hex, unsigned char *sha1)
37{
38 int i;
39 for (i = 0; i < 20; i++) {
40 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
41 if (val & ~0xff)
42 return -1;
43 *sha1++ = val;
44 hex += 2;
45 }
46 return 0;
47}
48
e99d59ff 49static int get_sha1_file(const char *path, unsigned char *result)
3c249c95
LT
50{
51 char buffer[60];
52 int fd = open(path, O_RDONLY);
53 int len;
54
55 if (fd < 0)
56 return -1;
57 len = read(fd, buffer, sizeof(buffer));
58 close(fd);
59 if (len < 40)
60 return -1;
61 return get_sha1_hex(buffer, result);
62}
63
95fc7512 64static char *git_dir, *git_object_dir, *git_index_file, *git_refs_dir;
8ac069ac
JH
65static void setup_git_env(void)
66{
67 git_dir = gitenv(GIT_DIR_ENVIRONMENT);
68 if (!git_dir)
69 git_dir = DEFAULT_GIT_DIR_ENVIRONMENT;
70 git_object_dir = gitenv(DB_ENVIRONMENT);
71 if (!git_object_dir) {
72 git_object_dir = xmalloc(strlen(git_dir) + 9);
73 sprintf(git_object_dir, "%s/objects", git_dir);
74 }
95fc7512
DB
75 git_refs_dir = xmalloc(strlen(git_dir) + 6);
76 sprintf(git_refs_dir, "%s/refs", git_dir);
8ac069ac
JH
77 git_index_file = gitenv(INDEX_ENVIRONMENT);
78 if (!git_index_file) {
79 git_index_file = xmalloc(strlen(git_dir) + 7);
80 sprintf(git_index_file, "%s/index", git_dir);
81 }
82}
83
84char *get_object_directory(void)
85{
86 if (!git_object_dir)
87 setup_git_env();
88 return git_object_dir;
89}
90
95fc7512
DB
91char *get_refs_directory(void)
92{
93 if (!git_refs_dir)
94 setup_git_env();
95 return git_refs_dir;
96}
97
8ac069ac
JH
98char *get_index_file(void)
99{
100 if (!git_index_file)
101 setup_git_env();
102 return git_index_file;
103}
104
3c249c95
LT
105int get_sha1(const char *str, unsigned char *sha1)
106{
107 static char pathname[PATH_MAX];
35ad3382
LT
108 static const char *prefix[] = {
109 "",
110 "refs",
111 "refs/tags",
112 "refs/heads",
113 "refs/snap",
114 NULL
115 };
35ad3382 116 const char **p;
3c249c95
LT
117
118 if (!get_sha1_hex(str, sha1))
119 return 0;
35ad3382 120
8ac069ac
JH
121 if (!git_dir)
122 setup_git_env();
35ad3382 123 for (p = prefix; *p; p++) {
8ac069ac
JH
124 snprintf(pathname, sizeof(pathname), "%s/%s/%s",
125 git_dir, *p, str);
35ad3382
LT
126 if (!get_sha1_file(pathname, sha1))
127 return 0;
128 }
129
3c249c95
LT
130 return -1;
131}
132
0fcfd160
LT
133char * sha1_to_hex(const unsigned char *sha1)
134{
135 static char buffer[50];
136 static const char hex[] = "0123456789abcdef";
137 char *buf = buffer;
138 int i;
139
140 for (i = 0; i < 20; i++) {
141 unsigned int val = *sha1++;
142 *buf++ = hex[val >> 4];
143 *buf++ = hex[val & 0xf];
144 }
145 return buffer;
146}
147
ace1534d
JH
148static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
149{
150 int i;
151 for (i = 0; i < 20; i++) {
152 static char hex[] = "0123456789abcdef";
153 unsigned int val = sha1[i];
154 char *pos = pathbuf + i*2 + (i > 0);
155 *pos++ = hex[val >> 4];
156 *pos = hex[val & 0xf];
157 }
158}
159
0fcfd160
LT
160/*
161 * NOTE! This returns a statically allocated buffer, so you have to be
162 * careful about using it. Do a "strdup()" if you need to save the
163 * filename.
ace1534d
JH
164 *
165 * Also note that this returns the location for creating. Reading
166 * SHA1 file can happen from any alternate directory listed in the
d19938ab 167 * DB_ENVIRONMENT environment variable if it is not found in
ace1534d 168 * the primary object database.
0fcfd160
LT
169 */
170char *sha1_file_name(const unsigned char *sha1)
171{
0fcfd160
LT
172 static char *name, *base;
173
174 if (!base) {
d19938ab 175 const char *sha1_file_directory = get_object_directory();
0fcfd160 176 int len = strlen(sha1_file_directory);
812666c8 177 base = xmalloc(len + 60);
0fcfd160
LT
178 memcpy(base, sha1_file_directory, len);
179 memset(base+len, 0, 60);
180 base[len] = '/';
181 base[len+3] = '/';
182 name = base + len + 1;
183 }
ace1534d 184 fill_sha1_path(name, sha1);
0fcfd160
LT
185 return base;
186}
187
9a217f2a 188struct alternate_object_database *alt_odb;
ace1534d 189
ddd5d056
JH
190/*
191 * Prepare alternate object database registry.
192 * alt_odb points at an array of struct alternate_object_database.
193 * This array is terminated with an element that has both its base
194 * and name set to NULL. alt_odb[n] comes from n'th non-empty
d19938ab 195 * element from colon separated ALTERNATE_DB_ENVIRONMENT environment
ddd5d056
JH
196 * variable, and its base points at a statically allocated buffer
197 * that contains "/the/directory/corresponding/to/.git/objects/...",
198 * while its name points just after the slash at the end of
199 * ".git/objects/" in the example above, and has enough space to hold
200 * 40-byte hex SHA1, an extra slash for the first level indirection,
201 * and the terminating NUL.
202 * This function allocates the alt_odb array and all the strings
203 * pointed by base fields of the array elements with one xmalloc();
204 * the string pool immediately follows the array.
205 */
9a217f2a 206void prepare_alt_odb(void)
ace1534d
JH
207{
208 int pass, totlen, i;
ace1534d 209 const char *cp, *last;
e99d59ff 210 char *op = NULL;
d19938ab 211 const char *alt = gitenv(ALTERNATE_DB_ENVIRONMENT) ? : "";
ace1534d 212
9a217f2a
JH
213 if (alt_odb)
214 return;
ddd5d056
JH
215 /* The first pass counts how large an area to allocate to
216 * hold the entire alt_odb structure, including array of
217 * structs and path buffers for them. The second pass fills
218 * the structure and prepares the path buffers for use by
219 * fill_sha1_path().
220 */
ace1534d
JH
221 for (totlen = pass = 0; pass < 2; pass++) {
222 last = alt;
223 i = 0;
224 do {
225 cp = strchr(last, ':') ? : last + strlen(last);
226 if (last != cp) {
227 /* 43 = 40-byte + 2 '/' + terminating NUL */
228 int pfxlen = cp - last;
229 int entlen = pfxlen + 43;
230 if (pass == 0)
231 totlen += entlen;
232 else {
233 alt_odb[i].base = op;
234 alt_odb[i].name = op + pfxlen + 1;
235 memcpy(op, last, pfxlen);
236 op[pfxlen] = op[pfxlen + 3] = '/';
237 op[entlen-1] = 0;
238 op += entlen;
239 }
240 i++;
241 }
242 while (*cp && *cp == ':')
243 cp++;
244 last = cp;
245 } while (*cp);
246 if (pass)
247 break;
ddd5d056 248 alt_odb = xmalloc(sizeof(*alt_odb) * (i + 1) + totlen);
e99d59ff 249 alt_odb[i].base = alt_odb[i].name = NULL;
ace1534d
JH
250 op = (char*)(&alt_odb[i+1]);
251 }
252}
253
254static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
255{
256 int i;
257 char *name = sha1_file_name(sha1);
258
259 if (!stat(name, st))
260 return name;
9a217f2a 261 prepare_alt_odb();
ace1534d
JH
262 for (i = 0; (name = alt_odb[i].name) != NULL; i++) {
263 fill_sha1_path(name, sha1);
264 if (!stat(alt_odb[i].base, st))
265 return alt_odb[i].base;
266 }
267 return NULL;
268}
269
1f688557
JH
270#define PACK_MAX_SZ (1<<26)
271static int pack_used_ctr;
272static unsigned long pack_mapped;
9a217f2a 273struct packed_git *packed_git;
1f688557 274
1f688557
JH
275static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
276 void **idx_map_)
277{
278 void *idx_map;
279 unsigned int *index;
280 unsigned long idx_size;
281 int nr, i;
282 int fd = open(path, O_RDONLY);
283 struct stat st;
284 if (fd < 0)
285 return -1;
286 if (fstat(fd, &st)) {
287 close(fd);
288 return -1;
289 }
290 idx_size = st.st_size;
291 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
292 close(fd);
293 if (idx_map == MAP_FAILED)
294 return -1;
295
296 index = idx_map;
297
298 /* check index map */
f9253394 299 if (idx_size < 4*256 + 20 + 20)
1f688557
JH
300 return error("index file too small");
301 nr = 0;
302 for (i = 0; i < 256; i++) {
303 unsigned int n = ntohl(index[i]);
304 if (n < nr)
305 return error("non-monotonic index");
306 nr = n;
307 }
308
309 /*
310 * Total size:
311 * - 256 index entries 4 bytes each
312 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
313 * - 20-byte SHA1 of the packfile
314 * - 20-byte SHA1 file checksum
315 */
316 if (idx_size != 4*256 + nr * 24 + 20 + 20)
317 return error("wrong index file size");
318
319 *idx_map_ = idx_map;
320 *idx_size_ = idx_size;
321 return 0;
322}
323
f9253394 324static int unuse_one_packed_git(void)
1f688557 325{
f9253394
JH
326 struct packed_git *p, *lru = NULL;
327
328 for (p = packed_git; p; p = p->next) {
329 if (p->pack_use_cnt || !p->pack_base)
330 continue;
331 if (!lru || p->pack_last_used < lru->pack_last_used)
332 lru = p;
333 }
334 if (!lru)
335 return 0;
336 munmap(lru->pack_base, lru->pack_size);
337 lru->pack_base = NULL;
338 return 1;
339}
340
341void unuse_packed_git(struct packed_git *p)
342{
343 p->pack_use_cnt--;
1f688557
JH
344}
345
f9253394 346int use_packed_git(struct packed_git *p)
1f688557
JH
347{
348 if (!p->pack_base) {
349 int fd;
350 struct stat st;
351 void *map;
352
353 pack_mapped += p->pack_size;
f9253394
JH
354 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
355 ; /* nothing */
1f688557
JH
356 fd = open(p->pack_name, O_RDONLY);
357 if (fd < 0)
f9253394 358 die("packfile %s cannot be opened", p->pack_name);
1f688557
JH
359 if (fstat(fd, &st)) {
360 close(fd);
f9253394 361 die("packfile %s cannot be opened", p->pack_name);
1f688557
JH
362 }
363 if (st.st_size != p->pack_size)
f9253394 364 die("packfile %s size mismatch.", p->pack_name);
1f688557
JH
365 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
366 close(fd);
367 if (map == MAP_FAILED)
f9253394 368 die("packfile %s cannot be mapped.", p->pack_name);
1f688557 369 p->pack_base = map;
f9253394
JH
370
371 /* Check if the pack file matches with the index file.
372 * this is cheap.
373 */
374 if (memcmp((char*)(p->index_base) + p->index_size - 40,
375 p->pack_base + p->pack_size - 20, 20))
376 die("packfile %s does not match index.", p->pack_name);
1f688557
JH
377 }
378 p->pack_last_used = pack_used_ctr++;
f9253394 379 p->pack_use_cnt++;
1f688557
JH
380 return 0;
381}
382
f9253394 383struct packed_git *add_packed_git(char *path, int path_len)
1f688557
JH
384{
385 struct stat st;
386 struct packed_git *p;
387 unsigned long idx_size;
388 void *idx_map;
389
390 if (check_packed_git_idx(path, &idx_size, &idx_map))
391 return NULL;
392
393 /* do we have a corresponding .pack file? */
394 strcpy(path + path_len - 4, ".pack");
395 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
396 munmap(idx_map, idx_size);
397 return NULL;
398 }
399 /* ok, it looks sane as far as we can check without
400 * actually mapping the pack file.
401 */
402 p = xmalloc(sizeof(*p) + path_len + 2);
403 strcpy(p->pack_name, path);
404 p->index_size = idx_size;
405 p->pack_size = st.st_size;
406 p->index_base = idx_map;
407 p->next = NULL;
d85a4fee 408 p->pack_base = NULL;
1f688557 409 p->pack_last_used = 0;
f9253394 410 p->pack_use_cnt = 0;
1f688557
JH
411 return p;
412}
413
414static void prepare_packed_git_one(char *objdir)
415{
416 char path[PATH_MAX];
417 int len;
418 DIR *dir;
419 struct dirent *de;
420
421 sprintf(path, "%s/pack", objdir);
422 len = strlen(path);
423 dir = opendir(path);
424 if (!dir)
425 return;
426 path[len++] = '/';
427 while ((de = readdir(dir)) != NULL) {
428 int namelen = strlen(de->d_name);
429 struct packed_git *p;
430
431 if (strcmp(de->d_name + namelen - 4, ".idx"))
432 continue;
433
434 /* we have .idx. Is it a file we can map? */
435 strcpy(path + len, de->d_name);
436 p = add_packed_git(path, len + namelen);
437 if (!p)
438 continue;
439 p->next = packed_git;
440 packed_git = p;
441 }
442}
443
9a217f2a 444void prepare_packed_git(void)
1f688557
JH
445{
446 int i;
447 static int run_once = 0;
448
449 if (run_once++)
450 return;
451
452 prepare_packed_git_one(get_object_directory());
9a217f2a 453 prepare_alt_odb();
1f688557
JH
454 for (i = 0; alt_odb[i].base != NULL; i++) {
455 alt_odb[i].name[0] = 0;
456 prepare_packed_git_one(alt_odb[i].base);
457 }
458}
459
5d6ccf5c 460int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
0fcfd160 461{
d98b46f8 462 char header[100];
0fcfd160
LT
463 unsigned char real_sha1[20];
464 SHA_CTX c;
465
466 SHA1_Init(&c);
d98b46f8 467 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
0fcfd160
LT
468 SHA1_Update(&c, map, size);
469 SHA1_Final(real_sha1, &c);
470 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
471}
472
1f688557
JH
473static void *map_sha1_file_internal(const unsigned char *sha1,
474 unsigned long *size,
475 int say_error)
0fcfd160 476{
0fcfd160
LT
477 struct stat st;
478 void *map;
144bde78 479 int fd;
ace1534d
JH
480 char *filename = find_sha1_file(sha1, &st);
481
482 if (!filename) {
1f688557
JH
483 if (say_error)
484 error("cannot map sha1 file %s", sha1_to_hex(sha1));
ace1534d
JH
485 return NULL;
486 }
0fcfd160 487
144bde78 488 fd = open(filename, O_RDONLY | sha1_file_open_flag);
0fcfd160 489 if (fd < 0) {
144bde78
LT
490 /* See if it works without O_NOATIME */
491 switch (sha1_file_open_flag) {
492 default:
493 fd = open(filename, O_RDONLY);
494 if (fd >= 0)
495 break;
496 /* Fallthrough */
497 case 0:
1f688557
JH
498 if (say_error)
499 perror(filename);
144bde78
LT
500 return NULL;
501 }
502
1f688557
JH
503 /* If it failed once, it will probably fail again.
504 * Stop using O_NOATIME
505 */
144bde78 506 sha1_file_open_flag = 0;
0fcfd160 507 }
0fcfd160
LT
508 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
509 close(fd);
510 if (-1 == (int)(long)map)
511 return NULL;
512 *size = st.st_size;
513 return map;
514}
515
1f688557
JH
516void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
517{
518 return map_sha1_file_internal(sha1, size, 1);
519}
520
c4483576
LT
521int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
522{
523 /* Get the data stream */
524 memset(stream, 0, sizeof(*stream));
525 stream->next_in = map;
526 stream->avail_in = mapsize;
527 stream->next_out = buffer;
528 stream->avail_out = size;
529
530 inflateInit(stream);
531 return inflate(stream, 0);
532}
533
5180cacc
LT
534void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
535{
536 int bytes = strlen(buffer) + 1;
d565b341 537 unsigned char *buf = xmalloc(1+size);
5180cacc
LT
538
539 memcpy(buf, buffer + bytes, stream->total_out - bytes);
540 bytes = stream->total_out - bytes;
541 if (bytes < size) {
542 stream->next_out = buf + bytes;
543 stream->avail_out = size - bytes;
544 while (inflate(stream, Z_FINISH) == Z_OK)
545 /* nothing */;
546 }
547 buf[size] = 0;
548 inflateEnd(stream);
549 return buf;
550}
551
552/*
553 * We used to just use "sscanf()", but that's actually way
554 * too permissive for what we want to check. So do an anal
555 * object header parse by hand.
556 */
557int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
558{
559 int i;
560 unsigned long size;
561
562 /*
563 * The type can be at most ten bytes (including the
564 * terminating '\0' that we add), and is followed by
565 * a space.
566 */
567 i = 10;
568 for (;;) {
569 char c = *hdr++;
570 if (c == ' ')
571 break;
572 if (!--i)
573 return -1;
574 *type++ = c;
575 }
576 *type = 0;
577
578 /*
579 * The length must follow immediately, and be in canonical
580 * decimal format (ie "010" is not valid).
581 */
582 size = *hdr++ - '0';
583 if (size > 9)
584 return -1;
585 if (size) {
586 for (;;) {
587 unsigned long c = *hdr - '0';
588 if (c > 9)
589 break;
590 hdr++;
591 size = size * 10 + c;
592 }
593 }
594 *sizep = size;
595
596 /*
597 * The length must be followed by a zero byte
598 */
599 return *hdr ? -1 : 0;
600}
601
0fcfd160
LT
602void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
603{
5180cacc 604 int ret;
0fcfd160 605 z_stream stream;
5180cacc 606 char hdr[8192];
0fcfd160 607
5180cacc
LT
608 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
609 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
0fcfd160
LT
610 return NULL;
611
5180cacc 612 return unpack_sha1_rest(&stream, hdr, *size);
0fcfd160
LT
613}
614
f3bf9224
JH
615/* forward declaration for a mutually recursive function */
616static int packed_object_info(struct pack_entry *entry,
617 char *type, unsigned long *sizep);
618
5db47c2b
JH
619static int packed_delta_info(unsigned char *base_sha1,
620 unsigned long delta_size,
621 unsigned long left,
622 char *type,
f3bf9224
JH
623 unsigned long *sizep,
624 struct packed_git *p)
5db47c2b 625{
f3bf9224
JH
626 struct pack_entry base_ent;
627
5db47c2b
JH
628 if (left < 20)
629 die("truncated pack file");
5db47c2b 630
f3bf9224
JH
631 /* The base entry _must_ be in the same pack */
632 if (!find_pack_entry_one(base_sha1, &base_ent, p))
633 die("failed to find delta-pack base object %s",
634 sha1_to_hex(base_sha1));
635
c62266f3
JH
636 /* We choose to only get the type of the base object and
637 * ignore potentially corrupt pack file that expects the delta
638 * based on a base with a wrong size. This saves tons of
639 * inflate() calls.
640 */
5db47c2b 641
f3bf9224 642 if (packed_object_info(&base_ent, type, NULL))
c62266f3 643 die("cannot get info for delta-pack base");
5db47c2b 644
c62266f3
JH
645 if (sizep) {
646 const unsigned char *data;
647 unsigned char delta_head[64];
648 unsigned long result_size;
649 z_stream stream;
650 int st;
651
652 memset(&stream, 0, sizeof(stream));
653
654 data = stream.next_in = base_sha1 + 20;
655 stream.avail_in = left - 20;
656 stream.next_out = delta_head;
657 stream.avail_out = sizeof(delta_head);
658
659 inflateInit(&stream);
660 st = inflate(&stream, Z_FINISH);
661 inflateEnd(&stream);
662 if ((st != Z_STREAM_END) &&
663 stream.total_out != sizeof(delta_head))
664 die("delta data unpack-initial failed");
665
666 /* Examine the initial part of the delta to figure out
667 * the result size.
668 */
669 data = delta_head;
670 get_delta_hdr_size(&data); /* ignore base size */
5db47c2b 671
c62266f3
JH
672 /* Read the result size */
673 result_size = get_delta_hdr_size(&data);
674 *sizep = result_size;
675 }
5db47c2b
JH
676 return 0;
677}
678
a733cb60
LT
679static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
680 enum object_type *type, unsigned long *sizep)
681{
01247d87 682 unsigned shift;
a733cb60
LT
683 unsigned char *pack, c;
684 unsigned long size;
685
686 if (offset >= p->pack_size)
687 die("object offset outside of pack file");
688
689 pack = p->pack_base + offset;
690 c = *pack++;
691 offset++;
692 *type = (c >> 4) & 7;
693 size = c & 15;
01247d87 694 shift = 4;
a733cb60
LT
695 while (c & 0x80) {
696 if (offset >= p->pack_size)
697 die("object offset outside of pack file");
698 c = *pack++;
699 offset++;
01247d87
LT
700 size += (c & 0x7f) << shift;
701 shift += 7;
a733cb60
LT
702 }
703 *sizep = size;
704 return offset;
705}
706
1f688557
JH
707static int packed_object_info(struct pack_entry *entry,
708 char *type, unsigned long *sizep)
709{
710 struct packed_git *p = entry->p;
711 unsigned long offset, size, left;
712 unsigned char *pack;
a733cb60 713 enum object_type kind;
f9253394 714 int retval;
5db47c2b
JH
715
716 if (use_packed_git(p))
717 die("cannot map packed file");
718
a733cb60 719 offset = unpack_object_header(p, entry->offset, &kind, &size);
1f688557 720 pack = p->pack_base + offset;
a733cb60
LT
721 left = p->pack_size - offset;
722
723 switch (kind) {
724 case OBJ_DELTA:
f3bf9224 725 retval = packed_delta_info(pack, size, left, type, sizep, p);
f9253394
JH
726 unuse_packed_git(p);
727 return retval;
a733cb60 728 case OBJ_COMMIT:
1f688557
JH
729 strcpy(type, "commit");
730 break;
a733cb60 731 case OBJ_TREE:
1f688557
JH
732 strcpy(type, "tree");
733 break;
a733cb60 734 case OBJ_BLOB:
1f688557
JH
735 strcpy(type, "blob");
736 break;
a733cb60 737 case OBJ_TAG:
a69d0943
LT
738 strcpy(type, "tag");
739 break;
1f688557
JH
740 default:
741 die("corrupted pack file");
742 }
c62266f3
JH
743 if (sizep)
744 *sizep = size;
f9253394 745 unuse_packed_git(p);
1f688557
JH
746 return 0;
747}
748
749/* forward declaration for a mutually recursive function */
750static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
751
752static void *unpack_delta_entry(unsigned char *base_sha1,
753 unsigned long delta_size,
754 unsigned long left,
755 char *type,
f3bf9224
JH
756 unsigned long *sizep,
757 struct packed_git *p)
1f688557 758{
f3bf9224 759 struct pack_entry base_ent;
1f688557
JH
760 void *data, *delta_data, *result, *base;
761 unsigned long data_size, result_size, base_size;
762 z_stream stream;
763 int st;
764
765 if (left < 20)
766 die("truncated pack file");
767 data = base_sha1 + 20;
768 data_size = left - 20;
769 delta_data = xmalloc(delta_size);
770
771 memset(&stream, 0, sizeof(stream));
772
773 stream.next_in = data;
774 stream.avail_in = data_size;
775 stream.next_out = delta_data;
776 stream.avail_out = delta_size;
777
778 inflateInit(&stream);
779 st = inflate(&stream, Z_FINISH);
780 inflateEnd(&stream);
781 if ((st != Z_STREAM_END) || stream.total_out != delta_size)
782 die("delta data unpack failed");
783
f3bf9224
JH
784 /* The base entry _must_ be in the same pack */
785 if (!find_pack_entry_one(base_sha1, &base_ent, p))
786 die("failed to find delta-pack base object %s",
787 sha1_to_hex(base_sha1));
788 base = unpack_entry_gently(&base_ent, type, &base_size);
1f688557
JH
789 if (!base)
790 die("failed to read delta-pack base object %s",
791 sha1_to_hex(base_sha1));
792 result = patch_delta(base, base_size,
793 delta_data, delta_size,
794 &result_size);
795 if (!result)
796 die("failed to apply delta");
797 free(delta_data);
798 free(base);
799 *sizep = result_size;
800 return result;
801}
802
803static void *unpack_non_delta_entry(unsigned char *data,
804 unsigned long size,
805 unsigned long left)
806{
807 int st;
808 z_stream stream;
809 char *buffer;
810
811 buffer = xmalloc(size + 1);
812 buffer[size] = 0;
813 memset(&stream, 0, sizeof(stream));
814 stream.next_in = data;
815 stream.avail_in = left;
816 stream.next_out = buffer;
817 stream.avail_out = size;
818
819 inflateInit(&stream);
820 st = inflate(&stream, Z_FINISH);
821 inflateEnd(&stream);
822 if ((st != Z_STREAM_END) || stream.total_out != size) {
823 free(buffer);
824 return NULL;
825 }
826
827 return buffer;
828}
829
830static void *unpack_entry(struct pack_entry *entry,
831 char *type, unsigned long *sizep)
832{
833 struct packed_git *p = entry->p;
f9253394 834 void *retval;
1f688557
JH
835
836 if (use_packed_git(p))
837 die("cannot map packed file");
f3bf9224
JH
838 retval = unpack_entry_gently(entry, type, sizep);
839 unuse_packed_git(p);
840 if (!retval)
841 die("corrupted pack file");
842 return retval;
843}
844
845/* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
846void *unpack_entry_gently(struct pack_entry *entry,
847 char *type, unsigned long *sizep)
848{
849 struct packed_git *p = entry->p;
850 unsigned long offset, size, left;
851 unsigned char *pack;
852 enum object_type kind;
853 void *retval;
1f688557 854
a733cb60 855 offset = unpack_object_header(p, entry->offset, &kind, &size);
1f688557 856 pack = p->pack_base + offset;
a733cb60
LT
857 left = p->pack_size - offset;
858 switch (kind) {
859 case OBJ_DELTA:
f3bf9224 860 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
f9253394 861 return retval;
a733cb60 862 case OBJ_COMMIT:
1f688557
JH
863 strcpy(type, "commit");
864 break;
a733cb60 865 case OBJ_TREE:
1f688557
JH
866 strcpy(type, "tree");
867 break;
a733cb60 868 case OBJ_BLOB:
1f688557
JH
869 strcpy(type, "blob");
870 break;
a733cb60 871 case OBJ_TAG:
a69d0943
LT
872 strcpy(type, "tag");
873 break;
1f688557 874 default:
f3bf9224 875 return NULL;
1f688557
JH
876 }
877 *sizep = size;
f9253394 878 retval = unpack_non_delta_entry(pack, size, left);
f9253394 879 return retval;
1f688557
JH
880}
881
9a217f2a
JH
882int num_packed_objects(const struct packed_git *p)
883{
f9253394 884 /* See check_packed_git_idx() */
9a217f2a
JH
885 return (p->index_size - 20 - 20 - 4*256) / 24;
886}
887
888int nth_packed_object_sha1(const struct packed_git *p, int n,
889 unsigned char* sha1)
890{
891 void *index = p->index_base + 256;
892 if (n < 0 || num_packed_objects(p) <= n)
893 return -1;
894 memcpy(sha1, (index + 24 * n + 4), 20);
895 return 0;
896}
897
f3bf9224
JH
898int find_pack_entry_one(const unsigned char *sha1,
899 struct pack_entry *e, struct packed_git *p)
1f688557
JH
900{
901 int *level1_ofs = p->index_base;
902 int hi = ntohl(level1_ofs[*sha1]);
903 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
904 void *index = p->index_base + 256;
905
906 do {
907 int mi = (lo + hi) / 2;
908 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
909 if (!cmp) {
910 e->offset = ntohl(*((int*)(index + 24 * mi)));
911 memcpy(e->sha1, sha1, 20);
912 e->p = p;
913 return 1;
914 }
915 if (cmp > 0)
916 hi = mi;
917 else
918 lo = mi+1;
919 } while (lo < hi);
920 return 0;
921}
922
923static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
924{
925 struct packed_git *p;
926 prepare_packed_git();
927
928 for (p = packed_git; p; p = p->next) {
f3bf9224 929 if (find_pack_entry_one(sha1, e, p))
1f688557
JH
930 return 1;
931 }
932 return 0;
933}
934
36e4d74a 935int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
65c2e0c3 936{
36e4d74a 937 int status;
65c2e0c3
JH
938 unsigned long mapsize, size;
939 void *map;
940 z_stream stream;
36e4d74a 941 char hdr[128];
65c2e0c3 942
1f688557
JH
943 map = map_sha1_file_internal(sha1, &mapsize, 0);
944 if (!map) {
945 struct pack_entry e;
946
947 if (!find_pack_entry(sha1, &e))
948 return error("unable to find %s", sha1_to_hex(sha1));
c62266f3 949 return packed_object_info(&e, type, sizep);
1f688557 950 }
36e4d74a
JH
951 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
952 status = error("unable to unpack %s header",
953 sha1_to_hex(sha1));
954 if (parse_sha1_header(hdr, type, &size) < 0)
955 status = error("unable to parse %s header", sha1_to_hex(sha1));
c4584ae3 956 else {
65c2e0c3 957 status = 0;
c62266f3
JH
958 if (sizep)
959 *sizep = size;
65c2e0c3 960 }
65c2e0c3
JH
961 inflateEnd(&stream);
962 munmap(map, mapsize);
963 return status;
964}
965
1f688557
JH
966static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
967{
968 struct pack_entry e;
969
970 if (!find_pack_entry(sha1, &e)) {
971 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
972 return NULL;
973 }
974 return unpack_entry(&e, type, size);
975}
976
0fcfd160
LT
977void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
978{
979 unsigned long mapsize;
980 void *map, *buf;
981
1f688557 982 map = map_sha1_file_internal(sha1, &mapsize, 0);
0fcfd160
LT
983 if (map) {
984 buf = unpack_sha1_file(map, mapsize, type, size);
985 munmap(map, mapsize);
986 return buf;
987 }
1f688557 988 return read_packed_sha1(sha1, type, size);
0fcfd160
LT
989}
990
40469ee9 991void *read_object_with_reference(const unsigned char *sha1,
bf0f910d 992 const char *required_type,
40469ee9
JH
993 unsigned long *size,
994 unsigned char *actual_sha1_return)
f4913f91
JH
995{
996 char type[20];
997 void *buffer;
998 unsigned long isize;
40469ee9 999 unsigned char actual_sha1[20];
f4913f91 1000
40469ee9
JH
1001 memcpy(actual_sha1, sha1, 20);
1002 while (1) {
1003 int ref_length = -1;
1004 const char *ref_type = NULL;
f4913f91 1005
40469ee9
JH
1006 buffer = read_sha1_file(actual_sha1, type, &isize);
1007 if (!buffer)
1008 return NULL;
1009 if (!strcmp(type, required_type)) {
1010 *size = isize;
1011 if (actual_sha1_return)
1012 memcpy(actual_sha1_return, actual_sha1, 20);
1013 return buffer;
1014 }
1015 /* Handle references */
1016 else if (!strcmp(type, "commit"))
1017 ref_type = "tree ";
1018 else if (!strcmp(type, "tag"))
1019 ref_type = "object ";
1020 else {
1021 free(buffer);
1022 return NULL;
1023 }
1024 ref_length = strlen(ref_type);
f4913f91 1025
40469ee9
JH
1026 if (memcmp(buffer, ref_type, ref_length) ||
1027 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1028 free(buffer);
1029 return NULL;
1030 }
1031 /* Now we have the ID of the referred-to object in
1032 * actual_sha1. Check again. */
f4913f91 1033 }
f4913f91
JH
1034}
1035
d410c0f5
JH
1036static char *write_sha1_file_prepare(void *buf,
1037 unsigned long len,
1038 const char *type,
1039 unsigned char *sha1,
1040 unsigned char *hdr,
1041 int *hdrlen)
1042{
1043 SHA_CTX c;
1044
1045 /* Generate the header */
1046 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1047
1048 /* Sha1.. */
1049 SHA1_Init(&c);
1050 SHA1_Update(&c, hdr, *hdrlen);
1051 SHA1_Update(&c, buf, len);
1052 SHA1_Final(sha1, &c);
1053
1054 return sha1_file_name(sha1);
1055}
1056
bf0f910d 1057int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
0fcfd160
LT
1058{
1059 int size;
bf0f910d 1060 unsigned char *compressed;
0fcfd160
LT
1061 z_stream stream;
1062 unsigned char sha1[20];
706bc531 1063 char *filename;
aac17941 1064 static char tmpfile[PATH_MAX];
bf0f910d 1065 unsigned char hdr[50];
aac17941 1066 int fd, hdrlen, ret;
a44c9a5e 1067
d410c0f5
JH
1068 /* Normally if we have it in the pack then we do not bother writing
1069 * it out into .git/objects/??/?{38} file.
1070 */
1071 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
706bc531
LT
1072 if (returnsha1)
1073 memcpy(returnsha1, sha1, 20);
d410c0f5
JH
1074 if (has_sha1_file(sha1))
1075 return 0;
aac17941
LT
1076 fd = open(filename, O_RDONLY);
1077 if (fd >= 0) {
706bc531 1078 /*
aac17941
LT
1079 * FIXME!!! We might do collision checking here, but we'd
1080 * need to uncompress the old file and check it. Later.
706bc531 1081 */
aac17941 1082 close(fd);
706bc531
LT
1083 return 0;
1084 }
1085
aac17941
LT
1086 if (errno != ENOENT) {
1087 fprintf(stderr, "sha1 file %s: %s", filename, strerror(errno));
1088 return -1;
1089 }
1090
1091 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
ace1534d 1092
aac17941
LT
1093 fd = mkstemp(tmpfile);
1094 if (fd < 0) {
1095 fprintf(stderr, "unable to create temporary sha1 filename %s: %s", tmpfile, strerror(errno));
1096 return -1;
1097 }
1098
0fcfd160
LT
1099 /* Set it up */
1100 memset(&stream, 0, sizeof(stream));
1101 deflateInit(&stream, Z_BEST_COMPRESSION);
a44c9a5e 1102 size = deflateBound(&stream, len+hdrlen);
812666c8 1103 compressed = xmalloc(size);
0fcfd160
LT
1104
1105 /* Compress it */
0fcfd160
LT
1106 stream.next_out = compressed;
1107 stream.avail_out = size;
a44c9a5e
LT
1108
1109 /* First header.. */
1110 stream.next_in = hdr;
1111 stream.avail_in = hdrlen;
1112 while (deflate(&stream, 0) == Z_OK)
6ffcee88 1113 /* nothing */;
a44c9a5e
LT
1114
1115 /* Then the data itself.. */
1116 stream.next_in = buf;
1117 stream.avail_in = len;
0fcfd160
LT
1118 while (deflate(&stream, Z_FINISH) == Z_OK)
1119 /* nothing */;
1120 deflateEnd(&stream);
1121 size = stream.total_out;
1122
706bc531
LT
1123 if (write(fd, compressed, size) != size)
1124 die("unable to write file");
aac17941 1125 fchmod(fd, 0444);
706bc531 1126 close(fd);
383f85b7 1127 free(compressed);
0fcfd160 1128
aac17941 1129 ret = link(tmpfile, filename);
a31c6d02 1130 if (ret < 0) {
aac17941 1131 ret = errno;
a31c6d02
LT
1132
1133 /*
1134 * Coda hack - coda doesn't like cross-directory links,
1135 * so we fall back to a rename, which will mean that it
1136 * won't be able to check collisions, but that's not a
1137 * big deal.
1138 *
1139 * When this succeeds, we just return 0. We have nothing
1140 * left to unlink.
1141 */
1142 if (ret == EXDEV && !rename(tmpfile, filename))
1143 return 0;
1144 }
aac17941
LT
1145 unlink(tmpfile);
1146 if (ret) {
1147 if (ret != EEXIST) {
1148 fprintf(stderr, "unable to write sha1 filename %s: %s", filename, strerror(ret));
0fcfd160 1149 return -1;
aac17941
LT
1150 }
1151 /* FIXME!!! Collision check here ? */
0fcfd160 1152 }
aac17941 1153
0fcfd160
LT
1154 return 0;
1155}
8237b185
DB
1156
1157int write_sha1_from_fd(const unsigned char *sha1, int fd)
1158{
1159 char *filename = sha1_file_name(sha1);
1160
1161 int local;
1162 z_stream stream;
1163 unsigned char real_sha1[20];
bf0f910d
BG
1164 unsigned char buf[4096];
1165 unsigned char discard[4096];
8237b185
DB
1166 int ret;
1167 SHA_CTX c;
1168
1169 local = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0666);
1170
1171 if (local < 0)
1172 return error("Couldn't open %s\n", filename);
1173
1174 memset(&stream, 0, sizeof(stream));
1175
1176 inflateInit(&stream);
1177
1178 SHA1_Init(&c);
1179
1180 do {
1181 ssize_t size;
1182 size = read(fd, buf, 4096);
1183 if (size <= 0) {
1184 close(local);
1185 unlink(filename);
1186 if (!size)
1187 return error("Connection closed?");
1188 perror("Reading from connection");
1189 return -1;
1190 }
1191 write(local, buf, size);
1192 stream.avail_in = size;
1193 stream.next_in = buf;
1194 do {
1195 stream.next_out = discard;
1196 stream.avail_out = sizeof(discard);
1197 ret = inflate(&stream, Z_SYNC_FLUSH);
1198 SHA1_Update(&c, discard, sizeof(discard) -
1199 stream.avail_out);
1200 } while (stream.avail_in && ret == Z_OK);
1201
1202 } while (ret == Z_OK);
1203 inflateEnd(&stream);
1204
1205 close(local);
1206 SHA1_Final(real_sha1, &c);
1207 if (ret != Z_STREAM_END) {
1208 unlink(filename);
1209 return error("File %s corrupted", sha1_to_hex(sha1));
1210 }
1211 if (memcmp(sha1, real_sha1, 20)) {
1212 unlink(filename);
1213 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1214 }
1215
1216 return 0;
1217}
1218
1219int has_sha1_file(const unsigned char *sha1)
1220{
8237b185 1221 struct stat st;
1f688557
JH
1222 struct pack_entry e;
1223
1224 if (find_sha1_file(sha1, &st))
1225 return 1;
1226 return find_pack_entry(sha1, &e);
8237b185 1227}
74400e71
JH
1228
1229int index_fd(unsigned char *sha1, int fd, struct stat *st)
1230{
74400e71 1231 unsigned long size = st->st_size;
aac17941
LT
1232 void *buf;
1233 int ret;
74400e71 1234
aac17941 1235 buf = "";
74400e71 1236 if (size)
aac17941 1237 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
74400e71 1238 close(fd);
aac17941 1239 if ((int)(long)buf == -1)
74400e71
JH
1240 return -1;
1241
aac17941
LT
1242 ret = write_sha1_file(buf, size, "blob", sha1);
1243 if (size)
1244 munmap(buf, size);
1245 return ret;
74400e71 1246}