[PATCH] Parallelize the pull algorithm
[git/dscho.git] / sha1_file.c
blobe808c91316975e08a0932887dabe2d10dab852d0
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
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)
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;
36 int get_sha1_hex(const char *hex, unsigned char *sha1)
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;
46 return 0;
49 static int get_sha1_file(const char *path, unsigned char *result)
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);
64 static char *git_dir, *git_object_dir, *git_index_file, *git_refs_dir,
65 *git_graft_file;
66 static void setup_git_env(void)
68 git_dir = gitenv(GIT_DIR_ENVIRONMENT);
69 if (!git_dir)
70 git_dir = DEFAULT_GIT_DIR_ENVIRONMENT;
71 git_object_dir = gitenv(DB_ENVIRONMENT);
72 if (!git_object_dir) {
73 git_object_dir = xmalloc(strlen(git_dir) + 9);
74 sprintf(git_object_dir, "%s/objects", git_dir);
76 git_refs_dir = xmalloc(strlen(git_dir) + 6);
77 sprintf(git_refs_dir, "%s/refs", git_dir);
78 git_index_file = gitenv(INDEX_ENVIRONMENT);
79 if (!git_index_file) {
80 git_index_file = xmalloc(strlen(git_dir) + 7);
81 sprintf(git_index_file, "%s/index", git_dir);
83 git_graft_file = gitenv(GRAFT_ENVIRONMENT);
84 if (!git_graft_file)
85 git_graft_file = strdup(git_path("info/grafts"));
88 char *get_object_directory(void)
90 if (!git_object_dir)
91 setup_git_env();
92 return git_object_dir;
95 char *get_refs_directory(void)
97 if (!git_refs_dir)
98 setup_git_env();
99 return git_refs_dir;
102 char *get_index_file(void)
104 if (!git_index_file)
105 setup_git_env();
106 return git_index_file;
109 char *get_graft_file(void)
111 if (!git_graft_file)
112 setup_git_env();
113 return git_graft_file;
116 int safe_create_leading_directories(char *path)
118 char *pos = path;
120 while (pos) {
121 pos = strchr(pos, '/');
122 if (!pos)
123 break;
124 *pos = 0;
125 if (mkdir(path, 0777) < 0)
126 if (errno != EEXIST) {
127 *pos = '/';
128 return -1;
130 *pos++ = '/';
132 return 0;
135 int get_sha1(const char *str, unsigned char *sha1)
137 static const char *prefix[] = {
139 "refs",
140 "refs/tags",
141 "refs/heads",
142 "refs/snap",
143 NULL
145 const char **p;
147 if (!get_sha1_hex(str, sha1))
148 return 0;
150 for (p = prefix; *p; p++) {
151 char * pathname = git_path("%s/%s", *p, str);
152 if (!get_sha1_file(pathname, sha1))
153 return 0;
156 return -1;
159 char * sha1_to_hex(const unsigned char *sha1)
161 static char buffer[50];
162 static const char hex[] = "0123456789abcdef";
163 char *buf = buffer;
164 int i;
166 for (i = 0; i < 20; i++) {
167 unsigned int val = *sha1++;
168 *buf++ = hex[val >> 4];
169 *buf++ = hex[val & 0xf];
171 return buffer;
174 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
176 int i;
177 for (i = 0; i < 20; i++) {
178 static char hex[] = "0123456789abcdef";
179 unsigned int val = sha1[i];
180 char *pos = pathbuf + i*2 + (i > 0);
181 *pos++ = hex[val >> 4];
182 *pos = hex[val & 0xf];
187 * NOTE! This returns a statically allocated buffer, so you have to be
188 * careful about using it. Do a "strdup()" if you need to save the
189 * filename.
191 * Also note that this returns the location for creating. Reading
192 * SHA1 file can happen from any alternate directory listed in the
193 * DB_ENVIRONMENT environment variable if it is not found in
194 * the primary object database.
196 char *sha1_file_name(const unsigned char *sha1)
198 static char *name, *base;
200 if (!base) {
201 const char *sha1_file_directory = get_object_directory();
202 int len = strlen(sha1_file_directory);
203 base = xmalloc(len + 60);
204 memcpy(base, sha1_file_directory, len);
205 memset(base+len, 0, 60);
206 base[len] = '/';
207 base[len+3] = '/';
208 name = base + len + 1;
210 fill_sha1_path(name, sha1);
211 return base;
214 char *sha1_pack_name(const unsigned char *sha1)
216 static const char hex[] = "0123456789abcdef";
217 static char *name, *base, *buf;
218 int i;
220 if (!base) {
221 const char *sha1_file_directory = get_object_directory();
222 int len = strlen(sha1_file_directory);
223 base = xmalloc(len + 60);
224 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
225 name = base + len + 11;
228 buf = name;
230 for (i = 0; i < 20; i++) {
231 unsigned int val = *sha1++;
232 *buf++ = hex[val >> 4];
233 *buf++ = hex[val & 0xf];
236 return base;
239 char *sha1_pack_index_name(const unsigned char *sha1)
241 static const char hex[] = "0123456789abcdef";
242 static char *name, *base, *buf;
243 int i;
245 if (!base) {
246 const char *sha1_file_directory = get_object_directory();
247 int len = strlen(sha1_file_directory);
248 base = xmalloc(len + 60);
249 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
250 name = base + len + 11;
253 buf = name;
255 for (i = 0; i < 20; i++) {
256 unsigned int val = *sha1++;
257 *buf++ = hex[val >> 4];
258 *buf++ = hex[val & 0xf];
261 return base;
264 struct alternate_object_database *alt_odb;
267 * Prepare alternate object database registry.
268 * alt_odb points at an array of struct alternate_object_database.
269 * This array is terminated with an element that has both its base
270 * and name set to NULL. alt_odb[n] comes from n'th non-empty
271 * element from colon separated ALTERNATE_DB_ENVIRONMENT environment
272 * variable, and its base points at a statically allocated buffer
273 * that contains "/the/directory/corresponding/to/.git/objects/...",
274 * while its name points just after the slash at the end of
275 * ".git/objects/" in the example above, and has enough space to hold
276 * 40-byte hex SHA1, an extra slash for the first level indirection,
277 * and the terminating NUL.
278 * This function allocates the alt_odb array and all the strings
279 * pointed by base fields of the array elements with one xmalloc();
280 * the string pool immediately follows the array.
282 void prepare_alt_odb(void)
284 int pass, totlen, i;
285 const char *cp, *last;
286 char *op = NULL;
287 const char *alt = gitenv(ALTERNATE_DB_ENVIRONMENT) ? : "";
289 if (alt_odb)
290 return;
291 /* The first pass counts how large an area to allocate to
292 * hold the entire alt_odb structure, including array of
293 * structs and path buffers for them. The second pass fills
294 * the structure and prepares the path buffers for use by
295 * fill_sha1_path().
297 for (totlen = pass = 0; pass < 2; pass++) {
298 last = alt;
299 i = 0;
300 do {
301 cp = strchr(last, ':') ? : last + strlen(last);
302 if (last != cp) {
303 /* 43 = 40-byte + 2 '/' + terminating NUL */
304 int pfxlen = cp - last;
305 int entlen = pfxlen + 43;
306 if (pass == 0)
307 totlen += entlen;
308 else {
309 alt_odb[i].base = op;
310 alt_odb[i].name = op + pfxlen + 1;
311 memcpy(op, last, pfxlen);
312 op[pfxlen] = op[pfxlen + 3] = '/';
313 op[entlen-1] = 0;
314 op += entlen;
316 i++;
318 while (*cp && *cp == ':')
319 cp++;
320 last = cp;
321 } while (*cp);
322 if (pass)
323 break;
324 alt_odb = xmalloc(sizeof(*alt_odb) * (i + 1) + totlen);
325 alt_odb[i].base = alt_odb[i].name = NULL;
326 op = (char*)(&alt_odb[i+1]);
330 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
332 int i;
333 char *name = sha1_file_name(sha1);
335 if (!stat(name, st))
336 return name;
337 prepare_alt_odb();
338 for (i = 0; (name = alt_odb[i].name) != NULL; i++) {
339 fill_sha1_path(name, sha1);
340 if (!stat(alt_odb[i].base, st))
341 return alt_odb[i].base;
343 return NULL;
346 #define PACK_MAX_SZ (1<<26)
347 static int pack_used_ctr;
348 static unsigned long pack_mapped;
349 struct packed_git *packed_git;
351 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
352 void **idx_map_)
354 void *idx_map;
355 unsigned int *index;
356 unsigned long idx_size;
357 int nr, i;
358 int fd = open(path, O_RDONLY);
359 struct stat st;
360 if (fd < 0)
361 return -1;
362 if (fstat(fd, &st)) {
363 close(fd);
364 return -1;
366 idx_size = st.st_size;
367 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
368 close(fd);
369 if (idx_map == MAP_FAILED)
370 return -1;
372 index = idx_map;
373 *idx_map_ = idx_map;
374 *idx_size_ = idx_size;
376 /* check index map */
377 if (idx_size < 4*256 + 20 + 20)
378 return error("index file too small");
379 nr = 0;
380 for (i = 0; i < 256; i++) {
381 unsigned int n = ntohl(index[i]);
382 if (n < nr)
383 return error("non-monotonic index");
384 nr = n;
388 * Total size:
389 * - 256 index entries 4 bytes each
390 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
391 * - 20-byte SHA1 of the packfile
392 * - 20-byte SHA1 file checksum
394 if (idx_size != 4*256 + nr * 24 + 20 + 20)
395 return error("wrong index file size");
397 return 0;
400 static int unuse_one_packed_git(void)
402 struct packed_git *p, *lru = NULL;
404 for (p = packed_git; p; p = p->next) {
405 if (p->pack_use_cnt || !p->pack_base)
406 continue;
407 if (!lru || p->pack_last_used < lru->pack_last_used)
408 lru = p;
410 if (!lru)
411 return 0;
412 munmap(lru->pack_base, lru->pack_size);
413 lru->pack_base = NULL;
414 return 1;
417 void unuse_packed_git(struct packed_git *p)
419 p->pack_use_cnt--;
422 int use_packed_git(struct packed_git *p)
424 if (!p->pack_size) {
425 struct stat st;
426 // We created the struct before we had the pack
427 stat(p->pack_name, &st);
428 if (!S_ISREG(st.st_mode))
429 die("packfile %s not a regular file", p->pack_name);
430 p->pack_size = st.st_size;
432 if (!p->pack_base) {
433 int fd;
434 struct stat st;
435 void *map;
437 pack_mapped += p->pack_size;
438 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
439 ; /* nothing */
440 fd = open(p->pack_name, O_RDONLY);
441 if (fd < 0)
442 die("packfile %s cannot be opened", p->pack_name);
443 if (fstat(fd, &st)) {
444 close(fd);
445 die("packfile %s cannot be opened", p->pack_name);
447 if (st.st_size != p->pack_size)
448 die("packfile %s size mismatch.", p->pack_name);
449 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
450 close(fd);
451 if (map == MAP_FAILED)
452 die("packfile %s cannot be mapped.", p->pack_name);
453 p->pack_base = map;
455 /* Check if the pack file matches with the index file.
456 * this is cheap.
458 if (memcmp((char*)(p->index_base) + p->index_size - 40,
459 p->pack_base + p->pack_size - 20, 20)) {
461 die("packfile %s does not match index.", p->pack_name);
464 p->pack_last_used = pack_used_ctr++;
465 p->pack_use_cnt++;
466 return 0;
469 struct packed_git *add_packed_git(char *path, int path_len)
471 struct stat st;
472 struct packed_git *p;
473 unsigned long idx_size;
474 void *idx_map;
476 if (check_packed_git_idx(path, &idx_size, &idx_map))
477 return NULL;
479 /* do we have a corresponding .pack file? */
480 strcpy(path + path_len - 4, ".pack");
481 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
482 munmap(idx_map, idx_size);
483 return NULL;
485 /* ok, it looks sane as far as we can check without
486 * actually mapping the pack file.
488 p = xmalloc(sizeof(*p) + path_len + 2);
489 strcpy(p->pack_name, path);
490 p->index_size = idx_size;
491 p->pack_size = st.st_size;
492 p->index_base = idx_map;
493 p->next = NULL;
494 p->pack_base = NULL;
495 p->pack_last_used = 0;
496 p->pack_use_cnt = 0;
497 return p;
500 struct packed_git *parse_pack_index(unsigned char *sha1)
502 struct packed_git *p;
503 unsigned long idx_size;
504 void *idx_map;
505 char *path = sha1_pack_index_name(sha1);
507 if (check_packed_git_idx(path, &idx_size, &idx_map))
508 return NULL;
510 path = sha1_pack_name(sha1);
512 p = xmalloc(sizeof(*p) + strlen(path) + 2);
513 strcpy(p->pack_name, path);
514 p->index_size = idx_size;
515 p->pack_size = 0;
516 p->index_base = idx_map;
517 p->next = NULL;
518 p->pack_base = NULL;
519 p->pack_last_used = 0;
520 p->pack_use_cnt = 0;
521 memcpy(p->sha1, sha1, 20);
522 return p;
525 void install_packed_git(struct packed_git *pack)
527 pack->next = packed_git;
528 packed_git = pack;
531 static void prepare_packed_git_one(char *objdir)
533 char path[PATH_MAX];
534 int len;
535 DIR *dir;
536 struct dirent *de;
538 sprintf(path, "%s/pack", objdir);
539 len = strlen(path);
540 dir = opendir(path);
541 if (!dir)
542 return;
543 path[len++] = '/';
544 while ((de = readdir(dir)) != NULL) {
545 int namelen = strlen(de->d_name);
546 struct packed_git *p;
548 if (strcmp(de->d_name + namelen - 4, ".idx"))
549 continue;
551 /* we have .idx. Is it a file we can map? */
552 strcpy(path + len, de->d_name);
553 p = add_packed_git(path, len + namelen);
554 if (!p)
555 continue;
556 p->next = packed_git;
557 packed_git = p;
559 closedir(dir);
562 void prepare_packed_git(void)
564 int i;
565 static int run_once = 0;
567 if (run_once++)
568 return;
570 prepare_packed_git_one(get_object_directory());
571 prepare_alt_odb();
572 for (i = 0; alt_odb[i].base != NULL; i++) {
573 alt_odb[i].name[0] = 0;
574 prepare_packed_git_one(alt_odb[i].base);
578 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
580 char header[100];
581 unsigned char real_sha1[20];
582 SHA_CTX c;
584 SHA1_Init(&c);
585 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
586 SHA1_Update(&c, map, size);
587 SHA1_Final(real_sha1, &c);
588 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
591 static void *map_sha1_file_internal(const unsigned char *sha1,
592 unsigned long *size)
594 struct stat st;
595 void *map;
596 int fd;
597 char *filename = find_sha1_file(sha1, &st);
599 if (!filename) {
600 return NULL;
603 fd = open(filename, O_RDONLY | sha1_file_open_flag);
604 if (fd < 0) {
605 /* See if it works without O_NOATIME */
606 switch (sha1_file_open_flag) {
607 default:
608 fd = open(filename, O_RDONLY);
609 if (fd >= 0)
610 break;
611 /* Fallthrough */
612 case 0:
613 return NULL;
616 /* If it failed once, it will probably fail again.
617 * Stop using O_NOATIME
619 sha1_file_open_flag = 0;
621 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
622 close(fd);
623 if (map == MAP_FAILED)
624 return NULL;
625 *size = st.st_size;
626 return map;
629 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
631 /* Get the data stream */
632 memset(stream, 0, sizeof(*stream));
633 stream->next_in = map;
634 stream->avail_in = mapsize;
635 stream->next_out = buffer;
636 stream->avail_out = size;
638 inflateInit(stream);
639 return inflate(stream, 0);
642 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
644 int bytes = strlen(buffer) + 1;
645 unsigned char *buf = xmalloc(1+size);
647 memcpy(buf, buffer + bytes, stream->total_out - bytes);
648 bytes = stream->total_out - bytes;
649 if (bytes < size) {
650 stream->next_out = buf + bytes;
651 stream->avail_out = size - bytes;
652 while (inflate(stream, Z_FINISH) == Z_OK)
653 /* nothing */;
655 buf[size] = 0;
656 inflateEnd(stream);
657 return buf;
661 * We used to just use "sscanf()", but that's actually way
662 * too permissive for what we want to check. So do an anal
663 * object header parse by hand.
665 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
667 int i;
668 unsigned long size;
671 * The type can be at most ten bytes (including the
672 * terminating '\0' that we add), and is followed by
673 * a space.
675 i = 10;
676 for (;;) {
677 char c = *hdr++;
678 if (c == ' ')
679 break;
680 if (!--i)
681 return -1;
682 *type++ = c;
684 *type = 0;
687 * The length must follow immediately, and be in canonical
688 * decimal format (ie "010" is not valid).
690 size = *hdr++ - '0';
691 if (size > 9)
692 return -1;
693 if (size) {
694 for (;;) {
695 unsigned long c = *hdr - '0';
696 if (c > 9)
697 break;
698 hdr++;
699 size = size * 10 + c;
702 *sizep = size;
705 * The length must be followed by a zero byte
707 return *hdr ? -1 : 0;
710 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
712 int ret;
713 z_stream stream;
714 char hdr[8192];
716 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
717 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
718 return NULL;
720 return unpack_sha1_rest(&stream, hdr, *size);
723 /* forward declaration for a mutually recursive function */
724 static int packed_object_info(struct pack_entry *entry,
725 char *type, unsigned long *sizep);
727 static int packed_delta_info(unsigned char *base_sha1,
728 unsigned long delta_size,
729 unsigned long left,
730 char *type,
731 unsigned long *sizep,
732 struct packed_git *p)
734 struct pack_entry base_ent;
736 if (left < 20)
737 die("truncated pack file");
739 /* The base entry _must_ be in the same pack */
740 if (!find_pack_entry_one(base_sha1, &base_ent, p))
741 die("failed to find delta-pack base object %s",
742 sha1_to_hex(base_sha1));
744 /* We choose to only get the type of the base object and
745 * ignore potentially corrupt pack file that expects the delta
746 * based on a base with a wrong size. This saves tons of
747 * inflate() calls.
750 if (packed_object_info(&base_ent, type, NULL))
751 die("cannot get info for delta-pack base");
753 if (sizep) {
754 const unsigned char *data;
755 unsigned char delta_head[64];
756 unsigned long result_size;
757 z_stream stream;
758 int st;
760 memset(&stream, 0, sizeof(stream));
762 data = stream.next_in = base_sha1 + 20;
763 stream.avail_in = left - 20;
764 stream.next_out = delta_head;
765 stream.avail_out = sizeof(delta_head);
767 inflateInit(&stream);
768 st = inflate(&stream, Z_FINISH);
769 inflateEnd(&stream);
770 if ((st != Z_STREAM_END) &&
771 stream.total_out != sizeof(delta_head))
772 die("delta data unpack-initial failed");
774 /* Examine the initial part of the delta to figure out
775 * the result size.
777 data = delta_head;
778 get_delta_hdr_size(&data); /* ignore base size */
780 /* Read the result size */
781 result_size = get_delta_hdr_size(&data);
782 *sizep = result_size;
784 return 0;
787 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
788 enum object_type *type, unsigned long *sizep)
790 unsigned shift;
791 unsigned char *pack, c;
792 unsigned long size;
794 if (offset >= p->pack_size)
795 die("object offset outside of pack file");
797 pack = p->pack_base + offset;
798 c = *pack++;
799 offset++;
800 *type = (c >> 4) & 7;
801 size = c & 15;
802 shift = 4;
803 while (c & 0x80) {
804 if (offset >= p->pack_size)
805 die("object offset outside of pack file");
806 c = *pack++;
807 offset++;
808 size += (c & 0x7f) << shift;
809 shift += 7;
811 *sizep = size;
812 return offset;
815 void packed_object_info_detail(struct pack_entry *e,
816 char *type,
817 unsigned long *size,
818 unsigned long *store_size,
819 int *delta_chain_length,
820 unsigned char *base_sha1)
822 struct packed_git *p = e->p;
823 unsigned long offset, left;
824 unsigned char *pack;
825 enum object_type kind;
827 offset = unpack_object_header(p, e->offset, &kind, size);
828 pack = p->pack_base + offset;
829 left = p->pack_size - offset;
830 if (kind != OBJ_DELTA)
831 *delta_chain_length = 0;
832 else {
833 int chain_length = 0;
834 memcpy(base_sha1, pack, 20);
835 do {
836 struct pack_entry base_ent;
837 unsigned long junk;
839 find_pack_entry_one(pack, &base_ent, p);
840 offset = unpack_object_header(p, base_ent.offset,
841 &kind, &junk);
842 pack = p->pack_base + offset;
843 chain_length++;
844 } while (kind == OBJ_DELTA);
845 *delta_chain_length = chain_length;
847 switch (kind) {
848 case OBJ_COMMIT:
849 strcpy(type, "commit");
850 break;
851 case OBJ_TREE:
852 strcpy(type, "tree");
853 break;
854 case OBJ_BLOB:
855 strcpy(type, "blob");
856 break;
857 case OBJ_TAG:
858 strcpy(type, "tag");
859 break;
860 default:
861 die("corrupted pack file");
863 *store_size = 0; /* notyet */
866 static int packed_object_info(struct pack_entry *entry,
867 char *type, unsigned long *sizep)
869 struct packed_git *p = entry->p;
870 unsigned long offset, size, left;
871 unsigned char *pack;
872 enum object_type kind;
873 int retval;
875 if (use_packed_git(p))
876 die("cannot map packed file");
878 offset = unpack_object_header(p, entry->offset, &kind, &size);
879 pack = p->pack_base + offset;
880 left = p->pack_size - offset;
882 switch (kind) {
883 case OBJ_DELTA:
884 retval = packed_delta_info(pack, size, left, type, sizep, p);
885 unuse_packed_git(p);
886 return retval;
887 case OBJ_COMMIT:
888 strcpy(type, "commit");
889 break;
890 case OBJ_TREE:
891 strcpy(type, "tree");
892 break;
893 case OBJ_BLOB:
894 strcpy(type, "blob");
895 break;
896 case OBJ_TAG:
897 strcpy(type, "tag");
898 break;
899 default:
900 die("corrupted pack file");
902 if (sizep)
903 *sizep = size;
904 unuse_packed_git(p);
905 return 0;
908 /* forward declaration for a mutually recursive function */
909 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
911 static void *unpack_delta_entry(unsigned char *base_sha1,
912 unsigned long delta_size,
913 unsigned long left,
914 char *type,
915 unsigned long *sizep,
916 struct packed_git *p)
918 struct pack_entry base_ent;
919 void *data, *delta_data, *result, *base;
920 unsigned long data_size, result_size, base_size;
921 z_stream stream;
922 int st;
924 if (left < 20)
925 die("truncated pack file");
926 data = base_sha1 + 20;
927 data_size = left - 20;
928 delta_data = xmalloc(delta_size);
930 memset(&stream, 0, sizeof(stream));
932 stream.next_in = data;
933 stream.avail_in = data_size;
934 stream.next_out = delta_data;
935 stream.avail_out = delta_size;
937 inflateInit(&stream);
938 st = inflate(&stream, Z_FINISH);
939 inflateEnd(&stream);
940 if ((st != Z_STREAM_END) || stream.total_out != delta_size)
941 die("delta data unpack failed");
943 /* The base entry _must_ be in the same pack */
944 if (!find_pack_entry_one(base_sha1, &base_ent, p))
945 die("failed to find delta-pack base object %s",
946 sha1_to_hex(base_sha1));
947 base = unpack_entry_gently(&base_ent, type, &base_size);
948 if (!base)
949 die("failed to read delta-pack base object %s",
950 sha1_to_hex(base_sha1));
951 result = patch_delta(base, base_size,
952 delta_data, delta_size,
953 &result_size);
954 if (!result)
955 die("failed to apply delta");
956 free(delta_data);
957 free(base);
958 *sizep = result_size;
959 return result;
962 static void *unpack_non_delta_entry(unsigned char *data,
963 unsigned long size,
964 unsigned long left)
966 int st;
967 z_stream stream;
968 unsigned char *buffer;
970 buffer = xmalloc(size + 1);
971 buffer[size] = 0;
972 memset(&stream, 0, sizeof(stream));
973 stream.next_in = data;
974 stream.avail_in = left;
975 stream.next_out = buffer;
976 stream.avail_out = size;
978 inflateInit(&stream);
979 st = inflate(&stream, Z_FINISH);
980 inflateEnd(&stream);
981 if ((st != Z_STREAM_END) || stream.total_out != size) {
982 free(buffer);
983 return NULL;
986 return buffer;
989 static void *unpack_entry(struct pack_entry *entry,
990 char *type, unsigned long *sizep)
992 struct packed_git *p = entry->p;
993 void *retval;
995 if (use_packed_git(p))
996 die("cannot map packed file");
997 retval = unpack_entry_gently(entry, type, sizep);
998 unuse_packed_git(p);
999 if (!retval)
1000 die("corrupted pack file");
1001 return retval;
1004 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
1005 void *unpack_entry_gently(struct pack_entry *entry,
1006 char *type, unsigned long *sizep)
1008 struct packed_git *p = entry->p;
1009 unsigned long offset, size, left;
1010 unsigned char *pack;
1011 enum object_type kind;
1012 void *retval;
1014 offset = unpack_object_header(p, entry->offset, &kind, &size);
1015 pack = p->pack_base + offset;
1016 left = p->pack_size - offset;
1017 switch (kind) {
1018 case OBJ_DELTA:
1019 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
1020 return retval;
1021 case OBJ_COMMIT:
1022 strcpy(type, "commit");
1023 break;
1024 case OBJ_TREE:
1025 strcpy(type, "tree");
1026 break;
1027 case OBJ_BLOB:
1028 strcpy(type, "blob");
1029 break;
1030 case OBJ_TAG:
1031 strcpy(type, "tag");
1032 break;
1033 default:
1034 return NULL;
1036 *sizep = size;
1037 retval = unpack_non_delta_entry(pack, size, left);
1038 return retval;
1041 int num_packed_objects(const struct packed_git *p)
1043 /* See check_packed_git_idx() */
1044 return (p->index_size - 20 - 20 - 4*256) / 24;
1047 int nth_packed_object_sha1(const struct packed_git *p, int n,
1048 unsigned char* sha1)
1050 void *index = p->index_base + 256;
1051 if (n < 0 || num_packed_objects(p) <= n)
1052 return -1;
1053 memcpy(sha1, (index + 24 * n + 4), 20);
1054 return 0;
1057 int find_pack_entry_one(const unsigned char *sha1,
1058 struct pack_entry *e, struct packed_git *p)
1060 unsigned int *level1_ofs = p->index_base;
1061 int hi = ntohl(level1_ofs[*sha1]);
1062 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1063 void *index = p->index_base + 256;
1065 do {
1066 int mi = (lo + hi) / 2;
1067 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
1068 if (!cmp) {
1069 e->offset = ntohl(*((int*)(index + 24 * mi)));
1070 memcpy(e->sha1, sha1, 20);
1071 e->p = p;
1072 return 1;
1074 if (cmp > 0)
1075 hi = mi;
1076 else
1077 lo = mi+1;
1078 } while (lo < hi);
1079 return 0;
1082 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1084 struct packed_git *p;
1085 prepare_packed_git();
1087 for (p = packed_git; p; p = p->next) {
1088 if (find_pack_entry_one(sha1, e, p))
1089 return 1;
1091 return 0;
1094 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1095 struct packed_git *packs)
1097 struct packed_git *p;
1098 struct pack_entry e;
1100 for (p = packs; p; p = p->next) {
1101 if (find_pack_entry_one(sha1, &e, p))
1102 return p;
1104 return NULL;
1108 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1110 int status;
1111 unsigned long mapsize, size;
1112 void *map;
1113 z_stream stream;
1114 char hdr[128];
1116 map = map_sha1_file_internal(sha1, &mapsize);
1117 if (!map) {
1118 struct pack_entry e;
1120 if (!find_pack_entry(sha1, &e))
1121 return error("unable to find %s", sha1_to_hex(sha1));
1122 return packed_object_info(&e, type, sizep);
1124 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1125 status = error("unable to unpack %s header",
1126 sha1_to_hex(sha1));
1127 if (parse_sha1_header(hdr, type, &size) < 0)
1128 status = error("unable to parse %s header", sha1_to_hex(sha1));
1129 else {
1130 status = 0;
1131 if (sizep)
1132 *sizep = size;
1134 inflateEnd(&stream);
1135 munmap(map, mapsize);
1136 return status;
1139 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1141 struct pack_entry e;
1143 if (!find_pack_entry(sha1, &e)) {
1144 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1145 return NULL;
1147 return unpack_entry(&e, type, size);
1150 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1152 unsigned long mapsize;
1153 void *map, *buf;
1154 struct pack_entry e;
1156 if (find_pack_entry(sha1, &e))
1157 return read_packed_sha1(sha1, type, size);
1158 map = map_sha1_file_internal(sha1, &mapsize);
1159 if (map) {
1160 buf = unpack_sha1_file(map, mapsize, type, size);
1161 munmap(map, mapsize);
1162 return buf;
1164 return NULL;
1167 void *read_object_with_reference(const unsigned char *sha1,
1168 const char *required_type,
1169 unsigned long *size,
1170 unsigned char *actual_sha1_return)
1172 char type[20];
1173 void *buffer;
1174 unsigned long isize;
1175 unsigned char actual_sha1[20];
1177 memcpy(actual_sha1, sha1, 20);
1178 while (1) {
1179 int ref_length = -1;
1180 const char *ref_type = NULL;
1182 buffer = read_sha1_file(actual_sha1, type, &isize);
1183 if (!buffer)
1184 return NULL;
1185 if (!strcmp(type, required_type)) {
1186 *size = isize;
1187 if (actual_sha1_return)
1188 memcpy(actual_sha1_return, actual_sha1, 20);
1189 return buffer;
1191 /* Handle references */
1192 else if (!strcmp(type, "commit"))
1193 ref_type = "tree ";
1194 else if (!strcmp(type, "tag"))
1195 ref_type = "object ";
1196 else {
1197 free(buffer);
1198 return NULL;
1200 ref_length = strlen(ref_type);
1202 if (memcmp(buffer, ref_type, ref_length) ||
1203 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1204 free(buffer);
1205 return NULL;
1207 /* Now we have the ID of the referred-to object in
1208 * actual_sha1. Check again. */
1212 char *write_sha1_file_prepare(void *buf,
1213 unsigned long len,
1214 const char *type,
1215 unsigned char *sha1,
1216 unsigned char *hdr,
1217 int *hdrlen)
1219 SHA_CTX c;
1221 /* Generate the header */
1222 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1224 /* Sha1.. */
1225 SHA1_Init(&c);
1226 SHA1_Update(&c, hdr, *hdrlen);
1227 SHA1_Update(&c, buf, len);
1228 SHA1_Final(sha1, &c);
1230 return sha1_file_name(sha1);
1233 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1235 int size;
1236 unsigned char *compressed;
1237 z_stream stream;
1238 unsigned char sha1[20];
1239 char *filename;
1240 static char tmpfile[PATH_MAX];
1241 unsigned char hdr[50];
1242 int fd, hdrlen, ret;
1244 /* Normally if we have it in the pack then we do not bother writing
1245 * it out into .git/objects/??/?{38} file.
1247 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1248 if (returnsha1)
1249 memcpy(returnsha1, sha1, 20);
1250 if (has_sha1_file(sha1))
1251 return 0;
1252 fd = open(filename, O_RDONLY);
1253 if (fd >= 0) {
1255 * FIXME!!! We might do collision checking here, but we'd
1256 * need to uncompress the old file and check it. Later.
1258 close(fd);
1259 return 0;
1262 if (errno != ENOENT) {
1263 fprintf(stderr, "sha1 file %s: %s", filename, strerror(errno));
1264 return -1;
1267 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1269 fd = mkstemp(tmpfile);
1270 if (fd < 0) {
1271 fprintf(stderr, "unable to create temporary sha1 filename %s: %s", tmpfile, strerror(errno));
1272 return -1;
1275 /* Set it up */
1276 memset(&stream, 0, sizeof(stream));
1277 deflateInit(&stream, Z_BEST_COMPRESSION);
1278 size = deflateBound(&stream, len+hdrlen);
1279 compressed = xmalloc(size);
1281 /* Compress it */
1282 stream.next_out = compressed;
1283 stream.avail_out = size;
1285 /* First header.. */
1286 stream.next_in = hdr;
1287 stream.avail_in = hdrlen;
1288 while (deflate(&stream, 0) == Z_OK)
1289 /* nothing */;
1291 /* Then the data itself.. */
1292 stream.next_in = buf;
1293 stream.avail_in = len;
1294 while (deflate(&stream, Z_FINISH) == Z_OK)
1295 /* nothing */;
1296 deflateEnd(&stream);
1297 size = stream.total_out;
1299 if (write(fd, compressed, size) != size)
1300 die("unable to write file");
1301 fchmod(fd, 0444);
1302 close(fd);
1303 free(compressed);
1305 ret = link(tmpfile, filename);
1306 if (ret < 0) {
1307 ret = errno;
1310 * Coda hack - coda doesn't like cross-directory links,
1311 * so we fall back to a rename, which will mean that it
1312 * won't be able to check collisions, but that's not a
1313 * big deal.
1315 * When this succeeds, we just return 0. We have nothing
1316 * left to unlink.
1318 if (ret == EXDEV && !rename(tmpfile, filename))
1319 return 0;
1321 unlink(tmpfile);
1322 if (ret) {
1323 if (ret != EEXIST) {
1324 fprintf(stderr, "unable to write sha1 filename %s: %s", filename, strerror(ret));
1325 return -1;
1327 /* FIXME!!! Collision check here ? */
1330 return 0;
1333 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1335 ssize_t size;
1336 unsigned long objsize;
1337 int posn = 0;
1338 void *buf = map_sha1_file_internal(sha1, &objsize);
1339 z_stream stream;
1340 if (!buf) {
1341 unsigned char *unpacked;
1342 unsigned long len;
1343 char type[20];
1344 char hdr[50];
1345 int hdrlen;
1346 // need to unpack and recompress it by itself
1347 unpacked = read_packed_sha1(sha1, type, &len);
1349 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1351 /* Set it up */
1352 memset(&stream, 0, sizeof(stream));
1353 deflateInit(&stream, Z_BEST_COMPRESSION);
1354 size = deflateBound(&stream, len + hdrlen);
1355 buf = xmalloc(size);
1357 /* Compress it */
1358 stream.next_out = buf;
1359 stream.avail_out = size;
1361 /* First header.. */
1362 stream.next_in = (void *)hdr;
1363 stream.avail_in = hdrlen;
1364 while (deflate(&stream, 0) == Z_OK)
1365 /* nothing */;
1367 /* Then the data itself.. */
1368 stream.next_in = unpacked;
1369 stream.avail_in = len;
1370 while (deflate(&stream, Z_FINISH) == Z_OK)
1371 /* nothing */;
1372 deflateEnd(&stream);
1374 objsize = stream.total_out;
1377 do {
1378 size = write(fd, buf + posn, objsize - posn);
1379 if (size <= 0) {
1380 if (!size) {
1381 fprintf(stderr, "write closed");
1382 } else {
1383 perror("write ");
1385 return -1;
1387 posn += size;
1388 } while (posn < objsize);
1389 return 0;
1392 int write_sha1_from_fd(const unsigned char *sha1, int fd)
1394 char *filename = sha1_file_name(sha1);
1396 int local;
1397 z_stream stream;
1398 unsigned char real_sha1[20];
1399 unsigned char buf[4096];
1400 unsigned char discard[4096];
1401 int ret;
1402 SHA_CTX c;
1404 local = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0666);
1406 if (local < 0)
1407 return error("Couldn't open %s\n", filename);
1409 memset(&stream, 0, sizeof(stream));
1411 inflateInit(&stream);
1413 SHA1_Init(&c);
1415 do {
1416 ssize_t size;
1417 size = read(fd, buf, 4096);
1418 if (size <= 0) {
1419 close(local);
1420 unlink(filename);
1421 if (!size)
1422 return error("Connection closed?");
1423 perror("Reading from connection");
1424 return -1;
1426 write(local, buf, size);
1427 stream.avail_in = size;
1428 stream.next_in = buf;
1429 do {
1430 stream.next_out = discard;
1431 stream.avail_out = sizeof(discard);
1432 ret = inflate(&stream, Z_SYNC_FLUSH);
1433 SHA1_Update(&c, discard, sizeof(discard) -
1434 stream.avail_out);
1435 } while (stream.avail_in && ret == Z_OK);
1437 } while (ret == Z_OK);
1438 inflateEnd(&stream);
1440 close(local);
1441 SHA1_Final(real_sha1, &c);
1442 if (ret != Z_STREAM_END) {
1443 unlink(filename);
1444 return error("File %s corrupted", sha1_to_hex(sha1));
1446 if (memcmp(sha1, real_sha1, 20)) {
1447 unlink(filename);
1448 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1451 return 0;
1454 int has_pack_index(const unsigned char *sha1)
1456 struct stat st;
1457 if (stat(sha1_pack_index_name(sha1), &st))
1458 return 0;
1459 return 1;
1462 int has_pack_file(const unsigned char *sha1)
1464 struct stat st;
1465 if (stat(sha1_pack_name(sha1), &st))
1466 return 0;
1467 return 1;
1470 int has_sha1_pack(const unsigned char *sha1)
1472 struct pack_entry e;
1473 return find_pack_entry(sha1, &e);
1476 int has_sha1_file(const unsigned char *sha1)
1478 struct stat st;
1479 struct pack_entry e;
1481 if (find_pack_entry(sha1, &e))
1482 return 1;
1483 return find_sha1_file(sha1, &st) ? 1 : 0;
1486 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1488 unsigned long size = st->st_size;
1489 void *buf;
1490 int ret;
1491 unsigned char hdr[50];
1492 int hdrlen;
1494 buf = "";
1495 if (size)
1496 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1497 close(fd);
1498 if (buf == MAP_FAILED)
1499 return -1;
1501 if (!type)
1502 type = "blob";
1503 if (write_object)
1504 ret = write_sha1_file(buf, size, type, sha1);
1505 else {
1506 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1507 ret = 0;
1509 if (size)
1510 munmap(buf, size);
1511 return ret;