GIT 1.1.6
[git/mingw/4msysgit/kblees.git] / sha1_file.c
blob20f6419bde22ee81b69f02e0336ecf92aa2e1323
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 <sys/types.h>
10 #include <dirent.h>
11 #include "cache.h"
12 #include "delta.h"
13 #include "pack.h"
15 #ifndef O_NOATIME
16 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
17 #define O_NOATIME 01000000
18 #else
19 #define O_NOATIME 0
20 #endif
21 #endif
23 const unsigned char null_sha1[20] = { 0, };
25 static unsigned int sha1_file_open_flag = O_NOATIME;
27 static unsigned hexval(char c)
29 if (c >= '0' && c <= '9')
30 return c - '0';
31 if (c >= 'a' && c <= 'f')
32 return c - 'a' + 10;
33 if (c >= 'A' && c <= 'F')
34 return c - 'A' + 10;
35 return ~0;
38 int get_sha1_hex(const char *hex, unsigned char *sha1)
40 int i;
41 for (i = 0; i < 20; i++) {
42 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
43 if (val & ~0xff)
44 return -1;
45 *sha1++ = val;
46 hex += 2;
48 return 0;
51 int adjust_shared_perm(const char *path)
53 struct stat st;
54 int mode;
56 if (!shared_repository)
57 return 0;
58 if (lstat(path, &st) < 0)
59 return -1;
60 mode = st.st_mode;
61 if (mode & S_IRUSR)
62 mode |= S_IRGRP;
63 if (mode & S_IWUSR)
64 mode |= S_IWGRP;
65 if (mode & S_IXUSR)
66 mode |= S_IXGRP;
67 if (S_ISDIR(mode))
68 mode |= S_ISGID;
69 if (chmod(path, mode) < 0)
70 return -2;
71 return 0;
74 int safe_create_leading_directories(char *path)
76 char *pos = path;
77 if (*pos == '/')
78 pos++;
80 while (pos) {
81 pos = strchr(pos, '/');
82 if (!pos)
83 break;
84 *pos = 0;
85 if (mkdir(path, 0777) < 0) {
86 if (errno != EEXIST) {
87 *pos = '/';
88 return -1;
91 else if (adjust_shared_perm(path)) {
92 *pos = '/';
93 return -2;
95 *pos++ = '/';
97 return 0;
100 char * sha1_to_hex(const unsigned char *sha1)
102 static char buffer[50];
103 static const char hex[] = "0123456789abcdef";
104 char *buf = buffer;
105 int i;
107 for (i = 0; i < 20; i++) {
108 unsigned int val = *sha1++;
109 *buf++ = hex[val >> 4];
110 *buf++ = hex[val & 0xf];
112 *buf = '\0';
114 return buffer;
117 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
119 int i;
120 for (i = 0; i < 20; i++) {
121 static char hex[] = "0123456789abcdef";
122 unsigned int val = sha1[i];
123 char *pos = pathbuf + i*2 + (i > 0);
124 *pos++ = hex[val >> 4];
125 *pos = hex[val & 0xf];
130 * NOTE! This returns a statically allocated buffer, so you have to be
131 * careful about using it. Do a "strdup()" if you need to save the
132 * filename.
134 * Also note that this returns the location for creating. Reading
135 * SHA1 file can happen from any alternate directory listed in the
136 * DB_ENVIRONMENT environment variable if it is not found in
137 * the primary object database.
139 char *sha1_file_name(const unsigned char *sha1)
141 static char *name, *base;
143 if (!base) {
144 const char *sha1_file_directory = get_object_directory();
145 int len = strlen(sha1_file_directory);
146 base = xmalloc(len + 60);
147 memcpy(base, sha1_file_directory, len);
148 memset(base+len, 0, 60);
149 base[len] = '/';
150 base[len+3] = '/';
151 name = base + len + 1;
153 fill_sha1_path(name, sha1);
154 return base;
157 char *sha1_pack_name(const unsigned char *sha1)
159 static const char hex[] = "0123456789abcdef";
160 static char *name, *base, *buf;
161 int i;
163 if (!base) {
164 const char *sha1_file_directory = get_object_directory();
165 int len = strlen(sha1_file_directory);
166 base = xmalloc(len + 60);
167 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
168 name = base + len + 11;
171 buf = name;
173 for (i = 0; i < 20; i++) {
174 unsigned int val = *sha1++;
175 *buf++ = hex[val >> 4];
176 *buf++ = hex[val & 0xf];
179 return base;
182 char *sha1_pack_index_name(const unsigned char *sha1)
184 static const char hex[] = "0123456789abcdef";
185 static char *name, *base, *buf;
186 int i;
188 if (!base) {
189 const char *sha1_file_directory = get_object_directory();
190 int len = strlen(sha1_file_directory);
191 base = xmalloc(len + 60);
192 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
193 name = base + len + 11;
196 buf = name;
198 for (i = 0; i < 20; i++) {
199 unsigned int val = *sha1++;
200 *buf++ = hex[val >> 4];
201 *buf++ = hex[val & 0xf];
204 return base;
207 struct alternate_object_database *alt_odb_list;
208 static struct alternate_object_database **alt_odb_tail;
211 * Prepare alternate object database registry.
213 * The variable alt_odb_list points at the list of struct
214 * alternate_object_database. The elements on this list come from
215 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
216 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
217 * whose contents is similar to that environment variable but can be
218 * LF separated. Its base points at a statically allocated buffer that
219 * contains "/the/directory/corresponding/to/.git/objects/...", while
220 * its name points just after the slash at the end of ".git/objects/"
221 * in the example above, and has enough space to hold 40-byte hex
222 * SHA1, an extra slash for the first level indirection, and the
223 * terminating NUL.
225 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
226 const char *relative_base)
228 const char *cp, *last;
229 struct alternate_object_database *ent;
230 const char *objdir = get_object_directory();
231 int base_len = -1;
233 last = alt;
234 while (last < ep) {
235 cp = last;
236 if (cp < ep && *cp == '#') {
237 while (cp < ep && *cp != sep)
238 cp++;
239 last = cp + 1;
240 continue;
242 for ( ; cp < ep && *cp != sep; cp++)
244 if (last != cp) {
245 struct alternate_object_database *alt;
246 /* 43 = 40-byte + 2 '/' + terminating NUL */
247 int pfxlen = cp - last;
248 int entlen = pfxlen + 43;
250 if (*last != '/' && relative_base) {
251 /* Relative alt-odb */
252 if (base_len < 0)
253 base_len = strlen(relative_base) + 1;
254 entlen += base_len;
255 pfxlen += base_len;
257 ent = xmalloc(sizeof(*ent) + entlen);
259 if (*last != '/' && relative_base) {
260 memcpy(ent->base, relative_base, base_len - 1);
261 ent->base[base_len - 1] = '/';
262 memcpy(ent->base + base_len,
263 last, cp - last);
265 else
266 memcpy(ent->base, last, pfxlen);
267 ent->name = ent->base + pfxlen + 1;
268 ent->base[pfxlen] = ent->base[pfxlen + 3] = '/';
269 ent->base[entlen-1] = 0;
271 /* Prevent the common mistake of listing the same
272 * thing twice, or object directory itself.
274 for (alt = alt_odb_list; alt; alt = alt->next)
275 if (!memcmp(ent->base, alt->base, pfxlen))
276 goto bad;
277 if (!memcmp(ent->base, objdir, pfxlen)) {
278 bad:
279 free(ent);
281 else {
282 *alt_odb_tail = ent;
283 alt_odb_tail = &(ent->next);
284 ent->next = NULL;
287 while (cp < ep && *cp == sep)
288 cp++;
289 last = cp;
293 void prepare_alt_odb(void)
295 char path[PATH_MAX];
296 char *map;
297 int fd;
298 struct stat st;
299 char *alt;
301 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
302 if (!alt) alt = "";
304 if (alt_odb_tail)
305 return;
306 alt_odb_tail = &alt_odb_list;
307 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL);
309 sprintf(path, "%s/info/alternates", get_object_directory());
310 fd = open(path, O_RDONLY);
311 if (fd < 0)
312 return;
313 if (fstat(fd, &st) || (st.st_size == 0)) {
314 close(fd);
315 return;
317 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
318 close(fd);
319 if (map == MAP_FAILED)
320 return;
322 link_alt_odb_entries(map, map + st.st_size, '\n',
323 get_object_directory());
324 munmap(map, st.st_size);
327 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
329 char *name = sha1_file_name(sha1);
330 struct alternate_object_database *alt;
332 if (!stat(name, st))
333 return name;
334 prepare_alt_odb();
335 for (alt = alt_odb_list; alt; alt = alt->next) {
336 name = alt->name;
337 fill_sha1_path(name, sha1);
338 if (!stat(alt->base, st))
339 return alt->base;
341 return NULL;
344 #define PACK_MAX_SZ (1<<26)
345 static int pack_used_ctr;
346 static unsigned long pack_mapped;
347 struct packed_git *packed_git;
349 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
350 void **idx_map_)
352 void *idx_map;
353 unsigned int *index;
354 unsigned long idx_size;
355 int nr, i;
356 int fd = open(path, O_RDONLY);
357 struct stat st;
358 if (fd < 0)
359 return -1;
360 if (fstat(fd, &st)) {
361 close(fd);
362 return -1;
364 idx_size = st.st_size;
365 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
366 close(fd);
367 if (idx_map == MAP_FAILED)
368 return -1;
370 index = idx_map;
371 *idx_map_ = idx_map;
372 *idx_size_ = idx_size;
374 /* check index map */
375 if (idx_size < 4*256 + 20 + 20)
376 return error("index file too small");
377 nr = 0;
378 for (i = 0; i < 256; i++) {
379 unsigned int n = ntohl(index[i]);
380 if (n < nr)
381 return error("non-monotonic index");
382 nr = n;
386 * Total size:
387 * - 256 index entries 4 bytes each
388 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
389 * - 20-byte SHA1 of the packfile
390 * - 20-byte SHA1 file checksum
392 if (idx_size != 4*256 + nr * 24 + 20 + 20)
393 return error("wrong index file size");
395 return 0;
398 static int unuse_one_packed_git(void)
400 struct packed_git *p, *lru = NULL;
402 for (p = packed_git; p; p = p->next) {
403 if (p->pack_use_cnt || !p->pack_base)
404 continue;
405 if (!lru || p->pack_last_used < lru->pack_last_used)
406 lru = p;
408 if (!lru)
409 return 0;
410 munmap(lru->pack_base, lru->pack_size);
411 lru->pack_base = NULL;
412 return 1;
415 void unuse_packed_git(struct packed_git *p)
417 p->pack_use_cnt--;
420 int use_packed_git(struct packed_git *p)
422 if (!p->pack_size) {
423 struct stat st;
424 // We created the struct before we had the pack
425 stat(p->pack_name, &st);
426 if (!S_ISREG(st.st_mode))
427 die("packfile %s not a regular file", p->pack_name);
428 p->pack_size = st.st_size;
430 if (!p->pack_base) {
431 int fd;
432 struct stat st;
433 void *map;
435 pack_mapped += p->pack_size;
436 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
437 ; /* nothing */
438 fd = open(p->pack_name, O_RDONLY);
439 if (fd < 0)
440 die("packfile %s cannot be opened", p->pack_name);
441 if (fstat(fd, &st)) {
442 close(fd);
443 die("packfile %s cannot be opened", p->pack_name);
445 if (st.st_size != p->pack_size)
446 die("packfile %s size mismatch.", p->pack_name);
447 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
448 close(fd);
449 if (map == MAP_FAILED)
450 die("packfile %s cannot be mapped.", p->pack_name);
451 p->pack_base = map;
453 /* Check if the pack file matches with the index file.
454 * this is cheap.
456 if (memcmp((char*)(p->index_base) + p->index_size - 40,
457 p->pack_base + p->pack_size - 20, 20)) {
459 die("packfile %s does not match index.", p->pack_name);
462 p->pack_last_used = pack_used_ctr++;
463 p->pack_use_cnt++;
464 return 0;
467 struct packed_git *add_packed_git(char *path, int path_len, int local)
469 struct stat st;
470 struct packed_git *p;
471 unsigned long idx_size;
472 void *idx_map;
473 unsigned char sha1[20];
475 if (check_packed_git_idx(path, &idx_size, &idx_map))
476 return NULL;
478 /* do we have a corresponding .pack file? */
479 strcpy(path + path_len - 4, ".pack");
480 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
481 munmap(idx_map, idx_size);
482 return NULL;
484 /* ok, it looks sane as far as we can check without
485 * actually mapping the pack file.
487 p = xmalloc(sizeof(*p) + path_len + 2);
488 strcpy(p->pack_name, path);
489 p->index_size = idx_size;
490 p->pack_size = st.st_size;
491 p->index_base = idx_map;
492 p->next = NULL;
493 p->pack_base = NULL;
494 p->pack_last_used = 0;
495 p->pack_use_cnt = 0;
496 p->pack_local = local;
497 if ((path_len > 44) && !get_sha1_hex(path + path_len - 44, sha1))
498 memcpy(p->sha1, sha1, 20);
499 return p;
502 struct packed_git *parse_pack_index(unsigned char *sha1)
504 char *path = sha1_pack_index_name(sha1);
505 return parse_pack_index_file(sha1, path);
508 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
510 struct packed_git *p;
511 unsigned long idx_size;
512 void *idx_map;
513 char *path;
515 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
516 return NULL;
518 path = sha1_pack_name(sha1);
520 p = xmalloc(sizeof(*p) + strlen(path) + 2);
521 strcpy(p->pack_name, path);
522 p->index_size = idx_size;
523 p->pack_size = 0;
524 p->index_base = idx_map;
525 p->next = NULL;
526 p->pack_base = NULL;
527 p->pack_last_used = 0;
528 p->pack_use_cnt = 0;
529 memcpy(p->sha1, sha1, 20);
530 return p;
533 void install_packed_git(struct packed_git *pack)
535 pack->next = packed_git;
536 packed_git = pack;
539 static void prepare_packed_git_one(char *objdir, int local)
541 char path[PATH_MAX];
542 int len;
543 DIR *dir;
544 struct dirent *de;
546 sprintf(path, "%s/pack", objdir);
547 len = strlen(path);
548 dir = opendir(path);
549 if (!dir)
550 return;
551 path[len++] = '/';
552 while ((de = readdir(dir)) != NULL) {
553 int namelen = strlen(de->d_name);
554 struct packed_git *p;
556 if (strcmp(de->d_name + namelen - 4, ".idx"))
557 continue;
559 /* we have .idx. Is it a file we can map? */
560 strcpy(path + len, de->d_name);
561 p = add_packed_git(path, len + namelen, local);
562 if (!p)
563 continue;
564 p->next = packed_git;
565 packed_git = p;
567 closedir(dir);
570 void prepare_packed_git(void)
572 static int run_once = 0;
573 struct alternate_object_database *alt;
575 if (run_once)
576 return;
577 prepare_packed_git_one(get_object_directory(), 1);
578 prepare_alt_odb();
579 for (alt = alt_odb_list; alt; alt = alt->next) {
580 alt->name[-1] = 0;
581 prepare_packed_git_one(alt->base, 0);
582 alt->name[-1] = '/';
584 run_once = 1;
587 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
589 char header[100];
590 unsigned char real_sha1[20];
591 SHA_CTX c;
593 SHA1_Init(&c);
594 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
595 SHA1_Update(&c, map, size);
596 SHA1_Final(real_sha1, &c);
597 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
600 static void *map_sha1_file_internal(const unsigned char *sha1,
601 unsigned long *size)
603 struct stat st;
604 void *map;
605 int fd;
606 char *filename = find_sha1_file(sha1, &st);
608 if (!filename) {
609 return NULL;
612 fd = open(filename, O_RDONLY | sha1_file_open_flag);
613 if (fd < 0) {
614 /* See if it works without O_NOATIME */
615 switch (sha1_file_open_flag) {
616 default:
617 fd = open(filename, O_RDONLY);
618 if (fd >= 0)
619 break;
620 /* Fallthrough */
621 case 0:
622 return NULL;
625 /* If it failed once, it will probably fail again.
626 * Stop using O_NOATIME
628 sha1_file_open_flag = 0;
630 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
631 close(fd);
632 if (map == MAP_FAILED)
633 return NULL;
634 *size = st.st_size;
635 return map;
638 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
640 /* Get the data stream */
641 memset(stream, 0, sizeof(*stream));
642 stream->next_in = map;
643 stream->avail_in = mapsize;
644 stream->next_out = buffer;
645 stream->avail_out = size;
647 inflateInit(stream);
648 return inflate(stream, 0);
651 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
653 int bytes = strlen(buffer) + 1;
654 unsigned char *buf = xmalloc(1+size);
656 memcpy(buf, buffer + bytes, stream->total_out - bytes);
657 bytes = stream->total_out - bytes;
658 if (bytes < size) {
659 stream->next_out = buf + bytes;
660 stream->avail_out = size - bytes;
661 while (inflate(stream, Z_FINISH) == Z_OK)
662 /* nothing */;
664 buf[size] = 0;
665 inflateEnd(stream);
666 return buf;
670 * We used to just use "sscanf()", but that's actually way
671 * too permissive for what we want to check. So do an anal
672 * object header parse by hand.
674 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
676 int i;
677 unsigned long size;
680 * The type can be at most ten bytes (including the
681 * terminating '\0' that we add), and is followed by
682 * a space.
684 i = 10;
685 for (;;) {
686 char c = *hdr++;
687 if (c == ' ')
688 break;
689 if (!--i)
690 return -1;
691 *type++ = c;
693 *type = 0;
696 * The length must follow immediately, and be in canonical
697 * decimal format (ie "010" is not valid).
699 size = *hdr++ - '0';
700 if (size > 9)
701 return -1;
702 if (size) {
703 for (;;) {
704 unsigned long c = *hdr - '0';
705 if (c > 9)
706 break;
707 hdr++;
708 size = size * 10 + c;
711 *sizep = size;
714 * The length must be followed by a zero byte
716 return *hdr ? -1 : 0;
719 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
721 int ret;
722 z_stream stream;
723 char hdr[8192];
725 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
726 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
727 return NULL;
729 return unpack_sha1_rest(&stream, hdr, *size);
732 /* forward declaration for a mutually recursive function */
733 static int packed_object_info(struct pack_entry *entry,
734 char *type, unsigned long *sizep);
736 static int packed_delta_info(unsigned char *base_sha1,
737 unsigned long delta_size,
738 unsigned long left,
739 char *type,
740 unsigned long *sizep,
741 struct packed_git *p)
743 struct pack_entry base_ent;
745 if (left < 20)
746 die("truncated pack file");
748 /* The base entry _must_ be in the same pack */
749 if (!find_pack_entry_one(base_sha1, &base_ent, p))
750 die("failed to find delta-pack base object %s",
751 sha1_to_hex(base_sha1));
753 /* We choose to only get the type of the base object and
754 * ignore potentially corrupt pack file that expects the delta
755 * based on a base with a wrong size. This saves tons of
756 * inflate() calls.
759 if (packed_object_info(&base_ent, type, NULL))
760 die("cannot get info for delta-pack base");
762 if (sizep) {
763 const unsigned char *data;
764 unsigned char delta_head[64];
765 unsigned long result_size;
766 z_stream stream;
767 int st;
769 memset(&stream, 0, sizeof(stream));
771 data = stream.next_in = base_sha1 + 20;
772 stream.avail_in = left - 20;
773 stream.next_out = delta_head;
774 stream.avail_out = sizeof(delta_head);
776 inflateInit(&stream);
777 st = inflate(&stream, Z_FINISH);
778 inflateEnd(&stream);
779 if ((st != Z_STREAM_END) &&
780 stream.total_out != sizeof(delta_head))
781 die("delta data unpack-initial failed");
783 /* Examine the initial part of the delta to figure out
784 * the result size.
786 data = delta_head;
787 get_delta_hdr_size(&data); /* ignore base size */
789 /* Read the result size */
790 result_size = get_delta_hdr_size(&data);
791 *sizep = result_size;
793 return 0;
796 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
797 enum object_type *type, unsigned long *sizep)
799 unsigned shift;
800 unsigned char *pack, c;
801 unsigned long size;
803 if (offset >= p->pack_size)
804 die("object offset outside of pack file");
806 pack = p->pack_base + offset;
807 c = *pack++;
808 offset++;
809 *type = (c >> 4) & 7;
810 size = c & 15;
811 shift = 4;
812 while (c & 0x80) {
813 if (offset >= p->pack_size)
814 die("object offset outside of pack file");
815 c = *pack++;
816 offset++;
817 size += (c & 0x7f) << shift;
818 shift += 7;
820 *sizep = size;
821 return offset;
824 void packed_object_info_detail(struct pack_entry *e,
825 char *type,
826 unsigned long *size,
827 unsigned long *store_size,
828 int *delta_chain_length,
829 unsigned char *base_sha1)
831 struct packed_git *p = e->p;
832 unsigned long offset, left;
833 unsigned char *pack;
834 enum object_type kind;
836 offset = unpack_object_header(p, e->offset, &kind, size);
837 pack = p->pack_base + offset;
838 left = p->pack_size - offset;
839 if (kind != OBJ_DELTA)
840 *delta_chain_length = 0;
841 else {
842 int chain_length = 0;
843 memcpy(base_sha1, pack, 20);
844 do {
845 struct pack_entry base_ent;
846 unsigned long junk;
848 find_pack_entry_one(pack, &base_ent, p);
849 offset = unpack_object_header(p, base_ent.offset,
850 &kind, &junk);
851 pack = p->pack_base + offset;
852 chain_length++;
853 } while (kind == OBJ_DELTA);
854 *delta_chain_length = chain_length;
856 switch (kind) {
857 case OBJ_COMMIT:
858 strcpy(type, "commit");
859 break;
860 case OBJ_TREE:
861 strcpy(type, "tree");
862 break;
863 case OBJ_BLOB:
864 strcpy(type, "blob");
865 break;
866 case OBJ_TAG:
867 strcpy(type, "tag");
868 break;
869 default:
870 die("corrupted pack file %s containing object of kind %d",
871 p->pack_name, kind);
873 *store_size = 0; /* notyet */
876 static int packed_object_info(struct pack_entry *entry,
877 char *type, unsigned long *sizep)
879 struct packed_git *p = entry->p;
880 unsigned long offset, size, left;
881 unsigned char *pack;
882 enum object_type kind;
883 int retval;
885 if (use_packed_git(p))
886 die("cannot map packed file");
888 offset = unpack_object_header(p, entry->offset, &kind, &size);
889 pack = p->pack_base + offset;
890 left = p->pack_size - offset;
892 switch (kind) {
893 case OBJ_DELTA:
894 retval = packed_delta_info(pack, size, left, type, sizep, p);
895 unuse_packed_git(p);
896 return retval;
897 case OBJ_COMMIT:
898 strcpy(type, "commit");
899 break;
900 case OBJ_TREE:
901 strcpy(type, "tree");
902 break;
903 case OBJ_BLOB:
904 strcpy(type, "blob");
905 break;
906 case OBJ_TAG:
907 strcpy(type, "tag");
908 break;
909 default:
910 die("corrupted pack file %s containing object of kind %d",
911 p->pack_name, kind);
913 if (sizep)
914 *sizep = size;
915 unuse_packed_git(p);
916 return 0;
919 /* forward declaration for a mutually recursive function */
920 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
922 static void *unpack_delta_entry(unsigned char *base_sha1,
923 unsigned long delta_size,
924 unsigned long left,
925 char *type,
926 unsigned long *sizep,
927 struct packed_git *p)
929 struct pack_entry base_ent;
930 void *data, *delta_data, *result, *base;
931 unsigned long data_size, result_size, base_size;
932 z_stream stream;
933 int st;
935 if (left < 20)
936 die("truncated pack file");
937 data = base_sha1 + 20;
938 data_size = left - 20;
939 delta_data = xmalloc(delta_size);
941 memset(&stream, 0, sizeof(stream));
943 stream.next_in = data;
944 stream.avail_in = data_size;
945 stream.next_out = delta_data;
946 stream.avail_out = delta_size;
948 inflateInit(&stream);
949 st = inflate(&stream, Z_FINISH);
950 inflateEnd(&stream);
951 if ((st != Z_STREAM_END) || stream.total_out != delta_size)
952 die("delta data unpack failed");
954 /* The base entry _must_ be in the same pack */
955 if (!find_pack_entry_one(base_sha1, &base_ent, p))
956 die("failed to find delta-pack base object %s",
957 sha1_to_hex(base_sha1));
958 base = unpack_entry_gently(&base_ent, type, &base_size);
959 if (!base)
960 die("failed to read delta-pack base object %s",
961 sha1_to_hex(base_sha1));
962 result = patch_delta(base, base_size,
963 delta_data, delta_size,
964 &result_size);
965 if (!result)
966 die("failed to apply delta");
967 free(delta_data);
968 free(base);
969 *sizep = result_size;
970 return result;
973 static void *unpack_non_delta_entry(unsigned char *data,
974 unsigned long size,
975 unsigned long left)
977 int st;
978 z_stream stream;
979 unsigned char *buffer;
981 buffer = xmalloc(size + 1);
982 buffer[size] = 0;
983 memset(&stream, 0, sizeof(stream));
984 stream.next_in = data;
985 stream.avail_in = left;
986 stream.next_out = buffer;
987 stream.avail_out = size;
989 inflateInit(&stream);
990 st = inflate(&stream, Z_FINISH);
991 inflateEnd(&stream);
992 if ((st != Z_STREAM_END) || stream.total_out != size) {
993 free(buffer);
994 return NULL;
997 return buffer;
1000 static void *unpack_entry(struct pack_entry *entry,
1001 char *type, unsigned long *sizep)
1003 struct packed_git *p = entry->p;
1004 void *retval;
1006 if (use_packed_git(p))
1007 die("cannot map packed file");
1008 retval = unpack_entry_gently(entry, type, sizep);
1009 unuse_packed_git(p);
1010 if (!retval)
1011 die("corrupted pack file %s", p->pack_name);
1012 return retval;
1015 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
1016 void *unpack_entry_gently(struct pack_entry *entry,
1017 char *type, unsigned long *sizep)
1019 struct packed_git *p = entry->p;
1020 unsigned long offset, size, left;
1021 unsigned char *pack;
1022 enum object_type kind;
1023 void *retval;
1025 offset = unpack_object_header(p, entry->offset, &kind, &size);
1026 pack = p->pack_base + offset;
1027 left = p->pack_size - offset;
1028 switch (kind) {
1029 case OBJ_DELTA:
1030 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
1031 return retval;
1032 case OBJ_COMMIT:
1033 strcpy(type, "commit");
1034 break;
1035 case OBJ_TREE:
1036 strcpy(type, "tree");
1037 break;
1038 case OBJ_BLOB:
1039 strcpy(type, "blob");
1040 break;
1041 case OBJ_TAG:
1042 strcpy(type, "tag");
1043 break;
1044 default:
1045 return NULL;
1047 *sizep = size;
1048 retval = unpack_non_delta_entry(pack, size, left);
1049 return retval;
1052 int num_packed_objects(const struct packed_git *p)
1054 /* See check_packed_git_idx() */
1055 return (p->index_size - 20 - 20 - 4*256) / 24;
1058 int nth_packed_object_sha1(const struct packed_git *p, int n,
1059 unsigned char* sha1)
1061 void *index = p->index_base + 256;
1062 if (n < 0 || num_packed_objects(p) <= n)
1063 return -1;
1064 memcpy(sha1, (index + 24 * n + 4), 20);
1065 return 0;
1068 int find_pack_entry_one(const unsigned char *sha1,
1069 struct pack_entry *e, struct packed_git *p)
1071 unsigned int *level1_ofs = p->index_base;
1072 int hi = ntohl(level1_ofs[*sha1]);
1073 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1074 void *index = p->index_base + 256;
1076 do {
1077 int mi = (lo + hi) / 2;
1078 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
1079 if (!cmp) {
1080 e->offset = ntohl(*((int*)(index + 24 * mi)));
1081 memcpy(e->sha1, sha1, 20);
1082 e->p = p;
1083 return 1;
1085 if (cmp > 0)
1086 hi = mi;
1087 else
1088 lo = mi+1;
1089 } while (lo < hi);
1090 return 0;
1093 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1095 struct packed_git *p;
1096 prepare_packed_git();
1098 for (p = packed_git; p; p = p->next) {
1099 if (find_pack_entry_one(sha1, e, p))
1100 return 1;
1102 return 0;
1105 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1106 struct packed_git *packs)
1108 struct packed_git *p;
1109 struct pack_entry e;
1111 for (p = packs; p; p = p->next) {
1112 if (find_pack_entry_one(sha1, &e, p))
1113 return p;
1115 return NULL;
1119 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1121 int status;
1122 unsigned long mapsize, size;
1123 void *map;
1124 z_stream stream;
1125 char hdr[128];
1127 map = map_sha1_file_internal(sha1, &mapsize);
1128 if (!map) {
1129 struct pack_entry e;
1131 if (!find_pack_entry(sha1, &e))
1132 return error("unable to find %s", sha1_to_hex(sha1));
1133 return packed_object_info(&e, type, sizep);
1135 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1136 status = error("unable to unpack %s header",
1137 sha1_to_hex(sha1));
1138 if (parse_sha1_header(hdr, type, &size) < 0)
1139 status = error("unable to parse %s header", sha1_to_hex(sha1));
1140 else {
1141 status = 0;
1142 if (sizep)
1143 *sizep = size;
1145 inflateEnd(&stream);
1146 munmap(map, mapsize);
1147 return status;
1150 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1152 struct pack_entry e;
1154 if (!find_pack_entry(sha1, &e)) {
1155 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1156 return NULL;
1158 return unpack_entry(&e, type, size);
1161 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1163 unsigned long mapsize;
1164 void *map, *buf;
1165 struct pack_entry e;
1167 if (find_pack_entry(sha1, &e))
1168 return read_packed_sha1(sha1, type, size);
1169 map = map_sha1_file_internal(sha1, &mapsize);
1170 if (map) {
1171 buf = unpack_sha1_file(map, mapsize, type, size);
1172 munmap(map, mapsize);
1173 return buf;
1175 return NULL;
1178 void *read_object_with_reference(const unsigned char *sha1,
1179 const char *required_type,
1180 unsigned long *size,
1181 unsigned char *actual_sha1_return)
1183 char type[20];
1184 void *buffer;
1185 unsigned long isize;
1186 unsigned char actual_sha1[20];
1188 memcpy(actual_sha1, sha1, 20);
1189 while (1) {
1190 int ref_length = -1;
1191 const char *ref_type = NULL;
1193 buffer = read_sha1_file(actual_sha1, type, &isize);
1194 if (!buffer)
1195 return NULL;
1196 if (!strcmp(type, required_type)) {
1197 *size = isize;
1198 if (actual_sha1_return)
1199 memcpy(actual_sha1_return, actual_sha1, 20);
1200 return buffer;
1202 /* Handle references */
1203 else if (!strcmp(type, "commit"))
1204 ref_type = "tree ";
1205 else if (!strcmp(type, "tag"))
1206 ref_type = "object ";
1207 else {
1208 free(buffer);
1209 return NULL;
1211 ref_length = strlen(ref_type);
1213 if (memcmp(buffer, ref_type, ref_length) ||
1214 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1215 free(buffer);
1216 return NULL;
1218 free(buffer);
1219 /* Now we have the ID of the referred-to object in
1220 * actual_sha1. Check again. */
1224 char *write_sha1_file_prepare(void *buf,
1225 unsigned long len,
1226 const char *type,
1227 unsigned char *sha1,
1228 unsigned char *hdr,
1229 int *hdrlen)
1231 SHA_CTX c;
1233 /* Generate the header */
1234 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1236 /* Sha1.. */
1237 SHA1_Init(&c);
1238 SHA1_Update(&c, hdr, *hdrlen);
1239 SHA1_Update(&c, buf, len);
1240 SHA1_Final(sha1, &c);
1242 return sha1_file_name(sha1);
1246 * Link the tempfile to the final place, possibly creating the
1247 * last directory level as you do so.
1249 * Returns the errno on failure, 0 on success.
1251 static int link_temp_to_file(const char *tmpfile, char *filename)
1253 int ret;
1255 if (!link(tmpfile, filename))
1256 return 0;
1259 * Try to mkdir the last path component if that failed
1260 * with an ENOENT.
1262 * Re-try the "link()" regardless of whether the mkdir
1263 * succeeds, since a race might mean that somebody
1264 * else succeeded.
1266 ret = errno;
1267 if (ret == ENOENT) {
1268 char *dir = strrchr(filename, '/');
1269 if (dir) {
1270 *dir = 0;
1271 mkdir(filename, 0777);
1272 if (adjust_shared_perm(filename))
1273 return -2;
1274 *dir = '/';
1275 if (!link(tmpfile, filename))
1276 return 0;
1277 ret = errno;
1280 return ret;
1284 * Move the just written object into its final resting place
1286 int move_temp_to_file(const char *tmpfile, char *filename)
1288 int ret = link_temp_to_file(tmpfile, filename);
1291 * Coda hack - coda doesn't like cross-directory links,
1292 * so we fall back to a rename, which will mean that it
1293 * won't be able to check collisions, but that's not a
1294 * big deal.
1296 * The same holds for FAT formatted media.
1298 * When this succeeds, we just return 0. We have nothing
1299 * left to unlink.
1301 if (ret && ret != EEXIST) {
1302 if (!rename(tmpfile, filename))
1303 return 0;
1304 ret = errno;
1306 unlink(tmpfile);
1307 if (ret) {
1308 if (ret != EEXIST) {
1309 fprintf(stderr, "unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1310 return -1;
1312 /* FIXME!!! Collision check here ? */
1315 return 0;
1318 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1320 int size;
1321 unsigned char *compressed;
1322 z_stream stream;
1323 unsigned char sha1[20];
1324 char *filename;
1325 static char tmpfile[PATH_MAX];
1326 unsigned char hdr[50];
1327 int fd, hdrlen;
1329 /* Normally if we have it in the pack then we do not bother writing
1330 * it out into .git/objects/??/?{38} file.
1332 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1333 if (returnsha1)
1334 memcpy(returnsha1, sha1, 20);
1335 if (has_sha1_file(sha1))
1336 return 0;
1337 fd = open(filename, O_RDONLY);
1338 if (fd >= 0) {
1340 * FIXME!!! We might do collision checking here, but we'd
1341 * need to uncompress the old file and check it. Later.
1343 close(fd);
1344 return 0;
1347 if (errno != ENOENT) {
1348 fprintf(stderr, "sha1 file %s: %s\n", filename, strerror(errno));
1349 return -1;
1352 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1354 fd = mkstemp(tmpfile);
1355 if (fd < 0) {
1356 fprintf(stderr, "unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
1357 return -1;
1360 /* Set it up */
1361 memset(&stream, 0, sizeof(stream));
1362 deflateInit(&stream, Z_BEST_COMPRESSION);
1363 size = deflateBound(&stream, len+hdrlen);
1364 compressed = xmalloc(size);
1366 /* Compress it */
1367 stream.next_out = compressed;
1368 stream.avail_out = size;
1370 /* First header.. */
1371 stream.next_in = hdr;
1372 stream.avail_in = hdrlen;
1373 while (deflate(&stream, 0) == Z_OK)
1374 /* nothing */;
1376 /* Then the data itself.. */
1377 stream.next_in = buf;
1378 stream.avail_in = len;
1379 while (deflate(&stream, Z_FINISH) == Z_OK)
1380 /* nothing */;
1381 deflateEnd(&stream);
1382 size = stream.total_out;
1384 if (write(fd, compressed, size) != size)
1385 die("unable to write file");
1386 fchmod(fd, 0444);
1387 close(fd);
1388 free(compressed);
1390 return move_temp_to_file(tmpfile, filename);
1393 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1395 ssize_t size;
1396 unsigned long objsize;
1397 int posn = 0;
1398 void *map = map_sha1_file_internal(sha1, &objsize);
1399 void *buf = map;
1400 void *temp_obj = NULL;
1401 z_stream stream;
1403 if (!buf) {
1404 unsigned char *unpacked;
1405 unsigned long len;
1406 char type[20];
1407 char hdr[50];
1408 int hdrlen;
1409 // need to unpack and recompress it by itself
1410 unpacked = read_packed_sha1(sha1, type, &len);
1412 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1414 /* Set it up */
1415 memset(&stream, 0, sizeof(stream));
1416 deflateInit(&stream, Z_BEST_COMPRESSION);
1417 size = deflateBound(&stream, len + hdrlen);
1418 temp_obj = buf = xmalloc(size);
1420 /* Compress it */
1421 stream.next_out = buf;
1422 stream.avail_out = size;
1424 /* First header.. */
1425 stream.next_in = (void *)hdr;
1426 stream.avail_in = hdrlen;
1427 while (deflate(&stream, 0) == Z_OK)
1428 /* nothing */;
1430 /* Then the data itself.. */
1431 stream.next_in = unpacked;
1432 stream.avail_in = len;
1433 while (deflate(&stream, Z_FINISH) == Z_OK)
1434 /* nothing */;
1435 deflateEnd(&stream);
1436 free(unpacked);
1438 objsize = stream.total_out;
1441 do {
1442 size = write(fd, buf + posn, objsize - posn);
1443 if (size <= 0) {
1444 if (!size) {
1445 fprintf(stderr, "write closed\n");
1446 } else {
1447 perror("write ");
1449 return -1;
1451 posn += size;
1452 } while (posn < objsize);
1454 if (map)
1455 munmap(map, objsize);
1456 if (temp_obj)
1457 free(temp_obj);
1459 return 0;
1462 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1463 size_t bufsize, size_t *bufposn)
1465 char tmpfile[PATH_MAX];
1466 int local;
1467 z_stream stream;
1468 unsigned char real_sha1[20];
1469 unsigned char discard[4096];
1470 int ret;
1471 SHA_CTX c;
1473 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1475 local = mkstemp(tmpfile);
1476 if (local < 0)
1477 return error("Couldn't open %s for %s\n", tmpfile, sha1_to_hex(sha1));
1479 memset(&stream, 0, sizeof(stream));
1481 inflateInit(&stream);
1483 SHA1_Init(&c);
1485 do {
1486 ssize_t size;
1487 if (*bufposn) {
1488 stream.avail_in = *bufposn;
1489 stream.next_in = (unsigned char *) buffer;
1490 do {
1491 stream.next_out = discard;
1492 stream.avail_out = sizeof(discard);
1493 ret = inflate(&stream, Z_SYNC_FLUSH);
1494 SHA1_Update(&c, discard, sizeof(discard) -
1495 stream.avail_out);
1496 } while (stream.avail_in && ret == Z_OK);
1497 write(local, buffer, *bufposn - stream.avail_in);
1498 memmove(buffer, buffer + *bufposn - stream.avail_in,
1499 stream.avail_in);
1500 *bufposn = stream.avail_in;
1501 if (ret != Z_OK)
1502 break;
1504 size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1505 if (size <= 0) {
1506 close(local);
1507 unlink(tmpfile);
1508 if (!size)
1509 return error("Connection closed?");
1510 perror("Reading from connection");
1511 return -1;
1513 *bufposn += size;
1514 } while (1);
1515 inflateEnd(&stream);
1517 close(local);
1518 SHA1_Final(real_sha1, &c);
1519 if (ret != Z_STREAM_END) {
1520 unlink(tmpfile);
1521 return error("File %s corrupted", sha1_to_hex(sha1));
1523 if (memcmp(sha1, real_sha1, 20)) {
1524 unlink(tmpfile);
1525 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1528 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1531 int has_pack_index(const unsigned char *sha1)
1533 struct stat st;
1534 if (stat(sha1_pack_index_name(sha1), &st))
1535 return 0;
1536 return 1;
1539 int has_pack_file(const unsigned char *sha1)
1541 struct stat st;
1542 if (stat(sha1_pack_name(sha1), &st))
1543 return 0;
1544 return 1;
1547 int has_sha1_pack(const unsigned char *sha1)
1549 struct pack_entry e;
1550 return find_pack_entry(sha1, &e);
1553 int has_sha1_file(const unsigned char *sha1)
1555 struct stat st;
1556 struct pack_entry e;
1558 if (find_pack_entry(sha1, &e))
1559 return 1;
1560 return find_sha1_file(sha1, &st) ? 1 : 0;
1563 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
1565 unsigned long size = 4096;
1566 char *buf = malloc(size);
1567 int iret, ret;
1568 unsigned long off = 0;
1569 unsigned char hdr[50];
1570 int hdrlen;
1571 do {
1572 iret = read(fd, buf + off, size - off);
1573 if (iret > 0) {
1574 off += iret;
1575 if (off == size) {
1576 size *= 2;
1577 buf = realloc(buf, size);
1580 } while (iret > 0);
1581 if (iret < 0) {
1582 free(buf);
1583 return -1;
1585 if (!type)
1586 type = "blob";
1587 if (write_object)
1588 ret = write_sha1_file(buf, off, type, sha1);
1589 else {
1590 write_sha1_file_prepare(buf, off, type, sha1, hdr, &hdrlen);
1591 ret = 0;
1593 free(buf);
1594 return ret;
1597 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1599 unsigned long size = st->st_size;
1600 void *buf;
1601 int ret;
1602 unsigned char hdr[50];
1603 int hdrlen;
1605 buf = "";
1606 if (size)
1607 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1608 close(fd);
1609 if (buf == MAP_FAILED)
1610 return -1;
1612 if (!type)
1613 type = "blob";
1614 if (write_object)
1615 ret = write_sha1_file(buf, size, type, sha1);
1616 else {
1617 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1618 ret = 0;
1620 if (size)
1621 munmap(buf, size);
1622 return ret;
1625 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1627 int fd;
1628 char *target;
1630 switch (st->st_mode & S_IFMT) {
1631 case S_IFREG:
1632 fd = open(path, O_RDONLY);
1633 if (fd < 0)
1634 return error("open(\"%s\"): %s", path,
1635 strerror(errno));
1636 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1637 return error("%s: failed to insert into database",
1638 path);
1639 break;
1640 case S_IFLNK:
1641 target = xmalloc(st->st_size+1);
1642 if (readlink(path, target, st->st_size+1) != st->st_size) {
1643 char *errstr = strerror(errno);
1644 free(target);
1645 return error("readlink(\"%s\"): %s", path,
1646 errstr);
1648 if (!write_object) {
1649 unsigned char hdr[50];
1650 int hdrlen;
1651 write_sha1_file_prepare(target, st->st_size, "blob",
1652 sha1, hdr, &hdrlen);
1653 } else if (write_sha1_file(target, st->st_size, "blob", sha1))
1654 return error("%s: failed to insert into database",
1655 path);
1656 free(target);
1657 break;
1658 default:
1659 return error("%s: unsupported file type", path);
1661 return 0;