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