2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
13 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
14 #define O_NOATIME 01000000
20 static unsigned int sha1_file_open_flag = O_NOATIME;
22 static unsigned hexval(char c)
24 if (c >= '0' && c <= '9')
26 if (c >= 'a' && c <= 'f')
28 if (c >= 'A' && c <= 'F')
33 int get_sha1_hex(const char *hex, unsigned char *sha1)
36 for (i = 0; i < 20; i++) {
37 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
46 static int get_sha1_file(const char *path, unsigned char *result)
49 int fd = open(path, O_RDONLY);
54 len = read(fd, buffer, sizeof(buffer));
58 return get_sha1_hex(buffer, result);
61 static char *git_dir, *git_object_dir, *git_index_file, *git_refs_dir;
62 static void setup_git_env(void)
64 git_dir = gitenv(GIT_DIR_ENVIRONMENT);
66 git_dir = DEFAULT_GIT_DIR_ENVIRONMENT;
67 git_object_dir = gitenv(DB_ENVIRONMENT);
68 if (!git_object_dir) {
69 git_object_dir = xmalloc(strlen(git_dir) + 9);
70 sprintf(git_object_dir, "%s/objects", git_dir);
72 git_refs_dir = xmalloc(strlen(git_dir) + 6);
73 sprintf(git_refs_dir, "%s/refs", git_dir);
74 git_index_file = gitenv(INDEX_ENVIRONMENT);
75 if (!git_index_file) {
76 git_index_file = xmalloc(strlen(git_dir) + 7);
77 sprintf(git_index_file, "%s/index", git_dir);
81 char *get_object_directory(void)
85 return git_object_dir;
88 char *get_refs_directory(void)
95 char *get_index_file(void)
99 return git_index_file;
102 int get_sha1(const char *str, unsigned char *sha1)
104 static char pathname[PATH_MAX];
105 static const char *prefix[] = {
115 if (!get_sha1_hex(str, sha1))
120 for (p = prefix; *p; p++) {
121 snprintf(pathname, sizeof(pathname), "%s/%s/%s",
123 if (!get_sha1_file(pathname, sha1))
130 char * sha1_to_hex(const unsigned char *sha1)
132 static char buffer[50];
133 static const char hex[] = "0123456789abcdef";
137 for (i = 0; i < 20; i++) {
138 unsigned int val = *sha1++;
139 *buf++ = hex[val >> 4];
140 *buf++ = hex[val & 0xf];
145 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
148 for (i = 0; i < 20; i++) {
149 static char hex[] = "0123456789abcdef";
150 unsigned int val = sha1[i];
151 char *pos = pathbuf + i*2 + (i > 0);
152 *pos++ = hex[val >> 4];
153 *pos = hex[val & 0xf];
158 * NOTE! This returns a statically allocated buffer, so you have to be
159 * careful about using it. Do a "strdup()" if you need to save the
162 * Also note that this returns the location for creating. Reading
163 * SHA1 file can happen from any alternate directory listed in the
164 * DB_ENVIRONMENT environment variable if it is not found in
165 * the primary object database.
167 char *sha1_file_name(const unsigned char *sha1)
169 static char *name, *base;
172 const char *sha1_file_directory = get_object_directory();
173 int len = strlen(sha1_file_directory);
174 base = xmalloc(len + 60);
175 memcpy(base, sha1_file_directory, len);
176 memset(base+len, 0, 60);
179 name = base + len + 1;
181 fill_sha1_path(name, sha1);
185 static struct alternate_object_database {
191 * Prepare alternate object database registry.
192 * alt_odb points at an array of struct alternate_object_database.
193 * This array is terminated with an element that has both its base
194 * and name set to NULL. alt_odb[n] comes from n'th non-empty
195 * element from colon separated ALTERNATE_DB_ENVIRONMENT environment
196 * variable, and its base points at a statically allocated buffer
197 * that contains "/the/directory/corresponding/to/.git/objects/...",
198 * while its name points just after the slash at the end of
199 * ".git/objects/" in the example above, and has enough space to hold
200 * 40-byte hex SHA1, an extra slash for the first level indirection,
201 * and the terminating NUL.
202 * This function allocates the alt_odb array and all the strings
203 * pointed by base fields of the array elements with one xmalloc();
204 * the string pool immediately follows the array.
206 static void prepare_alt_odb(void)
209 const char *cp, *last;
211 const char *alt = gitenv(ALTERNATE_DB_ENVIRONMENT) ? : "";
213 /* The first pass counts how large an area to allocate to
214 * hold the entire alt_odb structure, including array of
215 * structs and path buffers for them. The second pass fills
216 * the structure and prepares the path buffers for use by
219 for (totlen = pass = 0; pass < 2; pass++) {
223 cp = strchr(last, ':') ? : last + strlen(last);
225 /* 43 = 40-byte + 2 '/' + terminating NUL */
226 int pfxlen = cp - last;
227 int entlen = pfxlen + 43;
231 alt_odb[i].base = op;
232 alt_odb[i].name = op + pfxlen + 1;
233 memcpy(op, last, pfxlen);
234 op[pfxlen] = op[pfxlen + 3] = '/';
240 while (*cp && *cp == ':')
246 alt_odb = xmalloc(sizeof(*alt_odb) * (i + 1) + totlen);
247 alt_odb[i].base = alt_odb[i].name = NULL;
248 op = (char*)(&alt_odb[i+1]);
252 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
255 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 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
272 unsigned char real_sha1[20];
276 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
277 SHA1_Update(&c, map, size);
278 SHA1_Final(real_sha1, &c);
279 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
282 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
287 char *filename = find_sha1_file(sha1, &st);
290 error("cannot map sha1 file %s", sha1_to_hex(sha1));
294 fd = open(filename, O_RDONLY | sha1_file_open_flag);
296 /* See if it works without O_NOATIME */
297 switch (sha1_file_open_flag) {
299 fd = open(filename, O_RDONLY);
308 /* If it failed once, it will probably fail again. Stop using O_NOATIME */
309 sha1_file_open_flag = 0;
311 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
313 if (-1 == (int)(long)map)
319 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
321 /* Get the data stream */
322 memset(stream, 0, sizeof(*stream));
323 stream->next_in = map;
324 stream->avail_in = mapsize;
325 stream->next_out = buffer;
326 stream->avail_out = size;
329 return inflate(stream, 0);
332 void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
334 int bytes = strlen(buffer) + 1;
335 unsigned char *buf = xmalloc(1+size);
337 memcpy(buf, buffer + bytes, stream->total_out - bytes);
338 bytes = stream->total_out - bytes;
340 stream->next_out = buf + bytes;
341 stream->avail_out = size - bytes;
342 while (inflate(stream, Z_FINISH) == Z_OK)
351 * We used to just use "sscanf()", but that's actually way
352 * too permissive for what we want to check. So do an anal
353 * object header parse by hand.
355 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
361 * The type can be at most ten bytes (including the
362 * terminating '\0' that we add), and is followed by
377 * The length must follow immediately, and be in canonical
378 * decimal format (ie "010" is not valid).
385 unsigned long c = *hdr - '0';
389 size = size * 10 + c;
395 * The length must be followed by a zero byte
397 return *hdr ? -1 : 0;
400 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
406 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
407 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
410 return unpack_sha1_rest(&stream, hdr, *size);
413 int sha1_delta_base(const unsigned char *sha1, unsigned char *base_sha1)
416 unsigned long mapsize, size;
419 char hdr[64], type[20];
420 void *delta_data_head;
422 map = map_sha1_file(sha1, &mapsize);
425 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
426 if (ret < Z_OK || parse_sha1_header(hdr, type, &size) < 0) {
430 if (strcmp(type, "delta")) {
435 delta_data_head = hdr + strlen(hdr) + 1;
437 memcpy(base_sha1, delta_data_head, 20);
440 munmap(map, mapsize);
444 int sha1_file_size(const unsigned char *sha1, unsigned long *sizep)
447 unsigned long mapsize, size;
450 char hdr[64], type[20];
451 const unsigned char *data;
455 map = map_sha1_file(sha1, &mapsize);
458 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
460 if (ret < Z_OK || parse_sha1_header(hdr, type, &size) < 0)
462 if (strcmp(type, "delta")) {
468 /* We are dealing with a delta object. Inflated, the first
469 * 20 bytes hold the base object SHA1, and delta data follows
470 * immediately after it.
472 * The initial part of the delta starts at delta_data_head +
473 * 20. Borrow code from patch-delta to read the result size.
475 data = (unsigned char *)(hdr + strlen(hdr) + 1 + 20);
477 /* Skip over the source size; we are not interested in
478 * it and we cannot verify it because we do not want
479 * to read the base object.
487 /* Read the result size */
492 size |= *data++ << i;
500 munmap(map, mapsize);
504 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
506 unsigned long mapsize;
509 map = map_sha1_file(sha1, &mapsize);
511 buf = unpack_sha1_file(map, mapsize, type, size);
512 munmap(map, mapsize);
513 if (buf && !strcmp(type, "delta")) {
514 void *ref = NULL, *delta = buf;
515 unsigned long ref_size, delta_size = *size;
518 ref = read_sha1_file(delta, type, &ref_size);
520 buf = patch_delta(ref, ref_size,
521 delta+20, delta_size-20,
531 void *read_object_with_reference(const unsigned char *sha1,
532 const char *required_type,
534 unsigned char *actual_sha1_return)
539 unsigned char actual_sha1[20];
541 memcpy(actual_sha1, sha1, 20);
544 const char *ref_type = NULL;
546 buffer = read_sha1_file(actual_sha1, type, &isize);
549 if (!strcmp(type, required_type)) {
551 if (actual_sha1_return)
552 memcpy(actual_sha1_return, actual_sha1, 20);
555 /* Handle references */
556 else if (!strcmp(type, "commit"))
558 else if (!strcmp(type, "tag"))
559 ref_type = "object ";
564 ref_length = strlen(ref_type);
566 if (memcmp(buffer, ref_type, ref_length) ||
567 get_sha1_hex(buffer + ref_length, actual_sha1)) {
571 /* Now we have the ID of the referred-to object in
572 * actual_sha1. Check again. */
576 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
579 unsigned char *compressed;
581 unsigned char sha1[20];
584 static char tmpfile[PATH_MAX];
585 unsigned char hdr[50];
588 /* Generate the header */
589 hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
593 SHA1_Update(&c, hdr, hdrlen);
594 SHA1_Update(&c, buf, len);
595 SHA1_Final(sha1, &c);
598 memcpy(returnsha1, sha1, 20);
600 filename = sha1_file_name(sha1);
601 fd = open(filename, O_RDONLY);
604 * FIXME!!! We might do collision checking here, but we'd
605 * need to uncompress the old file and check it. Later.
611 if (errno != ENOENT) {
612 fprintf(stderr, "sha1 file %s: %s", filename, strerror(errno));
616 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
618 fd = mkstemp(tmpfile);
620 fprintf(stderr, "unable to create temporary sha1 filename %s: %s", tmpfile, strerror(errno));
625 memset(&stream, 0, sizeof(stream));
626 deflateInit(&stream, Z_BEST_COMPRESSION);
627 size = deflateBound(&stream, len+hdrlen);
628 compressed = xmalloc(size);
631 stream.next_out = compressed;
632 stream.avail_out = size;
635 stream.next_in = hdr;
636 stream.avail_in = hdrlen;
637 while (deflate(&stream, 0) == Z_OK)
640 /* Then the data itself.. */
641 stream.next_in = buf;
642 stream.avail_in = len;
643 while (deflate(&stream, Z_FINISH) == Z_OK)
646 size = stream.total_out;
648 if (write(fd, compressed, size) != size)
649 die("unable to write file");
654 ret = link(tmpfile, filename);
659 * Coda hack - coda doesn't like cross-directory links,
660 * so we fall back to a rename, which will mean that it
661 * won't be able to check collisions, but that's not a
664 * When this succeeds, we just return 0. We have nothing
667 if (ret == EXDEV && !rename(tmpfile, filename))
673 fprintf(stderr, "unable to write sha1 filename %s: %s", filename, strerror(ret));
676 /* FIXME!!! Collision check here ? */
682 int write_sha1_from_fd(const unsigned char *sha1, int fd)
684 char *filename = sha1_file_name(sha1);
688 unsigned char real_sha1[20];
689 unsigned char buf[4096];
690 unsigned char discard[4096];
694 local = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0666);
697 return error("Couldn't open %s\n", filename);
699 memset(&stream, 0, sizeof(stream));
701 inflateInit(&stream);
707 size = read(fd, buf, 4096);
712 return error("Connection closed?");
713 perror("Reading from connection");
716 write(local, buf, size);
717 stream.avail_in = size;
718 stream.next_in = buf;
720 stream.next_out = discard;
721 stream.avail_out = sizeof(discard);
722 ret = inflate(&stream, Z_SYNC_FLUSH);
723 SHA1_Update(&c, discard, sizeof(discard) -
725 } while (stream.avail_in && ret == Z_OK);
727 } while (ret == Z_OK);
731 SHA1_Final(real_sha1, &c);
732 if (ret != Z_STREAM_END) {
734 return error("File %s corrupted", sha1_to_hex(sha1));
736 if (memcmp(sha1, real_sha1, 20)) {
738 return error("File %s has bad hash\n", sha1_to_hex(sha1));
744 int has_sha1_file(const unsigned char *sha1)
747 return !!find_sha1_file(sha1, &st);
750 int index_fd(unsigned char *sha1, int fd, struct stat *st)
752 unsigned long size = st->st_size;
758 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
760 if ((int)(long)buf == -1)
763 ret = write_sha1_file(buf, size, "blob", sha1);