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_,
325 unsigned char sha1[20];
328 unsigned long idx_size;
333 fd = open(path, O_RDONLY);
336 if (fstat(fd, &st)) {
340 idx_size = st.st_size;
341 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
343 if (idx_map == MAP_FAILED)
348 *idx_size_ = idx_size;
350 /* check index map */
351 if (idx_size < 4*256 + 20 + 20)
352 return error("index file too small");
354 for (i = 0; i < 256; i++) {
355 unsigned int n = ntohl(index[i]);
357 return error("non-monotonic index");
363 * - 256 index entries 4 bytes each
364 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
365 * - 20-byte SHA1 of the packfile
366 * - 20-byte SHA1 file checksum
368 if (idx_size != 4*256 + nr * 24 + 20 + 20)
369 return error("wrong index file size");
375 SHA1_Update(&ctx, idx_map, idx_size-20);
376 SHA1_Final(sha1, &ctx);
378 if (memcmp(sha1, idx_map + idx_size - 20, 20))
379 return error("index checksum mismatch");
384 static int unuse_one_packed_git(void)
386 struct packed_git *p, *lru = NULL;
388 for (p = packed_git; p; p = p->next) {
389 if (p->pack_use_cnt || !p->pack_base)
391 if (!lru || p->pack_last_used < lru->pack_last_used)
396 munmap(lru->pack_base, lru->pack_size);
397 lru->pack_base = NULL;
401 void unuse_packed_git(struct packed_git *p)
406 int use_packed_git(struct packed_git *p)
410 // We created the struct before we had the pack
411 stat(p->pack_name, &st);
412 if (!S_ISREG(st.st_mode))
413 die("packfile %s not a regular file", p->pack_name);
414 p->pack_size = st.st_size;
421 pack_mapped += p->pack_size;
422 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
424 fd = open(p->pack_name, O_RDONLY);
426 die("packfile %s cannot be opened", p->pack_name);
427 if (fstat(fd, &st)) {
429 die("packfile %s cannot be opened", p->pack_name);
431 if (st.st_size != p->pack_size)
432 die("packfile %s size mismatch.", p->pack_name);
433 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
435 if (map == MAP_FAILED)
436 die("packfile %s cannot be mapped.", p->pack_name);
439 /* Check if the pack file matches with the index file.
442 if (memcmp((char*)(p->index_base) + p->index_size - 40,
443 p->pack_base + p->pack_size - 20, 20)) {
445 die("packfile %s does not match index.", p->pack_name);
448 p->pack_last_used = pack_used_ctr++;
453 struct packed_git *add_packed_git(char *path, int path_len, int local)
456 struct packed_git *p;
457 unsigned long idx_size;
459 unsigned char sha1[20];
461 if (check_packed_git_idx(path, &idx_size, &idx_map))
464 /* do we have a corresponding .pack file? */
465 strcpy(path + path_len - 4, ".pack");
466 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
467 munmap(idx_map, idx_size);
470 /* ok, it looks sane as far as we can check without
471 * actually mapping the pack file.
473 p = xmalloc(sizeof(*p) + path_len + 2);
474 strcpy(p->pack_name, path);
475 p->index_size = idx_size;
476 p->pack_size = st.st_size;
477 p->index_base = idx_map;
480 p->pack_last_used = 0;
482 p->pack_local = local;
483 if ((path_len > 44) && !get_sha1_hex(path + path_len - 44, sha1))
484 memcpy(p->sha1, sha1, 20);
488 struct packed_git *parse_pack_index(unsigned char *sha1)
490 char *path = sha1_pack_index_name(sha1);
491 return parse_pack_index_file(sha1, path);
494 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
496 struct packed_git *p;
497 unsigned long idx_size;
501 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
504 path = sha1_pack_name(sha1);
506 p = xmalloc(sizeof(*p) + strlen(path) + 2);
507 strcpy(p->pack_name, path);
508 p->index_size = idx_size;
510 p->index_base = idx_map;
513 p->pack_last_used = 0;
515 memcpy(p->sha1, sha1, 20);
519 void install_packed_git(struct packed_git *pack)
521 pack->next = packed_git;
525 static void prepare_packed_git_one(char *objdir, int local)
532 sprintf(path, "%s/pack", objdir);
538 while ((de = readdir(dir)) != NULL) {
539 int namelen = strlen(de->d_name);
540 struct packed_git *p;
542 if (strcmp(de->d_name + namelen - 4, ".idx"))
545 /* we have .idx. Is it a file we can map? */
546 strcpy(path + len, de->d_name);
547 p = add_packed_git(path, len + namelen, local);
550 p->next = packed_git;
556 void prepare_packed_git(void)
558 static int run_once = 0;
559 struct alternate_object_database *alt;
563 prepare_packed_git_one(get_object_directory(), 1);
565 for (alt = alt_odb_list; alt; alt = alt->next) {
567 prepare_packed_git_one(alt->base, 0);
573 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
576 unsigned char real_sha1[20];
580 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
581 SHA1_Update(&c, map, size);
582 SHA1_Final(real_sha1, &c);
583 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
586 static void *map_sha1_file_internal(const unsigned char *sha1,
592 char *filename = find_sha1_file(sha1, &st);
598 fd = open(filename, O_RDONLY | sha1_file_open_flag);
600 /* See if it works without O_NOATIME */
601 switch (sha1_file_open_flag) {
603 fd = open(filename, O_RDONLY);
611 /* If it failed once, it will probably fail again.
612 * Stop using O_NOATIME
614 sha1_file_open_flag = 0;
616 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
618 if (map == MAP_FAILED)
624 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
626 /* Get the data stream */
627 memset(stream, 0, sizeof(*stream));
628 stream->next_in = map;
629 stream->avail_in = mapsize;
630 stream->next_out = buffer;
631 stream->avail_out = size;
634 return inflate(stream, 0);
637 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
639 int bytes = strlen(buffer) + 1;
640 unsigned char *buf = xmalloc(1+size);
642 memcpy(buf, buffer + bytes, stream->total_out - bytes);
643 bytes = stream->total_out - bytes;
645 stream->next_out = buf + bytes;
646 stream->avail_out = size - bytes;
647 while (inflate(stream, Z_FINISH) == Z_OK)
656 * We used to just use "sscanf()", but that's actually way
657 * too permissive for what we want to check. So do an anal
658 * object header parse by hand.
660 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
666 * The type can be at most ten bytes (including the
667 * terminating '\0' that we add), and is followed by
682 * The length must follow immediately, and be in canonical
683 * decimal format (ie "010" is not valid).
690 unsigned long c = *hdr - '0';
694 size = size * 10 + c;
700 * The length must be followed by a zero byte
702 return *hdr ? -1 : 0;
705 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
711 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
712 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
715 return unpack_sha1_rest(&stream, hdr, *size);
718 /* forward declaration for a mutually recursive function */
719 static int packed_object_info(struct pack_entry *entry,
720 char *type, unsigned long *sizep);
722 static int packed_delta_info(unsigned char *base_sha1,
723 unsigned long delta_size,
726 unsigned long *sizep,
727 struct packed_git *p)
729 struct pack_entry base_ent;
732 die("truncated pack file");
734 /* The base entry _must_ be in the same pack */
735 if (!find_pack_entry_one(base_sha1, &base_ent, p))
736 die("failed to find delta-pack base object %s",
737 sha1_to_hex(base_sha1));
739 /* We choose to only get the type of the base object and
740 * ignore potentially corrupt pack file that expects the delta
741 * based on a base with a wrong size. This saves tons of
745 if (packed_object_info(&base_ent, type, NULL))
746 die("cannot get info for delta-pack base");
749 const unsigned char *data;
750 unsigned char delta_head[64];
751 unsigned long result_size;
755 memset(&stream, 0, sizeof(stream));
757 data = stream.next_in = base_sha1 + 20;
758 stream.avail_in = left - 20;
759 stream.next_out = delta_head;
760 stream.avail_out = sizeof(delta_head);
762 inflateInit(&stream);
763 st = inflate(&stream, Z_FINISH);
765 if ((st != Z_STREAM_END) &&
766 stream.total_out != sizeof(delta_head))
767 die("delta data unpack-initial failed");
769 /* Examine the initial part of the delta to figure out
773 get_delta_hdr_size(&data); /* ignore base size */
775 /* Read the result size */
776 result_size = get_delta_hdr_size(&data);
777 *sizep = result_size;
782 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
783 enum object_type *type, unsigned long *sizep)
786 unsigned char *pack, c;
789 if (offset >= p->pack_size)
790 die("object offset outside of pack file");
792 pack = p->pack_base + offset;
795 *type = (c >> 4) & 7;
799 if (offset >= p->pack_size)
800 die("object offset outside of pack file");
803 size += (c & 0x7f) << shift;
810 void packed_object_info_detail(struct pack_entry *e,
813 unsigned long *store_size,
814 int *delta_chain_length,
815 unsigned char *base_sha1)
817 struct packed_git *p = e->p;
818 unsigned long offset, left;
820 enum object_type kind;
822 offset = unpack_object_header(p, e->offset, &kind, size);
823 pack = p->pack_base + offset;
824 left = p->pack_size - offset;
825 if (kind != OBJ_DELTA)
826 *delta_chain_length = 0;
828 int chain_length = 0;
829 memcpy(base_sha1, pack, 20);
831 struct pack_entry base_ent;
834 find_pack_entry_one(pack, &base_ent, p);
835 offset = unpack_object_header(p, base_ent.offset,
837 pack = p->pack_base + offset;
839 } while (kind == OBJ_DELTA);
840 *delta_chain_length = chain_length;
844 strcpy(type, "commit");
847 strcpy(type, "tree");
850 strcpy(type, "blob");
856 die("corrupted pack file %s containing object of kind %d",
859 *store_size = 0; /* notyet */
862 static int packed_object_info(struct pack_entry *entry,
863 char *type, unsigned long *sizep)
865 struct packed_git *p = entry->p;
866 unsigned long offset, size, left;
868 enum object_type kind;
871 if (use_packed_git(p))
872 die("cannot map packed file");
874 offset = unpack_object_header(p, entry->offset, &kind, &size);
875 pack = p->pack_base + offset;
876 left = p->pack_size - offset;
880 retval = packed_delta_info(pack, size, left, type, sizep, p);
884 strcpy(type, "commit");
887 strcpy(type, "tree");
890 strcpy(type, "blob");
896 die("corrupted pack file %s containing object of kind %d",
905 /* forward declaration for a mutually recursive function */
906 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
908 static void *unpack_delta_entry(unsigned char *base_sha1,
909 unsigned long delta_size,
912 unsigned long *sizep,
913 struct packed_git *p)
915 struct pack_entry base_ent;
916 void *data, *delta_data, *result, *base;
917 unsigned long data_size, result_size, base_size;
922 die("truncated pack file");
923 data = base_sha1 + 20;
924 data_size = left - 20;
925 delta_data = xmalloc(delta_size);
927 memset(&stream, 0, sizeof(stream));
929 stream.next_in = data;
930 stream.avail_in = data_size;
931 stream.next_out = delta_data;
932 stream.avail_out = delta_size;
934 inflateInit(&stream);
935 st = inflate(&stream, Z_FINISH);
937 if ((st != Z_STREAM_END) || stream.total_out != delta_size)
938 die("delta data unpack failed");
940 /* The base entry _must_ be in the same pack */
941 if (!find_pack_entry_one(base_sha1, &base_ent, p))
942 die("failed to find delta-pack base object %s",
943 sha1_to_hex(base_sha1));
944 base = unpack_entry_gently(&base_ent, type, &base_size);
946 die("failed to read delta-pack base object %s",
947 sha1_to_hex(base_sha1));
948 result = patch_delta(base, base_size,
949 delta_data, delta_size,
952 die("failed to apply delta");
955 *sizep = result_size;
959 static void *unpack_non_delta_entry(unsigned char *data,
965 unsigned char *buffer;
967 buffer = xmalloc(size + 1);
969 memset(&stream, 0, sizeof(stream));
970 stream.next_in = data;
971 stream.avail_in = left;
972 stream.next_out = buffer;
973 stream.avail_out = size;
975 inflateInit(&stream);
976 st = inflate(&stream, Z_FINISH);
978 if ((st != Z_STREAM_END) || stream.total_out != size) {
986 static void *unpack_entry(struct pack_entry *entry,
987 char *type, unsigned long *sizep)
989 struct packed_git *p = entry->p;
992 if (use_packed_git(p))
993 die("cannot map packed file");
994 retval = unpack_entry_gently(entry, type, sizep);
997 die("corrupted pack file %s", p->pack_name);
1001 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
1002 void *unpack_entry_gently(struct pack_entry *entry,
1003 char *type, unsigned long *sizep)
1005 struct packed_git *p = entry->p;
1006 unsigned long offset, size, left;
1007 unsigned char *pack;
1008 enum object_type kind;
1011 offset = unpack_object_header(p, entry->offset, &kind, &size);
1012 pack = p->pack_base + offset;
1013 left = p->pack_size - offset;
1016 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
1019 strcpy(type, "commit");
1022 strcpy(type, "tree");
1025 strcpy(type, "blob");
1028 strcpy(type, "tag");
1034 retval = unpack_non_delta_entry(pack, size, left);
1038 int num_packed_objects(const struct packed_git *p)
1040 /* See check_packed_git_idx() */
1041 return (p->index_size - 20 - 20 - 4*256) / 24;
1044 int nth_packed_object_sha1(const struct packed_git *p, int n,
1045 unsigned char* sha1)
1047 void *index = p->index_base + 256;
1048 if (n < 0 || num_packed_objects(p) <= n)
1050 memcpy(sha1, (index + 24 * n + 4), 20);
1054 int find_pack_entry_one(const unsigned char *sha1,
1055 struct pack_entry *e, struct packed_git *p)
1057 unsigned int *level1_ofs = p->index_base;
1058 int hi = ntohl(level1_ofs[*sha1]);
1059 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1060 void *index = p->index_base + 256;
1063 int mi = (lo + hi) / 2;
1064 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
1066 e->offset = ntohl(*((int*)(index + 24 * mi)));
1067 memcpy(e->sha1, sha1, 20);
1079 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1081 struct packed_git *p;
1082 prepare_packed_git();
1084 for (p = packed_git; p; p = p->next) {
1085 if (find_pack_entry_one(sha1, e, p))
1091 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1092 struct packed_git *packs)
1094 struct packed_git *p;
1095 struct pack_entry e;
1097 for (p = packs; p; p = p->next) {
1098 if (find_pack_entry_one(sha1, &e, p))
1105 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1108 unsigned long mapsize, size;
1113 map = map_sha1_file_internal(sha1, &mapsize);
1115 struct pack_entry e;
1117 if (!find_pack_entry(sha1, &e))
1118 return error("unable to find %s", sha1_to_hex(sha1));
1119 return packed_object_info(&e, type, sizep);
1121 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1122 status = error("unable to unpack %s header",
1124 if (parse_sha1_header(hdr, type, &size) < 0)
1125 status = error("unable to parse %s header", sha1_to_hex(sha1));
1131 inflateEnd(&stream);
1132 munmap(map, mapsize);
1136 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1138 struct pack_entry e;
1140 if (!find_pack_entry(sha1, &e)) {
1141 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1144 return unpack_entry(&e, type, size);
1147 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1149 unsigned long mapsize;
1151 struct pack_entry e;
1153 if (find_pack_entry(sha1, &e))
1154 return read_packed_sha1(sha1, type, size);
1155 map = map_sha1_file_internal(sha1, &mapsize);
1157 buf = unpack_sha1_file(map, mapsize, type, size);
1158 munmap(map, mapsize);
1164 void *read_object_with_reference(const unsigned char *sha1,
1165 const char *required_type,
1166 unsigned long *size,
1167 unsigned char *actual_sha1_return)
1171 unsigned long isize;
1172 unsigned char actual_sha1[20];
1174 memcpy(actual_sha1, sha1, 20);
1176 int ref_length = -1;
1177 const char *ref_type = NULL;
1179 buffer = read_sha1_file(actual_sha1, type, &isize);
1182 if (!strcmp(type, required_type)) {
1184 if (actual_sha1_return)
1185 memcpy(actual_sha1_return, actual_sha1, 20);
1188 /* Handle references */
1189 else if (!strcmp(type, "commit"))
1191 else if (!strcmp(type, "tag"))
1192 ref_type = "object ";
1197 ref_length = strlen(ref_type);
1199 if (memcmp(buffer, ref_type, ref_length) ||
1200 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1205 /* Now we have the ID of the referred-to object in
1206 * actual_sha1. Check again. */
1210 char *write_sha1_file_prepare(void *buf,
1213 unsigned char *sha1,
1219 /* Generate the header */
1220 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1224 SHA1_Update(&c, hdr, *hdrlen);
1225 SHA1_Update(&c, buf, len);
1226 SHA1_Final(sha1, &c);
1228 return sha1_file_name(sha1);
1232 * Link the tempfile to the final place, possibly creating the
1233 * last directory level as you do so.
1235 * Returns the errno on failure, 0 on success.
1237 static int link_temp_to_file(const char *tmpfile, char *filename)
1241 if (!link(tmpfile, filename))
1245 * Try to mkdir the last path component if that failed
1248 * Re-try the "link()" regardless of whether the mkdir
1249 * succeeds, since a race might mean that somebody
1253 if (ret == ENOENT) {
1254 char *dir = strrchr(filename, '/');
1257 mkdir(filename, 0777);
1259 if (!link(tmpfile, filename))
1268 * Move the just written object into its final resting place
1270 int move_temp_to_file(const char *tmpfile, char *filename)
1272 int ret = link_temp_to_file(tmpfile, filename);
1275 * Coda hack - coda doesn't like cross-directory links,
1276 * so we fall back to a rename, which will mean that it
1277 * won't be able to check collisions, but that's not a
1280 * The same holds for FAT formatted media.
1282 * When this succeeds, we just return 0. We have nothing
1285 if (ret && ret != EEXIST) {
1286 if (!rename(tmpfile, filename))
1292 if (ret != EEXIST) {
1293 fprintf(stderr, "unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1296 /* FIXME!!! Collision check here ? */
1302 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1305 unsigned char *compressed;
1307 unsigned char sha1[20];
1309 static char tmpfile[PATH_MAX];
1310 unsigned char hdr[50];
1313 /* Normally if we have it in the pack then we do not bother writing
1314 * it out into .git/objects/??/?{38} file.
1316 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1318 memcpy(returnsha1, sha1, 20);
1319 if (has_sha1_file(sha1))
1321 fd = open(filename, O_RDONLY);
1324 * FIXME!!! We might do collision checking here, but we'd
1325 * need to uncompress the old file and check it. Later.
1331 if (errno != ENOENT) {
1332 fprintf(stderr, "sha1 file %s: %s\n", filename, strerror(errno));
1336 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1338 fd = mkstemp(tmpfile);
1340 fprintf(stderr, "unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
1345 memset(&stream, 0, sizeof(stream));
1346 deflateInit(&stream, Z_BEST_COMPRESSION);
1347 size = deflateBound(&stream, len+hdrlen);
1348 compressed = xmalloc(size);
1351 stream.next_out = compressed;
1352 stream.avail_out = size;
1354 /* First header.. */
1355 stream.next_in = hdr;
1356 stream.avail_in = hdrlen;
1357 while (deflate(&stream, 0) == Z_OK)
1360 /* Then the data itself.. */
1361 stream.next_in = buf;
1362 stream.avail_in = len;
1363 while (deflate(&stream, Z_FINISH) == Z_OK)
1365 deflateEnd(&stream);
1366 size = stream.total_out;
1368 if (write(fd, compressed, size) != size)
1369 die("unable to write file");
1374 return move_temp_to_file(tmpfile, filename);
1377 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1380 unsigned long objsize;
1382 void *map = map_sha1_file_internal(sha1, &objsize);
1384 void *temp_obj = NULL;
1388 unsigned char *unpacked;
1393 // need to unpack and recompress it by itself
1394 unpacked = read_packed_sha1(sha1, type, &len);
1396 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1399 memset(&stream, 0, sizeof(stream));
1400 deflateInit(&stream, Z_BEST_COMPRESSION);
1401 size = deflateBound(&stream, len + hdrlen);
1402 temp_obj = buf = xmalloc(size);
1405 stream.next_out = buf;
1406 stream.avail_out = size;
1408 /* First header.. */
1409 stream.next_in = (void *)hdr;
1410 stream.avail_in = hdrlen;
1411 while (deflate(&stream, 0) == Z_OK)
1414 /* Then the data itself.. */
1415 stream.next_in = unpacked;
1416 stream.avail_in = len;
1417 while (deflate(&stream, Z_FINISH) == Z_OK)
1419 deflateEnd(&stream);
1422 objsize = stream.total_out;
1426 size = write(fd, buf + posn, objsize - posn);
1429 fprintf(stderr, "write closed\n");
1436 } while (posn < objsize);
1439 munmap(map, objsize);
1446 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1447 size_t bufsize, size_t *bufposn)
1449 char tmpfile[PATH_MAX];
1452 unsigned char real_sha1[20];
1453 unsigned char discard[4096];
1457 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1459 local = mkstemp(tmpfile);
1461 return error("Couldn't open %s for %s\n", tmpfile, sha1_to_hex(sha1));
1463 memset(&stream, 0, sizeof(stream));
1465 inflateInit(&stream);
1472 stream.avail_in = *bufposn;
1473 stream.next_in = (unsigned char *) buffer;
1475 stream.next_out = discard;
1476 stream.avail_out = sizeof(discard);
1477 ret = inflate(&stream, Z_SYNC_FLUSH);
1478 SHA1_Update(&c, discard, sizeof(discard) -
1480 } while (stream.avail_in && ret == Z_OK);
1481 write(local, buffer, *bufposn - stream.avail_in);
1482 memmove(buffer, buffer + *bufposn - stream.avail_in,
1484 *bufposn = stream.avail_in;
1488 size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1493 return error("Connection closed?");
1494 perror("Reading from connection");
1499 inflateEnd(&stream);
1502 SHA1_Final(real_sha1, &c);
1503 if (ret != Z_STREAM_END) {
1505 return error("File %s corrupted", sha1_to_hex(sha1));
1507 if (memcmp(sha1, real_sha1, 20)) {
1509 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1512 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1515 int has_pack_index(const unsigned char *sha1)
1518 if (stat(sha1_pack_index_name(sha1), &st))
1523 int has_pack_file(const unsigned char *sha1)
1526 if (stat(sha1_pack_name(sha1), &st))
1531 int has_sha1_pack(const unsigned char *sha1)
1533 struct pack_entry e;
1534 return find_pack_entry(sha1, &e);
1537 int has_sha1_file(const unsigned char *sha1)
1540 struct pack_entry e;
1542 if (find_pack_entry(sha1, &e))
1544 return find_sha1_file(sha1, &st) ? 1 : 0;
1547 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
1549 unsigned long size = 4096;
1550 char *buf = malloc(size);
1552 unsigned long off = 0;
1553 unsigned char hdr[50];
1556 iret = read(fd, buf + off, size - off);
1561 buf = realloc(buf, size);
1572 ret = write_sha1_file(buf, off, type, sha1);
1574 write_sha1_file_prepare(buf, off, type, sha1, hdr, &hdrlen);
1581 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1583 unsigned long size = st->st_size;
1586 unsigned char hdr[50];
1591 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1593 if (buf == MAP_FAILED)
1599 ret = write_sha1_file(buf, size, type, sha1);
1601 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1609 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1614 switch (st->st_mode & S_IFMT) {
1616 fd = open(path, O_RDONLY);
1618 return error("open(\"%s\"): %s", path,
1620 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1621 return error("%s: failed to insert into database",
1625 target = xmalloc(st->st_size+1);
1626 if (readlink(path, target, st->st_size+1) != st->st_size) {
1627 char *errstr = strerror(errno);
1629 return error("readlink(\"%s\"): %s", path,
1632 if (!write_object) {
1633 unsigned char hdr[50];
1635 write_sha1_file_prepare(target, st->st_size, "blob",
1636 sha1, hdr, &hdrlen);
1637 } else if (write_sha1_file(target, st->st_size, "blob", sha1))
1638 return error("%s: failed to insert into database",
1643 return error("%s: unsupported file type", path);