detect broken alternates.
[git/gitweb.git] / sha1_file.c
blobc08da35d8a2c9f9fb02370769e87578ec1f2fcce
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 stat st;
251 struct alternate_object_database *alt;
252 /* 43 = 40-byte + 2 '/' + terminating NUL */
253 int pfxlen = cp - last;
254 int entlen = pfxlen + 43;
256 if (*last != '/' && relative_base) {
257 /* Relative alt-odb */
258 if (base_len < 0)
259 base_len = strlen(relative_base) + 1;
260 entlen += base_len;
261 pfxlen += base_len;
263 ent = xmalloc(sizeof(*ent) + entlen);
265 if (*last != '/' && relative_base) {
266 memcpy(ent->base, relative_base, base_len - 1);
267 ent->base[base_len - 1] = '/';
268 memcpy(ent->base + base_len,
269 last, cp - last);
271 else
272 memcpy(ent->base, last, pfxlen);
274 ent->name = ent->base + pfxlen + 1;
275 ent->base[pfxlen + 3] = '/';
276 ent->base[pfxlen] = ent->base[entlen-1] = 0;
278 /* Detect cases where alternate disappeared */
279 if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
280 error("object directory %s does not exist; "
281 "check .git/objects/info/alternates.",
282 ent->base);
283 goto bad;
285 ent->base[pfxlen] = '/';
287 /* Prevent the common mistake of listing the same
288 * thing twice, or object directory itself.
290 for (alt = alt_odb_list; alt; alt = alt->next)
291 if (!memcmp(ent->base, alt->base, pfxlen))
292 goto bad;
293 if (!memcmp(ent->base, objdir, pfxlen)) {
294 bad:
295 free(ent);
297 else {
298 *alt_odb_tail = ent;
299 alt_odb_tail = &(ent->next);
300 ent->next = NULL;
303 while (cp < ep && *cp == sep)
304 cp++;
305 last = cp;
309 void prepare_alt_odb(void)
311 char path[PATH_MAX];
312 char *map;
313 int fd;
314 struct stat st;
315 char *alt;
317 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
318 if (!alt) alt = "";
320 if (alt_odb_tail)
321 return;
322 alt_odb_tail = &alt_odb_list;
323 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL);
325 sprintf(path, "%s/info/alternates", get_object_directory());
326 fd = open(path, O_RDONLY);
327 if (fd < 0)
328 return;
329 if (fstat(fd, &st) || (st.st_size == 0)) {
330 close(fd);
331 return;
333 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
334 close(fd);
335 if (map == MAP_FAILED)
336 return;
338 link_alt_odb_entries(map, map + st.st_size, '\n',
339 get_object_directory());
340 munmap(map, st.st_size);
343 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
345 char *name = sha1_file_name(sha1);
346 struct alternate_object_database *alt;
348 if (!stat(name, st))
349 return name;
350 prepare_alt_odb();
351 for (alt = alt_odb_list; alt; alt = alt->next) {
352 name = alt->name;
353 fill_sha1_path(name, sha1);
354 if (!stat(alt->base, st))
355 return alt->base;
357 return NULL;
360 #define PACK_MAX_SZ (1<<26)
361 static int pack_used_ctr;
362 static unsigned long pack_mapped;
363 struct packed_git *packed_git;
365 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
366 void **idx_map_)
368 void *idx_map;
369 unsigned int *index;
370 unsigned long idx_size;
371 int nr, i;
372 int fd = open(path, O_RDONLY);
373 struct stat st;
374 if (fd < 0)
375 return -1;
376 if (fstat(fd, &st)) {
377 close(fd);
378 return -1;
380 idx_size = st.st_size;
381 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
382 close(fd);
383 if (idx_map == MAP_FAILED)
384 return -1;
386 index = idx_map;
387 *idx_map_ = idx_map;
388 *idx_size_ = idx_size;
390 /* check index map */
391 if (idx_size < 4*256 + 20 + 20)
392 return error("index file too small");
393 nr = 0;
394 for (i = 0; i < 256; i++) {
395 unsigned int n = ntohl(index[i]);
396 if (n < nr)
397 return error("non-monotonic index");
398 nr = n;
402 * Total size:
403 * - 256 index entries 4 bytes each
404 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
405 * - 20-byte SHA1 of the packfile
406 * - 20-byte SHA1 file checksum
408 if (idx_size != 4*256 + nr * 24 + 20 + 20)
409 return error("wrong index file size");
411 return 0;
414 static int unuse_one_packed_git(void)
416 struct packed_git *p, *lru = NULL;
418 for (p = packed_git; p; p = p->next) {
419 if (p->pack_use_cnt || !p->pack_base)
420 continue;
421 if (!lru || p->pack_last_used < lru->pack_last_used)
422 lru = p;
424 if (!lru)
425 return 0;
426 munmap(lru->pack_base, lru->pack_size);
427 lru->pack_base = NULL;
428 return 1;
431 void unuse_packed_git(struct packed_git *p)
433 p->pack_use_cnt--;
436 int use_packed_git(struct packed_git *p)
438 if (!p->pack_size) {
439 struct stat st;
440 // We created the struct before we had the pack
441 stat(p->pack_name, &st);
442 if (!S_ISREG(st.st_mode))
443 die("packfile %s not a regular file", p->pack_name);
444 p->pack_size = st.st_size;
446 if (!p->pack_base) {
447 int fd;
448 struct stat st;
449 void *map;
451 pack_mapped += p->pack_size;
452 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
453 ; /* nothing */
454 fd = open(p->pack_name, O_RDONLY);
455 if (fd < 0)
456 die("packfile %s cannot be opened", p->pack_name);
457 if (fstat(fd, &st)) {
458 close(fd);
459 die("packfile %s cannot be opened", p->pack_name);
461 if (st.st_size != p->pack_size)
462 die("packfile %s size mismatch.", p->pack_name);
463 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
464 close(fd);
465 if (map == MAP_FAILED)
466 die("packfile %s cannot be mapped.", p->pack_name);
467 p->pack_base = map;
469 /* Check if the pack file matches with the index file.
470 * this is cheap.
472 if (memcmp((char*)(p->index_base) + p->index_size - 40,
473 p->pack_base + p->pack_size - 20, 20)) {
475 die("packfile %s does not match index.", p->pack_name);
478 p->pack_last_used = pack_used_ctr++;
479 p->pack_use_cnt++;
480 return 0;
483 struct packed_git *add_packed_git(char *path, int path_len, int local)
485 struct stat st;
486 struct packed_git *p;
487 unsigned long idx_size;
488 void *idx_map;
489 unsigned char sha1[20];
491 if (check_packed_git_idx(path, &idx_size, &idx_map))
492 return NULL;
494 /* do we have a corresponding .pack file? */
495 strcpy(path + path_len - 4, ".pack");
496 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
497 munmap(idx_map, idx_size);
498 return NULL;
500 /* ok, it looks sane as far as we can check without
501 * actually mapping the pack file.
503 p = xmalloc(sizeof(*p) + path_len + 2);
504 strcpy(p->pack_name, path);
505 p->index_size = idx_size;
506 p->pack_size = st.st_size;
507 p->index_base = idx_map;
508 p->next = NULL;
509 p->pack_base = NULL;
510 p->pack_last_used = 0;
511 p->pack_use_cnt = 0;
512 p->pack_local = local;
513 if ((path_len > 44) && !get_sha1_hex(path + path_len - 44, sha1))
514 memcpy(p->sha1, sha1, 20);
515 return p;
518 struct packed_git *parse_pack_index(unsigned char *sha1)
520 char *path = sha1_pack_index_name(sha1);
521 return parse_pack_index_file(sha1, path);
524 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
526 struct packed_git *p;
527 unsigned long idx_size;
528 void *idx_map;
529 char *path;
531 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
532 return NULL;
534 path = sha1_pack_name(sha1);
536 p = xmalloc(sizeof(*p) + strlen(path) + 2);
537 strcpy(p->pack_name, path);
538 p->index_size = idx_size;
539 p->pack_size = 0;
540 p->index_base = idx_map;
541 p->next = NULL;
542 p->pack_base = NULL;
543 p->pack_last_used = 0;
544 p->pack_use_cnt = 0;
545 memcpy(p->sha1, sha1, 20);
546 return p;
549 void install_packed_git(struct packed_git *pack)
551 pack->next = packed_git;
552 packed_git = pack;
555 static void prepare_packed_git_one(char *objdir, int local)
557 char path[PATH_MAX];
558 int len;
559 DIR *dir;
560 struct dirent *de;
562 sprintf(path, "%s/pack", objdir);
563 len = strlen(path);
564 dir = opendir(path);
565 if (!dir) {
566 if (errno != ENOENT)
567 error("unable to open object pack directory: %s: %s\n",
568 path, strerror(errno));
569 return;
571 path[len++] = '/';
572 while ((de = readdir(dir)) != NULL) {
573 int namelen = strlen(de->d_name);
574 struct packed_git *p;
576 if (strcmp(de->d_name + namelen - 4, ".idx"))
577 continue;
579 /* we have .idx. Is it a file we can map? */
580 strcpy(path + len, de->d_name);
581 p = add_packed_git(path, len + namelen, local);
582 if (!p)
583 continue;
584 p->next = packed_git;
585 packed_git = p;
587 closedir(dir);
590 void prepare_packed_git(void)
592 static int run_once = 0;
593 struct alternate_object_database *alt;
595 if (run_once)
596 return;
597 prepare_packed_git_one(get_object_directory(), 1);
598 prepare_alt_odb();
599 for (alt = alt_odb_list; alt; alt = alt->next) {
600 alt->name[-1] = 0;
601 prepare_packed_git_one(alt->base, 0);
602 alt->name[-1] = '/';
604 run_once = 1;
607 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
609 char header[100];
610 unsigned char real_sha1[20];
611 SHA_CTX c;
613 SHA1_Init(&c);
614 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
615 SHA1_Update(&c, map, size);
616 SHA1_Final(real_sha1, &c);
617 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
620 static void *map_sha1_file_internal(const unsigned char *sha1,
621 unsigned long *size)
623 struct stat st;
624 void *map;
625 int fd;
626 char *filename = find_sha1_file(sha1, &st);
628 if (!filename) {
629 return NULL;
632 fd = open(filename, O_RDONLY | sha1_file_open_flag);
633 if (fd < 0) {
634 /* See if it works without O_NOATIME */
635 switch (sha1_file_open_flag) {
636 default:
637 fd = open(filename, O_RDONLY);
638 if (fd >= 0)
639 break;
640 /* Fallthrough */
641 case 0:
642 return NULL;
645 /* If it failed once, it will probably fail again.
646 * Stop using O_NOATIME
648 sha1_file_open_flag = 0;
650 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
651 close(fd);
652 if (map == MAP_FAILED)
653 return NULL;
654 *size = st.st_size;
655 return map;
658 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
660 /* Get the data stream */
661 memset(stream, 0, sizeof(*stream));
662 stream->next_in = map;
663 stream->avail_in = mapsize;
664 stream->next_out = buffer;
665 stream->avail_out = size;
667 inflateInit(stream);
668 return inflate(stream, 0);
671 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
673 int bytes = strlen(buffer) + 1;
674 unsigned char *buf = xmalloc(1+size);
676 memcpy(buf, buffer + bytes, stream->total_out - bytes);
677 bytes = stream->total_out - bytes;
678 if (bytes < size) {
679 stream->next_out = buf + bytes;
680 stream->avail_out = size - bytes;
681 while (inflate(stream, Z_FINISH) == Z_OK)
682 /* nothing */;
684 buf[size] = 0;
685 inflateEnd(stream);
686 return buf;
690 * We used to just use "sscanf()", but that's actually way
691 * too permissive for what we want to check. So do an anal
692 * object header parse by hand.
694 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
696 int i;
697 unsigned long size;
700 * The type can be at most ten bytes (including the
701 * terminating '\0' that we add), and is followed by
702 * a space.
704 i = 10;
705 for (;;) {
706 char c = *hdr++;
707 if (c == ' ')
708 break;
709 if (!--i)
710 return -1;
711 *type++ = c;
713 *type = 0;
716 * The length must follow immediately, and be in canonical
717 * decimal format (ie "010" is not valid).
719 size = *hdr++ - '0';
720 if (size > 9)
721 return -1;
722 if (size) {
723 for (;;) {
724 unsigned long c = *hdr - '0';
725 if (c > 9)
726 break;
727 hdr++;
728 size = size * 10 + c;
731 *sizep = size;
734 * The length must be followed by a zero byte
736 return *hdr ? -1 : 0;
739 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
741 int ret;
742 z_stream stream;
743 char hdr[8192];
745 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
746 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
747 return NULL;
749 return unpack_sha1_rest(&stream, hdr, *size);
752 /* forward declaration for a mutually recursive function */
753 static int packed_object_info(struct pack_entry *entry,
754 char *type, unsigned long *sizep);
756 static int packed_delta_info(unsigned char *base_sha1,
757 unsigned long delta_size,
758 unsigned long left,
759 char *type,
760 unsigned long *sizep,
761 struct packed_git *p)
763 struct pack_entry base_ent;
765 if (left < 20)
766 die("truncated pack file");
768 /* The base entry _must_ be in the same pack */
769 if (!find_pack_entry_one(base_sha1, &base_ent, p))
770 die("failed to find delta-pack base object %s",
771 sha1_to_hex(base_sha1));
773 /* We choose to only get the type of the base object and
774 * ignore potentially corrupt pack file that expects the delta
775 * based on a base with a wrong size. This saves tons of
776 * inflate() calls.
779 if (packed_object_info(&base_ent, type, NULL))
780 die("cannot get info for delta-pack base");
782 if (sizep) {
783 const unsigned char *data;
784 unsigned char delta_head[64];
785 unsigned long result_size;
786 z_stream stream;
787 int st;
789 memset(&stream, 0, sizeof(stream));
791 data = stream.next_in = base_sha1 + 20;
792 stream.avail_in = left - 20;
793 stream.next_out = delta_head;
794 stream.avail_out = sizeof(delta_head);
796 inflateInit(&stream);
797 st = inflate(&stream, Z_FINISH);
798 inflateEnd(&stream);
799 if ((st != Z_STREAM_END) &&
800 stream.total_out != sizeof(delta_head))
801 die("delta data unpack-initial failed");
803 /* Examine the initial part of the delta to figure out
804 * the result size.
806 data = delta_head;
807 get_delta_hdr_size(&data); /* ignore base size */
809 /* Read the result size */
810 result_size = get_delta_hdr_size(&data);
811 *sizep = result_size;
813 return 0;
816 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
817 enum object_type *type, unsigned long *sizep)
819 unsigned shift;
820 unsigned char *pack, c;
821 unsigned long size;
823 if (offset >= p->pack_size)
824 die("object offset outside of pack file");
826 pack = p->pack_base + offset;
827 c = *pack++;
828 offset++;
829 *type = (c >> 4) & 7;
830 size = c & 15;
831 shift = 4;
832 while (c & 0x80) {
833 if (offset >= p->pack_size)
834 die("object offset outside of pack file");
835 c = *pack++;
836 offset++;
837 size += (c & 0x7f) << shift;
838 shift += 7;
840 *sizep = size;
841 return offset;
844 void packed_object_info_detail(struct pack_entry *e,
845 char *type,
846 unsigned long *size,
847 unsigned long *store_size,
848 int *delta_chain_length,
849 unsigned char *base_sha1)
851 struct packed_git *p = e->p;
852 unsigned long offset, left;
853 unsigned char *pack;
854 enum object_type kind;
856 offset = unpack_object_header(p, e->offset, &kind, size);
857 pack = p->pack_base + offset;
858 left = p->pack_size - offset;
859 if (kind != OBJ_DELTA)
860 *delta_chain_length = 0;
861 else {
862 int chain_length = 0;
863 memcpy(base_sha1, pack, 20);
864 do {
865 struct pack_entry base_ent;
866 unsigned long junk;
868 find_pack_entry_one(pack, &base_ent, p);
869 offset = unpack_object_header(p, base_ent.offset,
870 &kind, &junk);
871 pack = p->pack_base + offset;
872 chain_length++;
873 } while (kind == OBJ_DELTA);
874 *delta_chain_length = chain_length;
876 switch (kind) {
877 case OBJ_COMMIT:
878 strcpy(type, "commit");
879 break;
880 case OBJ_TREE:
881 strcpy(type, "tree");
882 break;
883 case OBJ_BLOB:
884 strcpy(type, "blob");
885 break;
886 case OBJ_TAG:
887 strcpy(type, "tag");
888 break;
889 default:
890 die("corrupted pack file %s containing object of kind %d",
891 p->pack_name, kind);
893 *store_size = 0; /* notyet */
896 static int packed_object_info(struct pack_entry *entry,
897 char *type, unsigned long *sizep)
899 struct packed_git *p = entry->p;
900 unsigned long offset, size, left;
901 unsigned char *pack;
902 enum object_type kind;
903 int retval;
905 if (use_packed_git(p))
906 die("cannot map packed file");
908 offset = unpack_object_header(p, entry->offset, &kind, &size);
909 pack = p->pack_base + offset;
910 left = p->pack_size - offset;
912 switch (kind) {
913 case OBJ_DELTA:
914 retval = packed_delta_info(pack, size, left, type, sizep, p);
915 unuse_packed_git(p);
916 return retval;
917 case OBJ_COMMIT:
918 strcpy(type, "commit");
919 break;
920 case OBJ_TREE:
921 strcpy(type, "tree");
922 break;
923 case OBJ_BLOB:
924 strcpy(type, "blob");
925 break;
926 case OBJ_TAG:
927 strcpy(type, "tag");
928 break;
929 default:
930 die("corrupted pack file %s containing object of kind %d",
931 p->pack_name, kind);
933 if (sizep)
934 *sizep = size;
935 unuse_packed_git(p);
936 return 0;
939 /* forward declaration for a mutually recursive function */
940 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
942 static void *unpack_delta_entry(unsigned char *base_sha1,
943 unsigned long delta_size,
944 unsigned long left,
945 char *type,
946 unsigned long *sizep,
947 struct packed_git *p)
949 struct pack_entry base_ent;
950 void *data, *delta_data, *result, *base;
951 unsigned long data_size, result_size, base_size;
952 z_stream stream;
953 int st;
955 if (left < 20)
956 die("truncated pack file");
957 data = base_sha1 + 20;
958 data_size = left - 20;
959 delta_data = xmalloc(delta_size);
961 memset(&stream, 0, sizeof(stream));
963 stream.next_in = data;
964 stream.avail_in = data_size;
965 stream.next_out = delta_data;
966 stream.avail_out = delta_size;
968 inflateInit(&stream);
969 st = inflate(&stream, Z_FINISH);
970 inflateEnd(&stream);
971 if ((st != Z_STREAM_END) || stream.total_out != delta_size)
972 die("delta data unpack failed");
974 /* The base entry _must_ be in the same pack */
975 if (!find_pack_entry_one(base_sha1, &base_ent, p))
976 die("failed to find delta-pack base object %s",
977 sha1_to_hex(base_sha1));
978 base = unpack_entry_gently(&base_ent, type, &base_size);
979 if (!base)
980 die("failed to read delta-pack base object %s",
981 sha1_to_hex(base_sha1));
982 result = patch_delta(base, base_size,
983 delta_data, delta_size,
984 &result_size);
985 if (!result)
986 die("failed to apply delta");
987 free(delta_data);
988 free(base);
989 *sizep = result_size;
990 return result;
993 static void *unpack_non_delta_entry(unsigned char *data,
994 unsigned long size,
995 unsigned long left)
997 int st;
998 z_stream stream;
999 unsigned char *buffer;
1001 buffer = xmalloc(size + 1);
1002 buffer[size] = 0;
1003 memset(&stream, 0, sizeof(stream));
1004 stream.next_in = data;
1005 stream.avail_in = left;
1006 stream.next_out = buffer;
1007 stream.avail_out = size;
1009 inflateInit(&stream);
1010 st = inflate(&stream, Z_FINISH);
1011 inflateEnd(&stream);
1012 if ((st != Z_STREAM_END) || stream.total_out != size) {
1013 free(buffer);
1014 return NULL;
1017 return buffer;
1020 static void *unpack_entry(struct pack_entry *entry,
1021 char *type, unsigned long *sizep)
1023 struct packed_git *p = entry->p;
1024 void *retval;
1026 if (use_packed_git(p))
1027 die("cannot map packed file");
1028 retval = unpack_entry_gently(entry, type, sizep);
1029 unuse_packed_git(p);
1030 if (!retval)
1031 die("corrupted pack file %s", p->pack_name);
1032 return retval;
1035 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
1036 void *unpack_entry_gently(struct pack_entry *entry,
1037 char *type, unsigned long *sizep)
1039 struct packed_git *p = entry->p;
1040 unsigned long offset, size, left;
1041 unsigned char *pack;
1042 enum object_type kind;
1043 void *retval;
1045 offset = unpack_object_header(p, entry->offset, &kind, &size);
1046 pack = p->pack_base + offset;
1047 left = p->pack_size - offset;
1048 switch (kind) {
1049 case OBJ_DELTA:
1050 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
1051 return retval;
1052 case OBJ_COMMIT:
1053 strcpy(type, "commit");
1054 break;
1055 case OBJ_TREE:
1056 strcpy(type, "tree");
1057 break;
1058 case OBJ_BLOB:
1059 strcpy(type, "blob");
1060 break;
1061 case OBJ_TAG:
1062 strcpy(type, "tag");
1063 break;
1064 default:
1065 return NULL;
1067 *sizep = size;
1068 retval = unpack_non_delta_entry(pack, size, left);
1069 return retval;
1072 int num_packed_objects(const struct packed_git *p)
1074 /* See check_packed_git_idx() */
1075 return (p->index_size - 20 - 20 - 4*256) / 24;
1078 int nth_packed_object_sha1(const struct packed_git *p, int n,
1079 unsigned char* sha1)
1081 void *index = p->index_base + 256;
1082 if (n < 0 || num_packed_objects(p) <= n)
1083 return -1;
1084 memcpy(sha1, (index + 24 * n + 4), 20);
1085 return 0;
1088 int find_pack_entry_one(const unsigned char *sha1,
1089 struct pack_entry *e, struct packed_git *p)
1091 unsigned int *level1_ofs = p->index_base;
1092 int hi = ntohl(level1_ofs[*sha1]);
1093 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1094 void *index = p->index_base + 256;
1096 do {
1097 int mi = (lo + hi) / 2;
1098 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
1099 if (!cmp) {
1100 e->offset = ntohl(*((int*)(index + 24 * mi)));
1101 memcpy(e->sha1, sha1, 20);
1102 e->p = p;
1103 return 1;
1105 if (cmp > 0)
1106 hi = mi;
1107 else
1108 lo = mi+1;
1109 } while (lo < hi);
1110 return 0;
1113 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1115 struct packed_git *p;
1116 prepare_packed_git();
1118 for (p = packed_git; p; p = p->next) {
1119 if (find_pack_entry_one(sha1, e, p))
1120 return 1;
1122 return 0;
1125 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1126 struct packed_git *packs)
1128 struct packed_git *p;
1129 struct pack_entry e;
1131 for (p = packs; p; p = p->next) {
1132 if (find_pack_entry_one(sha1, &e, p))
1133 return p;
1135 return NULL;
1139 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1141 int status;
1142 unsigned long mapsize, size;
1143 void *map;
1144 z_stream stream;
1145 char hdr[128];
1147 map = map_sha1_file_internal(sha1, &mapsize);
1148 if (!map) {
1149 struct pack_entry e;
1151 if (!find_pack_entry(sha1, &e))
1152 return error("unable to find %s", sha1_to_hex(sha1));
1153 return packed_object_info(&e, type, sizep);
1155 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1156 status = error("unable to unpack %s header",
1157 sha1_to_hex(sha1));
1158 if (parse_sha1_header(hdr, type, &size) < 0)
1159 status = error("unable to parse %s header", sha1_to_hex(sha1));
1160 else {
1161 status = 0;
1162 if (sizep)
1163 *sizep = size;
1165 inflateEnd(&stream);
1166 munmap(map, mapsize);
1167 return status;
1170 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1172 struct pack_entry e;
1174 if (!find_pack_entry(sha1, &e)) {
1175 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1176 return NULL;
1178 return unpack_entry(&e, type, size);
1181 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1183 unsigned long mapsize;
1184 void *map, *buf;
1185 struct pack_entry e;
1187 if (find_pack_entry(sha1, &e))
1188 return read_packed_sha1(sha1, type, size);
1189 map = map_sha1_file_internal(sha1, &mapsize);
1190 if (map) {
1191 buf = unpack_sha1_file(map, mapsize, type, size);
1192 munmap(map, mapsize);
1193 return buf;
1195 return NULL;
1198 void *read_object_with_reference(const unsigned char *sha1,
1199 const char *required_type,
1200 unsigned long *size,
1201 unsigned char *actual_sha1_return)
1203 char type[20];
1204 void *buffer;
1205 unsigned long isize;
1206 unsigned char actual_sha1[20];
1208 memcpy(actual_sha1, sha1, 20);
1209 while (1) {
1210 int ref_length = -1;
1211 const char *ref_type = NULL;
1213 buffer = read_sha1_file(actual_sha1, type, &isize);
1214 if (!buffer)
1215 return NULL;
1216 if (!strcmp(type, required_type)) {
1217 *size = isize;
1218 if (actual_sha1_return)
1219 memcpy(actual_sha1_return, actual_sha1, 20);
1220 return buffer;
1222 /* Handle references */
1223 else if (!strcmp(type, "commit"))
1224 ref_type = "tree ";
1225 else if (!strcmp(type, "tag"))
1226 ref_type = "object ";
1227 else {
1228 free(buffer);
1229 return NULL;
1231 ref_length = strlen(ref_type);
1233 if (memcmp(buffer, ref_type, ref_length) ||
1234 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1235 free(buffer);
1236 return NULL;
1238 free(buffer);
1239 /* Now we have the ID of the referred-to object in
1240 * actual_sha1. Check again. */
1244 char *write_sha1_file_prepare(void *buf,
1245 unsigned long len,
1246 const char *type,
1247 unsigned char *sha1,
1248 unsigned char *hdr,
1249 int *hdrlen)
1251 SHA_CTX c;
1253 /* Generate the header */
1254 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1256 /* Sha1.. */
1257 SHA1_Init(&c);
1258 SHA1_Update(&c, hdr, *hdrlen);
1259 SHA1_Update(&c, buf, len);
1260 SHA1_Final(sha1, &c);
1262 return sha1_file_name(sha1);
1266 * Link the tempfile to the final place, possibly creating the
1267 * last directory level as you do so.
1269 * Returns the errno on failure, 0 on success.
1271 static int link_temp_to_file(const char *tmpfile, char *filename)
1273 int ret;
1275 if (!link(tmpfile, filename))
1276 return 0;
1279 * Try to mkdir the last path component if that failed
1280 * with an ENOENT.
1282 * Re-try the "link()" regardless of whether the mkdir
1283 * succeeds, since a race might mean that somebody
1284 * else succeeded.
1286 ret = errno;
1287 if (ret == ENOENT) {
1288 char *dir = strrchr(filename, '/');
1289 if (dir) {
1290 *dir = 0;
1291 mkdir(filename, 0777);
1292 if (adjust_shared_perm(filename))
1293 return -2;
1294 *dir = '/';
1295 if (!link(tmpfile, filename))
1296 return 0;
1297 ret = errno;
1300 return ret;
1304 * Move the just written object into its final resting place
1306 int move_temp_to_file(const char *tmpfile, char *filename)
1308 int ret = link_temp_to_file(tmpfile, filename);
1311 * Coda hack - coda doesn't like cross-directory links,
1312 * so we fall back to a rename, which will mean that it
1313 * won't be able to check collisions, but that's not a
1314 * big deal.
1316 * The same holds for FAT formatted media.
1318 * When this succeeds, we just return 0. We have nothing
1319 * left to unlink.
1321 if (ret && ret != EEXIST) {
1322 if (!rename(tmpfile, filename))
1323 return 0;
1324 ret = errno;
1326 unlink(tmpfile);
1327 if (ret) {
1328 if (ret != EEXIST) {
1329 fprintf(stderr, "unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1330 return -1;
1332 /* FIXME!!! Collision check here ? */
1335 return 0;
1338 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1340 int size;
1341 unsigned char *compressed;
1342 z_stream stream;
1343 unsigned char sha1[20];
1344 char *filename;
1345 static char tmpfile[PATH_MAX];
1346 unsigned char hdr[50];
1347 int fd, hdrlen;
1349 /* Normally if we have it in the pack then we do not bother writing
1350 * it out into .git/objects/??/?{38} file.
1352 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1353 if (returnsha1)
1354 memcpy(returnsha1, sha1, 20);
1355 if (has_sha1_file(sha1))
1356 return 0;
1357 fd = open(filename, O_RDONLY);
1358 if (fd >= 0) {
1360 * FIXME!!! We might do collision checking here, but we'd
1361 * need to uncompress the old file and check it. Later.
1363 close(fd);
1364 return 0;
1367 if (errno != ENOENT) {
1368 fprintf(stderr, "sha1 file %s: %s\n", filename, strerror(errno));
1369 return -1;
1372 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1374 fd = mkstemp(tmpfile);
1375 if (fd < 0) {
1376 fprintf(stderr, "unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
1377 return -1;
1380 /* Set it up */
1381 memset(&stream, 0, sizeof(stream));
1382 deflateInit(&stream, Z_BEST_COMPRESSION);
1383 size = deflateBound(&stream, len+hdrlen);
1384 compressed = xmalloc(size);
1386 /* Compress it */
1387 stream.next_out = compressed;
1388 stream.avail_out = size;
1390 /* First header.. */
1391 stream.next_in = hdr;
1392 stream.avail_in = hdrlen;
1393 while (deflate(&stream, 0) == Z_OK)
1394 /* nothing */;
1396 /* Then the data itself.. */
1397 stream.next_in = buf;
1398 stream.avail_in = len;
1399 while (deflate(&stream, Z_FINISH) == Z_OK)
1400 /* nothing */;
1401 deflateEnd(&stream);
1402 size = stream.total_out;
1404 if (write(fd, compressed, size) != size)
1405 die("unable to write file");
1406 fchmod(fd, 0444);
1407 close(fd);
1408 free(compressed);
1410 return move_temp_to_file(tmpfile, filename);
1413 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1415 ssize_t size;
1416 unsigned long objsize;
1417 int posn = 0;
1418 void *map = map_sha1_file_internal(sha1, &objsize);
1419 void *buf = map;
1420 void *temp_obj = NULL;
1421 z_stream stream;
1423 if (!buf) {
1424 unsigned char *unpacked;
1425 unsigned long len;
1426 char type[20];
1427 char hdr[50];
1428 int hdrlen;
1429 // need to unpack and recompress it by itself
1430 unpacked = read_packed_sha1(sha1, type, &len);
1432 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1434 /* Set it up */
1435 memset(&stream, 0, sizeof(stream));
1436 deflateInit(&stream, Z_BEST_COMPRESSION);
1437 size = deflateBound(&stream, len + hdrlen);
1438 temp_obj = buf = xmalloc(size);
1440 /* Compress it */
1441 stream.next_out = buf;
1442 stream.avail_out = size;
1444 /* First header.. */
1445 stream.next_in = (void *)hdr;
1446 stream.avail_in = hdrlen;
1447 while (deflate(&stream, 0) == Z_OK)
1448 /* nothing */;
1450 /* Then the data itself.. */
1451 stream.next_in = unpacked;
1452 stream.avail_in = len;
1453 while (deflate(&stream, Z_FINISH) == Z_OK)
1454 /* nothing */;
1455 deflateEnd(&stream);
1456 free(unpacked);
1458 objsize = stream.total_out;
1461 do {
1462 size = write(fd, buf + posn, objsize - posn);
1463 if (size <= 0) {
1464 if (!size) {
1465 fprintf(stderr, "write closed\n");
1466 } else {
1467 perror("write ");
1469 return -1;
1471 posn += size;
1472 } while (posn < objsize);
1474 if (map)
1475 munmap(map, objsize);
1476 if (temp_obj)
1477 free(temp_obj);
1479 return 0;
1482 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1483 size_t bufsize, size_t *bufposn)
1485 char tmpfile[PATH_MAX];
1486 int local;
1487 z_stream stream;
1488 unsigned char real_sha1[20];
1489 unsigned char discard[4096];
1490 int ret;
1491 SHA_CTX c;
1493 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1495 local = mkstemp(tmpfile);
1496 if (local < 0)
1497 return error("Couldn't open %s for %s\n", tmpfile, sha1_to_hex(sha1));
1499 memset(&stream, 0, sizeof(stream));
1501 inflateInit(&stream);
1503 SHA1_Init(&c);
1505 do {
1506 ssize_t size;
1507 if (*bufposn) {
1508 stream.avail_in = *bufposn;
1509 stream.next_in = (unsigned char *) buffer;
1510 do {
1511 stream.next_out = discard;
1512 stream.avail_out = sizeof(discard);
1513 ret = inflate(&stream, Z_SYNC_FLUSH);
1514 SHA1_Update(&c, discard, sizeof(discard) -
1515 stream.avail_out);
1516 } while (stream.avail_in && ret == Z_OK);
1517 write(local, buffer, *bufposn - stream.avail_in);
1518 memmove(buffer, buffer + *bufposn - stream.avail_in,
1519 stream.avail_in);
1520 *bufposn = stream.avail_in;
1521 if (ret != Z_OK)
1522 break;
1524 size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1525 if (size <= 0) {
1526 close(local);
1527 unlink(tmpfile);
1528 if (!size)
1529 return error("Connection closed?");
1530 perror("Reading from connection");
1531 return -1;
1533 *bufposn += size;
1534 } while (1);
1535 inflateEnd(&stream);
1537 close(local);
1538 SHA1_Final(real_sha1, &c);
1539 if (ret != Z_STREAM_END) {
1540 unlink(tmpfile);
1541 return error("File %s corrupted", sha1_to_hex(sha1));
1543 if (memcmp(sha1, real_sha1, 20)) {
1544 unlink(tmpfile);
1545 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1548 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1551 int has_pack_index(const unsigned char *sha1)
1553 struct stat st;
1554 if (stat(sha1_pack_index_name(sha1), &st))
1555 return 0;
1556 return 1;
1559 int has_pack_file(const unsigned char *sha1)
1561 struct stat st;
1562 if (stat(sha1_pack_name(sha1), &st))
1563 return 0;
1564 return 1;
1567 int has_sha1_pack(const unsigned char *sha1)
1569 struct pack_entry e;
1570 return find_pack_entry(sha1, &e);
1573 int has_sha1_file(const unsigned char *sha1)
1575 struct stat st;
1576 struct pack_entry e;
1578 if (find_pack_entry(sha1, &e))
1579 return 1;
1580 return find_sha1_file(sha1, &st) ? 1 : 0;
1583 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
1585 unsigned long size = 4096;
1586 char *buf = malloc(size);
1587 int iret, ret;
1588 unsigned long off = 0;
1589 unsigned char hdr[50];
1590 int hdrlen;
1591 do {
1592 iret = read(fd, buf + off, size - off);
1593 if (iret > 0) {
1594 off += iret;
1595 if (off == size) {
1596 size *= 2;
1597 buf = realloc(buf, size);
1600 } while (iret > 0);
1601 if (iret < 0) {
1602 free(buf);
1603 return -1;
1605 if (!type)
1606 type = "blob";
1607 if (write_object)
1608 ret = write_sha1_file(buf, off, type, sha1);
1609 else {
1610 write_sha1_file_prepare(buf, off, type, sha1, hdr, &hdrlen);
1611 ret = 0;
1613 free(buf);
1614 return ret;
1617 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1619 unsigned long size = st->st_size;
1620 void *buf;
1621 int ret;
1622 unsigned char hdr[50];
1623 int hdrlen;
1625 buf = "";
1626 if (size)
1627 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1628 close(fd);
1629 if (buf == MAP_FAILED)
1630 return -1;
1632 if (!type)
1633 type = "blob";
1634 if (write_object)
1635 ret = write_sha1_file(buf, size, type, sha1);
1636 else {
1637 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1638 ret = 0;
1640 if (size)
1641 munmap(buf, size);
1642 return ret;
1645 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1647 int fd;
1648 char *target;
1650 switch (st->st_mode & S_IFMT) {
1651 case S_IFREG:
1652 fd = open(path, O_RDONLY);
1653 if (fd < 0)
1654 return error("open(\"%s\"): %s", path,
1655 strerror(errno));
1656 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1657 return error("%s: failed to insert into database",
1658 path);
1659 break;
1660 case S_IFLNK:
1661 target = xmalloc(st->st_size+1);
1662 if (readlink(path, target, st->st_size+1) != st->st_size) {
1663 char *errstr = strerror(errno);
1664 free(target);
1665 return error("readlink(\"%s\"): %s", path,
1666 errstr);
1668 if (!write_object) {
1669 unsigned char hdr[50];
1670 int hdrlen;
1671 write_sha1_file_prepare(target, st->st_size, "blob",
1672 sha1, hdr, &hdrlen);
1673 } else if (write_sha1_file(target, st->st_size, "blob", sha1))
1674 return error("%s: failed to insert into database",
1675 path);
1676 free(target);
1677 break;
1678 default:
1679 return error("%s: unsupported file type", path);
1681 return 0;