2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
18 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
19 #define O_NOATIME 01000000
25 const unsigned char null_sha1[20];
27 static unsigned int sha1_file_open_flag = O_NOATIME;
29 static inline unsigned int hexval(unsigned int c)
31 static signed char val[256] = {
32 -1, -1, -1, -1, -1, -1, -1, -1, /* 00-07 */
33 -1, -1, -1, -1, -1, -1, -1, -1, /* 08-0f */
34 -1, -1, -1, -1, -1, -1, -1, -1, /* 10-17 */
35 -1, -1, -1, -1, -1, -1, -1, -1, /* 18-1f */
36 -1, -1, -1, -1, -1, -1, -1, -1, /* 20-27 */
37 -1, -1, -1, -1, -1, -1, -1, -1, /* 28-2f */
38 0, 1, 2, 3, 4, 5, 6, 7, /* 30-37 */
39 8, 9, -1, -1, -1, -1, -1, -1, /* 38-3f */
40 -1, 10, 11, 12, 13, 14, 15, -1, /* 40-47 */
41 -1, -1, -1, -1, -1, -1, -1, -1, /* 48-4f */
42 -1, -1, -1, -1, -1, -1, -1, -1, /* 50-57 */
43 -1, -1, -1, -1, -1, -1, -1, -1, /* 58-5f */
44 -1, 10, 11, 12, 13, 14, 15, -1, /* 60-67 */
45 -1, -1, -1, -1, -1, -1, -1, -1, /* 68-67 */
46 -1, -1, -1, -1, -1, -1, -1, -1, /* 70-77 */
47 -1, -1, -1, -1, -1, -1, -1, -1, /* 78-7f */
48 -1, -1, -1, -1, -1, -1, -1, -1, /* 80-87 */
49 -1, -1, -1, -1, -1, -1, -1, -1, /* 88-8f */
50 -1, -1, -1, -1, -1, -1, -1, -1, /* 90-97 */
51 -1, -1, -1, -1, -1, -1, -1, -1, /* 98-9f */
52 -1, -1, -1, -1, -1, -1, -1, -1, /* a0-a7 */
53 -1, -1, -1, -1, -1, -1, -1, -1, /* a8-af */
54 -1, -1, -1, -1, -1, -1, -1, -1, /* b0-b7 */
55 -1, -1, -1, -1, -1, -1, -1, -1, /* b8-bf */
56 -1, -1, -1, -1, -1, -1, -1, -1, /* c0-c7 */
57 -1, -1, -1, -1, -1, -1, -1, -1, /* c8-cf */
58 -1, -1, -1, -1, -1, -1, -1, -1, /* d0-d7 */
59 -1, -1, -1, -1, -1, -1, -1, -1, /* d8-df */
60 -1, -1, -1, -1, -1, -1, -1, -1, /* e0-e7 */
61 -1, -1, -1, -1, -1, -1, -1, -1, /* e8-ef */
62 -1, -1, -1, -1, -1, -1, -1, -1, /* f0-f7 */
63 -1, -1, -1, -1, -1, -1, -1, -1, /* f8-ff */
68 int get_sha1_hex(const char *hex, unsigned char *sha1)
71 for (i = 0; i < 20; i++) {
72 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
81 int safe_create_leading_directories(char *path)
90 pos = strchr(pos, '/');
94 if (!stat(path, &st)) {
96 if (!S_ISDIR(st.st_mode)) {
101 else if (mkdir(path, 0777)) {
105 else if (adjust_shared_perm(path)) {
114 char * sha1_to_hex(const unsigned char *sha1)
117 static char hexbuffer[4][50];
118 static const char hex[] = "0123456789abcdef";
119 char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
122 for (i = 0; i < 20; i++) {
123 unsigned int val = *sha1++;
124 *buf++ = hex[val >> 4];
125 *buf++ = hex[val & 0xf];
132 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
135 for (i = 0; i < 20; i++) {
136 static char hex[] = "0123456789abcdef";
137 unsigned int val = sha1[i];
138 char *pos = pathbuf + i*2 + (i > 0);
139 *pos++ = hex[val >> 4];
140 *pos = hex[val & 0xf];
145 * NOTE! This returns a statically allocated buffer, so you have to be
146 * careful about using it. Do a "xstrdup()" if you need to save the
149 * Also note that this returns the location for creating. Reading
150 * SHA1 file can happen from any alternate directory listed in the
151 * DB_ENVIRONMENT environment variable if it is not found in
152 * the primary object database.
154 char *sha1_file_name(const unsigned char *sha1)
156 static char *name, *base;
159 const char *sha1_file_directory = get_object_directory();
160 int len = strlen(sha1_file_directory);
161 base = xmalloc(len + 60);
162 memcpy(base, sha1_file_directory, len);
163 memset(base+len, 0, 60);
166 name = base + len + 1;
168 fill_sha1_path(name, sha1);
172 char *sha1_pack_name(const unsigned char *sha1)
174 static const char hex[] = "0123456789abcdef";
175 static char *name, *base, *buf;
179 const char *sha1_file_directory = get_object_directory();
180 int len = strlen(sha1_file_directory);
181 base = xmalloc(len + 60);
182 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
183 name = base + len + 11;
188 for (i = 0; i < 20; i++) {
189 unsigned int val = *sha1++;
190 *buf++ = hex[val >> 4];
191 *buf++ = hex[val & 0xf];
197 char *sha1_pack_index_name(const unsigned char *sha1)
199 static const char hex[] = "0123456789abcdef";
200 static char *name, *base, *buf;
204 const char *sha1_file_directory = get_object_directory();
205 int len = strlen(sha1_file_directory);
206 base = xmalloc(len + 60);
207 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
208 name = base + len + 11;
213 for (i = 0; i < 20; i++) {
214 unsigned int val = *sha1++;
215 *buf++ = hex[val >> 4];
216 *buf++ = hex[val & 0xf];
222 struct alternate_object_database *alt_odb_list;
223 static struct alternate_object_database **alt_odb_tail;
225 static void read_info_alternates(const char * alternates, int depth);
228 * Prepare alternate object database registry.
230 * The variable alt_odb_list points at the list of struct
231 * alternate_object_database. The elements on this list come from
232 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
233 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
234 * whose contents is similar to that environment variable but can be
235 * LF separated. Its base points at a statically allocated buffer that
236 * contains "/the/directory/corresponding/to/.git/objects/...", while
237 * its name points just after the slash at the end of ".git/objects/"
238 * in the example above, and has enough space to hold 40-byte hex
239 * SHA1, an extra slash for the first level indirection, and the
242 static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
245 const char *objdir = get_object_directory();
246 struct alternate_object_database *ent;
247 struct alternate_object_database *alt;
248 /* 43 = 40-byte + 2 '/' + terminating NUL */
250 int entlen = pfxlen + 43;
253 if (*entry != '/' && relative_base) {
254 /* Relative alt-odb */
256 base_len = strlen(relative_base) + 1;
260 ent = xmalloc(sizeof(*ent) + entlen);
262 if (*entry != '/' && relative_base) {
263 memcpy(ent->base, relative_base, base_len - 1);
264 ent->base[base_len - 1] = '/';
265 memcpy(ent->base + base_len, entry, len);
268 memcpy(ent->base, entry, pfxlen);
270 ent->name = ent->base + pfxlen + 1;
271 ent->base[pfxlen + 3] = '/';
272 ent->base[pfxlen] = ent->base[entlen-1] = 0;
274 /* Detect cases where alternate disappeared */
275 if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
276 error("object directory %s does not exist; "
277 "check .git/objects/info/alternates.",
283 /* Prevent the common mistake of listing the same
284 * thing twice, or object directory itself.
286 for (alt = alt_odb_list; alt; alt = alt->next) {
287 if (!memcmp(ent->base, alt->base, pfxlen)) {
292 if (!memcmp(ent->base, objdir, pfxlen)) {
297 /* add the alternate entry */
299 alt_odb_tail = &(ent->next);
302 /* recursively add alternates */
303 read_info_alternates(ent->base, depth + 1);
305 ent->base[pfxlen] = '/';
310 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
311 const char *relative_base, int depth)
313 const char *cp, *last;
316 error("%s: ignoring alternate object stores, nesting too deep.",
324 if (cp < ep && *cp == '#') {
325 while (cp < ep && *cp != sep)
330 while (cp < ep && *cp != sep)
333 if ((*last != '/') && depth) {
334 error("%s: ignoring relative alternate object store %s",
335 relative_base, last);
337 link_alt_odb_entry(last, cp - last,
338 relative_base, depth);
341 while (cp < ep && *cp == sep)
347 static void read_info_alternates(const char * relative_base, int depth)
354 sprintf(path, "%s/info/alternates", relative_base);
355 fd = open(path, O_RDONLY);
358 if (fstat(fd, &st) || (st.st_size == 0)) {
362 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
364 if (map == MAP_FAILED)
367 link_alt_odb_entries(map, map + st.st_size, '\n', relative_base, depth);
369 munmap(map, st.st_size);
372 void prepare_alt_odb(void)
376 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
381 alt_odb_tail = &alt_odb_list;
382 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL, 0);
384 read_info_alternates(get_object_directory(), 0);
387 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
389 char *name = sha1_file_name(sha1);
390 struct alternate_object_database *alt;
395 for (alt = alt_odb_list; alt; alt = alt->next) {
397 fill_sha1_path(name, sha1);
398 if (!stat(alt->base, st))
404 #define PACK_MAX_SZ (1<<26)
405 static int pack_used_ctr;
406 static unsigned long pack_mapped;
407 struct packed_git *packed_git;
409 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
414 unsigned long idx_size;
416 int fd = open(path, O_RDONLY);
420 if (fstat(fd, &st)) {
424 idx_size = st.st_size;
425 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
427 if (idx_map == MAP_FAILED)
432 *idx_size_ = idx_size;
434 /* check index map */
435 if (idx_size < 4*256 + 20 + 20)
436 return error("index file too small");
438 for (i = 0; i < 256; i++) {
439 unsigned int n = ntohl(index[i]);
441 return error("non-monotonic index");
447 * - 256 index entries 4 bytes each
448 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
449 * - 20-byte SHA1 of the packfile
450 * - 20-byte SHA1 file checksum
452 if (idx_size != 4*256 + nr * 24 + 20 + 20)
453 return error("wrong index file size");
458 static int unuse_one_packed_git(void)
460 struct packed_git *p, *lru = NULL;
462 for (p = packed_git; p; p = p->next) {
463 if (p->pack_use_cnt || !p->pack_base)
465 if (!lru || p->pack_last_used < lru->pack_last_used)
470 munmap(lru->pack_base, lru->pack_size);
471 lru->pack_base = NULL;
475 void unuse_packed_git(struct packed_git *p)
480 int use_packed_git(struct packed_git *p)
484 /* We created the struct before we had the pack */
485 stat(p->pack_name, &st);
486 if (!S_ISREG(st.st_mode))
487 die("packfile %s not a regular file", p->pack_name);
488 p->pack_size = st.st_size;
494 struct pack_header *hdr;
496 pack_mapped += p->pack_size;
497 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
499 fd = open(p->pack_name, O_RDONLY);
501 die("packfile %s cannot be opened", p->pack_name);
502 if (fstat(fd, &st)) {
504 die("packfile %s cannot be opened", p->pack_name);
506 if (st.st_size != p->pack_size)
507 die("packfile %s size mismatch.", p->pack_name);
508 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
510 if (map == MAP_FAILED)
511 die("packfile %s cannot be mapped.", p->pack_name);
514 /* Check if we understand this pack file. If we don't we're
515 * likely too old to handle it.
518 if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
519 die("packfile %s isn't actually a pack.", p->pack_name);
520 if (!pack_version_ok(hdr->hdr_version))
521 die("packfile %s is version %i and not supported"
522 " (try upgrading GIT to a newer version)",
523 p->pack_name, ntohl(hdr->hdr_version));
525 /* Check if the pack file matches with the index file.
528 if (hashcmp((unsigned char *)(p->index_base) +
530 (unsigned char *)p->pack_base +
531 p->pack_size - 20)) {
532 die("packfile %s does not match index.", p->pack_name);
535 p->pack_last_used = pack_used_ctr++;
540 struct packed_git *add_packed_git(char *path, int path_len, int local)
543 struct packed_git *p;
544 unsigned long idx_size;
546 unsigned char sha1[20];
548 if (check_packed_git_idx(path, &idx_size, &idx_map))
551 /* do we have a corresponding .pack file? */
552 strcpy(path + path_len - 4, ".pack");
553 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
554 munmap(idx_map, idx_size);
557 /* ok, it looks sane as far as we can check without
558 * actually mapping the pack file.
560 p = xmalloc(sizeof(*p) + path_len + 2);
561 strcpy(p->pack_name, path);
562 p->index_size = idx_size;
563 p->pack_size = st.st_size;
564 p->index_base = idx_map;
567 p->pack_last_used = 0;
569 p->pack_local = local;
570 if ((path_len > 44) && !get_sha1_hex(path + path_len - 44, sha1))
571 hashcpy(p->sha1, sha1);
575 struct packed_git *parse_pack_index(unsigned char *sha1)
577 char *path = sha1_pack_index_name(sha1);
578 return parse_pack_index_file(sha1, path);
581 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
583 struct packed_git *p;
584 unsigned long idx_size;
588 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
591 path = sha1_pack_name(sha1);
593 p = xmalloc(sizeof(*p) + strlen(path) + 2);
594 strcpy(p->pack_name, path);
595 p->index_size = idx_size;
597 p->index_base = idx_map;
600 p->pack_last_used = 0;
602 hashcpy(p->sha1, sha1);
606 void install_packed_git(struct packed_git *pack)
608 pack->next = packed_git;
612 static void prepare_packed_git_one(char *objdir, int local)
619 sprintf(path, "%s/pack", objdir);
624 error("unable to open object pack directory: %s: %s",
625 path, strerror(errno));
629 while ((de = readdir(dir)) != NULL) {
630 int namelen = strlen(de->d_name);
631 struct packed_git *p;
633 if (!has_extension(de->d_name, ".idx"))
636 /* we have .idx. Is it a file we can map? */
637 strcpy(path + len, de->d_name);
638 for (p = packed_git; p; p = p->next) {
639 if (!memcmp(path, p->pack_name, len + namelen - 4))
644 p = add_packed_git(path, len + namelen, local);
647 p->next = packed_git;
653 static int prepare_packed_git_run_once = 0;
654 void prepare_packed_git(void)
656 struct alternate_object_database *alt;
658 if (prepare_packed_git_run_once)
660 prepare_packed_git_one(get_object_directory(), 1);
662 for (alt = alt_odb_list; alt; alt = alt->next) {
664 prepare_packed_git_one(alt->base, 0);
667 prepare_packed_git_run_once = 1;
670 static void reprepare_packed_git(void)
672 prepare_packed_git_run_once = 0;
673 prepare_packed_git();
676 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
679 unsigned char real_sha1[20];
683 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
684 SHA1_Update(&c, map, size);
685 SHA1_Final(real_sha1, &c);
686 return hashcmp(sha1, real_sha1) ? -1 : 0;
689 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
694 char *filename = find_sha1_file(sha1, &st);
700 fd = open(filename, O_RDONLY | sha1_file_open_flag);
702 /* See if it works without O_NOATIME */
703 switch (sha1_file_open_flag) {
705 fd = open(filename, O_RDONLY);
713 /* If it failed once, it will probably fail again.
714 * Stop using O_NOATIME
716 sha1_file_open_flag = 0;
718 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
720 if (map == MAP_FAILED)
726 int legacy_loose_object(unsigned char *map)
731 * Is it a zlib-compressed buffer? If so, the first byte
732 * must be 0x78 (15-bit window size, deflated), and the
733 * first 16-bit word is evenly divisible by 31
735 word = (map[0] << 8) + map[1];
736 if (map[0] == 0x78 && !(word % 31))
742 unsigned long unpack_object_header_gently(const unsigned char *buf, unsigned long len, enum object_type *type, unsigned long *sizep)
747 unsigned long used = 0;
750 *type = (c >> 4) & 7;
756 if (sizeof(long) * 8 <= shift)
759 size += (c & 0x7f) << shift;
766 static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
768 unsigned long size, used;
769 static const char valid_loose_object_type[8] = {
771 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
772 0, /* "delta" and others are invalid in a loose object */
774 enum object_type type;
776 /* Get the data stream */
777 memset(stream, 0, sizeof(*stream));
778 stream->next_in = map;
779 stream->avail_in = mapsize;
780 stream->next_out = buffer;
781 stream->avail_out = bufsiz;
783 if (legacy_loose_object(map)) {
785 return inflate(stream, 0);
788 used = unpack_object_header_gently(map, mapsize, &type, &size);
789 if (!used || !valid_loose_object_type[type])
794 /* Set up the stream for the rest.. */
795 stream->next_in = map;
796 stream->avail_in = mapsize;
799 /* And generate the fake traditional header */
800 stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
801 type_names[type], size);
805 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
807 int bytes = strlen(buffer) + 1;
808 unsigned char *buf = xmalloc(1+size);
811 n = stream->total_out - bytes;
814 memcpy(buf, (char *) buffer + bytes, n);
817 stream->next_out = buf + bytes;
818 stream->avail_out = size - bytes;
819 while (inflate(stream, Z_FINISH) == Z_OK)
828 * We used to just use "sscanf()", but that's actually way
829 * too permissive for what we want to check. So do an anal
830 * object header parse by hand.
832 static int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
838 * The type can be at most ten bytes (including the
839 * terminating '\0' that we add), and is followed by
854 * The length must follow immediately, and be in canonical
855 * decimal format (ie "010" is not valid).
862 unsigned long c = *hdr - '0';
866 size = size * 10 + c;
872 * The length must be followed by a zero byte
874 return *hdr ? -1 : 0;
877 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
883 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
884 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
887 return unpack_sha1_rest(&stream, hdr, *size);
890 /* forward declaration for a mutually recursive function */
891 static int packed_object_info(struct pack_entry *entry,
892 char *type, unsigned long *sizep);
894 static int packed_delta_info(unsigned char *base_sha1,
895 unsigned long delta_size,
898 unsigned long *sizep,
899 struct packed_git *p)
901 struct pack_entry base_ent;
904 die("truncated pack file");
906 /* The base entry _must_ be in the same pack */
907 if (!find_pack_entry_one(base_sha1, &base_ent, p))
908 die("failed to find delta-pack base object %s",
909 sha1_to_hex(base_sha1));
911 /* We choose to only get the type of the base object and
912 * ignore potentially corrupt pack file that expects the delta
913 * based on a base with a wrong size. This saves tons of
917 if (packed_object_info(&base_ent, type, NULL))
918 die("cannot get info for delta-pack base");
921 const unsigned char *data;
922 unsigned char delta_head[64];
923 unsigned long result_size;
927 memset(&stream, 0, sizeof(stream));
929 data = stream.next_in = base_sha1 + 20;
930 stream.avail_in = left - 20;
931 stream.next_out = delta_head;
932 stream.avail_out = sizeof(delta_head);
934 inflateInit(&stream);
935 st = inflate(&stream, Z_FINISH);
937 if ((st != Z_STREAM_END) &&
938 stream.total_out != sizeof(delta_head))
939 die("delta data unpack-initial failed");
941 /* Examine the initial part of the delta to figure out
946 /* ignore base size */
947 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
949 /* Read the result size */
950 result_size = get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
951 *sizep = result_size;
956 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
957 enum object_type *type, unsigned long *sizep)
961 if (p->pack_size <= offset)
962 die("object offset outside of pack file");
964 used = unpack_object_header_gently((unsigned char *)p->pack_base +
966 p->pack_size - offset, type, sizep);
968 die("object offset outside of pack file");
970 return offset + used;
973 int check_reuse_pack_delta(struct packed_git *p, unsigned long offset,
974 unsigned char *base, unsigned long *sizep,
975 enum object_type *kindp)
982 ptr = unpack_object_header(p, ptr, kindp, sizep);
983 if (*kindp != OBJ_DELTA)
985 hashcpy(base, (unsigned char *) p->pack_base + ptr);
992 void packed_object_info_detail(struct pack_entry *e,
995 unsigned long *store_size,
996 unsigned int *delta_chain_length,
997 unsigned char *base_sha1)
999 struct packed_git *p = e->p;
1000 unsigned long offset;
1001 unsigned char *pack;
1002 enum object_type kind;
1004 offset = unpack_object_header(p, e->offset, &kind, size);
1005 pack = (unsigned char *) p->pack_base + offset;
1006 if (kind != OBJ_DELTA)
1007 *delta_chain_length = 0;
1009 unsigned int chain_length = 0;
1010 if (p->pack_size <= offset + 20)
1011 die("pack file %s records an incomplete delta base",
1013 hashcpy(base_sha1, pack);
1015 struct pack_entry base_ent;
1018 find_pack_entry_one(pack, &base_ent, p);
1019 offset = unpack_object_header(p, base_ent.offset,
1021 pack = (unsigned char *) p->pack_base + offset;
1023 } while (kind == OBJ_DELTA);
1024 *delta_chain_length = chain_length;
1031 strcpy(type, type_names[kind]);
1034 die("corrupted pack file %s containing object of kind %d",
1035 p->pack_name, kind);
1037 *store_size = 0; /* notyet */
1040 static int packed_object_info(struct pack_entry *entry,
1041 char *type, unsigned long *sizep)
1043 struct packed_git *p = entry->p;
1044 unsigned long offset, size, left;
1045 unsigned char *pack;
1046 enum object_type kind;
1049 if (use_packed_git(p))
1050 die("cannot map packed file");
1052 offset = unpack_object_header(p, entry->offset, &kind, &size);
1053 pack = (unsigned char *) p->pack_base + offset;
1054 left = p->pack_size - offset;
1058 retval = packed_delta_info(pack, size, left, type, sizep, p);
1059 unuse_packed_git(p);
1065 strcpy(type, type_names[kind]);
1068 die("corrupted pack file %s containing object of kind %d",
1069 p->pack_name, kind);
1073 unuse_packed_git(p);
1077 static void *unpack_compressed_entry(struct packed_git *p,
1078 unsigned long offset,
1083 unsigned char *buffer;
1085 buffer = xmalloc(size + 1);
1087 memset(&stream, 0, sizeof(stream));
1088 stream.next_in = (unsigned char*)p->pack_base + offset;
1089 stream.avail_in = p->pack_size - offset;
1090 stream.next_out = buffer;
1091 stream.avail_out = size;
1093 inflateInit(&stream);
1094 st = inflate(&stream, Z_FINISH);
1095 inflateEnd(&stream);
1096 if ((st != Z_STREAM_END) || stream.total_out != size) {
1104 static void *unpack_delta_entry(struct packed_git *p,
1105 unsigned long offset,
1106 unsigned long delta_size,
1108 unsigned long *sizep)
1110 struct pack_entry base_ent;
1111 void *delta_data, *result, *base;
1112 unsigned long result_size, base_size;
1113 unsigned char* base_sha1;
1115 if ((offset + 20) >= p->pack_size)
1116 die("truncated pack file");
1118 /* The base entry _must_ be in the same pack */
1119 base_sha1 = (unsigned char*)p->pack_base + offset;
1120 if (!find_pack_entry_one(base_sha1, &base_ent, p))
1121 die("failed to find delta-pack base object %s",
1122 sha1_to_hex(base_sha1));
1123 base = unpack_entry_gently(&base_ent, type, &base_size);
1125 die("failed to read delta-pack base object %s",
1126 sha1_to_hex(base_sha1));
1128 delta_data = unpack_compressed_entry(p, offset + 20, delta_size);
1129 result = patch_delta(base, base_size,
1130 delta_data, delta_size,
1133 die("failed to apply delta");
1136 *sizep = result_size;
1140 static void *unpack_entry(struct pack_entry *entry,
1141 char *type, unsigned long *sizep)
1143 struct packed_git *p = entry->p;
1146 if (use_packed_git(p))
1147 die("cannot map packed file");
1148 retval = unpack_entry_gently(entry, type, sizep);
1149 unuse_packed_git(p);
1151 die("corrupted pack file %s", p->pack_name);
1155 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
1156 void *unpack_entry_gently(struct pack_entry *entry,
1157 char *type, unsigned long *sizep)
1159 struct packed_git *p = entry->p;
1160 unsigned long offset, size;
1161 enum object_type kind;
1163 offset = unpack_object_header(p, entry->offset, &kind, &size);
1166 return unpack_delta_entry(p, offset, size, type, sizep);
1171 strcpy(type, type_names[kind]);
1173 return unpack_compressed_entry(p, offset, size);
1179 int num_packed_objects(const struct packed_git *p)
1181 /* See check_packed_git_idx() */
1182 return (p->index_size - 20 - 20 - 4*256) / 24;
1185 int nth_packed_object_sha1(const struct packed_git *p, int n,
1186 unsigned char* sha1)
1188 void *index = p->index_base + 256;
1189 if (n < 0 || num_packed_objects(p) <= n)
1191 hashcpy(sha1, (unsigned char *) index + (24 * n) + 4);
1195 int find_pack_entry_one(const unsigned char *sha1,
1196 struct pack_entry *e, struct packed_git *p)
1198 unsigned int *level1_ofs = p->index_base;
1199 int hi = ntohl(level1_ofs[*sha1]);
1200 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1201 void *index = p->index_base + 256;
1204 int mi = (lo + hi) / 2;
1205 int cmp = hashcmp((unsigned char *)index + (24 * mi) + 4, sha1);
1207 e->offset = ntohl(*((unsigned int *) ((char *) index + (24 * mi))));
1208 hashcpy(e->sha1, sha1);
1220 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1222 struct packed_git *p;
1223 prepare_packed_git();
1225 for (p = packed_git; p; p = p->next) {
1226 if (find_pack_entry_one(sha1, e, p))
1232 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1233 struct packed_git *packs)
1235 struct packed_git *p;
1236 struct pack_entry e;
1238 for (p = packs; p; p = p->next) {
1239 if (find_pack_entry_one(sha1, &e, p))
1246 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1249 unsigned long mapsize, size;
1254 map = map_sha1_file(sha1, &mapsize);
1256 struct pack_entry e;
1258 if (find_pack_entry(sha1, &e))
1259 return packed_object_info(&e, type, sizep);
1260 reprepare_packed_git();
1261 if (find_pack_entry(sha1, &e))
1262 return packed_object_info(&e, type, sizep);
1263 return error("unable to find %s", sha1_to_hex(sha1));
1265 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1266 status = error("unable to unpack %s header",
1268 if (parse_sha1_header(hdr, type, &size) < 0)
1269 status = error("unable to parse %s header", sha1_to_hex(sha1));
1275 inflateEnd(&stream);
1276 munmap(map, mapsize);
1280 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1282 struct pack_entry e;
1284 if (!find_pack_entry(sha1, &e)) {
1285 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1288 return unpack_entry(&e, type, size);
1291 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1293 unsigned long mapsize;
1295 struct pack_entry e;
1297 if (find_pack_entry(sha1, &e))
1298 return read_packed_sha1(sha1, type, size);
1299 map = map_sha1_file(sha1, &mapsize);
1301 buf = unpack_sha1_file(map, mapsize, type, size);
1302 munmap(map, mapsize);
1305 reprepare_packed_git();
1306 if (find_pack_entry(sha1, &e))
1307 return read_packed_sha1(sha1, type, size);
1311 void *read_object_with_reference(const unsigned char *sha1,
1312 const char *required_type,
1313 unsigned long *size,
1314 unsigned char *actual_sha1_return)
1318 unsigned long isize;
1319 unsigned char actual_sha1[20];
1321 hashcpy(actual_sha1, sha1);
1323 int ref_length = -1;
1324 const char *ref_type = NULL;
1326 buffer = read_sha1_file(actual_sha1, type, &isize);
1329 if (!strcmp(type, required_type)) {
1331 if (actual_sha1_return)
1332 hashcpy(actual_sha1_return, actual_sha1);
1335 /* Handle references */
1336 else if (!strcmp(type, commit_type))
1338 else if (!strcmp(type, tag_type))
1339 ref_type = "object ";
1344 ref_length = strlen(ref_type);
1346 if (memcmp(buffer, ref_type, ref_length) ||
1347 get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
1352 /* Now we have the ID of the referred-to object in
1353 * actual_sha1. Check again. */
1357 char *write_sha1_file_prepare(void *buf,
1360 unsigned char *sha1,
1366 /* Generate the header */
1367 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1371 SHA1_Update(&c, hdr, *hdrlen);
1372 SHA1_Update(&c, buf, len);
1373 SHA1_Final(sha1, &c);
1375 return sha1_file_name(sha1);
1379 * Link the tempfile to the final place, possibly creating the
1380 * last directory level as you do so.
1382 * Returns the errno on failure, 0 on success.
1384 static int link_temp_to_file(const char *tmpfile, const char *filename)
1389 if (!link(tmpfile, filename))
1393 * Try to mkdir the last path component if that failed.
1395 * Re-try the "link()" regardless of whether the mkdir
1396 * succeeds, since a race might mean that somebody
1400 dir = strrchr(filename, '/');
1403 mkdir(filename, 0777);
1404 if (adjust_shared_perm(filename))
1407 if (!link(tmpfile, filename))
1415 * Move the just written object into its final resting place
1417 int move_temp_to_file(const char *tmpfile, const char *filename)
1419 int ret = link_temp_to_file(tmpfile, filename);
1422 * Coda hack - coda doesn't like cross-directory links,
1423 * so we fall back to a rename, which will mean that it
1424 * won't be able to check collisions, but that's not a
1427 * The same holds for FAT formatted media.
1429 * When this succeeds, we just return 0. We have nothing
1432 if (ret && ret != EEXIST) {
1433 if (!rename(tmpfile, filename))
1439 if (ret != EEXIST) {
1440 fprintf(stderr, "unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1443 /* FIXME!!! Collision check here ? */
1449 static int write_buffer(int fd, const void *buf, size_t len)
1454 size = write(fd, buf, len);
1456 return error("file write: disk full");
1458 if (errno == EINTR || errno == EAGAIN)
1460 return error("file write error (%s)", strerror(errno));
1463 buf = (char *) buf + size;
1468 static int write_binary_header(unsigned char *hdr, enum object_type type, unsigned long len)
1473 c = (type << 4) | (len & 15);
1486 static void setup_object_header(z_stream *stream, const char *type, unsigned long len)
1490 if (use_legacy_headers) {
1491 while (deflate(stream, 0) == Z_OK)
1495 if (!strcmp(type, blob_type))
1496 obj_type = OBJ_BLOB;
1497 else if (!strcmp(type, tree_type))
1498 obj_type = OBJ_TREE;
1499 else if (!strcmp(type, commit_type))
1500 obj_type = OBJ_COMMIT;
1501 else if (!strcmp(type, tag_type))
1504 die("trying to generate bogus object of type '%s'", type);
1505 hdr = write_binary_header(stream->next_out, obj_type, len);
1506 stream->total_out = hdr;
1507 stream->next_out += hdr;
1508 stream->avail_out -= hdr;
1511 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1514 unsigned char *compressed;
1516 unsigned char sha1[20];
1518 static char tmpfile[PATH_MAX];
1519 unsigned char hdr[50];
1522 /* Normally if we have it in the pack then we do not bother writing
1523 * it out into .git/objects/??/?{38} file.
1525 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1527 hashcpy(returnsha1, sha1);
1528 if (has_sha1_file(sha1))
1530 fd = open(filename, O_RDONLY);
1533 * FIXME!!! We might do collision checking here, but we'd
1534 * need to uncompress the old file and check it. Later.
1540 if (errno != ENOENT) {
1541 fprintf(stderr, "sha1 file %s: %s\n", filename, strerror(errno));
1545 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1547 fd = mkstemp(tmpfile);
1549 fprintf(stderr, "unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
1554 memset(&stream, 0, sizeof(stream));
1555 deflateInit(&stream, zlib_compression_level);
1556 size = 8 + deflateBound(&stream, len+hdrlen);
1557 compressed = xmalloc(size);
1560 stream.next_out = compressed;
1561 stream.avail_out = size;
1563 /* First header.. */
1564 stream.next_in = hdr;
1565 stream.avail_in = hdrlen;
1566 setup_object_header(&stream, type, len);
1568 /* Then the data itself.. */
1569 stream.next_in = buf;
1570 stream.avail_in = len;
1571 while (deflate(&stream, Z_FINISH) == Z_OK)
1573 deflateEnd(&stream);
1574 size = stream.total_out;
1576 if (write_buffer(fd, compressed, size) < 0)
1577 die("unable to write sha1 file");
1582 return move_temp_to_file(tmpfile, filename);
1586 * We need to unpack and recompress the object for writing
1587 * it out to a different file.
1589 static void *repack_object(const unsigned char *sha1, unsigned long *objsize)
1593 unsigned char *unpacked;
1600 /* need to unpack and recompress it by itself */
1601 unpacked = read_packed_sha1(sha1, type, &len);
1603 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1606 memset(&stream, 0, sizeof(stream));
1607 deflateInit(&stream, zlib_compression_level);
1608 size = deflateBound(&stream, len + hdrlen);
1609 buf = xmalloc(size);
1612 stream.next_out = buf;
1613 stream.avail_out = size;
1615 /* First header.. */
1616 stream.next_in = (void *)hdr;
1617 stream.avail_in = hdrlen;
1618 while (deflate(&stream, 0) == Z_OK)
1621 /* Then the data itself.. */
1622 stream.next_in = unpacked;
1623 stream.avail_in = len;
1624 while (deflate(&stream, Z_FINISH) == Z_OK)
1626 deflateEnd(&stream);
1629 *objsize = stream.total_out;
1633 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1636 unsigned long objsize;
1637 void *buf = map_sha1_file(sha1, &objsize);
1640 retval = write_buffer(fd, buf, objsize);
1641 munmap(buf, objsize);
1645 buf = repack_object(sha1, &objsize);
1646 retval = write_buffer(fd, buf, objsize);
1651 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1652 size_t bufsize, size_t *bufposn)
1654 char tmpfile[PATH_MAX];
1657 unsigned char real_sha1[20];
1658 unsigned char discard[4096];
1662 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1664 local = mkstemp(tmpfile);
1666 return error("Couldn't open %s for %s",
1667 tmpfile, sha1_to_hex(sha1));
1669 memset(&stream, 0, sizeof(stream));
1671 inflateInit(&stream);
1678 stream.avail_in = *bufposn;
1679 stream.next_in = (unsigned char *) buffer;
1681 stream.next_out = discard;
1682 stream.avail_out = sizeof(discard);
1683 ret = inflate(&stream, Z_SYNC_FLUSH);
1684 SHA1_Update(&c, discard, sizeof(discard) -
1686 } while (stream.avail_in && ret == Z_OK);
1687 if (write_buffer(local, buffer, *bufposn - stream.avail_in) < 0)
1688 die("unable to write sha1 file");
1689 memmove(buffer, buffer + *bufposn - stream.avail_in,
1691 *bufposn = stream.avail_in;
1695 size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1700 return error("Connection closed?");
1701 perror("Reading from connection");
1706 inflateEnd(&stream);
1709 SHA1_Final(real_sha1, &c);
1710 if (ret != Z_STREAM_END) {
1712 return error("File %s corrupted", sha1_to_hex(sha1));
1714 if (hashcmp(sha1, real_sha1)) {
1716 return error("File %s has bad hash", sha1_to_hex(sha1));
1719 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1722 int has_pack_index(const unsigned char *sha1)
1725 if (stat(sha1_pack_index_name(sha1), &st))
1730 int has_pack_file(const unsigned char *sha1)
1733 if (stat(sha1_pack_name(sha1), &st))
1738 int has_sha1_pack(const unsigned char *sha1)
1740 struct pack_entry e;
1741 return find_pack_entry(sha1, &e);
1744 int has_sha1_file(const unsigned char *sha1)
1747 struct pack_entry e;
1749 if (find_pack_entry(sha1, &e))
1751 return find_sha1_file(sha1, &st) ? 1 : 0;
1755 * reads from fd as long as possible into a supplied buffer of size bytes.
1756 * If necessary the buffer's size is increased using realloc()
1758 * returns 0 if anything went fine and -1 otherwise
1760 * NOTE: both buf and size may change, but even when -1 is returned
1761 * you still have to free() it yourself.
1763 int read_pipe(int fd, char** return_buf, unsigned long* return_size)
1765 char* buf = *return_buf;
1766 unsigned long size = *return_size;
1768 unsigned long off = 0;
1771 iret = xread(fd, buf + off, size - off);
1776 buf = xrealloc(buf, size);
1789 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
1791 unsigned long size = 4096;
1792 char *buf = xmalloc(size);
1794 unsigned char hdr[50];
1797 if (read_pipe(fd, &buf, &size)) {
1805 ret = write_sha1_file(buf, size, type, sha1);
1807 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1814 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1816 unsigned long size = st->st_size;
1819 unsigned char hdr[50];
1824 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1826 if (buf == MAP_FAILED)
1832 ret = write_sha1_file(buf, size, type, sha1);
1834 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1842 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1847 switch (st->st_mode & S_IFMT) {
1849 fd = open(path, O_RDONLY);
1851 return error("open(\"%s\"): %s", path,
1853 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1854 return error("%s: failed to insert into database",
1858 target = xmalloc(st->st_size+1);
1859 if (readlink(path, target, st->st_size+1) != st->st_size) {
1860 char *errstr = strerror(errno);
1862 return error("readlink(\"%s\"): %s", path,
1865 if (!write_object) {
1866 unsigned char hdr[50];
1868 write_sha1_file_prepare(target, st->st_size, blob_type,
1869 sha1, hdr, &hdrlen);
1870 } else if (write_sha1_file(target, st->st_size, blob_type, sha1))
1871 return error("%s: failed to insert into database",
1876 return error("%s: unsupported file type", path);