2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
16 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
17 #define O_NOATIME 01000000
23 const unsigned char null_sha1[20] = { 0, };
25 static unsigned int sha1_file_open_flag = O_NOATIME;
27 static unsigned hexval(char c)
29 if (c >= '0' && c <= '9')
31 if (c >= 'a' && c <= 'f')
33 if (c >= 'A' && c <= 'F')
38 int get_sha1_hex(const char *hex, unsigned char *sha1)
41 for (i = 0; i < 20; i++) {
42 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
51 int safe_create_leading_directories(char *path)
58 pos = strchr(pos, '/');
62 if (mkdir(path, 0777) < 0)
63 if (errno != EEXIST) {
72 char * sha1_to_hex(const unsigned char *sha1)
74 static char buffer[50];
75 static const char hex[] = "0123456789abcdef";
79 for (i = 0; i < 20; i++) {
80 unsigned int val = *sha1++;
81 *buf++ = hex[val >> 4];
82 *buf++ = hex[val & 0xf];
89 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
92 for (i = 0; i < 20; i++) {
93 static char hex[] = "0123456789abcdef";
94 unsigned int val = sha1[i];
95 char *pos = pathbuf + i*2 + (i > 0);
96 *pos++ = hex[val >> 4];
97 *pos = hex[val & 0xf];
102 * NOTE! This returns a statically allocated buffer, so you have to be
103 * careful about using it. Do a "strdup()" if you need to save the
106 * Also note that this returns the location for creating. Reading
107 * SHA1 file can happen from any alternate directory listed in the
108 * DB_ENVIRONMENT environment variable if it is not found in
109 * the primary object database.
111 char *sha1_file_name(const unsigned char *sha1)
113 static char *name, *base;
116 const char *sha1_file_directory = get_object_directory();
117 int len = strlen(sha1_file_directory);
118 base = xmalloc(len + 60);
119 memcpy(base, sha1_file_directory, len);
120 memset(base+len, 0, 60);
123 name = base + len + 1;
125 fill_sha1_path(name, sha1);
129 char *sha1_pack_name(const unsigned char *sha1)
131 static const char hex[] = "0123456789abcdef";
132 static char *name, *base, *buf;
136 const char *sha1_file_directory = get_object_directory();
137 int len = strlen(sha1_file_directory);
138 base = xmalloc(len + 60);
139 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
140 name = base + len + 11;
145 for (i = 0; i < 20; i++) {
146 unsigned int val = *sha1++;
147 *buf++ = hex[val >> 4];
148 *buf++ = hex[val & 0xf];
154 char *sha1_pack_index_name(const unsigned char *sha1)
156 static const char hex[] = "0123456789abcdef";
157 static char *name, *base, *buf;
161 const char *sha1_file_directory = get_object_directory();
162 int len = strlen(sha1_file_directory);
163 base = xmalloc(len + 60);
164 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
165 name = base + len + 11;
170 for (i = 0; i < 20; i++) {
171 unsigned int val = *sha1++;
172 *buf++ = hex[val >> 4];
173 *buf++ = hex[val & 0xf];
179 struct alternate_object_database *alt_odb_list;
180 static struct alternate_object_database **alt_odb_tail;
183 * Prepare alternate object database registry.
185 * The variable alt_odb_list points at the list of struct
186 * alternate_object_database. The elements on this list come from
187 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
188 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
189 * whose contents is similar to that environment variable but can be
190 * LF separated. Its base points at a statically allocated buffer that
191 * contains "/the/directory/corresponding/to/.git/objects/...", while
192 * its name points just after the slash at the end of ".git/objects/"
193 * in the example above, and has enough space to hold 40-byte hex
194 * SHA1, an extra slash for the first level indirection, and the
197 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
198 const char *relative_base)
200 const char *cp, *last;
201 struct alternate_object_database *ent;
202 const char *objdir = get_object_directory();
208 if (cp < ep && *cp == '#') {
209 while (cp < ep && *cp != sep)
214 for ( ; cp < ep && *cp != sep; cp++)
217 struct alternate_object_database *alt;
218 /* 43 = 40-byte + 2 '/' + terminating NUL */
219 int pfxlen = cp - last;
220 int entlen = pfxlen + 43;
222 if (*last != '/' && relative_base) {
223 /* Relative alt-odb */
225 base_len = strlen(relative_base) + 1;
229 ent = xmalloc(sizeof(*ent) + entlen);
231 if (*last != '/' && relative_base) {
232 memcpy(ent->base, relative_base, base_len - 1);
233 ent->base[base_len - 1] = '/';
234 memcpy(ent->base + base_len,
238 memcpy(ent->base, last, pfxlen);
239 ent->name = ent->base + pfxlen + 1;
240 ent->base[pfxlen] = ent->base[pfxlen + 3] = '/';
241 ent->base[entlen-1] = 0;
243 /* Prevent the common mistake of listing the same
244 * thing twice, or object directory itself.
246 for (alt = alt_odb_list; alt; alt = alt->next)
247 if (!memcmp(ent->base, alt->base, pfxlen))
249 if (!memcmp(ent->base, objdir, pfxlen)) {
255 alt_odb_tail = &(ent->next);
259 while (cp < ep && *cp == sep)
265 void prepare_alt_odb(void)
273 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
278 alt_odb_tail = &alt_odb_list;
279 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL);
281 sprintf(path, "%s/info/alternates", get_object_directory());
282 fd = open(path, O_RDONLY);
285 if (fstat(fd, &st) || (st.st_size == 0)) {
289 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
291 if (map == MAP_FAILED)
294 link_alt_odb_entries(map, map + st.st_size, '\n',
295 get_object_directory());
296 munmap(map, st.st_size);
299 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
301 char *name = sha1_file_name(sha1);
302 struct alternate_object_database *alt;
307 for (alt = alt_odb_list; alt; alt = alt->next) {
309 fill_sha1_path(name, sha1);
310 if (!stat(alt->base, st))
316 #define PACK_MAX_SZ (1<<26)
317 static int pack_used_ctr;
318 static unsigned long pack_mapped;
319 struct packed_git *packed_git;
321 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
326 unsigned long idx_size;
328 int fd = open(path, O_RDONLY);
332 if (fstat(fd, &st)) {
336 idx_size = st.st_size;
337 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
339 if (idx_map == MAP_FAILED)
344 *idx_size_ = idx_size;
346 /* check index map */
347 if (idx_size < 4*256 + 20 + 20)
348 return error("index file too small");
350 for (i = 0; i < 256; i++) {
351 unsigned int n = ntohl(index[i]);
353 return error("non-monotonic index");
359 * - 256 index entries 4 bytes each
360 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
361 * - 20-byte SHA1 of the packfile
362 * - 20-byte SHA1 file checksum
364 if (idx_size != 4*256 + nr * 24 + 20 + 20)
365 return error("wrong index file size");
370 static int unuse_one_packed_git(void)
372 struct packed_git *p, *lru = NULL;
374 for (p = packed_git; p; p = p->next) {
375 if (p->pack_use_cnt || !p->pack_base)
377 if (!lru || p->pack_last_used < lru->pack_last_used)
382 munmap(lru->pack_base, lru->pack_size);
383 lru->pack_base = NULL;
387 void unuse_packed_git(struct packed_git *p)
392 int use_packed_git(struct packed_git *p)
396 // We created the struct before we had the pack
397 stat(p->pack_name, &st);
398 if (!S_ISREG(st.st_mode))
399 die("packfile %s not a regular file", p->pack_name);
400 p->pack_size = st.st_size;
407 pack_mapped += p->pack_size;
408 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
410 fd = open(p->pack_name, O_RDONLY);
412 die("packfile %s cannot be opened", p->pack_name);
413 if (fstat(fd, &st)) {
415 die("packfile %s cannot be opened", p->pack_name);
417 if (st.st_size != p->pack_size)
418 die("packfile %s size mismatch.", p->pack_name);
419 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
421 if (map == MAP_FAILED)
422 die("packfile %s cannot be mapped.", p->pack_name);
425 /* Check if the pack file matches with the index file.
428 if (memcmp((char*)(p->index_base) + p->index_size - 40,
429 p->pack_base + p->pack_size - 20, 20)) {
431 die("packfile %s does not match index.", p->pack_name);
434 p->pack_last_used = pack_used_ctr++;
439 struct packed_git *add_packed_git(char *path, int path_len, int local)
442 struct packed_git *p;
443 unsigned long idx_size;
445 unsigned char sha1[20];
447 if (check_packed_git_idx(path, &idx_size, &idx_map))
450 /* do we have a corresponding .pack file? */
451 strcpy(path + path_len - 4, ".pack");
452 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
453 munmap(idx_map, idx_size);
456 /* ok, it looks sane as far as we can check without
457 * actually mapping the pack file.
459 p = xmalloc(sizeof(*p) + path_len + 2);
460 strcpy(p->pack_name, path);
461 p->index_size = idx_size;
462 p->pack_size = st.st_size;
463 p->index_base = idx_map;
466 p->pack_last_used = 0;
468 p->pack_local = local;
469 if ((path_len > 44) && !get_sha1_hex(path + path_len - 44, sha1))
470 memcpy(p->sha1, sha1, 20);
474 struct packed_git *parse_pack_index(unsigned char *sha1)
476 char *path = sha1_pack_index_name(sha1);
477 return parse_pack_index_file(sha1, path);
480 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
482 struct packed_git *p;
483 unsigned long idx_size;
487 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
490 path = sha1_pack_name(sha1);
492 p = xmalloc(sizeof(*p) + strlen(path) + 2);
493 strcpy(p->pack_name, path);
494 p->index_size = idx_size;
496 p->index_base = idx_map;
499 p->pack_last_used = 0;
501 memcpy(p->sha1, sha1, 20);
505 void install_packed_git(struct packed_git *pack)
507 pack->next = packed_git;
511 static void prepare_packed_git_one(char *objdir, int local)
518 sprintf(path, "%s/pack", objdir);
524 while ((de = readdir(dir)) != NULL) {
525 int namelen = strlen(de->d_name);
526 struct packed_git *p;
528 if (strcmp(de->d_name + namelen - 4, ".idx"))
531 /* we have .idx. Is it a file we can map? */
532 strcpy(path + len, de->d_name);
533 p = add_packed_git(path, len + namelen, local);
536 p->next = packed_git;
542 void prepare_packed_git(void)
544 static int run_once = 0;
545 struct alternate_object_database *alt;
549 prepare_packed_git_one(get_object_directory(), 1);
551 for (alt = alt_odb_list; alt; alt = alt->next) {
553 prepare_packed_git_one(alt->base, 0);
559 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
562 unsigned char real_sha1[20];
566 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
567 SHA1_Update(&c, map, size);
568 SHA1_Final(real_sha1, &c);
569 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
572 static void *map_sha1_file_internal(const unsigned char *sha1,
578 char *filename = find_sha1_file(sha1, &st);
584 fd = open(filename, O_RDONLY | sha1_file_open_flag);
586 /* See if it works without O_NOATIME */
587 switch (sha1_file_open_flag) {
589 fd = open(filename, O_RDONLY);
597 /* If it failed once, it will probably fail again.
598 * Stop using O_NOATIME
600 sha1_file_open_flag = 0;
602 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
604 if (map == MAP_FAILED)
610 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
612 /* Get the data stream */
613 memset(stream, 0, sizeof(*stream));
614 stream->next_in = map;
615 stream->avail_in = mapsize;
616 stream->next_out = buffer;
617 stream->avail_out = size;
620 return inflate(stream, 0);
623 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
625 int bytes = strlen(buffer) + 1;
626 unsigned char *buf = xmalloc(1+size);
628 memcpy(buf, buffer + bytes, stream->total_out - bytes);
629 bytes = stream->total_out - bytes;
631 stream->next_out = buf + bytes;
632 stream->avail_out = size - bytes;
633 while (inflate(stream, Z_FINISH) == Z_OK)
642 * We used to just use "sscanf()", but that's actually way
643 * too permissive for what we want to check. So do an anal
644 * object header parse by hand.
646 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
652 * The type can be at most ten bytes (including the
653 * terminating '\0' that we add), and is followed by
668 * The length must follow immediately, and be in canonical
669 * decimal format (ie "010" is not valid).
676 unsigned long c = *hdr - '0';
680 size = size * 10 + c;
686 * The length must be followed by a zero byte
688 return *hdr ? -1 : 0;
691 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
697 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
698 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
701 return unpack_sha1_rest(&stream, hdr, *size);
704 /* forward declaration for a mutually recursive function */
705 static int packed_object_info(struct pack_entry *entry,
706 char *type, unsigned long *sizep);
708 static int packed_delta_info(unsigned char *base_sha1,
709 unsigned long delta_size,
712 unsigned long *sizep,
713 struct packed_git *p)
715 struct pack_entry base_ent;
718 die("truncated pack file");
720 /* The base entry _must_ be in the same pack */
721 if (!find_pack_entry_one(base_sha1, &base_ent, p))
722 die("failed to find delta-pack base object %s",
723 sha1_to_hex(base_sha1));
725 /* We choose to only get the type of the base object and
726 * ignore potentially corrupt pack file that expects the delta
727 * based on a base with a wrong size. This saves tons of
731 if (packed_object_info(&base_ent, type, NULL))
732 die("cannot get info for delta-pack base");
735 const unsigned char *data;
736 unsigned char delta_head[64];
737 unsigned long result_size;
741 memset(&stream, 0, sizeof(stream));
743 data = stream.next_in = base_sha1 + 20;
744 stream.avail_in = left - 20;
745 stream.next_out = delta_head;
746 stream.avail_out = sizeof(delta_head);
748 inflateInit(&stream);
749 st = inflate(&stream, Z_FINISH);
751 if ((st != Z_STREAM_END) &&
752 stream.total_out != sizeof(delta_head))
753 die("delta data unpack-initial failed");
755 /* Examine the initial part of the delta to figure out
759 get_delta_hdr_size(&data); /* ignore base size */
761 /* Read the result size */
762 result_size = get_delta_hdr_size(&data);
763 *sizep = result_size;
768 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
769 enum object_type *type, unsigned long *sizep)
772 unsigned char *pack, c;
775 if (offset >= p->pack_size)
776 die("object offset outside of pack file");
778 pack = p->pack_base + offset;
781 *type = (c >> 4) & 7;
785 if (offset >= p->pack_size)
786 die("object offset outside of pack file");
789 size += (c & 0x7f) << shift;
796 void packed_object_info_detail(struct pack_entry *e,
799 unsigned long *store_size,
800 int *delta_chain_length,
801 unsigned char *base_sha1)
803 struct packed_git *p = e->p;
804 unsigned long offset, left;
806 enum object_type kind;
808 offset = unpack_object_header(p, e->offset, &kind, size);
809 pack = p->pack_base + offset;
810 left = p->pack_size - offset;
811 if (kind != OBJ_DELTA)
812 *delta_chain_length = 0;
814 int chain_length = 0;
815 memcpy(base_sha1, pack, 20);
817 struct pack_entry base_ent;
820 find_pack_entry_one(pack, &base_ent, p);
821 offset = unpack_object_header(p, base_ent.offset,
823 pack = p->pack_base + offset;
825 } while (kind == OBJ_DELTA);
826 *delta_chain_length = chain_length;
830 strcpy(type, "commit");
833 strcpy(type, "tree");
836 strcpy(type, "blob");
842 die("corrupted pack file %s containing object of kind %d",
845 *store_size = 0; /* notyet */
848 static int packed_object_info(struct pack_entry *entry,
849 char *type, unsigned long *sizep)
851 struct packed_git *p = entry->p;
852 unsigned long offset, size, left;
854 enum object_type kind;
857 if (use_packed_git(p))
858 die("cannot map packed file");
860 offset = unpack_object_header(p, entry->offset, &kind, &size);
861 pack = p->pack_base + offset;
862 left = p->pack_size - offset;
866 retval = packed_delta_info(pack, size, left, type, sizep, p);
870 strcpy(type, "commit");
873 strcpy(type, "tree");
876 strcpy(type, "blob");
882 die("corrupted pack file %s containing object of kind %d",
891 /* forward declaration for a mutually recursive function */
892 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
894 static void *unpack_delta_entry(unsigned char *base_sha1,
895 unsigned long delta_size,
898 unsigned long *sizep,
899 struct packed_git *p)
901 struct pack_entry base_ent;
902 void *data, *delta_data, *result, *base;
903 unsigned long data_size, result_size, base_size;
908 die("truncated pack file");
909 data = base_sha1 + 20;
910 data_size = left - 20;
911 delta_data = xmalloc(delta_size);
913 memset(&stream, 0, sizeof(stream));
915 stream.next_in = data;
916 stream.avail_in = data_size;
917 stream.next_out = delta_data;
918 stream.avail_out = delta_size;
920 inflateInit(&stream);
921 st = inflate(&stream, Z_FINISH);
923 if ((st != Z_STREAM_END) || stream.total_out != delta_size)
924 die("delta data unpack failed");
926 /* The base entry _must_ be in the same pack */
927 if (!find_pack_entry_one(base_sha1, &base_ent, p))
928 die("failed to find delta-pack base object %s",
929 sha1_to_hex(base_sha1));
930 base = unpack_entry_gently(&base_ent, type, &base_size);
932 die("failed to read delta-pack base object %s",
933 sha1_to_hex(base_sha1));
934 result = patch_delta(base, base_size,
935 delta_data, delta_size,
938 die("failed to apply delta");
941 *sizep = result_size;
945 static void *unpack_non_delta_entry(unsigned char *data,
951 unsigned char *buffer;
953 buffer = xmalloc(size + 1);
955 memset(&stream, 0, sizeof(stream));
956 stream.next_in = data;
957 stream.avail_in = left;
958 stream.next_out = buffer;
959 stream.avail_out = size;
961 inflateInit(&stream);
962 st = inflate(&stream, Z_FINISH);
964 if ((st != Z_STREAM_END) || stream.total_out != size) {
972 static void *unpack_entry(struct pack_entry *entry,
973 char *type, unsigned long *sizep)
975 struct packed_git *p = entry->p;
978 if (use_packed_git(p))
979 die("cannot map packed file");
980 retval = unpack_entry_gently(entry, type, sizep);
983 die("corrupted pack file %s", p->pack_name);
987 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
988 void *unpack_entry_gently(struct pack_entry *entry,
989 char *type, unsigned long *sizep)
991 struct packed_git *p = entry->p;
992 unsigned long offset, size, left;
994 enum object_type kind;
997 offset = unpack_object_header(p, entry->offset, &kind, &size);
998 pack = p->pack_base + offset;
999 left = p->pack_size - offset;
1002 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
1005 strcpy(type, "commit");
1008 strcpy(type, "tree");
1011 strcpy(type, "blob");
1014 strcpy(type, "tag");
1020 retval = unpack_non_delta_entry(pack, size, left);
1024 int num_packed_objects(const struct packed_git *p)
1026 /* See check_packed_git_idx() */
1027 return (p->index_size - 20 - 20 - 4*256) / 24;
1030 int nth_packed_object_sha1(const struct packed_git *p, int n,
1031 unsigned char* sha1)
1033 void *index = p->index_base + 256;
1034 if (n < 0 || num_packed_objects(p) <= n)
1036 memcpy(sha1, (index + 24 * n + 4), 20);
1040 int find_pack_entry_one(const unsigned char *sha1,
1041 struct pack_entry *e, struct packed_git *p)
1043 unsigned int *level1_ofs = p->index_base;
1044 int hi = ntohl(level1_ofs[*sha1]);
1045 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1046 void *index = p->index_base + 256;
1049 int mi = (lo + hi) / 2;
1050 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
1052 e->offset = ntohl(*((int*)(index + 24 * mi)));
1053 memcpy(e->sha1, sha1, 20);
1065 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1067 struct packed_git *p;
1068 prepare_packed_git();
1070 for (p = packed_git; p; p = p->next) {
1071 if (find_pack_entry_one(sha1, e, p))
1077 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1078 struct packed_git *packs)
1080 struct packed_git *p;
1081 struct pack_entry e;
1083 for (p = packs; p; p = p->next) {
1084 if (find_pack_entry_one(sha1, &e, p))
1091 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1094 unsigned long mapsize, size;
1099 map = map_sha1_file_internal(sha1, &mapsize);
1101 struct pack_entry e;
1103 if (!find_pack_entry(sha1, &e))
1104 return error("unable to find %s", sha1_to_hex(sha1));
1105 return packed_object_info(&e, type, sizep);
1107 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1108 status = error("unable to unpack %s header",
1110 if (parse_sha1_header(hdr, type, &size) < 0)
1111 status = error("unable to parse %s header", sha1_to_hex(sha1));
1117 inflateEnd(&stream);
1118 munmap(map, mapsize);
1122 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1124 struct pack_entry e;
1126 if (!find_pack_entry(sha1, &e)) {
1127 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1130 return unpack_entry(&e, type, size);
1133 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1135 unsigned long mapsize;
1137 struct pack_entry e;
1139 if (find_pack_entry(sha1, &e))
1140 return read_packed_sha1(sha1, type, size);
1141 map = map_sha1_file_internal(sha1, &mapsize);
1143 buf = unpack_sha1_file(map, mapsize, type, size);
1144 munmap(map, mapsize);
1150 void *read_object_with_reference(const unsigned char *sha1,
1151 const char *required_type,
1152 unsigned long *size,
1153 unsigned char *actual_sha1_return)
1157 unsigned long isize;
1158 unsigned char actual_sha1[20];
1160 memcpy(actual_sha1, sha1, 20);
1162 int ref_length = -1;
1163 const char *ref_type = NULL;
1165 buffer = read_sha1_file(actual_sha1, type, &isize);
1168 if (!strcmp(type, required_type)) {
1170 if (actual_sha1_return)
1171 memcpy(actual_sha1_return, actual_sha1, 20);
1174 /* Handle references */
1175 else if (!strcmp(type, "commit"))
1177 else if (!strcmp(type, "tag"))
1178 ref_type = "object ";
1183 ref_length = strlen(ref_type);
1185 if (memcmp(buffer, ref_type, ref_length) ||
1186 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1191 /* Now we have the ID of the referred-to object in
1192 * actual_sha1. Check again. */
1196 char *write_sha1_file_prepare(void *buf,
1199 unsigned char *sha1,
1205 /* Generate the header */
1206 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1210 SHA1_Update(&c, hdr, *hdrlen);
1211 SHA1_Update(&c, buf, len);
1212 SHA1_Final(sha1, &c);
1214 return sha1_file_name(sha1);
1218 * Link the tempfile to the final place, possibly creating the
1219 * last directory level as you do so.
1221 * Returns the errno on failure, 0 on success.
1223 static int link_temp_to_file(const char *tmpfile, char *filename)
1227 if (!link(tmpfile, filename))
1231 * Try to mkdir the last path component if that failed
1234 * Re-try the "link()" regardless of whether the mkdir
1235 * succeeds, since a race might mean that somebody
1239 if (ret == ENOENT) {
1240 char *dir = strrchr(filename, '/');
1243 mkdir(filename, 0777);
1245 if (!link(tmpfile, filename))
1254 * Move the just written object into its final resting place
1256 int move_temp_to_file(const char *tmpfile, char *filename)
1258 int ret = link_temp_to_file(tmpfile, filename);
1261 * Coda hack - coda doesn't like cross-directory links,
1262 * so we fall back to a rename, which will mean that it
1263 * won't be able to check collisions, but that's not a
1266 * The same holds for FAT formatted media.
1268 * When this succeeds, we just return 0. We have nothing
1271 if (ret && ret != EEXIST) {
1272 if (!rename(tmpfile, filename))
1278 if (ret != EEXIST) {
1279 fprintf(stderr, "unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1282 /* FIXME!!! Collision check here ? */
1288 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1291 unsigned char *compressed;
1293 unsigned char sha1[20];
1295 static char tmpfile[PATH_MAX];
1296 unsigned char hdr[50];
1299 /* Normally if we have it in the pack then we do not bother writing
1300 * it out into .git/objects/??/?{38} file.
1302 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1304 memcpy(returnsha1, sha1, 20);
1305 if (has_sha1_file(sha1))
1307 fd = open(filename, O_RDONLY);
1310 * FIXME!!! We might do collision checking here, but we'd
1311 * need to uncompress the old file and check it. Later.
1317 if (errno != ENOENT) {
1318 fprintf(stderr, "sha1 file %s: %s\n", filename, strerror(errno));
1322 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1324 fd = mkstemp(tmpfile);
1326 fprintf(stderr, "unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
1331 memset(&stream, 0, sizeof(stream));
1332 deflateInit(&stream, Z_BEST_COMPRESSION);
1333 size = deflateBound(&stream, len+hdrlen);
1334 compressed = xmalloc(size);
1337 stream.next_out = compressed;
1338 stream.avail_out = size;
1340 /* First header.. */
1341 stream.next_in = hdr;
1342 stream.avail_in = hdrlen;
1343 while (deflate(&stream, 0) == Z_OK)
1346 /* Then the data itself.. */
1347 stream.next_in = buf;
1348 stream.avail_in = len;
1349 while (deflate(&stream, Z_FINISH) == Z_OK)
1351 deflateEnd(&stream);
1352 size = stream.total_out;
1354 if (write(fd, compressed, size) != size)
1355 die("unable to write file");
1360 return move_temp_to_file(tmpfile, filename);
1363 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1366 unsigned long objsize;
1368 void *map = map_sha1_file_internal(sha1, &objsize);
1370 void *temp_obj = NULL;
1374 unsigned char *unpacked;
1379 // need to unpack and recompress it by itself
1380 unpacked = read_packed_sha1(sha1, type, &len);
1382 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1385 memset(&stream, 0, sizeof(stream));
1386 deflateInit(&stream, Z_BEST_COMPRESSION);
1387 size = deflateBound(&stream, len + hdrlen);
1388 temp_obj = buf = xmalloc(size);
1391 stream.next_out = buf;
1392 stream.avail_out = size;
1394 /* First header.. */
1395 stream.next_in = (void *)hdr;
1396 stream.avail_in = hdrlen;
1397 while (deflate(&stream, 0) == Z_OK)
1400 /* Then the data itself.. */
1401 stream.next_in = unpacked;
1402 stream.avail_in = len;
1403 while (deflate(&stream, Z_FINISH) == Z_OK)
1405 deflateEnd(&stream);
1408 objsize = stream.total_out;
1412 size = write(fd, buf + posn, objsize - posn);
1415 fprintf(stderr, "write closed\n");
1422 } while (posn < objsize);
1425 munmap(map, objsize);
1432 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1433 size_t bufsize, size_t *bufposn)
1435 char tmpfile[PATH_MAX];
1438 unsigned char real_sha1[20];
1439 unsigned char discard[4096];
1443 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1445 local = mkstemp(tmpfile);
1447 return error("Couldn't open %s for %s\n", tmpfile, sha1_to_hex(sha1));
1449 memset(&stream, 0, sizeof(stream));
1451 inflateInit(&stream);
1458 stream.avail_in = *bufposn;
1459 stream.next_in = (unsigned char *) buffer;
1461 stream.next_out = discard;
1462 stream.avail_out = sizeof(discard);
1463 ret = inflate(&stream, Z_SYNC_FLUSH);
1464 SHA1_Update(&c, discard, sizeof(discard) -
1466 } while (stream.avail_in && ret == Z_OK);
1467 write(local, buffer, *bufposn - stream.avail_in);
1468 memmove(buffer, buffer + *bufposn - stream.avail_in,
1470 *bufposn = stream.avail_in;
1474 size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1479 return error("Connection closed?");
1480 perror("Reading from connection");
1485 inflateEnd(&stream);
1488 SHA1_Final(real_sha1, &c);
1489 if (ret != Z_STREAM_END) {
1491 return error("File %s corrupted", sha1_to_hex(sha1));
1493 if (memcmp(sha1, real_sha1, 20)) {
1495 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1498 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1501 int has_pack_index(const unsigned char *sha1)
1504 if (stat(sha1_pack_index_name(sha1), &st))
1509 int has_pack_file(const unsigned char *sha1)
1512 if (stat(sha1_pack_name(sha1), &st))
1517 int has_sha1_pack(const unsigned char *sha1)
1519 struct pack_entry e;
1520 return find_pack_entry(sha1, &e);
1523 int has_sha1_file(const unsigned char *sha1)
1526 struct pack_entry e;
1528 if (find_pack_entry(sha1, &e))
1530 return find_sha1_file(sha1, &st) ? 1 : 0;
1533 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
1535 unsigned long size = 4096;
1536 char *buf = malloc(size);
1538 unsigned long off = 0;
1539 unsigned char hdr[50];
1542 iret = read(fd, buf + off, size - off);
1547 buf = realloc(buf, size);
1558 ret = write_sha1_file(buf, off, type, sha1);
1560 write_sha1_file_prepare(buf, off, type, sha1, hdr, &hdrlen);
1567 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1569 unsigned long size = st->st_size;
1572 unsigned char hdr[50];
1577 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1579 if (buf == MAP_FAILED)
1585 ret = write_sha1_file(buf, size, type, sha1);
1587 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1595 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1600 switch (st->st_mode & S_IFMT) {
1602 fd = open(path, O_RDONLY);
1604 return error("open(\"%s\"): %s", path,
1606 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1607 return error("%s: failed to insert into database",
1611 target = xmalloc(st->st_size+1);
1612 if (readlink(path, target, st->st_size+1) != st->st_size) {
1613 char *errstr = strerror(errno);
1615 return error("readlink(\"%s\"): %s", path,
1618 if (!write_object) {
1619 unsigned char hdr[50];
1621 write_sha1_file_prepare(target, st->st_size, "blob",
1622 sha1, hdr, &hdrlen);
1623 } else if (write_sha1_file(target, st->st_size, "blob", sha1))
1624 return error("%s: failed to insert into database",
1629 return error("%s: unsupported file type", path);