diff-delta: produce optimal pack data
[git.git] / sha1_file.c
blob9cab99ae7c2b1e59db7be26d79d287254db21211
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
7 * creation etc.
8 */
9 #include "cache.h"
10 #include "delta.h"
11 #include "pack.h"
13 #ifndef O_NOATIME
14 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
15 #define O_NOATIME 01000000
16 #else
17 #define O_NOATIME 0
18 #endif
19 #endif
21 const unsigned char null_sha1[20] = { 0, };
23 static unsigned int sha1_file_open_flag = O_NOATIME;
25 static unsigned hexval(char c)
27 if (c >= '0' && c <= '9')
28 return c - '0';
29 if (c >= 'a' && c <= 'f')
30 return c - 'a' + 10;
31 if (c >= 'A' && c <= 'F')
32 return c - 'A' + 10;
33 return ~0;
36 int get_sha1_hex(const char *hex, unsigned char *sha1)
38 int i;
39 for (i = 0; i < 20; i++) {
40 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
41 if (val & ~0xff)
42 return -1;
43 *sha1++ = val;
44 hex += 2;
46 return 0;
49 int adjust_shared_perm(const char *path)
51 struct stat st;
52 int mode;
54 if (!shared_repository)
55 return 0;
56 if (lstat(path, &st) < 0)
57 return -1;
58 mode = st.st_mode;
59 if (mode & S_IRUSR)
60 mode |= S_IRGRP;
61 if (mode & S_IWUSR)
62 mode |= S_IWGRP;
63 if (mode & S_IXUSR)
64 mode |= S_IXGRP;
65 if (S_ISDIR(mode))
66 mode |= S_ISGID;
67 if (chmod(path, mode) < 0)
68 return -2;
69 return 0;
72 int safe_create_leading_directories(char *path)
74 char *pos = path;
75 struct stat st;
77 if (*pos == '/')
78 pos++;
80 while (pos) {
81 pos = strchr(pos, '/');
82 if (!pos)
83 break;
84 *pos = 0;
85 if (!stat(path, &st)) {
86 /* path exists */
87 if (!S_ISDIR(st.st_mode)) {
88 *pos = '/';
89 return -3;
92 else if (mkdir(path, 0777)) {
93 *pos = '/';
94 return -1;
96 else if (adjust_shared_perm(path)) {
97 *pos = '/';
98 return -2;
100 *pos++ = '/';
102 return 0;
105 char * sha1_to_hex(const unsigned char *sha1)
107 static char buffer[50];
108 static const char hex[] = "0123456789abcdef";
109 char *buf = buffer;
110 int i;
112 for (i = 0; i < 20; i++) {
113 unsigned int val = *sha1++;
114 *buf++ = hex[val >> 4];
115 *buf++ = hex[val & 0xf];
117 *buf = '\0';
119 return buffer;
122 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
124 int i;
125 for (i = 0; i < 20; i++) {
126 static char hex[] = "0123456789abcdef";
127 unsigned int val = sha1[i];
128 char *pos = pathbuf + i*2 + (i > 0);
129 *pos++ = hex[val >> 4];
130 *pos = hex[val & 0xf];
135 * NOTE! This returns a statically allocated buffer, so you have to be
136 * careful about using it. Do a "strdup()" if you need to save the
137 * filename.
139 * Also note that this returns the location for creating. Reading
140 * SHA1 file can happen from any alternate directory listed in the
141 * DB_ENVIRONMENT environment variable if it is not found in
142 * the primary object database.
144 char *sha1_file_name(const unsigned char *sha1)
146 static char *name, *base;
148 if (!base) {
149 const char *sha1_file_directory = get_object_directory();
150 int len = strlen(sha1_file_directory);
151 base = xmalloc(len + 60);
152 memcpy(base, sha1_file_directory, len);
153 memset(base+len, 0, 60);
154 base[len] = '/';
155 base[len+3] = '/';
156 name = base + len + 1;
158 fill_sha1_path(name, sha1);
159 return base;
162 char *sha1_pack_name(const unsigned char *sha1)
164 static const char hex[] = "0123456789abcdef";
165 static char *name, *base, *buf;
166 int i;
168 if (!base) {
169 const char *sha1_file_directory = get_object_directory();
170 int len = strlen(sha1_file_directory);
171 base = xmalloc(len + 60);
172 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
173 name = base + len + 11;
176 buf = name;
178 for (i = 0; i < 20; i++) {
179 unsigned int val = *sha1++;
180 *buf++ = hex[val >> 4];
181 *buf++ = hex[val & 0xf];
184 return base;
187 char *sha1_pack_index_name(const unsigned char *sha1)
189 static const char hex[] = "0123456789abcdef";
190 static char *name, *base, *buf;
191 int i;
193 if (!base) {
194 const char *sha1_file_directory = get_object_directory();
195 int len = strlen(sha1_file_directory);
196 base = xmalloc(len + 60);
197 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
198 name = base + len + 11;
201 buf = name;
203 for (i = 0; i < 20; i++) {
204 unsigned int val = *sha1++;
205 *buf++ = hex[val >> 4];
206 *buf++ = hex[val & 0xf];
209 return base;
212 struct alternate_object_database *alt_odb_list;
213 static struct alternate_object_database **alt_odb_tail;
216 * Prepare alternate object database registry.
218 * The variable alt_odb_list points at the list of struct
219 * alternate_object_database. The elements on this list come from
220 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
221 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
222 * whose contents is similar to that environment variable but can be
223 * LF separated. Its base points at a statically allocated buffer that
224 * contains "/the/directory/corresponding/to/.git/objects/...", while
225 * its name points just after the slash at the end of ".git/objects/"
226 * in the example above, and has enough space to hold 40-byte hex
227 * SHA1, an extra slash for the first level indirection, and the
228 * terminating NUL.
230 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
231 const char *relative_base)
233 const char *cp, *last;
234 struct alternate_object_database *ent;
235 const char *objdir = get_object_directory();
236 int base_len = -1;
238 last = alt;
239 while (last < ep) {
240 cp = last;
241 if (cp < ep && *cp == '#') {
242 while (cp < ep && *cp != sep)
243 cp++;
244 last = cp + 1;
245 continue;
247 for ( ; cp < ep && *cp != sep; cp++)
249 if (last != cp) {
250 struct alternate_object_database *alt;
251 /* 43 = 40-byte + 2 '/' + terminating NUL */
252 int pfxlen = cp - last;
253 int entlen = pfxlen + 43;
255 if (*last != '/' && relative_base) {
256 /* Relative alt-odb */
257 if (base_len < 0)
258 base_len = strlen(relative_base) + 1;
259 entlen += base_len;
260 pfxlen += base_len;
262 ent = xmalloc(sizeof(*ent) + entlen);
264 if (*last != '/' && relative_base) {
265 memcpy(ent->base, relative_base, base_len - 1);
266 ent->base[base_len - 1] = '/';
267 memcpy(ent->base + base_len,
268 last, cp - last);
270 else
271 memcpy(ent->base, last, pfxlen);
272 ent->name = ent->base + pfxlen + 1;
273 ent->base[pfxlen] = ent->base[pfxlen + 3] = '/';
274 ent->base[entlen-1] = 0;
276 /* Prevent the common mistake of listing the same
277 * thing twice, or object directory itself.
279 for (alt = alt_odb_list; alt; alt = alt->next)
280 if (!memcmp(ent->base, alt->base, pfxlen))
281 goto bad;
282 if (!memcmp(ent->base, objdir, pfxlen)) {
283 bad:
284 free(ent);
286 else {
287 *alt_odb_tail = ent;
288 alt_odb_tail = &(ent->next);
289 ent->next = NULL;
292 while (cp < ep && *cp == sep)
293 cp++;
294 last = cp;
298 void prepare_alt_odb(void)
300 char path[PATH_MAX];
301 char *map;
302 int fd;
303 struct stat st;
304 char *alt;
306 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
307 if (!alt) alt = "";
309 if (alt_odb_tail)
310 return;
311 alt_odb_tail = &alt_odb_list;
312 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL);
314 sprintf(path, "%s/info/alternates", get_object_directory());
315 fd = open(path, O_RDONLY);
316 if (fd < 0)
317 return;
318 if (fstat(fd, &st) || (st.st_size == 0)) {
319 close(fd);
320 return;
322 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
323 close(fd);
324 if (map == MAP_FAILED)
325 return;
327 link_alt_odb_entries(map, map + st.st_size, '\n',
328 get_object_directory());
329 munmap(map, st.st_size);
332 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
334 char *name = sha1_file_name(sha1);
335 struct alternate_object_database *alt;
337 if (!stat(name, st))
338 return name;
339 prepare_alt_odb();
340 for (alt = alt_odb_list; alt; alt = alt->next) {
341 name = alt->name;
342 fill_sha1_path(name, sha1);
343 if (!stat(alt->base, st))
344 return alt->base;
346 return NULL;
349 #define PACK_MAX_SZ (1<<26)
350 static int pack_used_ctr;
351 static unsigned long pack_mapped;
352 struct packed_git *packed_git;
354 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
355 void **idx_map_)
357 void *idx_map;
358 unsigned int *index;
359 unsigned long idx_size;
360 int nr, i;
361 int fd = open(path, O_RDONLY);
362 struct stat st;
363 if (fd < 0)
364 return -1;
365 if (fstat(fd, &st)) {
366 close(fd);
367 return -1;
369 idx_size = st.st_size;
370 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
371 close(fd);
372 if (idx_map == MAP_FAILED)
373 return -1;
375 index = idx_map;
376 *idx_map_ = idx_map;
377 *idx_size_ = idx_size;
379 /* check index map */
380 if (idx_size < 4*256 + 20 + 20)
381 return error("index file too small");
382 nr = 0;
383 for (i = 0; i < 256; i++) {
384 unsigned int n = ntohl(index[i]);
385 if (n < nr)
386 return error("non-monotonic index");
387 nr = n;
391 * Total size:
392 * - 256 index entries 4 bytes each
393 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
394 * - 20-byte SHA1 of the packfile
395 * - 20-byte SHA1 file checksum
397 if (idx_size != 4*256 + nr * 24 + 20 + 20)
398 return error("wrong index file size");
400 return 0;
403 static int unuse_one_packed_git(void)
405 struct packed_git *p, *lru = NULL;
407 for (p = packed_git; p; p = p->next) {
408 if (p->pack_use_cnt || !p->pack_base)
409 continue;
410 if (!lru || p->pack_last_used < lru->pack_last_used)
411 lru = p;
413 if (!lru)
414 return 0;
415 munmap(lru->pack_base, lru->pack_size);
416 lru->pack_base = NULL;
417 return 1;
420 void unuse_packed_git(struct packed_git *p)
422 p->pack_use_cnt--;
425 int use_packed_git(struct packed_git *p)
427 if (!p->pack_size) {
428 struct stat st;
429 // We created the struct before we had the pack
430 stat(p->pack_name, &st);
431 if (!S_ISREG(st.st_mode))
432 die("packfile %s not a regular file", p->pack_name);
433 p->pack_size = st.st_size;
435 if (!p->pack_base) {
436 int fd;
437 struct stat st;
438 void *map;
440 pack_mapped += p->pack_size;
441 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
442 ; /* nothing */
443 fd = open(p->pack_name, O_RDONLY);
444 if (fd < 0)
445 die("packfile %s cannot be opened", p->pack_name);
446 if (fstat(fd, &st)) {
447 close(fd);
448 die("packfile %s cannot be opened", p->pack_name);
450 if (st.st_size != p->pack_size)
451 die("packfile %s size mismatch.", p->pack_name);
452 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
453 close(fd);
454 if (map == MAP_FAILED)
455 die("packfile %s cannot be mapped.", p->pack_name);
456 p->pack_base = map;
458 /* Check if the pack file matches with the index file.
459 * this is cheap.
461 if (memcmp((char*)(p->index_base) + p->index_size - 40,
462 p->pack_base + p->pack_size - 20, 20)) {
464 die("packfile %s does not match index.", p->pack_name);
467 p->pack_last_used = pack_used_ctr++;
468 p->pack_use_cnt++;
469 return 0;
472 struct packed_git *add_packed_git(char *path, int path_len, int local)
474 struct stat st;
475 struct packed_git *p;
476 unsigned long idx_size;
477 void *idx_map;
478 unsigned char sha1[20];
480 if (check_packed_git_idx(path, &idx_size, &idx_map))
481 return NULL;
483 /* do we have a corresponding .pack file? */
484 strcpy(path + path_len - 4, ".pack");
485 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
486 munmap(idx_map, idx_size);
487 return NULL;
489 /* ok, it looks sane as far as we can check without
490 * actually mapping the pack file.
492 p = xmalloc(sizeof(*p) + path_len + 2);
493 strcpy(p->pack_name, path);
494 p->index_size = idx_size;
495 p->pack_size = st.st_size;
496 p->index_base = idx_map;
497 p->next = NULL;
498 p->pack_base = NULL;
499 p->pack_last_used = 0;
500 p->pack_use_cnt = 0;
501 p->pack_local = local;
502 if ((path_len > 44) && !get_sha1_hex(path + path_len - 44, sha1))
503 memcpy(p->sha1, sha1, 20);
504 return p;
507 struct packed_git *parse_pack_index(unsigned char *sha1)
509 char *path = sha1_pack_index_name(sha1);
510 return parse_pack_index_file(sha1, path);
513 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
515 struct packed_git *p;
516 unsigned long idx_size;
517 void *idx_map;
518 char *path;
520 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
521 return NULL;
523 path = sha1_pack_name(sha1);
525 p = xmalloc(sizeof(*p) + strlen(path) + 2);
526 strcpy(p->pack_name, path);
527 p->index_size = idx_size;
528 p->pack_size = 0;
529 p->index_base = idx_map;
530 p->next = NULL;
531 p->pack_base = NULL;
532 p->pack_last_used = 0;
533 p->pack_use_cnt = 0;
534 memcpy(p->sha1, sha1, 20);
535 return p;
538 void install_packed_git(struct packed_git *pack)
540 pack->next = packed_git;
541 packed_git = pack;
544 static void prepare_packed_git_one(char *objdir, int local)
546 char path[PATH_MAX];
547 int len;
548 DIR *dir;
549 struct dirent *de;
551 sprintf(path, "%s/pack", objdir);
552 len = strlen(path);
553 dir = opendir(path);
554 if (!dir) {
555 fprintf(stderr, "unable to open object pack directory: %s: %s\n", path, strerror(errno));
556 return;
558 path[len++] = '/';
559 while ((de = readdir(dir)) != NULL) {
560 int namelen = strlen(de->d_name);
561 struct packed_git *p;
563 if (strcmp(de->d_name + namelen - 4, ".idx"))
564 continue;
566 /* we have .idx. Is it a file we can map? */
567 strcpy(path + len, de->d_name);
568 p = add_packed_git(path, len + namelen, local);
569 if (!p)
570 continue;
571 p->next = packed_git;
572 packed_git = p;
574 closedir(dir);
577 void prepare_packed_git(void)
579 static int run_once = 0;
580 struct alternate_object_database *alt;
582 if (run_once)
583 return;
584 prepare_packed_git_one(get_object_directory(), 1);
585 prepare_alt_odb();
586 for (alt = alt_odb_list; alt; alt = alt->next) {
587 alt->name[-1] = 0;
588 prepare_packed_git_one(alt->base, 0);
589 alt->name[-1] = '/';
591 run_once = 1;
594 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
596 char header[100];
597 unsigned char real_sha1[20];
598 SHA_CTX c;
600 SHA1_Init(&c);
601 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
602 SHA1_Update(&c, map, size);
603 SHA1_Final(real_sha1, &c);
604 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
607 static void *map_sha1_file_internal(const unsigned char *sha1,
608 unsigned long *size)
610 struct stat st;
611 void *map;
612 int fd;
613 char *filename = find_sha1_file(sha1, &st);
615 if (!filename) {
616 return NULL;
619 fd = open(filename, O_RDONLY | sha1_file_open_flag);
620 if (fd < 0) {
621 /* See if it works without O_NOATIME */
622 switch (sha1_file_open_flag) {
623 default:
624 fd = open(filename, O_RDONLY);
625 if (fd >= 0)
626 break;
627 /* Fallthrough */
628 case 0:
629 return NULL;
632 /* If it failed once, it will probably fail again.
633 * Stop using O_NOATIME
635 sha1_file_open_flag = 0;
637 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
638 close(fd);
639 if (map == MAP_FAILED)
640 return NULL;
641 *size = st.st_size;
642 return map;
645 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
647 /* Get the data stream */
648 memset(stream, 0, sizeof(*stream));
649 stream->next_in = map;
650 stream->avail_in = mapsize;
651 stream->next_out = buffer;
652 stream->avail_out = size;
654 inflateInit(stream);
655 return inflate(stream, 0);
658 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
660 int bytes = strlen(buffer) + 1;
661 unsigned char *buf = xmalloc(1+size);
663 memcpy(buf, buffer + bytes, stream->total_out - bytes);
664 bytes = stream->total_out - bytes;
665 if (bytes < size) {
666 stream->next_out = buf + bytes;
667 stream->avail_out = size - bytes;
668 while (inflate(stream, Z_FINISH) == Z_OK)
669 /* nothing */;
671 buf[size] = 0;
672 inflateEnd(stream);
673 return buf;
677 * We used to just use "sscanf()", but that's actually way
678 * too permissive for what we want to check. So do an anal
679 * object header parse by hand.
681 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
683 int i;
684 unsigned long size;
687 * The type can be at most ten bytes (including the
688 * terminating '\0' that we add), and is followed by
689 * a space.
691 i = 10;
692 for (;;) {
693 char c = *hdr++;
694 if (c == ' ')
695 break;
696 if (!--i)
697 return -1;
698 *type++ = c;
700 *type = 0;
703 * The length must follow immediately, and be in canonical
704 * decimal format (ie "010" is not valid).
706 size = *hdr++ - '0';
707 if (size > 9)
708 return -1;
709 if (size) {
710 for (;;) {
711 unsigned long c = *hdr - '0';
712 if (c > 9)
713 break;
714 hdr++;
715 size = size * 10 + c;
718 *sizep = size;
721 * The length must be followed by a zero byte
723 return *hdr ? -1 : 0;
726 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
728 int ret;
729 z_stream stream;
730 char hdr[8192];
732 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
733 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
734 return NULL;
736 return unpack_sha1_rest(&stream, hdr, *size);
739 /* forward declaration for a mutually recursive function */
740 static int packed_object_info(struct pack_entry *entry,
741 char *type, unsigned long *sizep);
743 static int packed_delta_info(unsigned char *base_sha1,
744 unsigned long delta_size,
745 unsigned long left,
746 char *type,
747 unsigned long *sizep,
748 struct packed_git *p)
750 struct pack_entry base_ent;
752 if (left < 20)
753 die("truncated pack file");
755 /* The base entry _must_ be in the same pack */
756 if (!find_pack_entry_one(base_sha1, &base_ent, p))
757 die("failed to find delta-pack base object %s",
758 sha1_to_hex(base_sha1));
760 /* We choose to only get the type of the base object and
761 * ignore potentially corrupt pack file that expects the delta
762 * based on a base with a wrong size. This saves tons of
763 * inflate() calls.
766 if (packed_object_info(&base_ent, type, NULL))
767 die("cannot get info for delta-pack base");
769 if (sizep) {
770 const unsigned char *data;
771 unsigned char delta_head[64];
772 unsigned long result_size;
773 z_stream stream;
774 int st;
776 memset(&stream, 0, sizeof(stream));
778 data = stream.next_in = base_sha1 + 20;
779 stream.avail_in = left - 20;
780 stream.next_out = delta_head;
781 stream.avail_out = sizeof(delta_head);
783 inflateInit(&stream);
784 st = inflate(&stream, Z_FINISH);
785 inflateEnd(&stream);
786 if ((st != Z_STREAM_END) &&
787 stream.total_out != sizeof(delta_head))
788 die("delta data unpack-initial failed");
790 /* Examine the initial part of the delta to figure out
791 * the result size.
793 data = delta_head;
794 get_delta_hdr_size(&data); /* ignore base size */
796 /* Read the result size */
797 result_size = get_delta_hdr_size(&data);
798 *sizep = result_size;
800 return 0;
803 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
804 enum object_type *type, unsigned long *sizep)
806 unsigned shift;
807 unsigned char *pack, c;
808 unsigned long size;
810 if (offset >= p->pack_size)
811 die("object offset outside of pack file");
813 pack = p->pack_base + offset;
814 c = *pack++;
815 offset++;
816 *type = (c >> 4) & 7;
817 size = c & 15;
818 shift = 4;
819 while (c & 0x80) {
820 if (offset >= p->pack_size)
821 die("object offset outside of pack file");
822 c = *pack++;
823 offset++;
824 size += (c & 0x7f) << shift;
825 shift += 7;
827 *sizep = size;
828 return offset;
831 int check_reuse_pack_delta(struct packed_git *p, unsigned long offset,
832 unsigned char *base, unsigned long *sizep,
833 enum object_type *kindp)
835 unsigned long ptr;
836 int status = -1;
838 use_packed_git(p);
839 ptr = offset;
840 ptr = unpack_object_header(p, ptr, kindp, sizep);
841 if (*kindp != OBJ_DELTA)
842 goto done;
843 memcpy(base, p->pack_base + ptr, 20);
844 status = 0;
845 done:
846 unuse_packed_git(p);
847 return status;
850 void packed_object_info_detail(struct pack_entry *e,
851 char *type,
852 unsigned long *size,
853 unsigned long *store_size,
854 unsigned int *delta_chain_length,
855 unsigned char *base_sha1)
857 struct packed_git *p = e->p;
858 unsigned long offset, left;
859 unsigned char *pack;
860 enum object_type kind;
862 offset = unpack_object_header(p, e->offset, &kind, size);
863 pack = p->pack_base + offset;
864 left = p->pack_size - offset;
865 if (kind != OBJ_DELTA)
866 *delta_chain_length = 0;
867 else {
868 unsigned int chain_length = 0;
869 memcpy(base_sha1, pack, 20);
870 do {
871 struct pack_entry base_ent;
872 unsigned long junk;
874 find_pack_entry_one(pack, &base_ent, p);
875 offset = unpack_object_header(p, base_ent.offset,
876 &kind, &junk);
877 pack = p->pack_base + offset;
878 chain_length++;
879 } while (kind == OBJ_DELTA);
880 *delta_chain_length = chain_length;
882 switch (kind) {
883 case OBJ_COMMIT:
884 strcpy(type, "commit");
885 break;
886 case OBJ_TREE:
887 strcpy(type, "tree");
888 break;
889 case OBJ_BLOB:
890 strcpy(type, "blob");
891 break;
892 case OBJ_TAG:
893 strcpy(type, "tag");
894 break;
895 default:
896 die("corrupted pack file %s containing object of kind %d",
897 p->pack_name, kind);
899 *store_size = 0; /* notyet */
902 static int packed_object_info(struct pack_entry *entry,
903 char *type, unsigned long *sizep)
905 struct packed_git *p = entry->p;
906 unsigned long offset, size, left;
907 unsigned char *pack;
908 enum object_type kind;
909 int retval;
911 if (use_packed_git(p))
912 die("cannot map packed file");
914 offset = unpack_object_header(p, entry->offset, &kind, &size);
915 pack = p->pack_base + offset;
916 left = p->pack_size - offset;
918 switch (kind) {
919 case OBJ_DELTA:
920 retval = packed_delta_info(pack, size, left, type, sizep, p);
921 unuse_packed_git(p);
922 return retval;
923 case OBJ_COMMIT:
924 strcpy(type, "commit");
925 break;
926 case OBJ_TREE:
927 strcpy(type, "tree");
928 break;
929 case OBJ_BLOB:
930 strcpy(type, "blob");
931 break;
932 case OBJ_TAG:
933 strcpy(type, "tag");
934 break;
935 default:
936 die("corrupted pack file %s containing object of kind %d",
937 p->pack_name, kind);
939 if (sizep)
940 *sizep = size;
941 unuse_packed_git(p);
942 return 0;
945 /* forward declaration for a mutually recursive function */
946 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
948 static void *unpack_delta_entry(unsigned char *base_sha1,
949 unsigned long delta_size,
950 unsigned long left,
951 char *type,
952 unsigned long *sizep,
953 struct packed_git *p)
955 struct pack_entry base_ent;
956 void *data, *delta_data, *result, *base;
957 unsigned long data_size, result_size, base_size;
958 z_stream stream;
959 int st;
961 if (left < 20)
962 die("truncated pack file");
963 data = base_sha1 + 20;
964 data_size = left - 20;
965 delta_data = xmalloc(delta_size);
967 memset(&stream, 0, sizeof(stream));
969 stream.next_in = data;
970 stream.avail_in = data_size;
971 stream.next_out = delta_data;
972 stream.avail_out = delta_size;
974 inflateInit(&stream);
975 st = inflate(&stream, Z_FINISH);
976 inflateEnd(&stream);
977 if ((st != Z_STREAM_END) || stream.total_out != delta_size)
978 die("delta data unpack failed");
980 /* The base entry _must_ be in the same pack */
981 if (!find_pack_entry_one(base_sha1, &base_ent, p))
982 die("failed to find delta-pack base object %s",
983 sha1_to_hex(base_sha1));
984 base = unpack_entry_gently(&base_ent, type, &base_size);
985 if (!base)
986 die("failed to read delta-pack base object %s",
987 sha1_to_hex(base_sha1));
988 result = patch_delta(base, base_size,
989 delta_data, delta_size,
990 &result_size);
991 if (!result)
992 die("failed to apply delta");
993 free(delta_data);
994 free(base);
995 *sizep = result_size;
996 return result;
999 static void *unpack_non_delta_entry(unsigned char *data,
1000 unsigned long size,
1001 unsigned long left)
1003 int st;
1004 z_stream stream;
1005 unsigned char *buffer;
1007 buffer = xmalloc(size + 1);
1008 buffer[size] = 0;
1009 memset(&stream, 0, sizeof(stream));
1010 stream.next_in = data;
1011 stream.avail_in = left;
1012 stream.next_out = buffer;
1013 stream.avail_out = size;
1015 inflateInit(&stream);
1016 st = inflate(&stream, Z_FINISH);
1017 inflateEnd(&stream);
1018 if ((st != Z_STREAM_END) || stream.total_out != size) {
1019 free(buffer);
1020 return NULL;
1023 return buffer;
1026 static void *unpack_entry(struct pack_entry *entry,
1027 char *type, unsigned long *sizep)
1029 struct packed_git *p = entry->p;
1030 void *retval;
1032 if (use_packed_git(p))
1033 die("cannot map packed file");
1034 retval = unpack_entry_gently(entry, type, sizep);
1035 unuse_packed_git(p);
1036 if (!retval)
1037 die("corrupted pack file %s", p->pack_name);
1038 return retval;
1041 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
1042 void *unpack_entry_gently(struct pack_entry *entry,
1043 char *type, unsigned long *sizep)
1045 struct packed_git *p = entry->p;
1046 unsigned long offset, size, left;
1047 unsigned char *pack;
1048 enum object_type kind;
1049 void *retval;
1051 offset = unpack_object_header(p, entry->offset, &kind, &size);
1052 pack = p->pack_base + offset;
1053 left = p->pack_size - offset;
1054 switch (kind) {
1055 case OBJ_DELTA:
1056 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
1057 return retval;
1058 case OBJ_COMMIT:
1059 strcpy(type, "commit");
1060 break;
1061 case OBJ_TREE:
1062 strcpy(type, "tree");
1063 break;
1064 case OBJ_BLOB:
1065 strcpy(type, "blob");
1066 break;
1067 case OBJ_TAG:
1068 strcpy(type, "tag");
1069 break;
1070 default:
1071 return NULL;
1073 *sizep = size;
1074 retval = unpack_non_delta_entry(pack, size, left);
1075 return retval;
1078 int num_packed_objects(const struct packed_git *p)
1080 /* See check_packed_git_idx() */
1081 return (p->index_size - 20 - 20 - 4*256) / 24;
1084 int nth_packed_object_sha1(const struct packed_git *p, int n,
1085 unsigned char* sha1)
1087 void *index = p->index_base + 256;
1088 if (n < 0 || num_packed_objects(p) <= n)
1089 return -1;
1090 memcpy(sha1, (index + 24 * n + 4), 20);
1091 return 0;
1094 int find_pack_entry_one(const unsigned char *sha1,
1095 struct pack_entry *e, struct packed_git *p)
1097 unsigned int *level1_ofs = p->index_base;
1098 int hi = ntohl(level1_ofs[*sha1]);
1099 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1100 void *index = p->index_base + 256;
1102 do {
1103 int mi = (lo + hi) / 2;
1104 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
1105 if (!cmp) {
1106 e->offset = ntohl(*((int*)(index + 24 * mi)));
1107 memcpy(e->sha1, sha1, 20);
1108 e->p = p;
1109 return 1;
1111 if (cmp > 0)
1112 hi = mi;
1113 else
1114 lo = mi+1;
1115 } while (lo < hi);
1116 return 0;
1119 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1121 struct packed_git *p;
1122 prepare_packed_git();
1124 for (p = packed_git; p; p = p->next) {
1125 if (find_pack_entry_one(sha1, e, p))
1126 return 1;
1128 return 0;
1131 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1132 struct packed_git *packs)
1134 struct packed_git *p;
1135 struct pack_entry e;
1137 for (p = packs; p; p = p->next) {
1138 if (find_pack_entry_one(sha1, &e, p))
1139 return p;
1141 return NULL;
1145 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1147 int status;
1148 unsigned long mapsize, size;
1149 void *map;
1150 z_stream stream;
1151 char hdr[128];
1153 map = map_sha1_file_internal(sha1, &mapsize);
1154 if (!map) {
1155 struct pack_entry e;
1157 if (!find_pack_entry(sha1, &e))
1158 return error("unable to find %s", sha1_to_hex(sha1));
1159 return packed_object_info(&e, type, sizep);
1161 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1162 status = error("unable to unpack %s header",
1163 sha1_to_hex(sha1));
1164 if (parse_sha1_header(hdr, type, &size) < 0)
1165 status = error("unable to parse %s header", sha1_to_hex(sha1));
1166 else {
1167 status = 0;
1168 if (sizep)
1169 *sizep = size;
1171 inflateEnd(&stream);
1172 munmap(map, mapsize);
1173 return status;
1176 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1178 struct pack_entry e;
1180 if (!find_pack_entry(sha1, &e)) {
1181 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1182 return NULL;
1184 return unpack_entry(&e, type, size);
1187 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1189 unsigned long mapsize;
1190 void *map, *buf;
1191 struct pack_entry e;
1193 if (find_pack_entry(sha1, &e))
1194 return read_packed_sha1(sha1, type, size);
1195 map = map_sha1_file_internal(sha1, &mapsize);
1196 if (map) {
1197 buf = unpack_sha1_file(map, mapsize, type, size);
1198 munmap(map, mapsize);
1199 return buf;
1201 return NULL;
1204 void *read_object_with_reference(const unsigned char *sha1,
1205 const char *required_type,
1206 unsigned long *size,
1207 unsigned char *actual_sha1_return)
1209 char type[20];
1210 void *buffer;
1211 unsigned long isize;
1212 unsigned char actual_sha1[20];
1214 memcpy(actual_sha1, sha1, 20);
1215 while (1) {
1216 int ref_length = -1;
1217 const char *ref_type = NULL;
1219 buffer = read_sha1_file(actual_sha1, type, &isize);
1220 if (!buffer)
1221 return NULL;
1222 if (!strcmp(type, required_type)) {
1223 *size = isize;
1224 if (actual_sha1_return)
1225 memcpy(actual_sha1_return, actual_sha1, 20);
1226 return buffer;
1228 /* Handle references */
1229 else if (!strcmp(type, "commit"))
1230 ref_type = "tree ";
1231 else if (!strcmp(type, "tag"))
1232 ref_type = "object ";
1233 else {
1234 free(buffer);
1235 return NULL;
1237 ref_length = strlen(ref_type);
1239 if (memcmp(buffer, ref_type, ref_length) ||
1240 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1241 free(buffer);
1242 return NULL;
1244 free(buffer);
1245 /* Now we have the ID of the referred-to object in
1246 * actual_sha1. Check again. */
1250 char *write_sha1_file_prepare(void *buf,
1251 unsigned long len,
1252 const char *type,
1253 unsigned char *sha1,
1254 unsigned char *hdr,
1255 int *hdrlen)
1257 SHA_CTX c;
1259 /* Generate the header */
1260 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1262 /* Sha1.. */
1263 SHA1_Init(&c);
1264 SHA1_Update(&c, hdr, *hdrlen);
1265 SHA1_Update(&c, buf, len);
1266 SHA1_Final(sha1, &c);
1268 return sha1_file_name(sha1);
1272 * Link the tempfile to the final place, possibly creating the
1273 * last directory level as you do so.
1275 * Returns the errno on failure, 0 on success.
1277 static int link_temp_to_file(const char *tmpfile, char *filename)
1279 int ret;
1281 if (!link(tmpfile, filename))
1282 return 0;
1285 * Try to mkdir the last path component if that failed
1286 * with an ENOENT.
1288 * Re-try the "link()" regardless of whether the mkdir
1289 * succeeds, since a race might mean that somebody
1290 * else succeeded.
1292 ret = errno;
1293 if (ret == ENOENT) {
1294 char *dir = strrchr(filename, '/');
1295 if (dir) {
1296 *dir = 0;
1297 mkdir(filename, 0777);
1298 if (adjust_shared_perm(filename))
1299 return -2;
1300 *dir = '/';
1301 if (!link(tmpfile, filename))
1302 return 0;
1303 ret = errno;
1306 return ret;
1310 * Move the just written object into its final resting place
1312 int move_temp_to_file(const char *tmpfile, char *filename)
1314 int ret = link_temp_to_file(tmpfile, filename);
1317 * Coda hack - coda doesn't like cross-directory links,
1318 * so we fall back to a rename, which will mean that it
1319 * won't be able to check collisions, but that's not a
1320 * big deal.
1322 * The same holds for FAT formatted media.
1324 * When this succeeds, we just return 0. We have nothing
1325 * left to unlink.
1327 if (ret && ret != EEXIST) {
1328 if (!rename(tmpfile, filename))
1329 return 0;
1330 ret = errno;
1332 unlink(tmpfile);
1333 if (ret) {
1334 if (ret != EEXIST) {
1335 fprintf(stderr, "unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1336 return -1;
1338 /* FIXME!!! Collision check here ? */
1341 return 0;
1344 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1346 int size;
1347 unsigned char *compressed;
1348 z_stream stream;
1349 unsigned char sha1[20];
1350 char *filename;
1351 static char tmpfile[PATH_MAX];
1352 unsigned char hdr[50];
1353 int fd, hdrlen;
1355 /* Normally if we have it in the pack then we do not bother writing
1356 * it out into .git/objects/??/?{38} file.
1358 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1359 if (returnsha1)
1360 memcpy(returnsha1, sha1, 20);
1361 if (has_sha1_file(sha1))
1362 return 0;
1363 fd = open(filename, O_RDONLY);
1364 if (fd >= 0) {
1366 * FIXME!!! We might do collision checking here, but we'd
1367 * need to uncompress the old file and check it. Later.
1369 close(fd);
1370 return 0;
1373 if (errno != ENOENT) {
1374 fprintf(stderr, "sha1 file %s: %s\n", filename, strerror(errno));
1375 return -1;
1378 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1380 fd = mkstemp(tmpfile);
1381 if (fd < 0) {
1382 fprintf(stderr, "unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
1383 return -1;
1386 /* Set it up */
1387 memset(&stream, 0, sizeof(stream));
1388 deflateInit(&stream, Z_BEST_COMPRESSION);
1389 size = deflateBound(&stream, len+hdrlen);
1390 compressed = xmalloc(size);
1392 /* Compress it */
1393 stream.next_out = compressed;
1394 stream.avail_out = size;
1396 /* First header.. */
1397 stream.next_in = hdr;
1398 stream.avail_in = hdrlen;
1399 while (deflate(&stream, 0) == Z_OK)
1400 /* nothing */;
1402 /* Then the data itself.. */
1403 stream.next_in = buf;
1404 stream.avail_in = len;
1405 while (deflate(&stream, Z_FINISH) == Z_OK)
1406 /* nothing */;
1407 deflateEnd(&stream);
1408 size = stream.total_out;
1410 if (write(fd, compressed, size) != size)
1411 die("unable to write file");
1412 fchmod(fd, 0444);
1413 close(fd);
1414 free(compressed);
1416 return move_temp_to_file(tmpfile, filename);
1419 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1421 ssize_t size;
1422 unsigned long objsize;
1423 int posn = 0;
1424 void *map = map_sha1_file_internal(sha1, &objsize);
1425 void *buf = map;
1426 void *temp_obj = NULL;
1427 z_stream stream;
1429 if (!buf) {
1430 unsigned char *unpacked;
1431 unsigned long len;
1432 char type[20];
1433 char hdr[50];
1434 int hdrlen;
1435 // need to unpack and recompress it by itself
1436 unpacked = read_packed_sha1(sha1, type, &len);
1438 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1440 /* Set it up */
1441 memset(&stream, 0, sizeof(stream));
1442 deflateInit(&stream, Z_BEST_COMPRESSION);
1443 size = deflateBound(&stream, len + hdrlen);
1444 temp_obj = buf = xmalloc(size);
1446 /* Compress it */
1447 stream.next_out = buf;
1448 stream.avail_out = size;
1450 /* First header.. */
1451 stream.next_in = (void *)hdr;
1452 stream.avail_in = hdrlen;
1453 while (deflate(&stream, 0) == Z_OK)
1454 /* nothing */;
1456 /* Then the data itself.. */
1457 stream.next_in = unpacked;
1458 stream.avail_in = len;
1459 while (deflate(&stream, Z_FINISH) == Z_OK)
1460 /* nothing */;
1461 deflateEnd(&stream);
1462 free(unpacked);
1464 objsize = stream.total_out;
1467 do {
1468 size = write(fd, buf + posn, objsize - posn);
1469 if (size <= 0) {
1470 if (!size) {
1471 fprintf(stderr, "write closed\n");
1472 } else {
1473 perror("write ");
1475 return -1;
1477 posn += size;
1478 } while (posn < objsize);
1480 if (map)
1481 munmap(map, objsize);
1482 if (temp_obj)
1483 free(temp_obj);
1485 return 0;
1488 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1489 size_t bufsize, size_t *bufposn)
1491 char tmpfile[PATH_MAX];
1492 int local;
1493 z_stream stream;
1494 unsigned char real_sha1[20];
1495 unsigned char discard[4096];
1496 int ret;
1497 SHA_CTX c;
1499 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1501 local = mkstemp(tmpfile);
1502 if (local < 0)
1503 return error("Couldn't open %s for %s\n", tmpfile, sha1_to_hex(sha1));
1505 memset(&stream, 0, sizeof(stream));
1507 inflateInit(&stream);
1509 SHA1_Init(&c);
1511 do {
1512 ssize_t size;
1513 if (*bufposn) {
1514 stream.avail_in = *bufposn;
1515 stream.next_in = (unsigned char *) buffer;
1516 do {
1517 stream.next_out = discard;
1518 stream.avail_out = sizeof(discard);
1519 ret = inflate(&stream, Z_SYNC_FLUSH);
1520 SHA1_Update(&c, discard, sizeof(discard) -
1521 stream.avail_out);
1522 } while (stream.avail_in && ret == Z_OK);
1523 write(local, buffer, *bufposn - stream.avail_in);
1524 memmove(buffer, buffer + *bufposn - stream.avail_in,
1525 stream.avail_in);
1526 *bufposn = stream.avail_in;
1527 if (ret != Z_OK)
1528 break;
1530 size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1531 if (size <= 0) {
1532 close(local);
1533 unlink(tmpfile);
1534 if (!size)
1535 return error("Connection closed?");
1536 perror("Reading from connection");
1537 return -1;
1539 *bufposn += size;
1540 } while (1);
1541 inflateEnd(&stream);
1543 close(local);
1544 SHA1_Final(real_sha1, &c);
1545 if (ret != Z_STREAM_END) {
1546 unlink(tmpfile);
1547 return error("File %s corrupted", sha1_to_hex(sha1));
1549 if (memcmp(sha1, real_sha1, 20)) {
1550 unlink(tmpfile);
1551 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1554 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1557 int has_pack_index(const unsigned char *sha1)
1559 struct stat st;
1560 if (stat(sha1_pack_index_name(sha1), &st))
1561 return 0;
1562 return 1;
1565 int has_pack_file(const unsigned char *sha1)
1567 struct stat st;
1568 if (stat(sha1_pack_name(sha1), &st))
1569 return 0;
1570 return 1;
1573 int has_sha1_pack(const unsigned char *sha1)
1575 struct pack_entry e;
1576 return find_pack_entry(sha1, &e);
1579 int has_sha1_file(const unsigned char *sha1)
1581 struct stat st;
1582 struct pack_entry e;
1584 if (find_pack_entry(sha1, &e))
1585 return 1;
1586 return find_sha1_file(sha1, &st) ? 1 : 0;
1589 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
1591 unsigned long size = 4096;
1592 char *buf = malloc(size);
1593 int iret, ret;
1594 unsigned long off = 0;
1595 unsigned char hdr[50];
1596 int hdrlen;
1597 do {
1598 iret = read(fd, buf + off, size - off);
1599 if (iret > 0) {
1600 off += iret;
1601 if (off == size) {
1602 size *= 2;
1603 buf = realloc(buf, size);
1606 } while (iret > 0);
1607 if (iret < 0) {
1608 free(buf);
1609 return -1;
1611 if (!type)
1612 type = "blob";
1613 if (write_object)
1614 ret = write_sha1_file(buf, off, type, sha1);
1615 else {
1616 write_sha1_file_prepare(buf, off, type, sha1, hdr, &hdrlen);
1617 ret = 0;
1619 free(buf);
1620 return ret;
1623 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1625 unsigned long size = st->st_size;
1626 void *buf;
1627 int ret;
1628 unsigned char hdr[50];
1629 int hdrlen;
1631 buf = "";
1632 if (size)
1633 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1634 close(fd);
1635 if (buf == MAP_FAILED)
1636 return -1;
1638 if (!type)
1639 type = "blob";
1640 if (write_object)
1641 ret = write_sha1_file(buf, size, type, sha1);
1642 else {
1643 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1644 ret = 0;
1646 if (size)
1647 munmap(buf, size);
1648 return ret;
1651 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1653 int fd;
1654 char *target;
1656 switch (st->st_mode & S_IFMT) {
1657 case S_IFREG:
1658 fd = open(path, O_RDONLY);
1659 if (fd < 0)
1660 return error("open(\"%s\"): %s", path,
1661 strerror(errno));
1662 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1663 return error("%s: failed to insert into database",
1664 path);
1665 break;
1666 case S_IFLNK:
1667 target = xmalloc(st->st_size+1);
1668 if (readlink(path, target, st->st_size+1) != st->st_size) {
1669 char *errstr = strerror(errno);
1670 free(target);
1671 return error("readlink(\"%s\"): %s", path,
1672 errstr);
1674 if (!write_object) {
1675 unsigned char hdr[50];
1676 int hdrlen;
1677 write_sha1_file_prepare(target, st->st_size, "blob",
1678 sha1, hdr, &hdrlen);
1679 } else if (write_sha1_file(target, st->st_size, "blob", sha1))
1680 return error("%s: failed to insert into database",
1681 path);
1682 free(target);
1683 break;
1684 default:
1685 return error("%s: unsupported file type", path);
1687 return 0;