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