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"
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
23 static unsigned int sha1_file_open_flag = O_NOATIME;
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 }
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 }
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;
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 }
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 }
84 char *get_object_directory(void)
85 {
86 if (!git_object_dir)
87 setup_git_env();
88 return git_object_dir;
89 }
91 char *get_refs_directory(void)
92 {
93 if (!git_refs_dir)
94 setup_git_env();
95 return git_refs_dir;
96 }
98 char *get_index_file(void)
99 {
100 if (!git_index_file)
101 setup_git_env();
102 return git_index_file;
103 }
105 char *git_path(const char *fmt, ...)
106 {
107 static char pathname[PATH_MAX], *ret;
108 va_list args;
109 int len;
111 if (!git_dir)
112 setup_git_env();
113 len = strlen(git_dir);
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);
122 ret = pathname;
124 /* Clean it up */
125 if (!memcmp(pathname, "./", 2)) {
126 ret += 2;
127 while (*ret == '/')
128 ret++;
129 }
130 return ret;
131 }
133 int get_sha1(const char *str, unsigned char *sha1)
134 {
135 static const char *prefix[] = {
136 "",
137 "refs",
138 "refs/tags",
139 "refs/heads",
140 "refs/snap",
141 NULL
142 };
143 const char **p;
145 if (!get_sha1_hex(str, sha1))
146 return 0;
148 for (p = prefix; *p; p++) {
149 char * pathname = git_path("%s/%s", *p, str);
150 if (!get_sha1_file(pathname, sha1))
151 return 0;
152 }
154 return -1;
155 }
157 char * 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;
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 }
172 static 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 }
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.
188 *
189 * Also note that this returns the location for creating. Reading
190 * SHA1 file can happen from any alternate directory listed in the
191 * DB_ENVIRONMENT environment variable if it is not found in
192 * the primary object database.
193 */
194 char *sha1_file_name(const unsigned char *sha1)
195 {
196 static char *name, *base;
198 if (!base) {
199 const char *sha1_file_directory = get_object_directory();
200 int len = strlen(sha1_file_directory);
201 base = xmalloc(len + 60);
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 }
208 fill_sha1_path(name, sha1);
209 return base;
210 }
212 struct alternate_object_database *alt_odb;
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
219 * element from colon separated ALTERNATE_DB_ENVIRONMENT environment
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 */
230 void prepare_alt_odb(void)
231 {
232 int pass, totlen, i;
233 const char *cp, *last;
234 char *op = NULL;
235 const char *alt = gitenv(ALTERNATE_DB_ENVIRONMENT) ? : "";
237 if (alt_odb)
238 return;
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 */
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;
272 alt_odb = xmalloc(sizeof(*alt_odb) * (i + 1) + totlen);
273 alt_odb[i].base = alt_odb[i].name = NULL;
274 op = (char*)(&alt_odb[i+1]);
275 }
276 }
278 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
279 {
280 int i;
281 char *name = sha1_file_name(sha1);
283 if (!stat(name, st))
284 return name;
285 prepare_alt_odb();
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 }
294 #define PACK_MAX_SZ (1<<26)
295 static int pack_used_ctr;
296 static unsigned long pack_mapped;
297 struct packed_git *packed_git;
299 static 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;
320 index = idx_map;
321 *idx_map_ = idx_map;
322 *idx_size_ = idx_size;
324 /* check index map */
325 if (idx_size < 4*256 + 20 + 20)
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 }
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");
345 return 0;
346 }
348 static int unuse_one_packed_git(void)
349 {
350 struct packed_git *p, *lru = NULL;
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 }
365 void unuse_packed_git(struct packed_git *p)
366 {
367 p->pack_use_cnt--;
368 }
370 int use_packed_git(struct packed_git *p)
371 {
372 if (!p->pack_base) {
373 int fd;
374 struct stat st;
375 void *map;
377 pack_mapped += p->pack_size;
378 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
379 ; /* nothing */
380 fd = open(p->pack_name, O_RDONLY);
381 if (fd < 0)
382 die("packfile %s cannot be opened", p->pack_name);
383 if (fstat(fd, &st)) {
384 close(fd);
385 die("packfile %s cannot be opened", p->pack_name);
386 }
387 if (st.st_size != p->pack_size)
388 die("packfile %s size mismatch.", p->pack_name);
389 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
390 close(fd);
391 if (map == MAP_FAILED)
392 die("packfile %s cannot be mapped.", p->pack_name);
393 p->pack_base = map;
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);
401 }
402 p->pack_last_used = pack_used_ctr++;
403 p->pack_use_cnt++;
404 return 0;
405 }
407 struct packed_git *add_packed_git(char *path, int path_len)
408 {
409 struct stat st;
410 struct packed_git *p;
411 unsigned long idx_size;
412 void *idx_map;
414 if (check_packed_git_idx(path, &idx_size, &idx_map))
415 return NULL;
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;
432 p->pack_base = NULL;
433 p->pack_last_used = 0;
434 p->pack_use_cnt = 0;
435 return p;
436 }
438 static void prepare_packed_git_one(char *objdir)
439 {
440 char path[PATH_MAX];
441 int len;
442 DIR *dir;
443 struct dirent *de;
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;
455 if (strcmp(de->d_name + namelen - 4, ".idx"))
456 continue;
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 }
468 void prepare_packed_git(void)
469 {
470 int i;
471 static int run_once = 0;
473 if (run_once++)
474 return;
476 prepare_packed_git_one(get_object_directory());
477 prepare_alt_odb();
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 }
484 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
485 {
486 char header[100];
487 unsigned char real_sha1[20];
488 SHA_CTX c;
490 SHA1_Init(&c);
491 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
492 SHA1_Update(&c, map, size);
493 SHA1_Final(real_sha1, &c);
494 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
495 }
497 static void *map_sha1_file_internal(const unsigned char *sha1,
498 unsigned long *size,
499 int say_error)
500 {
501 struct stat st;
502 void *map;
503 int fd;
504 char *filename = find_sha1_file(sha1, &st);
506 if (!filename) {
507 if (say_error)
508 error("cannot map sha1 file %s", sha1_to_hex(sha1));
509 return NULL;
510 }
512 fd = open(filename, O_RDONLY | sha1_file_open_flag);
513 if (fd < 0) {
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:
522 if (say_error)
523 perror(filename);
524 return NULL;
525 }
527 /* If it failed once, it will probably fail again.
528 * Stop using O_NOATIME
529 */
530 sha1_file_open_flag = 0;
531 }
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 }
540 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
541 {
542 return map_sha1_file_internal(sha1, size, 1);
543 }
545 int 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;
554 inflateInit(stream);
555 return inflate(stream, 0);
556 }
558 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
559 {
560 int bytes = strlen(buffer) + 1;
561 unsigned char *buf = xmalloc(1+size);
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 }
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 */
581 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
582 {
583 int i;
584 unsigned long size;
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;
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;
620 /*
621 * The length must be followed by a zero byte
622 */
623 return *hdr ? -1 : 0;
624 }
626 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
627 {
628 int ret;
629 z_stream stream;
630 char hdr[8192];
632 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
633 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
634 return NULL;
636 return unpack_sha1_rest(&stream, hdr, *size);
637 }
639 /* forward declaration for a mutually recursive function */
640 static int packed_object_info(struct pack_entry *entry,
641 char *type, unsigned long *sizep);
643 static int packed_delta_info(unsigned char *base_sha1,
644 unsigned long delta_size,
645 unsigned long left,
646 char *type,
647 unsigned long *sizep,
648 struct packed_git *p)
649 {
650 struct pack_entry base_ent;
652 if (left < 20)
653 die("truncated pack file");
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));
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 */
666 if (packed_object_info(&base_ent, type, NULL))
667 die("cannot get info for delta-pack base");
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;
676 memset(&stream, 0, sizeof(stream));
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);
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");
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 */
696 /* Read the result size */
697 result_size = get_delta_hdr_size(&data);
698 *sizep = result_size;
699 }
700 return 0;
701 }
703 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
704 enum object_type *type, unsigned long *sizep)
705 {
706 unsigned shift;
707 unsigned char *pack, c;
708 unsigned long size;
710 if (offset >= p->pack_size)
711 die("object offset outside of pack file");
713 pack = p->pack_base + offset;
714 c = *pack++;
715 offset++;
716 *type = (c >> 4) & 7;
717 size = c & 15;
718 shift = 4;
719 while (c & 0x80) {
720 if (offset >= p->pack_size)
721 die("object offset outside of pack file");
722 c = *pack++;
723 offset++;
724 size += (c & 0x7f) << shift;
725 shift += 7;
726 }
727 *sizep = size;
728 return offset;
729 }
731 void 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;
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;
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 }
782 static 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;
788 enum object_type kind;
789 int retval;
791 if (use_packed_git(p))
792 die("cannot map packed file");
794 offset = unpack_object_header(p, entry->offset, &kind, &size);
795 pack = p->pack_base + offset;
796 left = p->pack_size - offset;
798 switch (kind) {
799 case OBJ_DELTA:
800 retval = packed_delta_info(pack, size, left, type, sizep, p);
801 unuse_packed_git(p);
802 return retval;
803 case OBJ_COMMIT:
804 strcpy(type, "commit");
805 break;
806 case OBJ_TREE:
807 strcpy(type, "tree");
808 break;
809 case OBJ_BLOB:
810 strcpy(type, "blob");
811 break;
812 case OBJ_TAG:
813 strcpy(type, "tag");
814 break;
815 default:
816 die("corrupted pack file");
817 }
818 if (sizep)
819 *sizep = size;
820 unuse_packed_git(p);
821 return 0;
822 }
824 /* forward declaration for a mutually recursive function */
825 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
827 static void *unpack_delta_entry(unsigned char *base_sha1,
828 unsigned long delta_size,
829 unsigned long left,
830 char *type,
831 unsigned long *sizep,
832 struct packed_git *p)
833 {
834 struct pack_entry base_ent;
835 void *data, *delta_data, *result, *base;
836 unsigned long data_size, result_size, base_size;
837 z_stream stream;
838 int st;
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);
846 memset(&stream, 0, sizeof(stream));
848 stream.next_in = data;
849 stream.avail_in = data_size;
850 stream.next_out = delta_data;
851 stream.avail_out = delta_size;
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");
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);
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 }
878 static void *unpack_non_delta_entry(unsigned char *data,
879 unsigned long size,
880 unsigned long left)
881 {
882 int st;
883 z_stream stream;
884 unsigned char *buffer;
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;
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 }
902 return buffer;
903 }
905 static void *unpack_entry(struct pack_entry *entry,
906 char *type, unsigned long *sizep)
907 {
908 struct packed_git *p = entry->p;
909 void *retval;
911 if (use_packed_git(p))
912 die("cannot map packed file");
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 }
920 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
921 void *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;
930 offset = unpack_object_header(p, entry->offset, &kind, &size);
931 pack = p->pack_base + offset;
932 left = p->pack_size - offset;
933 switch (kind) {
934 case OBJ_DELTA:
935 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
936 return retval;
937 case OBJ_COMMIT:
938 strcpy(type, "commit");
939 break;
940 case OBJ_TREE:
941 strcpy(type, "tree");
942 break;
943 case OBJ_BLOB:
944 strcpy(type, "blob");
945 break;
946 case OBJ_TAG:
947 strcpy(type, "tag");
948 break;
949 default:
950 return NULL;
951 }
952 *sizep = size;
953 retval = unpack_non_delta_entry(pack, size, left);
954 return retval;
955 }
957 int num_packed_objects(const struct packed_git *p)
958 {
959 /* See check_packed_git_idx() */
960 return (p->index_size - 20 - 20 - 4*256) / 24;
961 }
963 int 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 }
973 int find_pack_entry_one(const unsigned char *sha1,
974 struct pack_entry *e, struct packed_git *p)
975 {
976 unsigned int *level1_ofs = p->index_base;
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;
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 }
998 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
999 {
1000 struct packed_git *p;
1001 prepare_packed_git();
1003 for (p = packed_git; p; p = p->next) {
1004 if (find_pack_entry_one(sha1, e, p))
1005 return 1;
1006 }
1007 return 0;
1008 }
1010 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1011 {
1012 int status;
1013 unsigned long mapsize, size;
1014 void *map;
1015 z_stream stream;
1016 char hdr[128];
1018 map = map_sha1_file_internal(sha1, &mapsize, 0);
1019 if (!map) {
1020 struct pack_entry e;
1022 if (!find_pack_entry(sha1, &e))
1023 return error("unable to find %s", sha1_to_hex(sha1));
1024 return packed_object_info(&e, type, sizep);
1025 }
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));
1031 else {
1032 status = 0;
1033 if (sizep)
1034 *sizep = size;
1035 }
1036 inflateEnd(&stream);
1037 munmap(map, mapsize);
1038 return status;
1039 }
1041 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1042 {
1043 struct pack_entry e;
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 }
1052 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1053 {
1054 unsigned long mapsize;
1055 void *map, *buf;
1057 map = map_sha1_file_internal(sha1, &mapsize, 0);
1058 if (map) {
1059 buf = unpack_sha1_file(map, mapsize, type, size);
1060 munmap(map, mapsize);
1061 return buf;
1062 }
1063 return read_packed_sha1(sha1, type, size);
1064 }
1066 void *read_object_with_reference(const unsigned char *sha1,
1067 const char *required_type,
1068 unsigned long *size,
1069 unsigned char *actual_sha1_return)
1070 {
1071 char type[20];
1072 void *buffer;
1073 unsigned long isize;
1074 unsigned char actual_sha1[20];
1076 memcpy(actual_sha1, sha1, 20);
1077 while (1) {
1078 int ref_length = -1;
1079 const char *ref_type = NULL;
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);
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. */
1108 }
1109 }
1111 static 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;
1120 /* Generate the header */
1121 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1123 /* Sha1.. */
1124 SHA1_Init(&c);
1125 SHA1_Update(&c, hdr, *hdrlen);
1126 SHA1_Update(&c, buf, len);
1127 SHA1_Final(sha1, &c);
1129 return sha1_file_name(sha1);
1130 }
1132 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1133 {
1134 int size;
1135 unsigned char *compressed;
1136 z_stream stream;
1137 unsigned char sha1[20];
1138 char *filename;
1139 static char tmpfile[PATH_MAX];
1140 unsigned char hdr[50];
1141 int fd, hdrlen, ret;
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);
1147 if (returnsha1)
1148 memcpy(returnsha1, sha1, 20);
1149 if (has_sha1_file(sha1))
1150 return 0;
1151 fd = open(filename, O_RDONLY);
1152 if (fd >= 0) {
1153 /*
1154 * FIXME!!! We might do collision checking here, but we'd
1155 * need to uncompress the old file and check it. Later.
1156 */
1157 close(fd);
1158 return 0;
1159 }
1161 if (errno != ENOENT) {
1162 fprintf(stderr, "sha1 file %s: %s", filename, strerror(errno));
1163 return -1;
1164 }
1166 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
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 }
1174 /* Set it up */
1175 memset(&stream, 0, sizeof(stream));
1176 deflateInit(&stream, Z_BEST_COMPRESSION);
1177 size = deflateBound(&stream, len+hdrlen);
1178 compressed = xmalloc(size);
1180 /* Compress it */
1181 stream.next_out = compressed;
1182 stream.avail_out = size;
1184 /* First header.. */
1185 stream.next_in = hdr;
1186 stream.avail_in = hdrlen;
1187 while (deflate(&stream, 0) == Z_OK)
1188 /* nothing */;
1190 /* Then the data itself.. */
1191 stream.next_in = buf;
1192 stream.avail_in = len;
1193 while (deflate(&stream, Z_FINISH) == Z_OK)
1194 /* nothing */;
1195 deflateEnd(&stream);
1196 size = stream.total_out;
1198 if (write(fd, compressed, size) != size)
1199 die("unable to write file");
1200 fchmod(fd, 0444);
1201 close(fd);
1202 free(compressed);
1204 ret = link(tmpfile, filename);
1205 if (ret < 0) {
1206 ret = errno;
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 }
1220 unlink(tmpfile);
1221 if (ret) {
1222 if (ret != EEXIST) {
1223 fprintf(stderr, "unable to write sha1 filename %s: %s", filename, strerror(ret));
1224 return -1;
1225 }
1226 /* FIXME!!! Collision check here ? */
1227 }
1229 return 0;
1230 }
1232 int write_sha1_from_fd(const unsigned char *sha1, int fd)
1233 {
1234 char *filename = sha1_file_name(sha1);
1236 int local;
1237 z_stream stream;
1238 unsigned char real_sha1[20];
1239 unsigned char buf[4096];
1240 unsigned char discard[4096];
1241 int ret;
1242 SHA_CTX c;
1244 local = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0666);
1246 if (local < 0)
1247 return error("Couldn't open %s\n", filename);
1249 memset(&stream, 0, sizeof(stream));
1251 inflateInit(&stream);
1253 SHA1_Init(&c);
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);
1277 } while (ret == Z_OK);
1278 inflateEnd(&stream);
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 }
1291 return 0;
1292 }
1294 int has_sha1_pack(const unsigned char *sha1)
1295 {
1296 struct pack_entry e;
1297 return find_pack_entry(sha1, &e);
1298 }
1300 int has_sha1_file(const unsigned char *sha1)
1301 {
1302 struct stat st;
1303 struct pack_entry e;
1305 if (find_sha1_file(sha1, &st))
1306 return 1;
1307 return find_pack_entry(sha1, &e);
1308 }
1310 int index_fd(unsigned char *sha1, int fd, struct stat *st)
1311 {
1312 unsigned long size = st->st_size;
1313 void *buf;
1314 int ret;
1316 buf = "";
1317 if (size)
1318 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1319 close(fd);
1320 if ((int)(long)buf == -1)
1321 return -1;
1323 ret = write_sha1_file(buf, size, "blob", sha1);
1324 if (size)
1325 munmap(buf, size);
1326 return ret;
1327 }