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)
56 pos = strchr(pos, '/');
60 if (mkdir(path, 0777) < 0)
61 if (errno != EEXIST) {
70 char * sha1_to_hex(const unsigned char *sha1)
72 static char buffer[50];
73 static const char hex[] = "0123456789abcdef";
77 for (i = 0; i < 20; i++) {
78 unsigned int val = *sha1++;
79 *buf++ = hex[val >> 4];
80 *buf++ = hex[val & 0xf];
85 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
88 for (i = 0; i < 20; i++) {
89 static char hex[] = "0123456789abcdef";
90 unsigned int val = sha1[i];
91 char *pos = pathbuf + i*2 + (i > 0);
92 *pos++ = hex[val >> 4];
93 *pos = hex[val & 0xf];
98 * NOTE! This returns a statically allocated buffer, so you have to be
99 * careful about using it. Do a "strdup()" if you need to save the
102 * Also note that this returns the location for creating. Reading
103 * SHA1 file can happen from any alternate directory listed in the
104 * DB_ENVIRONMENT environment variable if it is not found in
105 * the primary object database.
107 char *sha1_file_name(const unsigned char *sha1)
109 static char *name, *base;
112 const char *sha1_file_directory = get_object_directory();
113 int len = strlen(sha1_file_directory);
114 base = xmalloc(len + 60);
115 memcpy(base, sha1_file_directory, len);
116 memset(base+len, 0, 60);
119 name = base + len + 1;
121 fill_sha1_path(name, sha1);
125 char *sha1_pack_name(const unsigned char *sha1)
127 static const char hex[] = "0123456789abcdef";
128 static char *name, *base, *buf;
132 const char *sha1_file_directory = get_object_directory();
133 int len = strlen(sha1_file_directory);
134 base = xmalloc(len + 60);
135 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
136 name = base + len + 11;
141 for (i = 0; i < 20; i++) {
142 unsigned int val = *sha1++;
143 *buf++ = hex[val >> 4];
144 *buf++ = hex[val & 0xf];
150 char *sha1_pack_index_name(const unsigned char *sha1)
152 static const char hex[] = "0123456789abcdef";
153 static char *name, *base, *buf;
157 const char *sha1_file_directory = get_object_directory();
158 int len = strlen(sha1_file_directory);
159 base = xmalloc(len + 60);
160 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
161 name = base + len + 11;
166 for (i = 0; i < 20; i++) {
167 unsigned int val = *sha1++;
168 *buf++ = hex[val >> 4];
169 *buf++ = hex[val & 0xf];
175 struct alternate_object_database *alt_odb_list;
176 static struct alternate_object_database **alt_odb_tail;
179 * Prepare alternate object database registry.
181 * The variable alt_odb_list points at the list of struct
182 * alternate_object_database. The elements on this list come from
183 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
184 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
185 * whose contents is exactly in the same format as that environment
186 * variable. Its base points at a statically allocated buffer that
187 * contains "/the/directory/corresponding/to/.git/objects/...", while
188 * its name points just after the slash at the end of ".git/objects/"
189 * in the example above, and has enough space to hold 40-byte hex
190 * SHA1, an extra slash for the first level indirection, and the
193 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
194 const char *relative_base)
196 const char *cp, *last;
197 struct alternate_object_database *ent;
203 if (cp < ep && *cp == '#') {
204 while (cp < ep && *cp != sep)
209 for ( ; cp < ep && *cp != sep; cp++)
212 /* 43 = 40-byte + 2 '/' + terminating NUL */
213 int pfxlen = cp - last;
214 int entlen = pfxlen + 43;
216 if (*last != '/' && relative_base) {
217 /* Relative alt-odb */
219 base_len = strlen(relative_base) + 1;
223 ent = xmalloc(sizeof(*ent) + entlen);
225 alt_odb_tail = &(ent->next);
227 if (*last != '/' && relative_base) {
228 memcpy(ent->base, relative_base, base_len - 1);
229 ent->base[base_len - 1] = '/';
230 memcpy(ent->base + base_len,
234 memcpy(ent->base, last, pfxlen);
235 ent->name = ent->base + pfxlen + 1;
236 ent->base[pfxlen] = ent->base[pfxlen + 3] = '/';
237 ent->base[entlen-1] = 0;
239 while (cp < ep && *cp == sep)
245 void prepare_alt_odb(void)
253 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
258 alt_odb_tail = &alt_odb_list;
259 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL);
261 sprintf(path, "%s/info/alternates", get_object_directory());
262 fd = open(path, O_RDONLY);
265 if (fstat(fd, &st) || (st.st_size == 0)) {
269 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
271 if (map == MAP_FAILED)
274 link_alt_odb_entries(map, map + st.st_size, '\n',
275 get_object_directory());
276 munmap(map, st.st_size);
279 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
281 char *name = sha1_file_name(sha1);
282 struct alternate_object_database *alt;
287 for (alt = alt_odb_list; alt; alt = alt->next) {
289 fill_sha1_path(name, sha1);
290 if (!stat(alt->base, st))
296 #define PACK_MAX_SZ (1<<26)
297 static int pack_used_ctr;
298 static unsigned long pack_mapped;
299 struct packed_git *packed_git;
301 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
306 unsigned long idx_size;
308 int fd = open(path, O_RDONLY);
312 if (fstat(fd, &st)) {
316 idx_size = st.st_size;
317 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
319 if (idx_map == MAP_FAILED)
324 *idx_size_ = idx_size;
326 /* check index map */
327 if (idx_size < 4*256 + 20 + 20)
328 return error("index file too small");
330 for (i = 0; i < 256; i++) {
331 unsigned int n = ntohl(index[i]);
333 return error("non-monotonic index");
339 * - 256 index entries 4 bytes each
340 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
341 * - 20-byte SHA1 of the packfile
342 * - 20-byte SHA1 file checksum
344 if (idx_size != 4*256 + nr * 24 + 20 + 20)
345 return error("wrong index file size");
350 static int unuse_one_packed_git(void)
352 struct packed_git *p, *lru = NULL;
354 for (p = packed_git; p; p = p->next) {
355 if (p->pack_use_cnt || !p->pack_base)
357 if (!lru || p->pack_last_used < lru->pack_last_used)
362 munmap(lru->pack_base, lru->pack_size);
363 lru->pack_base = NULL;
367 void unuse_packed_git(struct packed_git *p)
372 int use_packed_git(struct packed_git *p)
376 // We created the struct before we had the pack
377 stat(p->pack_name, &st);
378 if (!S_ISREG(st.st_mode))
379 die("packfile %s not a regular file", p->pack_name);
380 p->pack_size = st.st_size;
387 pack_mapped += p->pack_size;
388 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
390 fd = open(p->pack_name, O_RDONLY);
392 die("packfile %s cannot be opened", p->pack_name);
393 if (fstat(fd, &st)) {
395 die("packfile %s cannot be opened", p->pack_name);
397 if (st.st_size != p->pack_size)
398 die("packfile %s size mismatch.", p->pack_name);
399 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
401 if (map == MAP_FAILED)
402 die("packfile %s cannot be mapped.", p->pack_name);
405 /* Check if the pack file matches with the index file.
408 if (memcmp((char*)(p->index_base) + p->index_size - 40,
409 p->pack_base + p->pack_size - 20, 20)) {
411 die("packfile %s does not match index.", p->pack_name);
414 p->pack_last_used = pack_used_ctr++;
419 struct packed_git *add_packed_git(char *path, int path_len)
422 struct packed_git *p;
423 unsigned long idx_size;
426 if (check_packed_git_idx(path, &idx_size, &idx_map))
429 /* do we have a corresponding .pack file? */
430 strcpy(path + path_len - 4, ".pack");
431 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
432 munmap(idx_map, idx_size);
435 /* ok, it looks sane as far as we can check without
436 * actually mapping the pack file.
438 p = xmalloc(sizeof(*p) + path_len + 2);
439 strcpy(p->pack_name, path);
440 p->index_size = idx_size;
441 p->pack_size = st.st_size;
442 p->index_base = idx_map;
445 p->pack_last_used = 0;
450 struct packed_git *parse_pack_index(unsigned char *sha1)
452 char *path = sha1_pack_index_name(sha1);
453 return parse_pack_index_file(sha1, path);
456 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
458 struct packed_git *p;
459 unsigned long idx_size;
463 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
466 path = sha1_pack_name(sha1);
468 p = xmalloc(sizeof(*p) + strlen(path) + 2);
469 strcpy(p->pack_name, path);
470 p->index_size = idx_size;
472 p->index_base = idx_map;
475 p->pack_last_used = 0;
477 memcpy(p->sha1, sha1, 20);
481 void install_packed_git(struct packed_git *pack)
483 pack->next = packed_git;
487 static void prepare_packed_git_one(char *objdir)
494 sprintf(path, "%s/pack", objdir);
500 while ((de = readdir(dir)) != NULL) {
501 int namelen = strlen(de->d_name);
502 struct packed_git *p;
504 if (strcmp(de->d_name + namelen - 4, ".idx"))
507 /* we have .idx. Is it a file we can map? */
508 strcpy(path + len, de->d_name);
509 p = add_packed_git(path, len + namelen);
512 p->next = packed_git;
518 void prepare_packed_git(void)
520 static int run_once = 0;
521 struct alternate_object_database *alt;
525 prepare_packed_git_one(get_object_directory());
527 for (alt = alt_odb_list; alt; alt = alt->next) {
529 prepare_packed_git_one(alt->base);
534 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
537 unsigned char real_sha1[20];
541 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
542 SHA1_Update(&c, map, size);
543 SHA1_Final(real_sha1, &c);
544 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
547 static void *map_sha1_file_internal(const unsigned char *sha1,
553 char *filename = find_sha1_file(sha1, &st);
559 fd = open(filename, O_RDONLY | sha1_file_open_flag);
561 /* See if it works without O_NOATIME */
562 switch (sha1_file_open_flag) {
564 fd = open(filename, O_RDONLY);
572 /* If it failed once, it will probably fail again.
573 * Stop using O_NOATIME
575 sha1_file_open_flag = 0;
577 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
579 if (map == MAP_FAILED)
585 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
587 /* Get the data stream */
588 memset(stream, 0, sizeof(*stream));
589 stream->next_in = map;
590 stream->avail_in = mapsize;
591 stream->next_out = buffer;
592 stream->avail_out = size;
595 return inflate(stream, 0);
598 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
600 int bytes = strlen(buffer) + 1;
601 unsigned char *buf = xmalloc(1+size);
603 memcpy(buf, buffer + bytes, stream->total_out - bytes);
604 bytes = stream->total_out - bytes;
606 stream->next_out = buf + bytes;
607 stream->avail_out = size - bytes;
608 while (inflate(stream, Z_FINISH) == Z_OK)
617 * We used to just use "sscanf()", but that's actually way
618 * too permissive for what we want to check. So do an anal
619 * object header parse by hand.
621 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
627 * The type can be at most ten bytes (including the
628 * terminating '\0' that we add), and is followed by
643 * The length must follow immediately, and be in canonical
644 * decimal format (ie "010" is not valid).
651 unsigned long c = *hdr - '0';
655 size = size * 10 + c;
661 * The length must be followed by a zero byte
663 return *hdr ? -1 : 0;
666 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
672 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
673 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
676 return unpack_sha1_rest(&stream, hdr, *size);
679 /* forward declaration for a mutually recursive function */
680 static int packed_object_info(struct pack_entry *entry,
681 char *type, unsigned long *sizep);
683 static int packed_delta_info(unsigned char *base_sha1,
684 unsigned long delta_size,
687 unsigned long *sizep,
688 struct packed_git *p)
690 struct pack_entry base_ent;
693 die("truncated pack file");
695 /* The base entry _must_ be in the same pack */
696 if (!find_pack_entry_one(base_sha1, &base_ent, p))
697 die("failed to find delta-pack base object %s",
698 sha1_to_hex(base_sha1));
700 /* We choose to only get the type of the base object and
701 * ignore potentially corrupt pack file that expects the delta
702 * based on a base with a wrong size. This saves tons of
706 if (packed_object_info(&base_ent, type, NULL))
707 die("cannot get info for delta-pack base");
710 const unsigned char *data;
711 unsigned char delta_head[64];
712 unsigned long result_size;
716 memset(&stream, 0, sizeof(stream));
718 data = stream.next_in = base_sha1 + 20;
719 stream.avail_in = left - 20;
720 stream.next_out = delta_head;
721 stream.avail_out = sizeof(delta_head);
723 inflateInit(&stream);
724 st = inflate(&stream, Z_FINISH);
726 if ((st != Z_STREAM_END) &&
727 stream.total_out != sizeof(delta_head))
728 die("delta data unpack-initial failed");
730 /* Examine the initial part of the delta to figure out
734 get_delta_hdr_size(&data); /* ignore base size */
736 /* Read the result size */
737 result_size = get_delta_hdr_size(&data);
738 *sizep = result_size;
743 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
744 enum object_type *type, unsigned long *sizep)
747 unsigned char *pack, c;
750 if (offset >= p->pack_size)
751 die("object offset outside of pack file");
753 pack = p->pack_base + offset;
756 *type = (c >> 4) & 7;
760 if (offset >= p->pack_size)
761 die("object offset outside of pack file");
764 size += (c & 0x7f) << shift;
771 void packed_object_info_detail(struct pack_entry *e,
774 unsigned long *store_size,
775 int *delta_chain_length,
776 unsigned char *base_sha1)
778 struct packed_git *p = e->p;
779 unsigned long offset, left;
781 enum object_type kind;
783 offset = unpack_object_header(p, e->offset, &kind, size);
784 pack = p->pack_base + offset;
785 left = p->pack_size - offset;
786 if (kind != OBJ_DELTA)
787 *delta_chain_length = 0;
789 int chain_length = 0;
790 memcpy(base_sha1, pack, 20);
792 struct pack_entry base_ent;
795 find_pack_entry_one(pack, &base_ent, p);
796 offset = unpack_object_header(p, base_ent.offset,
798 pack = p->pack_base + offset;
800 } while (kind == OBJ_DELTA);
801 *delta_chain_length = chain_length;
805 strcpy(type, "commit");
808 strcpy(type, "tree");
811 strcpy(type, "blob");
817 die("corrupted pack file %s containing object of kind %d",
820 *store_size = 0; /* notyet */
823 static int packed_object_info(struct pack_entry *entry,
824 char *type, unsigned long *sizep)
826 struct packed_git *p = entry->p;
827 unsigned long offset, size, left;
829 enum object_type kind;
832 if (use_packed_git(p))
833 die("cannot map packed file");
835 offset = unpack_object_header(p, entry->offset, &kind, &size);
836 pack = p->pack_base + offset;
837 left = p->pack_size - offset;
841 retval = packed_delta_info(pack, size, left, type, sizep, p);
845 strcpy(type, "commit");
848 strcpy(type, "tree");
851 strcpy(type, "blob");
857 die("corrupted pack file %s containing object of kind %d",
866 /* forward declaration for a mutually recursive function */
867 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
869 static void *unpack_delta_entry(unsigned char *base_sha1,
870 unsigned long delta_size,
873 unsigned long *sizep,
874 struct packed_git *p)
876 struct pack_entry base_ent;
877 void *data, *delta_data, *result, *base;
878 unsigned long data_size, result_size, base_size;
883 die("truncated pack file");
884 data = base_sha1 + 20;
885 data_size = left - 20;
886 delta_data = xmalloc(delta_size);
888 memset(&stream, 0, sizeof(stream));
890 stream.next_in = data;
891 stream.avail_in = data_size;
892 stream.next_out = delta_data;
893 stream.avail_out = delta_size;
895 inflateInit(&stream);
896 st = inflate(&stream, Z_FINISH);
898 if ((st != Z_STREAM_END) || stream.total_out != delta_size)
899 die("delta data unpack failed");
901 /* The base entry _must_ be in the same pack */
902 if (!find_pack_entry_one(base_sha1, &base_ent, p))
903 die("failed to find delta-pack base object %s",
904 sha1_to_hex(base_sha1));
905 base = unpack_entry_gently(&base_ent, type, &base_size);
907 die("failed to read delta-pack base object %s",
908 sha1_to_hex(base_sha1));
909 result = patch_delta(base, base_size,
910 delta_data, delta_size,
913 die("failed to apply delta");
916 *sizep = result_size;
920 static void *unpack_non_delta_entry(unsigned char *data,
926 unsigned char *buffer;
928 buffer = xmalloc(size + 1);
930 memset(&stream, 0, sizeof(stream));
931 stream.next_in = data;
932 stream.avail_in = left;
933 stream.next_out = buffer;
934 stream.avail_out = size;
936 inflateInit(&stream);
937 st = inflate(&stream, Z_FINISH);
939 if ((st != Z_STREAM_END) || stream.total_out != size) {
947 static void *unpack_entry(struct pack_entry *entry,
948 char *type, unsigned long *sizep)
950 struct packed_git *p = entry->p;
953 if (use_packed_git(p))
954 die("cannot map packed file");
955 retval = unpack_entry_gently(entry, type, sizep);
958 die("corrupted pack file %s", p->pack_name);
962 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
963 void *unpack_entry_gently(struct pack_entry *entry,
964 char *type, unsigned long *sizep)
966 struct packed_git *p = entry->p;
967 unsigned long offset, size, left;
969 enum object_type kind;
972 offset = unpack_object_header(p, entry->offset, &kind, &size);
973 pack = p->pack_base + offset;
974 left = p->pack_size - offset;
977 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
980 strcpy(type, "commit");
983 strcpy(type, "tree");
986 strcpy(type, "blob");
995 retval = unpack_non_delta_entry(pack, size, left);
999 int num_packed_objects(const struct packed_git *p)
1001 /* See check_packed_git_idx() */
1002 return (p->index_size - 20 - 20 - 4*256) / 24;
1005 int nth_packed_object_sha1(const struct packed_git *p, int n,
1006 unsigned char* sha1)
1008 void *index = p->index_base + 256;
1009 if (n < 0 || num_packed_objects(p) <= n)
1011 memcpy(sha1, (index + 24 * n + 4), 20);
1015 int find_pack_entry_one(const unsigned char *sha1,
1016 struct pack_entry *e, struct packed_git *p)
1018 unsigned int *level1_ofs = p->index_base;
1019 int hi = ntohl(level1_ofs[*sha1]);
1020 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1021 void *index = p->index_base + 256;
1024 int mi = (lo + hi) / 2;
1025 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
1027 e->offset = ntohl(*((int*)(index + 24 * mi)));
1028 memcpy(e->sha1, sha1, 20);
1040 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1042 struct packed_git *p;
1043 prepare_packed_git();
1045 for (p = packed_git; p; p = p->next) {
1046 if (find_pack_entry_one(sha1, e, p))
1052 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1053 struct packed_git *packs)
1055 struct packed_git *p;
1056 struct pack_entry e;
1058 for (p = packs; p; p = p->next) {
1059 if (find_pack_entry_one(sha1, &e, p))
1066 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1069 unsigned long mapsize, size;
1074 map = map_sha1_file_internal(sha1, &mapsize);
1076 struct pack_entry e;
1078 if (!find_pack_entry(sha1, &e))
1079 return error("unable to find %s", sha1_to_hex(sha1));
1080 return packed_object_info(&e, type, sizep);
1082 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1083 status = error("unable to unpack %s header",
1085 if (parse_sha1_header(hdr, type, &size) < 0)
1086 status = error("unable to parse %s header", sha1_to_hex(sha1));
1092 inflateEnd(&stream);
1093 munmap(map, mapsize);
1097 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1099 struct pack_entry e;
1101 if (!find_pack_entry(sha1, &e)) {
1102 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1105 return unpack_entry(&e, type, size);
1108 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1110 unsigned long mapsize;
1112 struct pack_entry e;
1114 if (find_pack_entry(sha1, &e))
1115 return read_packed_sha1(sha1, type, size);
1116 map = map_sha1_file_internal(sha1, &mapsize);
1118 buf = unpack_sha1_file(map, mapsize, type, size);
1119 munmap(map, mapsize);
1125 void *read_object_with_reference(const unsigned char *sha1,
1126 const char *required_type,
1127 unsigned long *size,
1128 unsigned char *actual_sha1_return)
1132 unsigned long isize;
1133 unsigned char actual_sha1[20];
1135 memcpy(actual_sha1, sha1, 20);
1137 int ref_length = -1;
1138 const char *ref_type = NULL;
1140 buffer = read_sha1_file(actual_sha1, type, &isize);
1143 if (!strcmp(type, required_type)) {
1145 if (actual_sha1_return)
1146 memcpy(actual_sha1_return, actual_sha1, 20);
1149 /* Handle references */
1150 else if (!strcmp(type, "commit"))
1152 else if (!strcmp(type, "tag"))
1153 ref_type = "object ";
1158 ref_length = strlen(ref_type);
1160 if (memcmp(buffer, ref_type, ref_length) ||
1161 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1166 /* Now we have the ID of the referred-to object in
1167 * actual_sha1. Check again. */
1171 char *write_sha1_file_prepare(void *buf,
1174 unsigned char *sha1,
1180 /* Generate the header */
1181 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1185 SHA1_Update(&c, hdr, *hdrlen);
1186 SHA1_Update(&c, buf, len);
1187 SHA1_Final(sha1, &c);
1189 return sha1_file_name(sha1);
1193 * Link the tempfile to the final place, possibly creating the
1194 * last directory level as you do so.
1196 * Returns the errno on failure, 0 on success.
1198 static int link_temp_to_file(const char *tmpfile, char *filename)
1202 if (!link(tmpfile, filename))
1206 * Try to mkdir the last path component if that failed
1209 * Re-try the "link()" regardless of whether the mkdir
1210 * succeeds, since a race might mean that somebody
1214 if (ret == ENOENT) {
1215 char *dir = strrchr(filename, '/');
1218 mkdir(filename, 0777);
1220 if (!link(tmpfile, filename))
1229 * Move the just written object into its final resting place
1231 int move_temp_to_file(const char *tmpfile, char *filename)
1233 int ret = link_temp_to_file(tmpfile, filename);
1236 * Coda hack - coda doesn't like cross-directory links,
1237 * so we fall back to a rename, which will mean that it
1238 * won't be able to check collisions, but that's not a
1241 * When this succeeds, we just return 0. We have nothing
1244 if (ret == EXDEV && !rename(tmpfile, filename))
1249 if (ret != EEXIST) {
1250 fprintf(stderr, "unable to write sha1 filename %s: %s", filename, strerror(ret));
1253 /* FIXME!!! Collision check here ? */
1259 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1262 unsigned char *compressed;
1264 unsigned char sha1[20];
1266 static char tmpfile[PATH_MAX];
1267 unsigned char hdr[50];
1270 /* Normally if we have it in the pack then we do not bother writing
1271 * it out into .git/objects/??/?{38} file.
1273 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1275 memcpy(returnsha1, sha1, 20);
1276 if (has_sha1_file(sha1))
1278 fd = open(filename, O_RDONLY);
1281 * FIXME!!! We might do collision checking here, but we'd
1282 * need to uncompress the old file and check it. Later.
1288 if (errno != ENOENT) {
1289 fprintf(stderr, "sha1 file %s: %s", filename, strerror(errno));
1293 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1295 fd = mkstemp(tmpfile);
1297 fprintf(stderr, "unable to create temporary sha1 filename %s: %s", tmpfile, strerror(errno));
1302 memset(&stream, 0, sizeof(stream));
1303 deflateInit(&stream, Z_BEST_COMPRESSION);
1304 size = deflateBound(&stream, len+hdrlen);
1305 compressed = xmalloc(size);
1308 stream.next_out = compressed;
1309 stream.avail_out = size;
1311 /* First header.. */
1312 stream.next_in = hdr;
1313 stream.avail_in = hdrlen;
1314 while (deflate(&stream, 0) == Z_OK)
1317 /* Then the data itself.. */
1318 stream.next_in = buf;
1319 stream.avail_in = len;
1320 while (deflate(&stream, Z_FINISH) == Z_OK)
1322 deflateEnd(&stream);
1323 size = stream.total_out;
1325 if (write(fd, compressed, size) != size)
1326 die("unable to write file");
1331 return move_temp_to_file(tmpfile, filename);
1334 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1337 unsigned long objsize;
1339 void *map = map_sha1_file_internal(sha1, &objsize);
1341 void *temp_obj = NULL;
1345 unsigned char *unpacked;
1350 // need to unpack and recompress it by itself
1351 unpacked = read_packed_sha1(sha1, type, &len);
1353 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1356 memset(&stream, 0, sizeof(stream));
1357 deflateInit(&stream, Z_BEST_COMPRESSION);
1358 size = deflateBound(&stream, len + hdrlen);
1359 temp_obj = buf = xmalloc(size);
1362 stream.next_out = buf;
1363 stream.avail_out = size;
1365 /* First header.. */
1366 stream.next_in = (void *)hdr;
1367 stream.avail_in = hdrlen;
1368 while (deflate(&stream, 0) == Z_OK)
1371 /* Then the data itself.. */
1372 stream.next_in = unpacked;
1373 stream.avail_in = len;
1374 while (deflate(&stream, Z_FINISH) == Z_OK)
1376 deflateEnd(&stream);
1379 objsize = stream.total_out;
1383 size = write(fd, buf + posn, objsize - posn);
1386 fprintf(stderr, "write closed");
1393 } while (posn < objsize);
1396 munmap(map, objsize);
1403 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1404 size_t bufsize, size_t *bufposn)
1406 char tmpfile[PATH_MAX];
1409 unsigned char real_sha1[20];
1410 unsigned char discard[4096];
1414 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1416 local = mkstemp(tmpfile);
1418 return error("Couldn't open %s for %s\n", tmpfile, sha1_to_hex(sha1));
1420 memset(&stream, 0, sizeof(stream));
1422 inflateInit(&stream);
1429 stream.avail_in = *bufposn;
1430 stream.next_in = (unsigned char *) buffer;
1432 stream.next_out = discard;
1433 stream.avail_out = sizeof(discard);
1434 ret = inflate(&stream, Z_SYNC_FLUSH);
1435 SHA1_Update(&c, discard, sizeof(discard) -
1437 } while (stream.avail_in && ret == Z_OK);
1438 write(local, buffer, *bufposn - stream.avail_in);
1439 memmove(buffer, buffer + *bufposn - stream.avail_in,
1441 *bufposn = stream.avail_in;
1445 size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1450 return error("Connection closed?");
1451 perror("Reading from connection");
1456 inflateEnd(&stream);
1459 SHA1_Final(real_sha1, &c);
1460 if (ret != Z_STREAM_END) {
1462 return error("File %s corrupted", sha1_to_hex(sha1));
1464 if (memcmp(sha1, real_sha1, 20)) {
1466 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1469 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1472 int has_pack_index(const unsigned char *sha1)
1475 if (stat(sha1_pack_index_name(sha1), &st))
1480 int has_pack_file(const unsigned char *sha1)
1483 if (stat(sha1_pack_name(sha1), &st))
1488 int has_sha1_pack(const unsigned char *sha1)
1490 struct pack_entry e;
1491 return find_pack_entry(sha1, &e);
1494 int has_sha1_file(const unsigned char *sha1)
1497 struct pack_entry e;
1499 if (find_pack_entry(sha1, &e))
1501 return find_sha1_file(sha1, &st) ? 1 : 0;
1504 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1506 unsigned long size = st->st_size;
1509 unsigned char hdr[50];
1514 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1516 if (buf == MAP_FAILED)
1522 ret = write_sha1_file(buf, size, type, sha1);
1524 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1532 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1537 switch (st->st_mode & S_IFMT) {
1539 fd = open(path, O_RDONLY);
1541 return error("open(\"%s\"): %s", path,
1543 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1544 return error("%s: failed to insert into database",
1548 target = xmalloc(st->st_size+1);
1549 if (readlink(path, target, st->st_size+1) != st->st_size) {
1550 char *errstr = strerror(errno);
1552 return error("readlink(\"%s\"): %s", path,
1555 if (!write_object) {
1556 unsigned char hdr[50];
1558 write_sha1_file_prepare(target, st->st_size, "blob",
1559 sha1, hdr, &hdrlen);
1560 } else if (write_sha1_file(target, st->st_size, "blob", sha1))
1561 return error("%s: failed to insert into database",
1566 return error("%s: unsupported file type", path);