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];
87 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
90 for (i = 0; i < 20; i++) {
91 static char hex[] = "0123456789abcdef";
92 unsigned int val = sha1[i];
93 char *pos = pathbuf + i*2 + (i > 0);
94 *pos++ = hex[val >> 4];
95 *pos = hex[val & 0xf];
100 * NOTE! This returns a statically allocated buffer, so you have to be
101 * careful about using it. Do a "strdup()" if you need to save the
104 * Also note that this returns the location for creating. Reading
105 * SHA1 file can happen from any alternate directory listed in the
106 * DB_ENVIRONMENT environment variable if it is not found in
107 * the primary object database.
109 char *sha1_file_name(const unsigned char *sha1)
111 static char *name, *base;
114 const char *sha1_file_directory = get_object_directory();
115 int len = strlen(sha1_file_directory);
116 base = xmalloc(len + 60);
117 memcpy(base, sha1_file_directory, len);
118 memset(base+len, 0, 60);
121 name = base + len + 1;
123 fill_sha1_path(name, sha1);
127 char *sha1_pack_name(const unsigned char *sha1)
129 static const char hex[] = "0123456789abcdef";
130 static char *name, *base, *buf;
134 const char *sha1_file_directory = get_object_directory();
135 int len = strlen(sha1_file_directory);
136 base = xmalloc(len + 60);
137 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
138 name = base + len + 11;
143 for (i = 0; i < 20; i++) {
144 unsigned int val = *sha1++;
145 *buf++ = hex[val >> 4];
146 *buf++ = hex[val & 0xf];
152 char *sha1_pack_index_name(const unsigned char *sha1)
154 static const char hex[] = "0123456789abcdef";
155 static char *name, *base, *buf;
159 const char *sha1_file_directory = get_object_directory();
160 int len = strlen(sha1_file_directory);
161 base = xmalloc(len + 60);
162 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
163 name = base + len + 11;
168 for (i = 0; i < 20; i++) {
169 unsigned int val = *sha1++;
170 *buf++ = hex[val >> 4];
171 *buf++ = hex[val & 0xf];
177 struct alternate_object_database *alt_odb_list;
178 static struct alternate_object_database **alt_odb_tail;
181 * Prepare alternate object database registry.
183 * The variable alt_odb_list points at the list of struct
184 * alternate_object_database. The elements on this list come from
185 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
186 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
187 * whose contents is exactly in the same format as that environment
188 * variable. Its base points at a statically allocated buffer that
189 * contains "/the/directory/corresponding/to/.git/objects/...", while
190 * its name points just after the slash at the end of ".git/objects/"
191 * in the example above, and has enough space to hold 40-byte hex
192 * SHA1, an extra slash for the first level indirection, and the
195 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
196 const char *relative_base)
198 const char *cp, *last;
199 struct alternate_object_database *ent;
205 if (cp < ep && *cp == '#') {
206 while (cp < ep && *cp != sep)
211 for ( ; cp < ep && *cp != sep; cp++)
214 /* 43 = 40-byte + 2 '/' + terminating NUL */
215 int pfxlen = cp - last;
216 int entlen = pfxlen + 43;
218 if (*last != '/' && relative_base) {
219 /* Relative alt-odb */
221 base_len = strlen(relative_base) + 1;
225 ent = xmalloc(sizeof(*ent) + entlen);
227 alt_odb_tail = &(ent->next);
229 if (*last != '/' && relative_base) {
230 memcpy(ent->base, relative_base, base_len - 1);
231 ent->base[base_len - 1] = '/';
232 memcpy(ent->base + base_len,
236 memcpy(ent->base, last, pfxlen);
237 ent->name = ent->base + pfxlen + 1;
238 ent->base[pfxlen] = ent->base[pfxlen + 3] = '/';
239 ent->base[entlen-1] = 0;
241 while (cp < ep && *cp == sep)
247 void prepare_alt_odb(void)
255 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
260 alt_odb_tail = &alt_odb_list;
261 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL);
263 sprintf(path, "%s/info/alternates", get_object_directory());
264 fd = open(path, O_RDONLY);
267 if (fstat(fd, &st) || (st.st_size == 0)) {
271 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
273 if (map == MAP_FAILED)
276 link_alt_odb_entries(map, map + st.st_size, '\n',
277 get_object_directory());
278 munmap(map, st.st_size);
281 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
283 char *name = sha1_file_name(sha1);
284 struct alternate_object_database *alt;
289 for (alt = alt_odb_list; alt; alt = alt->next) {
291 fill_sha1_path(name, sha1);
292 if (!stat(alt->base, st))
298 #define PACK_MAX_SZ (1<<26)
299 static int pack_used_ctr;
300 static unsigned long pack_mapped;
301 struct packed_git *packed_git;
303 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
308 unsigned long idx_size;
310 int fd = open(path, O_RDONLY);
314 if (fstat(fd, &st)) {
318 idx_size = st.st_size;
319 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
321 if (idx_map == MAP_FAILED)
326 *idx_size_ = idx_size;
328 /* check index map */
329 if (idx_size < 4*256 + 20 + 20)
330 return error("index file too small");
332 for (i = 0; i < 256; i++) {
333 unsigned int n = ntohl(index[i]);
335 return error("non-monotonic index");
341 * - 256 index entries 4 bytes each
342 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
343 * - 20-byte SHA1 of the packfile
344 * - 20-byte SHA1 file checksum
346 if (idx_size != 4*256 + nr * 24 + 20 + 20)
347 return error("wrong index file size");
352 static int unuse_one_packed_git(void)
354 struct packed_git *p, *lru = NULL;
356 for (p = packed_git; p; p = p->next) {
357 if (p->pack_use_cnt || !p->pack_base)
359 if (!lru || p->pack_last_used < lru->pack_last_used)
364 munmap(lru->pack_base, lru->pack_size);
365 lru->pack_base = NULL;
369 void unuse_packed_git(struct packed_git *p)
374 int use_packed_git(struct packed_git *p)
378 // We created the struct before we had the pack
379 stat(p->pack_name, &st);
380 if (!S_ISREG(st.st_mode))
381 die("packfile %s not a regular file", p->pack_name);
382 p->pack_size = st.st_size;
389 pack_mapped += p->pack_size;
390 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
392 fd = open(p->pack_name, O_RDONLY);
394 die("packfile %s cannot be opened", p->pack_name);
395 if (fstat(fd, &st)) {
397 die("packfile %s cannot be opened", p->pack_name);
399 if (st.st_size != p->pack_size)
400 die("packfile %s size mismatch.", p->pack_name);
401 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
403 if (map == MAP_FAILED)
404 die("packfile %s cannot be mapped.", p->pack_name);
407 /* Check if the pack file matches with the index file.
410 if (memcmp((char*)(p->index_base) + p->index_size - 40,
411 p->pack_base + p->pack_size - 20, 20)) {
413 die("packfile %s does not match index.", p->pack_name);
416 p->pack_last_used = pack_used_ctr++;
421 struct packed_git *add_packed_git(char *path, int path_len, int local)
424 struct packed_git *p;
425 unsigned long idx_size;
427 unsigned char sha1[20];
429 if (check_packed_git_idx(path, &idx_size, &idx_map))
432 /* do we have a corresponding .pack file? */
433 strcpy(path + path_len - 4, ".pack");
434 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
435 munmap(idx_map, idx_size);
438 /* ok, it looks sane as far as we can check without
439 * actually mapping the pack file.
441 p = xmalloc(sizeof(*p) + path_len + 2);
442 strcpy(p->pack_name, path);
443 p->index_size = idx_size;
444 p->pack_size = st.st_size;
445 p->index_base = idx_map;
448 p->pack_last_used = 0;
450 p->pack_local = local;
451 if (!get_sha1_hex(path + path_len - 40 - 4, sha1))
452 memcpy(p->sha1, sha1, 20);
456 struct packed_git *parse_pack_index(unsigned char *sha1)
458 char *path = sha1_pack_index_name(sha1);
459 return parse_pack_index_file(sha1, path);
462 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
464 struct packed_git *p;
465 unsigned long idx_size;
469 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
472 path = sha1_pack_name(sha1);
474 p = xmalloc(sizeof(*p) + strlen(path) + 2);
475 strcpy(p->pack_name, path);
476 p->index_size = idx_size;
478 p->index_base = idx_map;
481 p->pack_last_used = 0;
483 memcpy(p->sha1, sha1, 20);
487 void install_packed_git(struct packed_git *pack)
489 pack->next = packed_git;
493 static void prepare_packed_git_one(char *objdir, int local)
500 sprintf(path, "%s/pack", objdir);
506 while ((de = readdir(dir)) != NULL) {
507 int namelen = strlen(de->d_name);
508 struct packed_git *p;
510 if (strcmp(de->d_name + namelen - 4, ".idx"))
513 /* we have .idx. Is it a file we can map? */
514 strcpy(path + len, de->d_name);
515 p = add_packed_git(path, len + namelen, local);
518 p->next = packed_git;
524 void prepare_packed_git(void)
526 static int run_once = 0;
527 struct alternate_object_database *alt;
531 prepare_packed_git_one(get_object_directory(), 1);
533 for (alt = alt_odb_list; alt; alt = alt->next) {
535 prepare_packed_git_one(alt->base, 0);
540 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
543 unsigned char real_sha1[20];
547 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
548 SHA1_Update(&c, map, size);
549 SHA1_Final(real_sha1, &c);
550 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
553 static void *map_sha1_file_internal(const unsigned char *sha1,
559 char *filename = find_sha1_file(sha1, &st);
565 fd = open(filename, O_RDONLY | sha1_file_open_flag);
567 /* See if it works without O_NOATIME */
568 switch (sha1_file_open_flag) {
570 fd = open(filename, O_RDONLY);
578 /* If it failed once, it will probably fail again.
579 * Stop using O_NOATIME
581 sha1_file_open_flag = 0;
583 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
585 if (map == MAP_FAILED)
591 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
593 /* Get the data stream */
594 memset(stream, 0, sizeof(*stream));
595 stream->next_in = map;
596 stream->avail_in = mapsize;
597 stream->next_out = buffer;
598 stream->avail_out = size;
601 return inflate(stream, 0);
604 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
606 int bytes = strlen(buffer) + 1;
607 unsigned char *buf = xmalloc(1+size);
609 memcpy(buf, buffer + bytes, stream->total_out - bytes);
610 bytes = stream->total_out - bytes;
612 stream->next_out = buf + bytes;
613 stream->avail_out = size - bytes;
614 while (inflate(stream, Z_FINISH) == Z_OK)
623 * We used to just use "sscanf()", but that's actually way
624 * too permissive for what we want to check. So do an anal
625 * object header parse by hand.
627 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
633 * The type can be at most ten bytes (including the
634 * terminating '\0' that we add), and is followed by
649 * The length must follow immediately, and be in canonical
650 * decimal format (ie "010" is not valid).
657 unsigned long c = *hdr - '0';
661 size = size * 10 + c;
667 * The length must be followed by a zero byte
669 return *hdr ? -1 : 0;
672 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
678 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
679 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
682 return unpack_sha1_rest(&stream, hdr, *size);
685 /* forward declaration for a mutually recursive function */
686 static int packed_object_info(struct pack_entry *entry,
687 char *type, unsigned long *sizep);
689 static int packed_delta_info(unsigned char *base_sha1,
690 unsigned long delta_size,
693 unsigned long *sizep,
694 struct packed_git *p)
696 struct pack_entry base_ent;
699 die("truncated pack file");
701 /* The base entry _must_ be in the same pack */
702 if (!find_pack_entry_one(base_sha1, &base_ent, p))
703 die("failed to find delta-pack base object %s",
704 sha1_to_hex(base_sha1));
706 /* We choose to only get the type of the base object and
707 * ignore potentially corrupt pack file that expects the delta
708 * based on a base with a wrong size. This saves tons of
712 if (packed_object_info(&base_ent, type, NULL))
713 die("cannot get info for delta-pack base");
716 const unsigned char *data;
717 unsigned char delta_head[64];
718 unsigned long result_size;
722 memset(&stream, 0, sizeof(stream));
724 data = stream.next_in = base_sha1 + 20;
725 stream.avail_in = left - 20;
726 stream.next_out = delta_head;
727 stream.avail_out = sizeof(delta_head);
729 inflateInit(&stream);
730 st = inflate(&stream, Z_FINISH);
732 if ((st != Z_STREAM_END) &&
733 stream.total_out != sizeof(delta_head))
734 die("delta data unpack-initial failed");
736 /* Examine the initial part of the delta to figure out
740 get_delta_hdr_size(&data); /* ignore base size */
742 /* Read the result size */
743 result_size = get_delta_hdr_size(&data);
744 *sizep = result_size;
749 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
750 enum object_type *type, unsigned long *sizep)
753 unsigned char *pack, c;
756 if (offset >= p->pack_size)
757 die("object offset outside of pack file");
759 pack = p->pack_base + offset;
762 *type = (c >> 4) & 7;
766 if (offset >= p->pack_size)
767 die("object offset outside of pack file");
770 size += (c & 0x7f) << shift;
777 void packed_object_info_detail(struct pack_entry *e,
780 unsigned long *store_size,
781 int *delta_chain_length,
782 unsigned char *base_sha1)
784 struct packed_git *p = e->p;
785 unsigned long offset, left;
787 enum object_type kind;
789 offset = unpack_object_header(p, e->offset, &kind, size);
790 pack = p->pack_base + offset;
791 left = p->pack_size - offset;
792 if (kind != OBJ_DELTA)
793 *delta_chain_length = 0;
795 int chain_length = 0;
796 memcpy(base_sha1, pack, 20);
798 struct pack_entry base_ent;
801 find_pack_entry_one(pack, &base_ent, p);
802 offset = unpack_object_header(p, base_ent.offset,
804 pack = p->pack_base + offset;
806 } while (kind == OBJ_DELTA);
807 *delta_chain_length = chain_length;
811 strcpy(type, "commit");
814 strcpy(type, "tree");
817 strcpy(type, "blob");
823 die("corrupted pack file %s containing object of kind %d",
826 *store_size = 0; /* notyet */
829 static int packed_object_info(struct pack_entry *entry,
830 char *type, unsigned long *sizep)
832 struct packed_git *p = entry->p;
833 unsigned long offset, size, left;
835 enum object_type kind;
838 if (use_packed_git(p))
839 die("cannot map packed file");
841 offset = unpack_object_header(p, entry->offset, &kind, &size);
842 pack = p->pack_base + offset;
843 left = p->pack_size - offset;
847 retval = packed_delta_info(pack, size, left, type, sizep, p);
851 strcpy(type, "commit");
854 strcpy(type, "tree");
857 strcpy(type, "blob");
863 die("corrupted pack file %s containing object of kind %d",
872 /* forward declaration for a mutually recursive function */
873 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
875 static void *unpack_delta_entry(unsigned char *base_sha1,
876 unsigned long delta_size,
879 unsigned long *sizep,
880 struct packed_git *p)
882 struct pack_entry base_ent;
883 void *data, *delta_data, *result, *base;
884 unsigned long data_size, result_size, base_size;
889 die("truncated pack file");
890 data = base_sha1 + 20;
891 data_size = left - 20;
892 delta_data = xmalloc(delta_size);
894 memset(&stream, 0, sizeof(stream));
896 stream.next_in = data;
897 stream.avail_in = data_size;
898 stream.next_out = delta_data;
899 stream.avail_out = delta_size;
901 inflateInit(&stream);
902 st = inflate(&stream, Z_FINISH);
904 if ((st != Z_STREAM_END) || stream.total_out != delta_size)
905 die("delta data unpack failed");
907 /* The base entry _must_ be in the same pack */
908 if (!find_pack_entry_one(base_sha1, &base_ent, p))
909 die("failed to find delta-pack base object %s",
910 sha1_to_hex(base_sha1));
911 base = unpack_entry_gently(&base_ent, type, &base_size);
913 die("failed to read delta-pack base object %s",
914 sha1_to_hex(base_sha1));
915 result = patch_delta(base, base_size,
916 delta_data, delta_size,
919 die("failed to apply delta");
922 *sizep = result_size;
926 static void *unpack_non_delta_entry(unsigned char *data,
932 unsigned char *buffer;
934 buffer = xmalloc(size + 1);
936 memset(&stream, 0, sizeof(stream));
937 stream.next_in = data;
938 stream.avail_in = left;
939 stream.next_out = buffer;
940 stream.avail_out = size;
942 inflateInit(&stream);
943 st = inflate(&stream, Z_FINISH);
945 if ((st != Z_STREAM_END) || stream.total_out != size) {
953 static void *unpack_entry(struct pack_entry *entry,
954 char *type, unsigned long *sizep)
956 struct packed_git *p = entry->p;
959 if (use_packed_git(p))
960 die("cannot map packed file");
961 retval = unpack_entry_gently(entry, type, sizep);
964 die("corrupted pack file %s", p->pack_name);
968 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
969 void *unpack_entry_gently(struct pack_entry *entry,
970 char *type, unsigned long *sizep)
972 struct packed_git *p = entry->p;
973 unsigned long offset, size, left;
975 enum object_type kind;
978 offset = unpack_object_header(p, entry->offset, &kind, &size);
979 pack = p->pack_base + offset;
980 left = p->pack_size - offset;
983 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
986 strcpy(type, "commit");
989 strcpy(type, "tree");
992 strcpy(type, "blob");
1001 retval = unpack_non_delta_entry(pack, size, left);
1005 int num_packed_objects(const struct packed_git *p)
1007 /* See check_packed_git_idx() */
1008 return (p->index_size - 20 - 20 - 4*256) / 24;
1011 int nth_packed_object_sha1(const struct packed_git *p, int n,
1012 unsigned char* sha1)
1014 void *index = p->index_base + 256;
1015 if (n < 0 || num_packed_objects(p) <= n)
1017 memcpy(sha1, (index + 24 * n + 4), 20);
1021 int find_pack_entry_one(const unsigned char *sha1,
1022 struct pack_entry *e, struct packed_git *p)
1024 unsigned int *level1_ofs = p->index_base;
1025 int hi = ntohl(level1_ofs[*sha1]);
1026 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1027 void *index = p->index_base + 256;
1030 int mi = (lo + hi) / 2;
1031 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
1033 e->offset = ntohl(*((int*)(index + 24 * mi)));
1034 memcpy(e->sha1, sha1, 20);
1046 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1048 struct packed_git *p;
1049 prepare_packed_git();
1051 for (p = packed_git; p; p = p->next) {
1052 if (find_pack_entry_one(sha1, e, p))
1058 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1059 struct packed_git *packs)
1061 struct packed_git *p;
1062 struct pack_entry e;
1064 for (p = packs; p; p = p->next) {
1065 if (find_pack_entry_one(sha1, &e, p))
1072 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1075 unsigned long mapsize, size;
1080 map = map_sha1_file_internal(sha1, &mapsize);
1082 struct pack_entry e;
1084 if (!find_pack_entry(sha1, &e))
1085 return error("unable to find %s", sha1_to_hex(sha1));
1086 return packed_object_info(&e, type, sizep);
1088 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1089 status = error("unable to unpack %s header",
1091 if (parse_sha1_header(hdr, type, &size) < 0)
1092 status = error("unable to parse %s header", sha1_to_hex(sha1));
1098 inflateEnd(&stream);
1099 munmap(map, mapsize);
1103 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1105 struct pack_entry e;
1107 if (!find_pack_entry(sha1, &e)) {
1108 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1111 return unpack_entry(&e, type, size);
1114 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1116 unsigned long mapsize;
1118 struct pack_entry e;
1120 if (find_pack_entry(sha1, &e))
1121 return read_packed_sha1(sha1, type, size);
1122 map = map_sha1_file_internal(sha1, &mapsize);
1124 buf = unpack_sha1_file(map, mapsize, type, size);
1125 munmap(map, mapsize);
1131 void *read_object_with_reference(const unsigned char *sha1,
1132 const char *required_type,
1133 unsigned long *size,
1134 unsigned char *actual_sha1_return)
1138 unsigned long isize;
1139 unsigned char actual_sha1[20];
1141 memcpy(actual_sha1, sha1, 20);
1143 int ref_length = -1;
1144 const char *ref_type = NULL;
1146 buffer = read_sha1_file(actual_sha1, type, &isize);
1149 if (!strcmp(type, required_type)) {
1151 if (actual_sha1_return)
1152 memcpy(actual_sha1_return, actual_sha1, 20);
1155 /* Handle references */
1156 else if (!strcmp(type, "commit"))
1158 else if (!strcmp(type, "tag"))
1159 ref_type = "object ";
1164 ref_length = strlen(ref_type);
1166 if (memcmp(buffer, ref_type, ref_length) ||
1167 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1172 /* Now we have the ID of the referred-to object in
1173 * actual_sha1. Check again. */
1177 char *write_sha1_file_prepare(void *buf,
1180 unsigned char *sha1,
1186 /* Generate the header */
1187 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1191 SHA1_Update(&c, hdr, *hdrlen);
1192 SHA1_Update(&c, buf, len);
1193 SHA1_Final(sha1, &c);
1195 return sha1_file_name(sha1);
1199 * Link the tempfile to the final place, possibly creating the
1200 * last directory level as you do so.
1202 * Returns the errno on failure, 0 on success.
1204 static int link_temp_to_file(const char *tmpfile, char *filename)
1208 if (!link(tmpfile, filename))
1212 * Try to mkdir the last path component if that failed
1215 * Re-try the "link()" regardless of whether the mkdir
1216 * succeeds, since a race might mean that somebody
1220 if (ret == ENOENT) {
1221 char *dir = strrchr(filename, '/');
1224 mkdir(filename, 0777);
1226 if (!link(tmpfile, filename))
1235 * Move the just written object into its final resting place
1237 int move_temp_to_file(const char *tmpfile, char *filename)
1239 int ret = link_temp_to_file(tmpfile, filename);
1242 * Coda hack - coda doesn't like cross-directory links,
1243 * so we fall back to a rename, which will mean that it
1244 * won't be able to check collisions, but that's not a
1247 * The same holds for FAT formatted media.
1249 * When this succeeds, we just return 0. We have nothing
1252 if (ret && ret != EEXIST) {
1253 if (!rename(tmpfile, filename))
1259 if (ret != EEXIST) {
1260 fprintf(stderr, "unable to write sha1 filename %s: %s", filename, strerror(ret));
1263 /* FIXME!!! Collision check here ? */
1269 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1272 unsigned char *compressed;
1274 unsigned char sha1[20];
1276 static char tmpfile[PATH_MAX];
1277 unsigned char hdr[50];
1280 /* Normally if we have it in the pack then we do not bother writing
1281 * it out into .git/objects/??/?{38} file.
1283 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1285 memcpy(returnsha1, sha1, 20);
1286 if (has_sha1_file(sha1))
1288 fd = open(filename, O_RDONLY);
1291 * FIXME!!! We might do collision checking here, but we'd
1292 * need to uncompress the old file and check it. Later.
1298 if (errno != ENOENT) {
1299 fprintf(stderr, "sha1 file %s: %s", filename, strerror(errno));
1303 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1305 fd = mkstemp(tmpfile);
1307 fprintf(stderr, "unable to create temporary sha1 filename %s: %s", tmpfile, strerror(errno));
1312 memset(&stream, 0, sizeof(stream));
1313 deflateInit(&stream, Z_BEST_COMPRESSION);
1314 size = deflateBound(&stream, len+hdrlen);
1315 compressed = xmalloc(size);
1318 stream.next_out = compressed;
1319 stream.avail_out = size;
1321 /* First header.. */
1322 stream.next_in = hdr;
1323 stream.avail_in = hdrlen;
1324 while (deflate(&stream, 0) == Z_OK)
1327 /* Then the data itself.. */
1328 stream.next_in = buf;
1329 stream.avail_in = len;
1330 while (deflate(&stream, Z_FINISH) == Z_OK)
1332 deflateEnd(&stream);
1333 size = stream.total_out;
1335 if (write(fd, compressed, size) != size)
1336 die("unable to write file");
1341 return move_temp_to_file(tmpfile, filename);
1344 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1347 unsigned long objsize;
1349 void *map = map_sha1_file_internal(sha1, &objsize);
1351 void *temp_obj = NULL;
1355 unsigned char *unpacked;
1360 // need to unpack and recompress it by itself
1361 unpacked = read_packed_sha1(sha1, type, &len);
1363 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1366 memset(&stream, 0, sizeof(stream));
1367 deflateInit(&stream, Z_BEST_COMPRESSION);
1368 size = deflateBound(&stream, len + hdrlen);
1369 temp_obj = buf = xmalloc(size);
1372 stream.next_out = buf;
1373 stream.avail_out = size;
1375 /* First header.. */
1376 stream.next_in = (void *)hdr;
1377 stream.avail_in = hdrlen;
1378 while (deflate(&stream, 0) == Z_OK)
1381 /* Then the data itself.. */
1382 stream.next_in = unpacked;
1383 stream.avail_in = len;
1384 while (deflate(&stream, Z_FINISH) == Z_OK)
1386 deflateEnd(&stream);
1389 objsize = stream.total_out;
1393 size = write(fd, buf + posn, objsize - posn);
1396 fprintf(stderr, "write closed");
1403 } while (posn < objsize);
1406 munmap(map, objsize);
1413 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1414 size_t bufsize, size_t *bufposn)
1416 char tmpfile[PATH_MAX];
1419 unsigned char real_sha1[20];
1420 unsigned char discard[4096];
1424 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1426 local = mkstemp(tmpfile);
1428 return error("Couldn't open %s for %s\n", tmpfile, sha1_to_hex(sha1));
1430 memset(&stream, 0, sizeof(stream));
1432 inflateInit(&stream);
1439 stream.avail_in = *bufposn;
1440 stream.next_in = (unsigned char *) buffer;
1442 stream.next_out = discard;
1443 stream.avail_out = sizeof(discard);
1444 ret = inflate(&stream, Z_SYNC_FLUSH);
1445 SHA1_Update(&c, discard, sizeof(discard) -
1447 } while (stream.avail_in && ret == Z_OK);
1448 write(local, buffer, *bufposn - stream.avail_in);
1449 memmove(buffer, buffer + *bufposn - stream.avail_in,
1451 *bufposn = stream.avail_in;
1455 size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1460 return error("Connection closed?");
1461 perror("Reading from connection");
1466 inflateEnd(&stream);
1469 SHA1_Final(real_sha1, &c);
1470 if (ret != Z_STREAM_END) {
1472 return error("File %s corrupted", sha1_to_hex(sha1));
1474 if (memcmp(sha1, real_sha1, 20)) {
1476 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1479 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1482 int has_pack_index(const unsigned char *sha1)
1485 if (stat(sha1_pack_index_name(sha1), &st))
1490 int has_pack_file(const unsigned char *sha1)
1493 if (stat(sha1_pack_name(sha1), &st))
1498 int has_sha1_pack(const unsigned char *sha1)
1500 struct pack_entry e;
1501 return find_pack_entry(sha1, &e);
1504 int has_sha1_file(const unsigned char *sha1)
1507 struct pack_entry e;
1509 if (find_pack_entry(sha1, &e))
1511 return find_sha1_file(sha1, &st) ? 1 : 0;
1514 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1516 unsigned long size = st->st_size;
1519 unsigned char hdr[50];
1524 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1526 if (buf == MAP_FAILED)
1532 ret = write_sha1_file(buf, size, type, sha1);
1534 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1542 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1547 switch (st->st_mode & S_IFMT) {
1549 fd = open(path, O_RDONLY);
1551 return error("open(\"%s\"): %s", path,
1553 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1554 return error("%s: failed to insert into database",
1558 target = xmalloc(st->st_size+1);
1559 if (readlink(path, target, st->st_size+1) != st->st_size) {
1560 char *errstr = strerror(errno);
1562 return error("readlink(\"%s\"): %s", path,
1565 if (!write_object) {
1566 unsigned char hdr[50];
1568 write_sha1_file_prepare(target, st->st_size, "blob",
1569 sha1, hdr, &hdrlen);
1570 } else if (write_sha1_file(target, st->st_size, "blob", sha1))
1571 return error("%s: failed to insert into database",
1576 return error("%s: unsupported file type", path);