2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
15 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
16 #define O_NOATIME 01000000
22 static unsigned int sha1_file_open_flag = O_NOATIME;
24 static unsigned hexval(char c)
26 if (c >= '0' && c <= '9')
28 if (c >= 'a' && c <= 'f')
30 if (c >= 'A' && c <= 'F')
35 int get_sha1_hex(const char *hex, unsigned char *sha1)
38 for (i = 0; i < 20; i++) {
39 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
48 static int get_sha1_file(const char *path, unsigned char *result)
51 int fd = open(path, O_RDONLY);
56 len = read(fd, buffer, sizeof(buffer));
60 return get_sha1_hex(buffer, result);
63 static char *git_dir, *git_object_dir, *git_index_file, *git_refs_dir;
64 static void setup_git_env(void)
66 git_dir = gitenv(GIT_DIR_ENVIRONMENT);
68 git_dir = DEFAULT_GIT_DIR_ENVIRONMENT;
69 git_object_dir = gitenv(DB_ENVIRONMENT);
70 if (!git_object_dir) {
71 git_object_dir = xmalloc(strlen(git_dir) + 9);
72 sprintf(git_object_dir, "%s/objects", git_dir);
74 git_refs_dir = xmalloc(strlen(git_dir) + 6);
75 sprintf(git_refs_dir, "%s/refs", git_dir);
76 git_index_file = gitenv(INDEX_ENVIRONMENT);
77 if (!git_index_file) {
78 git_index_file = xmalloc(strlen(git_dir) + 7);
79 sprintf(git_index_file, "%s/index", git_dir);
83 char *get_object_directory(void)
87 return git_object_dir;
90 char *get_refs_directory(void)
97 char *get_index_file(void)
101 return git_index_file;
104 int get_sha1(const char *str, unsigned char *sha1)
106 static char pathname[PATH_MAX];
107 static const char *prefix[] = {
117 if (!get_sha1_hex(str, sha1))
122 for (p = prefix; *p; p++) {
123 snprintf(pathname, sizeof(pathname), "%s/%s/%s",
125 if (!get_sha1_file(pathname, sha1))
132 char * sha1_to_hex(const unsigned char *sha1)
134 static char buffer[50];
135 static const char hex[] = "0123456789abcdef";
139 for (i = 0; i < 20; i++) {
140 unsigned int val = *sha1++;
141 *buf++ = hex[val >> 4];
142 *buf++ = hex[val & 0xf];
147 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
150 for (i = 0; i < 20; i++) {
151 static char hex[] = "0123456789abcdef";
152 unsigned int val = sha1[i];
153 char *pos = pathbuf + i*2 + (i > 0);
154 *pos++ = hex[val >> 4];
155 *pos = hex[val & 0xf];
160 * NOTE! This returns a statically allocated buffer, so you have to be
161 * careful about using it. Do a "strdup()" if you need to save the
164 * Also note that this returns the location for creating. Reading
165 * SHA1 file can happen from any alternate directory listed in the
166 * DB_ENVIRONMENT environment variable if it is not found in
167 * the primary object database.
169 char *sha1_file_name(const unsigned char *sha1)
171 static char *name, *base;
174 const char *sha1_file_directory = get_object_directory();
175 int len = strlen(sha1_file_directory);
176 base = xmalloc(len + 60);
177 memcpy(base, sha1_file_directory, len);
178 memset(base+len, 0, 60);
181 name = base + len + 1;
183 fill_sha1_path(name, sha1);
187 struct alternate_object_database *alt_odb;
190 * Prepare alternate object database registry.
191 * alt_odb points at an array of struct alternate_object_database.
192 * This array is terminated with an element that has both its base
193 * and name set to NULL. alt_odb[n] comes from n'th non-empty
194 * element from colon separated ALTERNATE_DB_ENVIRONMENT environment
195 * variable, and its base points at a statically allocated buffer
196 * that contains "/the/directory/corresponding/to/.git/objects/...",
197 * while its name points just after the slash at the end of
198 * ".git/objects/" in the example above, and has enough space to hold
199 * 40-byte hex SHA1, an extra slash for the first level indirection,
200 * and the terminating NUL.
201 * This function allocates the alt_odb array and all the strings
202 * pointed by base fields of the array elements with one xmalloc();
203 * the string pool immediately follows the array.
205 void prepare_alt_odb(void)
208 const char *cp, *last;
210 const char *alt = gitenv(ALTERNATE_DB_ENVIRONMENT) ? : "";
214 /* The first pass counts how large an area to allocate to
215 * hold the entire alt_odb structure, including array of
216 * structs and path buffers for them. The second pass fills
217 * the structure and prepares the path buffers for use by
220 for (totlen = pass = 0; pass < 2; pass++) {
224 cp = strchr(last, ':') ? : last + strlen(last);
226 /* 43 = 40-byte + 2 '/' + terminating NUL */
227 int pfxlen = cp - last;
228 int entlen = pfxlen + 43;
232 alt_odb[i].base = op;
233 alt_odb[i].name = op + pfxlen + 1;
234 memcpy(op, last, pfxlen);
235 op[pfxlen] = op[pfxlen + 3] = '/';
241 while (*cp && *cp == ':')
247 alt_odb = xmalloc(sizeof(*alt_odb) * (i + 1) + totlen);
248 alt_odb[i].base = alt_odb[i].name = NULL;
249 op = (char*)(&alt_odb[i+1]);
253 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
256 char *name = sha1_file_name(sha1);
261 for (i = 0; (name = alt_odb[i].name) != NULL; i++) {
262 fill_sha1_path(name, sha1);
263 if (!stat(alt_odb[i].base, st))
264 return alt_odb[i].base;
269 #define PACK_MAX_SZ (1<<26)
270 static int pack_used_ctr;
271 static unsigned long pack_mapped;
272 struct packed_git *packed_git;
276 unsigned char sha1[20];
277 struct packed_git *p;
280 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
285 unsigned long idx_size;
287 int fd = open(path, O_RDONLY);
291 if (fstat(fd, &st)) {
295 idx_size = st.st_size;
296 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
298 if (idx_map == MAP_FAILED)
303 /* check index map */
304 if (idx_size < 4*256 + 20)
305 return error("index file too small");
307 for (i = 0; i < 256; i++) {
308 unsigned int n = ntohl(index[i]);
310 return error("non-monotonic index");
316 * - 256 index entries 4 bytes each
317 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
318 * - 20-byte SHA1 of the packfile
319 * - 20-byte SHA1 file checksum
321 if (idx_size != 4*256 + nr * 24 + 20 + 20)
322 return error("wrong index file size");
325 *idx_size_ = idx_size;
329 static void unuse_one_packed_git(void)
334 static int use_packed_git(struct packed_git *p)
341 pack_mapped += p->pack_size;
342 while (PACK_MAX_SZ < pack_mapped)
343 unuse_one_packed_git();
344 fd = open(p->pack_name, O_RDONLY);
347 if (fstat(fd, &st)) {
351 if (st.st_size != p->pack_size)
353 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
355 if (map == MAP_FAILED)
359 p->pack_last_used = pack_used_ctr++;
363 static struct packed_git *add_packed_git(char *path, int path_len)
366 struct packed_git *p;
367 unsigned long idx_size;
370 if (check_packed_git_idx(path, &idx_size, &idx_map))
373 /* do we have a corresponding .pack file? */
374 strcpy(path + path_len - 4, ".pack");
375 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
376 munmap(idx_map, idx_size);
379 /* ok, it looks sane as far as we can check without
380 * actually mapping the pack file.
382 p = xmalloc(sizeof(*p) + path_len + 2);
383 strcpy(p->pack_name, path);
384 p->index_size = idx_size;
385 p->pack_size = st.st_size;
386 p->index_base = idx_map;
388 p->pack_last_used = 0;
392 static void prepare_packed_git_one(char *objdir)
399 sprintf(path, "%s/pack", objdir);
405 while ((de = readdir(dir)) != NULL) {
406 int namelen = strlen(de->d_name);
407 struct packed_git *p;
409 if (strcmp(de->d_name + namelen - 4, ".idx"))
412 /* we have .idx. Is it a file we can map? */
413 strcpy(path + len, de->d_name);
414 p = add_packed_git(path, len + namelen);
417 p->next = packed_git;
422 void prepare_packed_git(void)
425 static int run_once = 0;
430 prepare_packed_git_one(get_object_directory());
432 for (i = 0; alt_odb[i].base != NULL; i++) {
433 alt_odb[i].name[0] = 0;
434 prepare_packed_git_one(alt_odb[i].base);
438 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
441 unsigned char real_sha1[20];
445 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
446 SHA1_Update(&c, map, size);
447 SHA1_Final(real_sha1, &c);
448 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
451 static void *map_sha1_file_internal(const unsigned char *sha1,
458 char *filename = find_sha1_file(sha1, &st);
462 error("cannot map sha1 file %s", sha1_to_hex(sha1));
466 fd = open(filename, O_RDONLY | sha1_file_open_flag);
468 /* See if it works without O_NOATIME */
469 switch (sha1_file_open_flag) {
471 fd = open(filename, O_RDONLY);
481 /* If it failed once, it will probably fail again.
482 * Stop using O_NOATIME
484 sha1_file_open_flag = 0;
486 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
488 if (-1 == (int)(long)map)
494 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
496 return map_sha1_file_internal(sha1, size, 1);
499 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
501 /* Get the data stream */
502 memset(stream, 0, sizeof(*stream));
503 stream->next_in = map;
504 stream->avail_in = mapsize;
505 stream->next_out = buffer;
506 stream->avail_out = size;
509 return inflate(stream, 0);
512 void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
514 int bytes = strlen(buffer) + 1;
515 unsigned char *buf = xmalloc(1+size);
517 memcpy(buf, buffer + bytes, stream->total_out - bytes);
518 bytes = stream->total_out - bytes;
520 stream->next_out = buf + bytes;
521 stream->avail_out = size - bytes;
522 while (inflate(stream, Z_FINISH) == Z_OK)
531 * We used to just use "sscanf()", but that's actually way
532 * too permissive for what we want to check. So do an anal
533 * object header parse by hand.
535 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
541 * The type can be at most ten bytes (including the
542 * terminating '\0' that we add), and is followed by
557 * The length must follow immediately, and be in canonical
558 * decimal format (ie "010" is not valid).
565 unsigned long c = *hdr - '0';
569 size = size * 10 + c;
575 * The length must be followed by a zero byte
577 return *hdr ? -1 : 0;
580 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
586 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
587 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
590 return unpack_sha1_rest(&stream, hdr, *size);
593 static int packed_delta_info(unsigned char *base_sha1,
594 unsigned long delta_size,
597 unsigned long *sizep)
600 unsigned char delta_head[64];
603 unsigned long data_size, result_size, base_size, verify_base_size;
608 die("truncated pack file");
609 if (sha1_object_info(base_sha1, type, &base_size))
610 die("cannot get info for delta-pack base");
612 data = base_sha1 + 20;
613 data_size = left - 20;
615 memset(&stream, 0, sizeof(stream));
617 stream.next_in = data;
618 stream.avail_in = data_size;
619 stream.next_out = delta_head;
620 stream.avail_out = sizeof(delta_head);
622 inflateInit(&stream);
623 st = inflate(&stream, Z_FINISH);
625 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head))
626 die("delta data unpack-initial failed");
628 /* Examine the initial part of the delta to figure out
629 * the result size. Verify the base size while we are at it.
632 verify_base_size = i = 0;
636 verify_base_size |= *data++ << i;
641 /* Read the result size */
646 result_size |= *data++ << i;
650 if (verify_base_size != base_size)
651 die("delta base size mismatch");
653 *sizep = result_size;
657 static int packed_object_info(struct pack_entry *entry,
658 char *type, unsigned long *sizep)
660 struct packed_git *p = entry->p;
661 unsigned long offset, size, left;
664 offset = entry->offset;
665 if (p->pack_size - 5 < offset)
666 die("object offset outside of pack file");
668 if (use_packed_git(p))
669 die("cannot map packed file");
671 pack = p->pack_base + offset;
672 size = (pack[1] << 24) + (pack[2] << 16) + (pack[3] << 8) + pack[4];
673 left = p->pack_size - offset - 5;
676 return packed_delta_info(pack+5, size, left, type, sizep);
679 strcpy(type, "commit");
682 strcpy(type, "tree");
685 strcpy(type, "blob");
691 die("corrupted pack file");
697 /* forward declaration for a mutually recursive function */
698 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
700 static void *unpack_delta_entry(unsigned char *base_sha1,
701 unsigned long delta_size,
704 unsigned long *sizep)
706 void *data, *delta_data, *result, *base;
707 unsigned long data_size, result_size, base_size;
712 die("truncated pack file");
713 data = base_sha1 + 20;
714 data_size = left - 20;
715 delta_data = xmalloc(delta_size);
717 memset(&stream, 0, sizeof(stream));
719 stream.next_in = data;
720 stream.avail_in = data_size;
721 stream.next_out = delta_data;
722 stream.avail_out = delta_size;
724 inflateInit(&stream);
725 st = inflate(&stream, Z_FINISH);
727 if ((st != Z_STREAM_END) || stream.total_out != delta_size)
728 die("delta data unpack failed");
730 /* This may recursively unpack the base, which is what we want */
731 base = read_sha1_file(base_sha1, type, &base_size);
733 die("failed to read delta-pack base object %s",
734 sha1_to_hex(base_sha1));
735 result = patch_delta(base, base_size,
736 delta_data, delta_size,
739 die("failed to apply delta");
742 *sizep = result_size;
746 static void *unpack_non_delta_entry(unsigned char *data,
754 buffer = xmalloc(size + 1);
756 memset(&stream, 0, sizeof(stream));
757 stream.next_in = data;
758 stream.avail_in = left;
759 stream.next_out = buffer;
760 stream.avail_out = size;
762 inflateInit(&stream);
763 st = inflate(&stream, Z_FINISH);
765 if ((st != Z_STREAM_END) || stream.total_out != size) {
773 static void *unpack_entry(struct pack_entry *entry,
774 char *type, unsigned long *sizep)
776 struct packed_git *p = entry->p;
777 unsigned long offset, size, left;
780 offset = entry->offset;
781 if (p->pack_size - 5 < offset)
782 die("object offset outside of pack file");
784 if (use_packed_git(p))
785 die("cannot map packed file");
787 pack = p->pack_base + offset;
788 size = (pack[1] << 24) + (pack[2] << 16) + (pack[3] << 8) + pack[4];
789 left = p->pack_size - offset - 5;
792 return unpack_delta_entry(pack+5, size, left, type, sizep);
794 strcpy(type, "commit");
797 strcpy(type, "tree");
800 strcpy(type, "blob");
806 die("corrupted pack file");
809 return unpack_non_delta_entry(pack+5, size, left);
812 int num_packed_objects(const struct packed_git *p)
814 /* See check_packed_git_idx and pack-objects.c */
815 return (p->index_size - 20 - 20 - 4*256) / 24;
818 int nth_packed_object_sha1(const struct packed_git *p, int n,
821 void *index = p->index_base + 256;
822 if (n < 0 || num_packed_objects(p) <= n)
824 memcpy(sha1, (index + 24 * n + 4), 20);
828 static int find_pack_entry_1(const unsigned char *sha1,
829 struct pack_entry *e, struct packed_git *p)
831 int *level1_ofs = p->index_base;
832 int hi = ntohl(level1_ofs[*sha1]);
833 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
834 void *index = p->index_base + 256;
837 int mi = (lo + hi) / 2;
838 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
840 e->offset = ntohl(*((int*)(index + 24 * mi)));
841 memcpy(e->sha1, sha1, 20);
853 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
855 struct packed_git *p;
856 prepare_packed_git();
858 for (p = packed_git; p; p = p->next) {
859 if (find_pack_entry_1(sha1, e, p))
865 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
868 unsigned long mapsize, size;
873 map = map_sha1_file_internal(sha1, &mapsize, 0);
877 if (!find_pack_entry(sha1, &e))
878 return error("unable to find %s", sha1_to_hex(sha1));
879 if (!packed_object_info(&e, type, sizep))
882 map = unpack_entry(&e, type, sizep);
884 return (map == NULL) ? 0 : -1;
886 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
887 status = error("unable to unpack %s header",
889 if (parse_sha1_header(hdr, type, &size) < 0)
890 status = error("unable to parse %s header", sha1_to_hex(sha1));
896 munmap(map, mapsize);
900 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
904 if (!find_pack_entry(sha1, &e)) {
905 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
908 return unpack_entry(&e, type, size);
911 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
913 unsigned long mapsize;
916 map = map_sha1_file_internal(sha1, &mapsize, 0);
918 buf = unpack_sha1_file(map, mapsize, type, size);
919 munmap(map, mapsize);
922 return read_packed_sha1(sha1, type, size);
925 void *read_object_with_reference(const unsigned char *sha1,
926 const char *required_type,
928 unsigned char *actual_sha1_return)
933 unsigned char actual_sha1[20];
935 memcpy(actual_sha1, sha1, 20);
938 const char *ref_type = NULL;
940 buffer = read_sha1_file(actual_sha1, type, &isize);
943 if (!strcmp(type, required_type)) {
945 if (actual_sha1_return)
946 memcpy(actual_sha1_return, actual_sha1, 20);
949 /* Handle references */
950 else if (!strcmp(type, "commit"))
952 else if (!strcmp(type, "tag"))
953 ref_type = "object ";
958 ref_length = strlen(ref_type);
960 if (memcmp(buffer, ref_type, ref_length) ||
961 get_sha1_hex(buffer + ref_length, actual_sha1)) {
965 /* Now we have the ID of the referred-to object in
966 * actual_sha1. Check again. */
970 static char *write_sha1_file_prepare(void *buf,
979 /* Generate the header */
980 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
984 SHA1_Update(&c, hdr, *hdrlen);
985 SHA1_Update(&c, buf, len);
986 SHA1_Final(sha1, &c);
988 return sha1_file_name(sha1);
991 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
994 unsigned char *compressed;
996 unsigned char sha1[20];
998 static char tmpfile[PATH_MAX];
999 unsigned char hdr[50];
1000 int fd, hdrlen, ret;
1002 /* Normally if we have it in the pack then we do not bother writing
1003 * it out into .git/objects/??/?{38} file.
1005 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1007 memcpy(returnsha1, sha1, 20);
1008 if (has_sha1_file(sha1))
1010 fd = open(filename, O_RDONLY);
1013 * FIXME!!! We might do collision checking here, but we'd
1014 * need to uncompress the old file and check it. Later.
1020 if (errno != ENOENT) {
1021 fprintf(stderr, "sha1 file %s: %s", filename, strerror(errno));
1025 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1027 fd = mkstemp(tmpfile);
1029 fprintf(stderr, "unable to create temporary sha1 filename %s: %s", tmpfile, strerror(errno));
1034 memset(&stream, 0, sizeof(stream));
1035 deflateInit(&stream, Z_BEST_COMPRESSION);
1036 size = deflateBound(&stream, len+hdrlen);
1037 compressed = xmalloc(size);
1040 stream.next_out = compressed;
1041 stream.avail_out = size;
1043 /* First header.. */
1044 stream.next_in = hdr;
1045 stream.avail_in = hdrlen;
1046 while (deflate(&stream, 0) == Z_OK)
1049 /* Then the data itself.. */
1050 stream.next_in = buf;
1051 stream.avail_in = len;
1052 while (deflate(&stream, Z_FINISH) == Z_OK)
1054 deflateEnd(&stream);
1055 size = stream.total_out;
1057 if (write(fd, compressed, size) != size)
1058 die("unable to write file");
1063 ret = link(tmpfile, filename);
1068 * Coda hack - coda doesn't like cross-directory links,
1069 * so we fall back to a rename, which will mean that it
1070 * won't be able to check collisions, but that's not a
1073 * When this succeeds, we just return 0. We have nothing
1076 if (ret == EXDEV && !rename(tmpfile, filename))
1081 if (ret != EEXIST) {
1082 fprintf(stderr, "unable to write sha1 filename %s: %s", filename, strerror(ret));
1085 /* FIXME!!! Collision check here ? */
1091 int write_sha1_from_fd(const unsigned char *sha1, int fd)
1093 char *filename = sha1_file_name(sha1);
1097 unsigned char real_sha1[20];
1098 unsigned char buf[4096];
1099 unsigned char discard[4096];
1103 local = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0666);
1106 return error("Couldn't open %s\n", filename);
1108 memset(&stream, 0, sizeof(stream));
1110 inflateInit(&stream);
1116 size = read(fd, buf, 4096);
1121 return error("Connection closed?");
1122 perror("Reading from connection");
1125 write(local, buf, size);
1126 stream.avail_in = size;
1127 stream.next_in = buf;
1129 stream.next_out = discard;
1130 stream.avail_out = sizeof(discard);
1131 ret = inflate(&stream, Z_SYNC_FLUSH);
1132 SHA1_Update(&c, discard, sizeof(discard) -
1134 } while (stream.avail_in && ret == Z_OK);
1136 } while (ret == Z_OK);
1137 inflateEnd(&stream);
1140 SHA1_Final(real_sha1, &c);
1141 if (ret != Z_STREAM_END) {
1143 return error("File %s corrupted", sha1_to_hex(sha1));
1145 if (memcmp(sha1, real_sha1, 20)) {
1147 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1153 int has_sha1_file(const unsigned char *sha1)
1156 struct pack_entry e;
1158 if (find_sha1_file(sha1, &st))
1160 return find_pack_entry(sha1, &e);
1163 int index_fd(unsigned char *sha1, int fd, struct stat *st)
1165 unsigned long size = st->st_size;
1171 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1173 if ((int)(long)buf == -1)
1176 ret = write_sha1_file(buf, size, "blob", sha1);