2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
14 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
15 #define O_NOATIME 01000000
21 const unsigned char null_sha1[20] = { 0, };
23 static unsigned int sha1_file_open_flag = O_NOATIME;
25 static unsigned hexval(char c)
27 if (c >= '0' && c <= '9')
29 if (c >= 'a' && c <= 'f')
31 if (c >= 'A' && c <= 'F')
36 int get_sha1_hex(const char *hex, unsigned char *sha1)
39 for (i = 0; i < 20; i++) {
40 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
49 int adjust_shared_perm(const char *path)
54 if (!shared_repository)
56 if (lstat(path, &st) < 0)
67 if (chmod(path, mode) < 0)
72 int safe_create_leading_directories(char *path)
81 pos = strchr(pos, '/');
85 if (!stat(path, &st)) {
87 if (!S_ISDIR(st.st_mode)) {
92 else if (mkdir(path, 0777)) {
96 else if (adjust_shared_perm(path)) {
105 char * sha1_to_hex(const unsigned char *sha1)
107 static char buffer[50];
108 static const char hex[] = "0123456789abcdef";
112 for (i = 0; i < 20; i++) {
113 unsigned int val = *sha1++;
114 *buf++ = hex[val >> 4];
115 *buf++ = hex[val & 0xf];
122 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
125 for (i = 0; i < 20; i++) {
126 static char hex[] = "0123456789abcdef";
127 unsigned int val = sha1[i];
128 char *pos = pathbuf + i*2 + (i > 0);
129 *pos++ = hex[val >> 4];
130 *pos = hex[val & 0xf];
135 * NOTE! This returns a statically allocated buffer, so you have to be
136 * careful about using it. Do a "strdup()" if you need to save the
139 * Also note that this returns the location for creating. Reading
140 * SHA1 file can happen from any alternate directory listed in the
141 * DB_ENVIRONMENT environment variable if it is not found in
142 * the primary object database.
144 char *sha1_file_name(const unsigned char *sha1)
146 static char *name, *base;
149 const char *sha1_file_directory = get_object_directory();
150 int len = strlen(sha1_file_directory);
151 base = xmalloc(len + 60);
152 memcpy(base, sha1_file_directory, len);
153 memset(base+len, 0, 60);
156 name = base + len + 1;
158 fill_sha1_path(name, sha1);
162 char *sha1_pack_name(const unsigned char *sha1)
164 static const char hex[] = "0123456789abcdef";
165 static char *name, *base, *buf;
169 const char *sha1_file_directory = get_object_directory();
170 int len = strlen(sha1_file_directory);
171 base = xmalloc(len + 60);
172 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
173 name = base + len + 11;
178 for (i = 0; i < 20; i++) {
179 unsigned int val = *sha1++;
180 *buf++ = hex[val >> 4];
181 *buf++ = hex[val & 0xf];
187 char *sha1_pack_index_name(const unsigned char *sha1)
189 static const char hex[] = "0123456789abcdef";
190 static char *name, *base, *buf;
194 const char *sha1_file_directory = get_object_directory();
195 int len = strlen(sha1_file_directory);
196 base = xmalloc(len + 60);
197 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
198 name = base + len + 11;
203 for (i = 0; i < 20; i++) {
204 unsigned int val = *sha1++;
205 *buf++ = hex[val >> 4];
206 *buf++ = hex[val & 0xf];
212 struct alternate_object_database *alt_odb_list;
213 static struct alternate_object_database **alt_odb_tail;
216 * Prepare alternate object database registry.
218 * The variable alt_odb_list points at the list of struct
219 * alternate_object_database. The elements on this list come from
220 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
221 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
222 * whose contents is similar to that environment variable but can be
223 * LF separated. Its base points at a statically allocated buffer that
224 * contains "/the/directory/corresponding/to/.git/objects/...", while
225 * its name points just after the slash at the end of ".git/objects/"
226 * in the example above, and has enough space to hold 40-byte hex
227 * SHA1, an extra slash for the first level indirection, and the
230 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
231 const char *relative_base)
233 const char *cp, *last;
234 struct alternate_object_database *ent;
235 const char *objdir = get_object_directory();
241 if (cp < ep && *cp == '#') {
242 while (cp < ep && *cp != sep)
247 for ( ; cp < ep && *cp != sep; cp++)
250 struct alternate_object_database *alt;
251 /* 43 = 40-byte + 2 '/' + terminating NUL */
252 int pfxlen = cp - last;
253 int entlen = pfxlen + 43;
255 if (*last != '/' && relative_base) {
256 /* Relative alt-odb */
258 base_len = strlen(relative_base) + 1;
262 ent = xmalloc(sizeof(*ent) + entlen);
264 if (*last != '/' && relative_base) {
265 memcpy(ent->base, relative_base, base_len - 1);
266 ent->base[base_len - 1] = '/';
267 memcpy(ent->base + base_len,
271 memcpy(ent->base, last, pfxlen);
272 ent->name = ent->base + pfxlen + 1;
273 ent->base[pfxlen] = ent->base[pfxlen + 3] = '/';
274 ent->base[entlen-1] = 0;
276 /* Prevent the common mistake of listing the same
277 * thing twice, or object directory itself.
279 for (alt = alt_odb_list; alt; alt = alt->next)
280 if (!memcmp(ent->base, alt->base, pfxlen))
282 if (!memcmp(ent->base, objdir, pfxlen)) {
288 alt_odb_tail = &(ent->next);
292 while (cp < ep && *cp == sep)
298 void prepare_alt_odb(void)
306 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
311 alt_odb_tail = &alt_odb_list;
312 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL);
314 sprintf(path, "%s/info/alternates", get_object_directory());
315 fd = open(path, O_RDONLY);
318 if (fstat(fd, &st) || (st.st_size == 0)) {
322 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
324 if (map == MAP_FAILED)
327 link_alt_odb_entries(map, map + st.st_size, '\n',
328 get_object_directory());
329 munmap(map, st.st_size);
332 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
334 char *name = sha1_file_name(sha1);
335 struct alternate_object_database *alt;
340 for (alt = alt_odb_list; alt; alt = alt->next) {
342 fill_sha1_path(name, sha1);
343 if (!stat(alt->base, st))
349 #define PACK_MAX_SZ (1<<26)
350 static int pack_used_ctr;
351 static unsigned long pack_mapped;
352 struct packed_git *packed_git;
354 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
359 unsigned long idx_size;
361 int fd = open(path, O_RDONLY);
365 if (fstat(fd, &st)) {
369 idx_size = st.st_size;
370 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
372 if (idx_map == MAP_FAILED)
377 *idx_size_ = idx_size;
379 /* check index map */
380 if (idx_size < 4*256 + 20 + 20)
381 return error("index file too small");
383 for (i = 0; i < 256; i++) {
384 unsigned int n = ntohl(index[i]);
386 return error("non-monotonic index");
392 * - 256 index entries 4 bytes each
393 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
394 * - 20-byte SHA1 of the packfile
395 * - 20-byte SHA1 file checksum
397 if (idx_size != 4*256 + nr * 24 + 20 + 20)
398 return error("wrong index file size");
403 static int unuse_one_packed_git(void)
405 struct packed_git *p, *lru = NULL;
407 for (p = packed_git; p; p = p->next) {
408 if (p->pack_use_cnt || !p->pack_base)
410 if (!lru || p->pack_last_used < lru->pack_last_used)
415 munmap(lru->pack_base, lru->pack_size);
416 lru->pack_base = NULL;
420 void unuse_packed_git(struct packed_git *p)
425 int use_packed_git(struct packed_git *p)
429 // We created the struct before we had the pack
430 stat(p->pack_name, &st);
431 if (!S_ISREG(st.st_mode))
432 die("packfile %s not a regular file", p->pack_name);
433 p->pack_size = st.st_size;
440 pack_mapped += p->pack_size;
441 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
443 fd = open(p->pack_name, O_RDONLY);
445 die("packfile %s cannot be opened", p->pack_name);
446 if (fstat(fd, &st)) {
448 die("packfile %s cannot be opened", p->pack_name);
450 if (st.st_size != p->pack_size)
451 die("packfile %s size mismatch.", p->pack_name);
452 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
454 if (map == MAP_FAILED)
455 die("packfile %s cannot be mapped.", p->pack_name);
458 /* Check if the pack file matches with the index file.
461 if (memcmp((char*)(p->index_base) + p->index_size - 40,
462 p->pack_base + p->pack_size - 20, 20)) {
464 die("packfile %s does not match index.", p->pack_name);
467 p->pack_last_used = pack_used_ctr++;
472 struct packed_git *add_packed_git(char *path, int path_len, int local)
475 struct packed_git *p;
476 unsigned long idx_size;
478 unsigned char sha1[20];
480 if (check_packed_git_idx(path, &idx_size, &idx_map))
483 /* do we have a corresponding .pack file? */
484 strcpy(path + path_len - 4, ".pack");
485 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
486 munmap(idx_map, idx_size);
489 /* ok, it looks sane as far as we can check without
490 * actually mapping the pack file.
492 p = xmalloc(sizeof(*p) + path_len + 2);
493 strcpy(p->pack_name, path);
494 p->index_size = idx_size;
495 p->pack_size = st.st_size;
496 p->index_base = idx_map;
499 p->pack_last_used = 0;
501 p->pack_local = local;
502 if ((path_len > 44) && !get_sha1_hex(path + path_len - 44, sha1))
503 memcpy(p->sha1, sha1, 20);
507 struct packed_git *parse_pack_index(unsigned char *sha1)
509 char *path = sha1_pack_index_name(sha1);
510 return parse_pack_index_file(sha1, path);
513 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
515 struct packed_git *p;
516 unsigned long idx_size;
520 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
523 path = sha1_pack_name(sha1);
525 p = xmalloc(sizeof(*p) + strlen(path) + 2);
526 strcpy(p->pack_name, path);
527 p->index_size = idx_size;
529 p->index_base = idx_map;
532 p->pack_last_used = 0;
534 memcpy(p->sha1, sha1, 20);
538 void install_packed_git(struct packed_git *pack)
540 pack->next = packed_git;
544 static void prepare_packed_git_one(char *objdir, int local)
551 sprintf(path, "%s/pack", objdir);
557 while ((de = readdir(dir)) != NULL) {
558 int namelen = strlen(de->d_name);
559 struct packed_git *p;
561 if (strcmp(de->d_name + namelen - 4, ".idx"))
564 /* we have .idx. Is it a file we can map? */
565 strcpy(path + len, de->d_name);
566 p = add_packed_git(path, len + namelen, local);
569 p->next = packed_git;
575 void prepare_packed_git(void)
577 static int run_once = 0;
578 struct alternate_object_database *alt;
582 prepare_packed_git_one(get_object_directory(), 1);
584 for (alt = alt_odb_list; alt; alt = alt->next) {
586 prepare_packed_git_one(alt->base, 0);
592 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
595 unsigned char real_sha1[20];
599 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
600 SHA1_Update(&c, map, size);
601 SHA1_Final(real_sha1, &c);
602 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
605 static void *map_sha1_file_internal(const unsigned char *sha1,
611 char *filename = find_sha1_file(sha1, &st);
617 fd = open(filename, O_RDONLY | sha1_file_open_flag);
619 /* See if it works without O_NOATIME */
620 switch (sha1_file_open_flag) {
622 fd = open(filename, O_RDONLY);
630 /* If it failed once, it will probably fail again.
631 * Stop using O_NOATIME
633 sha1_file_open_flag = 0;
635 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
637 if (map == MAP_FAILED)
643 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
645 /* Get the data stream */
646 memset(stream, 0, sizeof(*stream));
647 stream->next_in = map;
648 stream->avail_in = mapsize;
649 stream->next_out = buffer;
650 stream->avail_out = size;
653 return inflate(stream, 0);
656 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
658 int bytes = strlen(buffer) + 1;
659 unsigned char *buf = xmalloc(1+size);
661 memcpy(buf, buffer + bytes, stream->total_out - bytes);
662 bytes = stream->total_out - bytes;
664 stream->next_out = buf + bytes;
665 stream->avail_out = size - bytes;
666 while (inflate(stream, Z_FINISH) == Z_OK)
675 * We used to just use "sscanf()", but that's actually way
676 * too permissive for what we want to check. So do an anal
677 * object header parse by hand.
679 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
685 * The type can be at most ten bytes (including the
686 * terminating '\0' that we add), and is followed by
701 * The length must follow immediately, and be in canonical
702 * decimal format (ie "010" is not valid).
709 unsigned long c = *hdr - '0';
713 size = size * 10 + c;
719 * The length must be followed by a zero byte
721 return *hdr ? -1 : 0;
724 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
730 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
731 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
734 return unpack_sha1_rest(&stream, hdr, *size);
737 /* forward declaration for a mutually recursive function */
738 static int packed_object_info(struct pack_entry *entry,
739 char *type, unsigned long *sizep);
741 static int packed_delta_info(unsigned char *base_sha1,
742 unsigned long delta_size,
745 unsigned long *sizep,
746 struct packed_git *p)
748 struct pack_entry base_ent;
751 die("truncated pack file");
753 /* The base entry _must_ be in the same pack */
754 if (!find_pack_entry_one(base_sha1, &base_ent, p))
755 die("failed to find delta-pack base object %s",
756 sha1_to_hex(base_sha1));
758 /* We choose to only get the type of the base object and
759 * ignore potentially corrupt pack file that expects the delta
760 * based on a base with a wrong size. This saves tons of
764 if (packed_object_info(&base_ent, type, NULL))
765 die("cannot get info for delta-pack base");
768 const unsigned char *data;
769 unsigned char delta_head[64];
770 unsigned long result_size;
774 memset(&stream, 0, sizeof(stream));
776 data = stream.next_in = base_sha1 + 20;
777 stream.avail_in = left - 20;
778 stream.next_out = delta_head;
779 stream.avail_out = sizeof(delta_head);
781 inflateInit(&stream);
782 st = inflate(&stream, Z_FINISH);
784 if ((st != Z_STREAM_END) &&
785 stream.total_out != sizeof(delta_head))
786 die("delta data unpack-initial failed");
788 /* Examine the initial part of the delta to figure out
792 get_delta_hdr_size(&data); /* ignore base size */
794 /* Read the result size */
795 result_size = get_delta_hdr_size(&data);
796 *sizep = result_size;
801 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
802 enum object_type *type, unsigned long *sizep)
805 unsigned char *pack, c;
808 if (offset >= p->pack_size)
809 die("object offset outside of pack file");
811 pack = p->pack_base + offset;
814 *type = (c >> 4) & 7;
818 if (offset >= p->pack_size)
819 die("object offset outside of pack file");
822 size += (c & 0x7f) << shift;
829 int check_reuse_pack_delta(struct packed_git *p, unsigned long offset,
830 unsigned char *base, unsigned long *sizep,
831 enum object_type *kindp)
838 ptr = unpack_object_header(p, ptr, kindp, sizep);
839 if (*kindp != OBJ_DELTA)
841 memcpy(base, p->pack_base + ptr, 20);
848 void packed_object_info_detail(struct pack_entry *e,
851 unsigned long *store_size,
852 unsigned int *delta_chain_length,
853 unsigned char *base_sha1)
855 struct packed_git *p = e->p;
856 unsigned long offset, left;
858 enum object_type kind;
860 offset = unpack_object_header(p, e->offset, &kind, size);
861 pack = p->pack_base + offset;
862 left = p->pack_size - offset;
863 if (kind != OBJ_DELTA)
864 *delta_chain_length = 0;
866 unsigned int chain_length = 0;
867 memcpy(base_sha1, pack, 20);
869 struct pack_entry base_ent;
872 find_pack_entry_one(pack, &base_ent, p);
873 offset = unpack_object_header(p, base_ent.offset,
875 pack = p->pack_base + offset;
877 } while (kind == OBJ_DELTA);
878 *delta_chain_length = chain_length;
882 strcpy(type, "commit");
885 strcpy(type, "tree");
888 strcpy(type, "blob");
894 die("corrupted pack file %s containing object of kind %d",
897 *store_size = 0; /* notyet */
900 static int packed_object_info(struct pack_entry *entry,
901 char *type, unsigned long *sizep)
903 struct packed_git *p = entry->p;
904 unsigned long offset, size, left;
906 enum object_type kind;
909 if (use_packed_git(p))
910 die("cannot map packed file");
912 offset = unpack_object_header(p, entry->offset, &kind, &size);
913 pack = p->pack_base + offset;
914 left = p->pack_size - offset;
918 retval = packed_delta_info(pack, size, left, type, sizep, p);
922 strcpy(type, "commit");
925 strcpy(type, "tree");
928 strcpy(type, "blob");
934 die("corrupted pack file %s containing object of kind %d",
943 /* forward declaration for a mutually recursive function */
944 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
946 static void *unpack_delta_entry(unsigned char *base_sha1,
947 unsigned long delta_size,
950 unsigned long *sizep,
951 struct packed_git *p)
953 struct pack_entry base_ent;
954 void *data, *delta_data, *result, *base;
955 unsigned long data_size, result_size, base_size;
960 die("truncated pack file");
961 data = base_sha1 + 20;
962 data_size = left - 20;
963 delta_data = xmalloc(delta_size);
965 memset(&stream, 0, sizeof(stream));
967 stream.next_in = data;
968 stream.avail_in = data_size;
969 stream.next_out = delta_data;
970 stream.avail_out = delta_size;
972 inflateInit(&stream);
973 st = inflate(&stream, Z_FINISH);
975 if ((st != Z_STREAM_END) || stream.total_out != delta_size)
976 die("delta data unpack failed");
978 /* The base entry _must_ be in the same pack */
979 if (!find_pack_entry_one(base_sha1, &base_ent, p))
980 die("failed to find delta-pack base object %s",
981 sha1_to_hex(base_sha1));
982 base = unpack_entry_gently(&base_ent, type, &base_size);
984 die("failed to read delta-pack base object %s",
985 sha1_to_hex(base_sha1));
986 result = patch_delta(base, base_size,
987 delta_data, delta_size,
990 die("failed to apply delta");
993 *sizep = result_size;
997 static void *unpack_non_delta_entry(unsigned char *data,
1003 unsigned char *buffer;
1005 buffer = xmalloc(size + 1);
1007 memset(&stream, 0, sizeof(stream));
1008 stream.next_in = data;
1009 stream.avail_in = left;
1010 stream.next_out = buffer;
1011 stream.avail_out = size;
1013 inflateInit(&stream);
1014 st = inflate(&stream, Z_FINISH);
1015 inflateEnd(&stream);
1016 if ((st != Z_STREAM_END) || stream.total_out != size) {
1024 static void *unpack_entry(struct pack_entry *entry,
1025 char *type, unsigned long *sizep)
1027 struct packed_git *p = entry->p;
1030 if (use_packed_git(p))
1031 die("cannot map packed file");
1032 retval = unpack_entry_gently(entry, type, sizep);
1033 unuse_packed_git(p);
1035 die("corrupted pack file %s", p->pack_name);
1039 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
1040 void *unpack_entry_gently(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 offset = unpack_object_header(p, entry->offset, &kind, &size);
1050 pack = p->pack_base + offset;
1051 left = p->pack_size - offset;
1054 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
1057 strcpy(type, "commit");
1060 strcpy(type, "tree");
1063 strcpy(type, "blob");
1066 strcpy(type, "tag");
1072 retval = unpack_non_delta_entry(pack, size, left);
1076 int num_packed_objects(const struct packed_git *p)
1078 /* See check_packed_git_idx() */
1079 return (p->index_size - 20 - 20 - 4*256) / 24;
1082 int nth_packed_object_sha1(const struct packed_git *p, int n,
1083 unsigned char* sha1)
1085 void *index = p->index_base + 256;
1086 if (n < 0 || num_packed_objects(p) <= n)
1088 memcpy(sha1, (index + 24 * n + 4), 20);
1092 int find_pack_entry_one(const unsigned char *sha1,
1093 struct pack_entry *e, struct packed_git *p)
1095 unsigned int *level1_ofs = p->index_base;
1096 int hi = ntohl(level1_ofs[*sha1]);
1097 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1098 void *index = p->index_base + 256;
1101 int mi = (lo + hi) / 2;
1102 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
1104 e->offset = ntohl(*((int*)(index + 24 * mi)));
1105 memcpy(e->sha1, sha1, 20);
1117 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1119 struct packed_git *p;
1120 prepare_packed_git();
1122 for (p = packed_git; p; p = p->next) {
1123 if (find_pack_entry_one(sha1, e, p))
1129 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1130 struct packed_git *packs)
1132 struct packed_git *p;
1133 struct pack_entry e;
1135 for (p = packs; p; p = p->next) {
1136 if (find_pack_entry_one(sha1, &e, p))
1143 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1146 unsigned long mapsize, size;
1151 map = map_sha1_file_internal(sha1, &mapsize);
1153 struct pack_entry e;
1155 if (!find_pack_entry(sha1, &e))
1156 return error("unable to find %s", sha1_to_hex(sha1));
1157 return packed_object_info(&e, type, sizep);
1159 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1160 status = error("unable to unpack %s header",
1162 if (parse_sha1_header(hdr, type, &size) < 0)
1163 status = error("unable to parse %s header", sha1_to_hex(sha1));
1169 inflateEnd(&stream);
1170 munmap(map, mapsize);
1174 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1176 struct pack_entry e;
1178 if (!find_pack_entry(sha1, &e)) {
1179 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1182 return unpack_entry(&e, type, size);
1185 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1187 unsigned long mapsize;
1189 struct pack_entry e;
1191 if (find_pack_entry(sha1, &e))
1192 return read_packed_sha1(sha1, type, size);
1193 map = map_sha1_file_internal(sha1, &mapsize);
1195 buf = unpack_sha1_file(map, mapsize, type, size);
1196 munmap(map, mapsize);
1202 void *read_object_with_reference(const unsigned char *sha1,
1203 const char *required_type,
1204 unsigned long *size,
1205 unsigned char *actual_sha1_return)
1209 unsigned long isize;
1210 unsigned char actual_sha1[20];
1212 memcpy(actual_sha1, sha1, 20);
1214 int ref_length = -1;
1215 const char *ref_type = NULL;
1217 buffer = read_sha1_file(actual_sha1, type, &isize);
1220 if (!strcmp(type, required_type)) {
1222 if (actual_sha1_return)
1223 memcpy(actual_sha1_return, actual_sha1, 20);
1226 /* Handle references */
1227 else if (!strcmp(type, "commit"))
1229 else if (!strcmp(type, "tag"))
1230 ref_type = "object ";
1235 ref_length = strlen(ref_type);
1237 if (memcmp(buffer, ref_type, ref_length) ||
1238 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1243 /* Now we have the ID of the referred-to object in
1244 * actual_sha1. Check again. */
1248 char *write_sha1_file_prepare(void *buf,
1251 unsigned char *sha1,
1257 /* Generate the header */
1258 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1262 SHA1_Update(&c, hdr, *hdrlen);
1263 SHA1_Update(&c, buf, len);
1264 SHA1_Final(sha1, &c);
1266 return sha1_file_name(sha1);
1270 * Link the tempfile to the final place, possibly creating the
1271 * last directory level as you do so.
1273 * Returns the errno on failure, 0 on success.
1275 static int link_temp_to_file(const char *tmpfile, char *filename)
1279 if (!link(tmpfile, filename))
1283 * Try to mkdir the last path component if that failed
1286 * Re-try the "link()" regardless of whether the mkdir
1287 * succeeds, since a race might mean that somebody
1291 if (ret == ENOENT) {
1292 char *dir = strrchr(filename, '/');
1295 mkdir(filename, 0777);
1296 if (adjust_shared_perm(filename))
1299 if (!link(tmpfile, filename))
1308 * Move the just written object into its final resting place
1310 int move_temp_to_file(const char *tmpfile, char *filename)
1312 int ret = link_temp_to_file(tmpfile, filename);
1315 * Coda hack - coda doesn't like cross-directory links,
1316 * so we fall back to a rename, which will mean that it
1317 * won't be able to check collisions, but that's not a
1320 * The same holds for FAT formatted media.
1322 * When this succeeds, we just return 0. We have nothing
1325 if (ret && ret != EEXIST) {
1326 if (!rename(tmpfile, filename))
1332 if (ret != EEXIST) {
1333 fprintf(stderr, "unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1336 /* FIXME!!! Collision check here ? */
1342 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1345 unsigned char *compressed;
1347 unsigned char sha1[20];
1349 static char tmpfile[PATH_MAX];
1350 unsigned char hdr[50];
1353 /* Normally if we have it in the pack then we do not bother writing
1354 * it out into .git/objects/??/?{38} file.
1356 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1358 memcpy(returnsha1, sha1, 20);
1359 if (has_sha1_file(sha1))
1361 fd = open(filename, O_RDONLY);
1364 * FIXME!!! We might do collision checking here, but we'd
1365 * need to uncompress the old file and check it. Later.
1371 if (errno != ENOENT) {
1372 fprintf(stderr, "sha1 file %s: %s\n", filename, strerror(errno));
1376 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1378 fd = mkstemp(tmpfile);
1380 fprintf(stderr, "unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
1385 memset(&stream, 0, sizeof(stream));
1386 deflateInit(&stream, Z_BEST_COMPRESSION);
1387 size = deflateBound(&stream, len+hdrlen);
1388 compressed = xmalloc(size);
1391 stream.next_out = compressed;
1392 stream.avail_out = size;
1394 /* First header.. */
1395 stream.next_in = hdr;
1396 stream.avail_in = hdrlen;
1397 while (deflate(&stream, 0) == Z_OK)
1400 /* Then the data itself.. */
1401 stream.next_in = buf;
1402 stream.avail_in = len;
1403 while (deflate(&stream, Z_FINISH) == Z_OK)
1405 deflateEnd(&stream);
1406 size = stream.total_out;
1408 if (write(fd, compressed, size) != size)
1409 die("unable to write file");
1414 return move_temp_to_file(tmpfile, filename);
1417 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1420 unsigned long objsize;
1422 void *map = map_sha1_file_internal(sha1, &objsize);
1424 void *temp_obj = NULL;
1428 unsigned char *unpacked;
1433 // need to unpack and recompress it by itself
1434 unpacked = read_packed_sha1(sha1, type, &len);
1436 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1439 memset(&stream, 0, sizeof(stream));
1440 deflateInit(&stream, Z_BEST_COMPRESSION);
1441 size = deflateBound(&stream, len + hdrlen);
1442 temp_obj = buf = xmalloc(size);
1445 stream.next_out = buf;
1446 stream.avail_out = size;
1448 /* First header.. */
1449 stream.next_in = (void *)hdr;
1450 stream.avail_in = hdrlen;
1451 while (deflate(&stream, 0) == Z_OK)
1454 /* Then the data itself.. */
1455 stream.next_in = unpacked;
1456 stream.avail_in = len;
1457 while (deflate(&stream, Z_FINISH) == Z_OK)
1459 deflateEnd(&stream);
1462 objsize = stream.total_out;
1466 size = write(fd, buf + posn, objsize - posn);
1469 fprintf(stderr, "write closed\n");
1476 } while (posn < objsize);
1479 munmap(map, objsize);
1486 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1487 size_t bufsize, size_t *bufposn)
1489 char tmpfile[PATH_MAX];
1492 unsigned char real_sha1[20];
1493 unsigned char discard[4096];
1497 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1499 local = mkstemp(tmpfile);
1501 return error("Couldn't open %s for %s\n", tmpfile, sha1_to_hex(sha1));
1503 memset(&stream, 0, sizeof(stream));
1505 inflateInit(&stream);
1512 stream.avail_in = *bufposn;
1513 stream.next_in = (unsigned char *) buffer;
1515 stream.next_out = discard;
1516 stream.avail_out = sizeof(discard);
1517 ret = inflate(&stream, Z_SYNC_FLUSH);
1518 SHA1_Update(&c, discard, sizeof(discard) -
1520 } while (stream.avail_in && ret == Z_OK);
1521 write(local, buffer, *bufposn - stream.avail_in);
1522 memmove(buffer, buffer + *bufposn - stream.avail_in,
1524 *bufposn = stream.avail_in;
1528 size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1533 return error("Connection closed?");
1534 perror("Reading from connection");
1539 inflateEnd(&stream);
1542 SHA1_Final(real_sha1, &c);
1543 if (ret != Z_STREAM_END) {
1545 return error("File %s corrupted", sha1_to_hex(sha1));
1547 if (memcmp(sha1, real_sha1, 20)) {
1549 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1552 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1555 int has_pack_index(const unsigned char *sha1)
1558 if (stat(sha1_pack_index_name(sha1), &st))
1563 int has_pack_file(const unsigned char *sha1)
1566 if (stat(sha1_pack_name(sha1), &st))
1571 int has_sha1_pack(const unsigned char *sha1)
1573 struct pack_entry e;
1574 return find_pack_entry(sha1, &e);
1577 int has_sha1_file(const unsigned char *sha1)
1580 struct pack_entry e;
1582 if (find_pack_entry(sha1, &e))
1584 return find_sha1_file(sha1, &st) ? 1 : 0;
1587 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
1589 unsigned long size = 4096;
1590 char *buf = malloc(size);
1592 unsigned long off = 0;
1593 unsigned char hdr[50];
1596 iret = read(fd, buf + off, size - off);
1601 buf = realloc(buf, size);
1612 ret = write_sha1_file(buf, off, type, sha1);
1614 write_sha1_file_prepare(buf, off, type, sha1, hdr, &hdrlen);
1621 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1623 unsigned long size = st->st_size;
1626 unsigned char hdr[50];
1631 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1633 if (buf == MAP_FAILED)
1639 ret = write_sha1_file(buf, size, type, sha1);
1641 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1649 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1654 switch (st->st_mode & S_IFMT) {
1656 fd = open(path, O_RDONLY);
1658 return error("open(\"%s\"): %s", path,
1660 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1661 return error("%s: failed to insert into database",
1665 target = xmalloc(st->st_size+1);
1666 if (readlink(path, target, st->st_size+1) != st->st_size) {
1667 char *errstr = strerror(errno);
1669 return error("readlink(\"%s\"): %s", path,
1672 if (!write_object) {
1673 unsigned char hdr[50];
1675 write_sha1_file_prepare(target, st->st_size, "blob",
1676 sha1, hdr, &hdrlen);
1677 } else if (write_sha1_file(target, st->st_size, "blob", sha1))
1678 return error("%s: failed to insert into database",
1683 return error("%s: unsupported file type", path);