2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
18 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
19 #define O_NOATIME 01000000
25 const unsigned char null_sha1[20] = { 0, };
27 static unsigned int sha1_file_open_flag = O_NOATIME;
29 static unsigned hexval(char c)
31 if (c >= '0' && c <= '9')
33 if (c >= 'a' && c <= 'f')
35 if (c >= 'A' && c <= 'F')
40 int get_sha1_hex(const char *hex, unsigned char *sha1)
43 for (i = 0; i < 20; i++) {
44 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
53 int adjust_shared_perm(const char *path)
58 if (!shared_repository)
60 if (lstat(path, &st) < 0)
71 if (chmod(path, mode) < 0)
76 int safe_create_leading_directories(char *path)
85 pos = strchr(pos, '/');
89 if (!stat(path, &st)) {
91 if (!S_ISDIR(st.st_mode)) {
96 else if (mkdir(path, 0777)) {
100 else if (adjust_shared_perm(path)) {
109 char * sha1_to_hex(const unsigned char *sha1)
112 static char hexbuffer[4][50];
113 static const char hex[] = "0123456789abcdef";
114 char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
117 for (i = 0; i < 20; i++) {
118 unsigned int val = *sha1++;
119 *buf++ = hex[val >> 4];
120 *buf++ = hex[val & 0xf];
127 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
130 for (i = 0; i < 20; i++) {
131 static char hex[] = "0123456789abcdef";
132 unsigned int val = sha1[i];
133 char *pos = pathbuf + i*2 + (i > 0);
134 *pos++ = hex[val >> 4];
135 *pos = hex[val & 0xf];
140 * NOTE! This returns a statically allocated buffer, so you have to be
141 * careful about using it. Do a "strdup()" if you need to save the
144 * Also note that this returns the location for creating. Reading
145 * SHA1 file can happen from any alternate directory listed in the
146 * DB_ENVIRONMENT environment variable if it is not found in
147 * the primary object database.
149 char *sha1_file_name(const unsigned char *sha1)
151 static char *name, *base;
154 const char *sha1_file_directory = get_object_directory();
155 int len = strlen(sha1_file_directory);
156 base = xmalloc(len + 60);
157 memcpy(base, sha1_file_directory, len);
158 memset(base+len, 0, 60);
161 name = base + len + 1;
163 fill_sha1_path(name, sha1);
167 char *sha1_pack_name(const unsigned char *sha1)
169 static const char hex[] = "0123456789abcdef";
170 static char *name, *base, *buf;
174 const char *sha1_file_directory = get_object_directory();
175 int len = strlen(sha1_file_directory);
176 base = xmalloc(len + 60);
177 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
178 name = base + len + 11;
183 for (i = 0; i < 20; i++) {
184 unsigned int val = *sha1++;
185 *buf++ = hex[val >> 4];
186 *buf++ = hex[val & 0xf];
192 char *sha1_pack_index_name(const unsigned char *sha1)
194 static const char hex[] = "0123456789abcdef";
195 static char *name, *base, *buf;
199 const char *sha1_file_directory = get_object_directory();
200 int len = strlen(sha1_file_directory);
201 base = xmalloc(len + 60);
202 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
203 name = base + len + 11;
208 for (i = 0; i < 20; i++) {
209 unsigned int val = *sha1++;
210 *buf++ = hex[val >> 4];
211 *buf++ = hex[val & 0xf];
217 struct alternate_object_database *alt_odb_list;
218 static struct alternate_object_database **alt_odb_tail;
221 * Prepare alternate object database registry.
223 * The variable alt_odb_list points at the list of struct
224 * alternate_object_database. The elements on this list come from
225 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
226 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
227 * whose contents is similar to that environment variable but can be
228 * LF separated. Its base points at a statically allocated buffer that
229 * contains "/the/directory/corresponding/to/.git/objects/...", while
230 * its name points just after the slash at the end of ".git/objects/"
231 * in the example above, and has enough space to hold 40-byte hex
232 * SHA1, an extra slash for the first level indirection, and the
235 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
236 const char *relative_base)
238 const char *cp, *last;
239 struct alternate_object_database *ent;
240 const char *objdir = get_object_directory();
246 if (cp < ep && *cp == '#') {
247 while (cp < ep && *cp != sep)
252 for ( ; cp < ep && *cp != sep; cp++)
256 struct alternate_object_database *alt;
257 /* 43 = 40-byte + 2 '/' + terminating NUL */
258 int pfxlen = cp - last;
259 int entlen = pfxlen + 43;
261 if (*last != '/' && relative_base) {
262 /* Relative alt-odb */
264 base_len = strlen(relative_base) + 1;
268 ent = xmalloc(sizeof(*ent) + entlen);
270 if (*last != '/' && relative_base) {
271 memcpy(ent->base, relative_base, base_len - 1);
272 ent->base[base_len - 1] = '/';
273 memcpy(ent->base + base_len,
277 memcpy(ent->base, last, pfxlen);
279 ent->name = ent->base + pfxlen + 1;
280 ent->base[pfxlen + 3] = '/';
281 ent->base[pfxlen] = ent->base[entlen-1] = 0;
283 /* Detect cases where alternate disappeared */
284 if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
285 error("object directory %s does not exist; "
286 "check .git/objects/info/alternates.",
290 ent->base[pfxlen] = '/';
292 /* Prevent the common mistake of listing the same
293 * thing twice, or object directory itself.
295 for (alt = alt_odb_list; alt; alt = alt->next)
296 if (!memcmp(ent->base, alt->base, pfxlen))
298 if (!memcmp(ent->base, objdir, pfxlen)) {
304 alt_odb_tail = &(ent->next);
308 while (cp < ep && *cp == sep)
314 void prepare_alt_odb(void)
322 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
327 alt_odb_tail = &alt_odb_list;
328 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL);
330 sprintf(path, "%s/info/alternates", get_object_directory());
331 fd = open(path, O_RDONLY);
334 if (fstat(fd, &st) || (st.st_size == 0)) {
338 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
340 if (map == MAP_FAILED)
343 link_alt_odb_entries(map, map + st.st_size, '\n',
344 get_object_directory());
345 munmap(map, st.st_size);
348 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
350 char *name = sha1_file_name(sha1);
351 struct alternate_object_database *alt;
356 for (alt = alt_odb_list; alt; alt = alt->next) {
358 fill_sha1_path(name, sha1);
359 if (!stat(alt->base, st))
365 #define PACK_MAX_SZ (1<<26)
366 static int pack_used_ctr;
367 static unsigned long pack_mapped;
368 struct packed_git *packed_git;
370 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
375 unsigned long idx_size;
377 int fd = open(path, O_RDONLY);
381 if (fstat(fd, &st)) {
385 idx_size = st.st_size;
386 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
388 if (idx_map == MAP_FAILED)
393 *idx_size_ = idx_size;
395 /* check index map */
396 if (idx_size < 4*256 + 20 + 20)
397 return error("index file too small");
399 for (i = 0; i < 256; i++) {
400 unsigned int n = ntohl(index[i]);
402 return error("non-monotonic index");
408 * - 256 index entries 4 bytes each
409 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
410 * - 20-byte SHA1 of the packfile
411 * - 20-byte SHA1 file checksum
413 if (idx_size != 4*256 + nr * 24 + 20 + 20)
414 return error("wrong index file size");
419 static int unuse_one_packed_git(void)
421 struct packed_git *p, *lru = NULL;
423 for (p = packed_git; p; p = p->next) {
424 if (p->pack_use_cnt || !p->pack_base)
426 if (!lru || p->pack_last_used < lru->pack_last_used)
431 munmap(lru->pack_base, lru->pack_size);
432 lru->pack_base = NULL;
436 void unuse_packed_git(struct packed_git *p)
441 int use_packed_git(struct packed_git *p)
445 // We created the struct before we had the pack
446 stat(p->pack_name, &st);
447 if (!S_ISREG(st.st_mode))
448 die("packfile %s not a regular file", p->pack_name);
449 p->pack_size = st.st_size;
456 pack_mapped += p->pack_size;
457 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
459 fd = open(p->pack_name, O_RDONLY);
461 die("packfile %s cannot be opened", p->pack_name);
462 if (fstat(fd, &st)) {
464 die("packfile %s cannot be opened", p->pack_name);
466 if (st.st_size != p->pack_size)
467 die("packfile %s size mismatch.", p->pack_name);
468 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
470 if (map == MAP_FAILED)
471 die("packfile %s cannot be mapped.", p->pack_name);
474 /* Check if the pack file matches with the index file.
477 if (memcmp((char*)(p->index_base) + p->index_size - 40,
478 p->pack_base + p->pack_size - 20, 20)) {
480 die("packfile %s does not match index.", p->pack_name);
483 p->pack_last_used = pack_used_ctr++;
488 struct packed_git *add_packed_git(char *path, int path_len, int local)
491 struct packed_git *p;
492 unsigned long idx_size;
494 unsigned char sha1[20];
496 if (check_packed_git_idx(path, &idx_size, &idx_map))
499 /* do we have a corresponding .pack file? */
500 strcpy(path + path_len - 4, ".pack");
501 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
502 munmap(idx_map, idx_size);
505 /* ok, it looks sane as far as we can check without
506 * actually mapping the pack file.
508 p = xmalloc(sizeof(*p) + path_len + 2);
509 strcpy(p->pack_name, path);
510 p->index_size = idx_size;
511 p->pack_size = st.st_size;
512 p->index_base = idx_map;
515 p->pack_last_used = 0;
517 p->pack_local = local;
518 if ((path_len > 44) && !get_sha1_hex(path + path_len - 44, sha1))
519 memcpy(p->sha1, sha1, 20);
523 struct packed_git *parse_pack_index(unsigned char *sha1)
525 char *path = sha1_pack_index_name(sha1);
526 return parse_pack_index_file(sha1, path);
529 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
531 struct packed_git *p;
532 unsigned long idx_size;
536 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
539 path = sha1_pack_name(sha1);
541 p = xmalloc(sizeof(*p) + strlen(path) + 2);
542 strcpy(p->pack_name, path);
543 p->index_size = idx_size;
545 p->index_base = idx_map;
548 p->pack_last_used = 0;
550 memcpy(p->sha1, sha1, 20);
554 void install_packed_git(struct packed_git *pack)
556 pack->next = packed_git;
560 static void prepare_packed_git_one(char *objdir, int local)
567 sprintf(path, "%s/pack", objdir);
572 error("unable to open object pack directory: %s: %s",
573 path, strerror(errno));
577 while ((de = readdir(dir)) != NULL) {
578 int namelen = strlen(de->d_name);
579 struct packed_git *p;
581 if (strcmp(de->d_name + namelen - 4, ".idx"))
584 /* we have .idx. Is it a file we can map? */
585 strcpy(path + len, de->d_name);
586 p = add_packed_git(path, len + namelen, local);
589 p->next = packed_git;
595 void prepare_packed_git(void)
597 static int run_once = 0;
598 struct alternate_object_database *alt;
602 prepare_packed_git_one(get_object_directory(), 1);
604 for (alt = alt_odb_list; alt; alt = alt->next) {
606 prepare_packed_git_one(alt->base, 0);
612 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
615 unsigned char real_sha1[20];
619 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
620 SHA1_Update(&c, map, size);
621 SHA1_Final(real_sha1, &c);
622 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
625 static void *map_sha1_file_internal(const unsigned char *sha1,
631 char *filename = find_sha1_file(sha1, &st);
637 fd = open(filename, O_RDONLY | sha1_file_open_flag);
639 /* See if it works without O_NOATIME */
640 switch (sha1_file_open_flag) {
642 fd = open(filename, O_RDONLY);
650 /* If it failed once, it will probably fail again.
651 * Stop using O_NOATIME
653 sha1_file_open_flag = 0;
655 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
657 if (map == MAP_FAILED)
663 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
665 /* Get the data stream */
666 memset(stream, 0, sizeof(*stream));
667 stream->next_in = map;
668 stream->avail_in = mapsize;
669 stream->next_out = buffer;
670 stream->avail_out = size;
673 return inflate(stream, 0);
676 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
678 int bytes = strlen(buffer) + 1;
679 unsigned char *buf = xmalloc(1+size);
681 memcpy(buf, buffer + bytes, stream->total_out - bytes);
682 bytes = stream->total_out - bytes;
684 stream->next_out = buf + bytes;
685 stream->avail_out = size - bytes;
686 while (inflate(stream, Z_FINISH) == Z_OK)
695 * We used to just use "sscanf()", but that's actually way
696 * too permissive for what we want to check. So do an anal
697 * object header parse by hand.
699 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
705 * The type can be at most ten bytes (including the
706 * terminating '\0' that we add), and is followed by
721 * The length must follow immediately, and be in canonical
722 * decimal format (ie "010" is not valid).
729 unsigned long c = *hdr - '0';
733 size = size * 10 + c;
739 * The length must be followed by a zero byte
741 return *hdr ? -1 : 0;
744 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
750 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
751 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
754 return unpack_sha1_rest(&stream, hdr, *size);
757 /* forward declaration for a mutually recursive function */
758 static int packed_object_info(struct pack_entry *entry,
759 char *type, unsigned long *sizep);
761 static int packed_delta_info(unsigned char *base_sha1,
762 unsigned long delta_size,
765 unsigned long *sizep,
766 struct packed_git *p)
768 struct pack_entry base_ent;
771 die("truncated pack file");
773 /* The base entry _must_ be in the same pack */
774 if (!find_pack_entry_one(base_sha1, &base_ent, p))
775 die("failed to find delta-pack base object %s",
776 sha1_to_hex(base_sha1));
778 /* We choose to only get the type of the base object and
779 * ignore potentially corrupt pack file that expects the delta
780 * based on a base with a wrong size. This saves tons of
784 if (packed_object_info(&base_ent, type, NULL))
785 die("cannot get info for delta-pack base");
788 const unsigned char *data;
789 unsigned char delta_head[64];
790 unsigned long result_size;
794 memset(&stream, 0, sizeof(stream));
796 data = stream.next_in = base_sha1 + 20;
797 stream.avail_in = left - 20;
798 stream.next_out = delta_head;
799 stream.avail_out = sizeof(delta_head);
801 inflateInit(&stream);
802 st = inflate(&stream, Z_FINISH);
804 if ((st != Z_STREAM_END) &&
805 stream.total_out != sizeof(delta_head))
806 die("delta data unpack-initial failed");
808 /* Examine the initial part of the delta to figure out
813 /* ignore base size */
814 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
816 /* Read the result size */
817 result_size = get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
818 *sizep = result_size;
823 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
824 enum object_type *type, unsigned long *sizep)
827 unsigned char *pack, c;
830 if (offset >= p->pack_size)
831 die("object offset outside of pack file");
833 pack = p->pack_base + offset;
836 *type = (c >> 4) & 7;
840 if (offset >= p->pack_size)
841 die("object offset outside of pack file");
844 size += (c & 0x7f) << shift;
851 int check_reuse_pack_delta(struct packed_git *p, unsigned long offset,
852 unsigned char *base, unsigned long *sizep,
853 enum object_type *kindp)
860 ptr = unpack_object_header(p, ptr, kindp, sizep);
861 if (*kindp != OBJ_DELTA)
863 memcpy(base, p->pack_base + ptr, 20);
870 void packed_object_info_detail(struct pack_entry *e,
873 unsigned long *store_size,
874 unsigned int *delta_chain_length,
875 unsigned char *base_sha1)
877 struct packed_git *p = e->p;
878 unsigned long offset;
880 enum object_type kind;
882 offset = unpack_object_header(p, e->offset, &kind, size);
883 pack = p->pack_base + offset;
884 if (kind != OBJ_DELTA)
885 *delta_chain_length = 0;
887 unsigned int chain_length = 0;
888 if (p->pack_size <= offset + 20)
889 die("pack file %s records an incomplete delta base",
891 memcpy(base_sha1, pack, 20);
893 struct pack_entry base_ent;
896 find_pack_entry_one(pack, &base_ent, p);
897 offset = unpack_object_header(p, base_ent.offset,
899 pack = p->pack_base + offset;
901 } while (kind == OBJ_DELTA);
902 *delta_chain_length = chain_length;
906 strcpy(type, commit_type);
909 strcpy(type, tree_type);
912 strcpy(type, blob_type);
915 strcpy(type, tag_type);
918 die("corrupted pack file %s containing object of kind %d",
921 *store_size = 0; /* notyet */
924 static int packed_object_info(struct pack_entry *entry,
925 char *type, unsigned long *sizep)
927 struct packed_git *p = entry->p;
928 unsigned long offset, size, left;
930 enum object_type kind;
933 if (use_packed_git(p))
934 die("cannot map packed file");
936 offset = unpack_object_header(p, entry->offset, &kind, &size);
937 pack = p->pack_base + offset;
938 left = p->pack_size - offset;
942 retval = packed_delta_info(pack, size, left, type, sizep, p);
946 strcpy(type, commit_type);
949 strcpy(type, tree_type);
952 strcpy(type, blob_type);
955 strcpy(type, tag_type);
958 die("corrupted pack file %s containing object of kind %d",
967 /* forward declaration for a mutually recursive function */
968 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
970 static void *unpack_delta_entry(unsigned char *base_sha1,
971 unsigned long delta_size,
974 unsigned long *sizep,
975 struct packed_git *p)
977 struct pack_entry base_ent;
978 void *data, *delta_data, *result, *base;
979 unsigned long data_size, result_size, base_size;
984 die("truncated pack file");
986 /* The base entry _must_ be in the same pack */
987 if (!find_pack_entry_one(base_sha1, &base_ent, p))
988 die("failed to find delta-pack base object %s",
989 sha1_to_hex(base_sha1));
990 base = unpack_entry_gently(&base_ent, type, &base_size);
992 die("failed to read delta-pack base object %s",
993 sha1_to_hex(base_sha1));
995 data = base_sha1 + 20;
996 data_size = left - 20;
997 delta_data = xmalloc(delta_size);
999 memset(&stream, 0, sizeof(stream));
1001 stream.next_in = data;
1002 stream.avail_in = data_size;
1003 stream.next_out = delta_data;
1004 stream.avail_out = delta_size;
1006 inflateInit(&stream);
1007 st = inflate(&stream, Z_FINISH);
1008 inflateEnd(&stream);
1009 if ((st != Z_STREAM_END) || stream.total_out != delta_size)
1010 die("delta data unpack failed");
1012 result = patch_delta(base, base_size,
1013 delta_data, delta_size,
1016 die("failed to apply delta");
1019 *sizep = result_size;
1023 static void *unpack_non_delta_entry(unsigned char *data,
1029 unsigned char *buffer;
1031 buffer = xmalloc(size + 1);
1033 memset(&stream, 0, sizeof(stream));
1034 stream.next_in = data;
1035 stream.avail_in = left;
1036 stream.next_out = buffer;
1037 stream.avail_out = size;
1039 inflateInit(&stream);
1040 st = inflate(&stream, Z_FINISH);
1041 inflateEnd(&stream);
1042 if ((st != Z_STREAM_END) || stream.total_out != size) {
1050 static void *unpack_entry(struct pack_entry *entry,
1051 char *type, unsigned long *sizep)
1053 struct packed_git *p = entry->p;
1056 if (use_packed_git(p))
1057 die("cannot map packed file");
1058 retval = unpack_entry_gently(entry, type, sizep);
1059 unuse_packed_git(p);
1061 die("corrupted pack file %s", p->pack_name);
1065 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
1066 void *unpack_entry_gently(struct pack_entry *entry,
1067 char *type, unsigned long *sizep)
1069 struct packed_git *p = entry->p;
1070 unsigned long offset, size, left;
1071 unsigned char *pack;
1072 enum object_type kind;
1075 offset = unpack_object_header(p, entry->offset, &kind, &size);
1076 pack = p->pack_base + offset;
1077 left = p->pack_size - offset;
1080 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
1083 strcpy(type, commit_type);
1086 strcpy(type, tree_type);
1089 strcpy(type, blob_type);
1092 strcpy(type, tag_type);
1098 retval = unpack_non_delta_entry(pack, size, left);
1102 int num_packed_objects(const struct packed_git *p)
1104 /* See check_packed_git_idx() */
1105 return (p->index_size - 20 - 20 - 4*256) / 24;
1108 int nth_packed_object_sha1(const struct packed_git *p, int n,
1109 unsigned char* sha1)
1111 void *index = p->index_base + 256;
1112 if (n < 0 || num_packed_objects(p) <= n)
1114 memcpy(sha1, (index + 24 * n + 4), 20);
1118 int find_pack_entry_one(const unsigned char *sha1,
1119 struct pack_entry *e, struct packed_git *p)
1121 unsigned int *level1_ofs = p->index_base;
1122 int hi = ntohl(level1_ofs[*sha1]);
1123 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1124 void *index = p->index_base + 256;
1127 int mi = (lo + hi) / 2;
1128 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
1130 e->offset = ntohl(*((int*)(index + 24 * mi)));
1131 memcpy(e->sha1, sha1, 20);
1143 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1145 struct packed_git *p;
1146 prepare_packed_git();
1148 for (p = packed_git; p; p = p->next) {
1149 if (find_pack_entry_one(sha1, e, p))
1155 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1156 struct packed_git *packs)
1158 struct packed_git *p;
1159 struct pack_entry e;
1161 for (p = packs; p; p = p->next) {
1162 if (find_pack_entry_one(sha1, &e, p))
1169 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1172 unsigned long mapsize, size;
1177 map = map_sha1_file_internal(sha1, &mapsize);
1179 struct pack_entry e;
1181 if (!find_pack_entry(sha1, &e))
1182 return error("unable to find %s", sha1_to_hex(sha1));
1183 return packed_object_info(&e, type, sizep);
1185 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1186 status = error("unable to unpack %s header",
1188 if (parse_sha1_header(hdr, type, &size) < 0)
1189 status = error("unable to parse %s header", sha1_to_hex(sha1));
1195 inflateEnd(&stream);
1196 munmap(map, mapsize);
1200 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1202 struct pack_entry e;
1204 if (!find_pack_entry(sha1, &e)) {
1205 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1208 return unpack_entry(&e, type, size);
1211 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1213 unsigned long mapsize;
1215 struct pack_entry e;
1217 if (find_pack_entry(sha1, &e))
1218 return read_packed_sha1(sha1, type, size);
1219 map = map_sha1_file_internal(sha1, &mapsize);
1221 buf = unpack_sha1_file(map, mapsize, type, size);
1222 munmap(map, mapsize);
1228 void *read_object_with_reference(const unsigned char *sha1,
1229 const char *required_type,
1230 unsigned long *size,
1231 unsigned char *actual_sha1_return)
1235 unsigned long isize;
1236 unsigned char actual_sha1[20];
1238 memcpy(actual_sha1, sha1, 20);
1240 int ref_length = -1;
1241 const char *ref_type = NULL;
1243 buffer = read_sha1_file(actual_sha1, type, &isize);
1246 if (!strcmp(type, required_type)) {
1248 if (actual_sha1_return)
1249 memcpy(actual_sha1_return, actual_sha1, 20);
1252 /* Handle references */
1253 else if (!strcmp(type, commit_type))
1255 else if (!strcmp(type, tag_type))
1256 ref_type = "object ";
1261 ref_length = strlen(ref_type);
1263 if (memcmp(buffer, ref_type, ref_length) ||
1264 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1269 /* Now we have the ID of the referred-to object in
1270 * actual_sha1. Check again. */
1274 char *write_sha1_file_prepare(void *buf,
1277 unsigned char *sha1,
1283 /* Generate the header */
1284 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1288 SHA1_Update(&c, hdr, *hdrlen);
1289 SHA1_Update(&c, buf, len);
1290 SHA1_Final(sha1, &c);
1292 return sha1_file_name(sha1);
1296 * Link the tempfile to the final place, possibly creating the
1297 * last directory level as you do so.
1299 * Returns the errno on failure, 0 on success.
1301 static int link_temp_to_file(const char *tmpfile, char *filename)
1305 if (!link(tmpfile, filename))
1309 * Try to mkdir the last path component if that failed
1312 * Re-try the "link()" regardless of whether the mkdir
1313 * succeeds, since a race might mean that somebody
1317 if (ret == ENOENT) {
1318 char *dir = strrchr(filename, '/');
1321 mkdir(filename, 0777);
1322 if (adjust_shared_perm(filename))
1325 if (!link(tmpfile, filename))
1334 * Move the just written object into its final resting place
1336 int move_temp_to_file(const char *tmpfile, char *filename)
1338 int ret = link_temp_to_file(tmpfile, filename);
1341 * Coda hack - coda doesn't like cross-directory links,
1342 * so we fall back to a rename, which will mean that it
1343 * won't be able to check collisions, but that's not a
1346 * The same holds for FAT formatted media.
1348 * When this succeeds, we just return 0. We have nothing
1351 if (ret && ret != EEXIST) {
1352 if (!rename(tmpfile, filename))
1358 if (ret != EEXIST) {
1359 fprintf(stderr, "unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1362 /* FIXME!!! Collision check here ? */
1368 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1371 unsigned char *compressed;
1373 unsigned char sha1[20];
1375 static char tmpfile[PATH_MAX];
1376 unsigned char hdr[50];
1379 /* Normally if we have it in the pack then we do not bother writing
1380 * it out into .git/objects/??/?{38} file.
1382 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1384 memcpy(returnsha1, sha1, 20);
1385 if (has_sha1_file(sha1))
1387 fd = open(filename, O_RDONLY);
1390 * FIXME!!! We might do collision checking here, but we'd
1391 * need to uncompress the old file and check it. Later.
1397 if (errno != ENOENT) {
1398 fprintf(stderr, "sha1 file %s: %s\n", filename, strerror(errno));
1402 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1404 fd = mkstemp(tmpfile);
1406 fprintf(stderr, "unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
1411 memset(&stream, 0, sizeof(stream));
1412 deflateInit(&stream, Z_BEST_COMPRESSION);
1413 size = deflateBound(&stream, len+hdrlen);
1414 compressed = xmalloc(size);
1417 stream.next_out = compressed;
1418 stream.avail_out = size;
1420 /* First header.. */
1421 stream.next_in = hdr;
1422 stream.avail_in = hdrlen;
1423 while (deflate(&stream, 0) == Z_OK)
1426 /* Then the data itself.. */
1427 stream.next_in = buf;
1428 stream.avail_in = len;
1429 while (deflate(&stream, Z_FINISH) == Z_OK)
1431 deflateEnd(&stream);
1432 size = stream.total_out;
1434 if (write(fd, compressed, size) != size)
1435 die("unable to write file");
1440 return move_temp_to_file(tmpfile, filename);
1443 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1446 unsigned long objsize;
1448 void *map = map_sha1_file_internal(sha1, &objsize);
1450 void *temp_obj = NULL;
1454 unsigned char *unpacked;
1459 // need to unpack and recompress it by itself
1460 unpacked = read_packed_sha1(sha1, type, &len);
1462 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1465 memset(&stream, 0, sizeof(stream));
1466 deflateInit(&stream, Z_BEST_COMPRESSION);
1467 size = deflateBound(&stream, len + hdrlen);
1468 temp_obj = buf = xmalloc(size);
1471 stream.next_out = buf;
1472 stream.avail_out = size;
1474 /* First header.. */
1475 stream.next_in = (void *)hdr;
1476 stream.avail_in = hdrlen;
1477 while (deflate(&stream, 0) == Z_OK)
1480 /* Then the data itself.. */
1481 stream.next_in = unpacked;
1482 stream.avail_in = len;
1483 while (deflate(&stream, Z_FINISH) == Z_OK)
1485 deflateEnd(&stream);
1488 objsize = stream.total_out;
1492 size = write(fd, buf + posn, objsize - posn);
1495 fprintf(stderr, "write closed\n");
1502 } while (posn < objsize);
1505 munmap(map, objsize);
1512 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1513 size_t bufsize, size_t *bufposn)
1515 char tmpfile[PATH_MAX];
1518 unsigned char real_sha1[20];
1519 unsigned char discard[4096];
1523 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1525 local = mkstemp(tmpfile);
1527 return error("Couldn't open %s for %s",
1528 tmpfile, sha1_to_hex(sha1));
1530 memset(&stream, 0, sizeof(stream));
1532 inflateInit(&stream);
1539 stream.avail_in = *bufposn;
1540 stream.next_in = (unsigned char *) buffer;
1542 stream.next_out = discard;
1543 stream.avail_out = sizeof(discard);
1544 ret = inflate(&stream, Z_SYNC_FLUSH);
1545 SHA1_Update(&c, discard, sizeof(discard) -
1547 } while (stream.avail_in && ret == Z_OK);
1548 write(local, buffer, *bufposn - stream.avail_in);
1549 memmove(buffer, buffer + *bufposn - stream.avail_in,
1551 *bufposn = stream.avail_in;
1555 size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1560 return error("Connection closed?");
1561 perror("Reading from connection");
1566 inflateEnd(&stream);
1569 SHA1_Final(real_sha1, &c);
1570 if (ret != Z_STREAM_END) {
1572 return error("File %s corrupted", sha1_to_hex(sha1));
1574 if (memcmp(sha1, real_sha1, 20)) {
1576 return error("File %s has bad hash", sha1_to_hex(sha1));
1579 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1582 int has_pack_index(const unsigned char *sha1)
1585 if (stat(sha1_pack_index_name(sha1), &st))
1590 int has_pack_file(const unsigned char *sha1)
1593 if (stat(sha1_pack_name(sha1), &st))
1598 int has_sha1_pack(const unsigned char *sha1)
1600 struct pack_entry e;
1601 return find_pack_entry(sha1, &e);
1604 int has_sha1_file(const unsigned char *sha1)
1607 struct pack_entry e;
1609 if (find_pack_entry(sha1, &e))
1611 return find_sha1_file(sha1, &st) ? 1 : 0;
1614 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
1616 unsigned long size = 4096;
1617 char *buf = malloc(size);
1619 unsigned long off = 0;
1620 unsigned char hdr[50];
1623 iret = read(fd, buf + off, size - off);
1628 buf = realloc(buf, size);
1639 ret = write_sha1_file(buf, off, type, sha1);
1641 write_sha1_file_prepare(buf, off, type, sha1, hdr, &hdrlen);
1648 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1650 unsigned long size = st->st_size;
1653 unsigned char hdr[50];
1658 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1660 if (buf == MAP_FAILED)
1666 ret = write_sha1_file(buf, size, type, sha1);
1668 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1676 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1681 switch (st->st_mode & S_IFMT) {
1683 fd = open(path, O_RDONLY);
1685 return error("open(\"%s\"): %s", path,
1687 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1688 return error("%s: failed to insert into database",
1692 target = xmalloc(st->st_size+1);
1693 if (readlink(path, target, st->st_size+1) != st->st_size) {
1694 char *errstr = strerror(errno);
1696 return error("readlink(\"%s\"): %s", path,
1699 if (!write_object) {
1700 unsigned char hdr[50];
1702 write_sha1_file_prepare(target, st->st_size, blob_type,
1703 sha1, hdr, &hdrlen);
1704 } else if (write_sha1_file(target, st->st_size, blob_type, sha1))
1705 return error("%s: failed to insert into database",
1710 return error("%s: unsupported file type", path);