GIT-VERSION-GEN: detect dirty tree and mark the version accordingly.
[git/git-svn.git] / sha1_file.c
blob8bebbb255f762fc36f165b87023d8cc37732968a
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 SHA_CTX ctx;
353 unsigned char sha1[20];
354 void *idx_map;
355 unsigned int *index;
356 unsigned long idx_size;
357 int nr, i;
358 int fd;
359 struct stat st;
361 fd = open(path, O_RDONLY);
362 if (fd < 0)
363 return -1;
364 if (fstat(fd, &st)) {
365 close(fd);
366 return -1;
368 idx_size = st.st_size;
369 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
370 close(fd);
371 if (idx_map == MAP_FAILED)
372 return -1;
374 index = idx_map;
375 *idx_map_ = idx_map;
376 *idx_size_ = idx_size;
378 /* check index map */
379 if (idx_size < 4*256 + 20 + 20)
380 return error("index file too small");
381 nr = 0;
382 for (i = 0; i < 256; i++) {
383 unsigned int n = ntohl(index[i]);
384 if (n < nr)
385 return error("non-monotonic index");
386 nr = n;
390 * Total size:
391 * - 256 index entries 4 bytes each
392 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
393 * - 20-byte SHA1 of the packfile
394 * - 20-byte SHA1 file checksum
396 if (idx_size != 4*256 + nr * 24 + 20 + 20)
397 return error("wrong index file size");
400 * File checksum.
402 SHA1_Init(&ctx);
403 SHA1_Update(&ctx, idx_map, idx_size-20);
404 SHA1_Final(sha1, &ctx);
406 if (memcmp(sha1, idx_map + idx_size - 20, 20))
407 return error("index checksum mismatch");
409 return 0;
412 static int unuse_one_packed_git(void)
414 struct packed_git *p, *lru = NULL;
416 for (p = packed_git; p; p = p->next) {
417 if (p->pack_use_cnt || !p->pack_base)
418 continue;
419 if (!lru || p->pack_last_used < lru->pack_last_used)
420 lru = p;
422 if (!lru)
423 return 0;
424 munmap(lru->pack_base, lru->pack_size);
425 lru->pack_base = NULL;
426 return 1;
429 void unuse_packed_git(struct packed_git *p)
431 p->pack_use_cnt--;
434 int use_packed_git(struct packed_git *p)
436 if (!p->pack_size) {
437 struct stat st;
438 // We created the struct before we had the pack
439 stat(p->pack_name, &st);
440 if (!S_ISREG(st.st_mode))
441 die("packfile %s not a regular file", p->pack_name);
442 p->pack_size = st.st_size;
444 if (!p->pack_base) {
445 int fd;
446 struct stat st;
447 void *map;
449 pack_mapped += p->pack_size;
450 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
451 ; /* nothing */
452 fd = open(p->pack_name, O_RDONLY);
453 if (fd < 0)
454 die("packfile %s cannot be opened", p->pack_name);
455 if (fstat(fd, &st)) {
456 close(fd);
457 die("packfile %s cannot be opened", p->pack_name);
459 if (st.st_size != p->pack_size)
460 die("packfile %s size mismatch.", p->pack_name);
461 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
462 close(fd);
463 if (map == MAP_FAILED)
464 die("packfile %s cannot be mapped.", p->pack_name);
465 p->pack_base = map;
467 /* Check if the pack file matches with the index file.
468 * this is cheap.
470 if (memcmp((char*)(p->index_base) + p->index_size - 40,
471 p->pack_base + p->pack_size - 20, 20)) {
473 die("packfile %s does not match index.", p->pack_name);
476 p->pack_last_used = pack_used_ctr++;
477 p->pack_use_cnt++;
478 return 0;
481 struct packed_git *add_packed_git(char *path, int path_len, int local)
483 struct stat st;
484 struct packed_git *p;
485 unsigned long idx_size;
486 void *idx_map;
487 unsigned char sha1[20];
489 if (check_packed_git_idx(path, &idx_size, &idx_map))
490 return NULL;
492 /* do we have a corresponding .pack file? */
493 strcpy(path + path_len - 4, ".pack");
494 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
495 munmap(idx_map, idx_size);
496 return NULL;
498 /* ok, it looks sane as far as we can check without
499 * actually mapping the pack file.
501 p = xmalloc(sizeof(*p) + path_len + 2);
502 strcpy(p->pack_name, path);
503 p->index_size = idx_size;
504 p->pack_size = st.st_size;
505 p->index_base = idx_map;
506 p->next = NULL;
507 p->pack_base = NULL;
508 p->pack_last_used = 0;
509 p->pack_use_cnt = 0;
510 p->pack_local = local;
511 if ((path_len > 44) && !get_sha1_hex(path + path_len - 44, sha1))
512 memcpy(p->sha1, sha1, 20);
513 return p;
516 struct packed_git *parse_pack_index(unsigned char *sha1)
518 char *path = sha1_pack_index_name(sha1);
519 return parse_pack_index_file(sha1, path);
522 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
524 struct packed_git *p;
525 unsigned long idx_size;
526 void *idx_map;
527 char *path;
529 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
530 return NULL;
532 path = sha1_pack_name(sha1);
534 p = xmalloc(sizeof(*p) + strlen(path) + 2);
535 strcpy(p->pack_name, path);
536 p->index_size = idx_size;
537 p->pack_size = 0;
538 p->index_base = idx_map;
539 p->next = NULL;
540 p->pack_base = NULL;
541 p->pack_last_used = 0;
542 p->pack_use_cnt = 0;
543 memcpy(p->sha1, sha1, 20);
544 return p;
547 void install_packed_git(struct packed_git *pack)
549 pack->next = packed_git;
550 packed_git = pack;
553 static void prepare_packed_git_one(char *objdir, int local)
555 char path[PATH_MAX];
556 int len;
557 DIR *dir;
558 struct dirent *de;
560 sprintf(path, "%s/pack", objdir);
561 len = strlen(path);
562 dir = opendir(path);
563 if (!dir)
564 return;
565 path[len++] = '/';
566 while ((de = readdir(dir)) != NULL) {
567 int namelen = strlen(de->d_name);
568 struct packed_git *p;
570 if (strcmp(de->d_name + namelen - 4, ".idx"))
571 continue;
573 /* we have .idx. Is it a file we can map? */
574 strcpy(path + len, de->d_name);
575 p = add_packed_git(path, len + namelen, local);
576 if (!p)
577 continue;
578 p->next = packed_git;
579 packed_git = p;
581 closedir(dir);
584 void prepare_packed_git(void)
586 static int run_once = 0;
587 struct alternate_object_database *alt;
589 if (run_once)
590 return;
591 prepare_packed_git_one(get_object_directory(), 1);
592 prepare_alt_odb();
593 for (alt = alt_odb_list; alt; alt = alt->next) {
594 alt->name[-1] = 0;
595 prepare_packed_git_one(alt->base, 0);
596 alt->name[-1] = '/';
598 run_once = 1;
601 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
603 char header[100];
604 unsigned char real_sha1[20];
605 SHA_CTX c;
607 SHA1_Init(&c);
608 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
609 SHA1_Update(&c, map, size);
610 SHA1_Final(real_sha1, &c);
611 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
614 static void *map_sha1_file_internal(const unsigned char *sha1,
615 unsigned long *size)
617 struct stat st;
618 void *map;
619 int fd;
620 char *filename = find_sha1_file(sha1, &st);
622 if (!filename) {
623 return NULL;
626 fd = open(filename, O_RDONLY | sha1_file_open_flag);
627 if (fd < 0) {
628 /* See if it works without O_NOATIME */
629 switch (sha1_file_open_flag) {
630 default:
631 fd = open(filename, O_RDONLY);
632 if (fd >= 0)
633 break;
634 /* Fallthrough */
635 case 0:
636 return NULL;
639 /* If it failed once, it will probably fail again.
640 * Stop using O_NOATIME
642 sha1_file_open_flag = 0;
644 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
645 close(fd);
646 if (map == MAP_FAILED)
647 return NULL;
648 *size = st.st_size;
649 return map;
652 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
654 /* Get the data stream */
655 memset(stream, 0, sizeof(*stream));
656 stream->next_in = map;
657 stream->avail_in = mapsize;
658 stream->next_out = buffer;
659 stream->avail_out = size;
661 inflateInit(stream);
662 return inflate(stream, 0);
665 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
667 int bytes = strlen(buffer) + 1;
668 unsigned char *buf = xmalloc(1+size);
670 memcpy(buf, buffer + bytes, stream->total_out - bytes);
671 bytes = stream->total_out - bytes;
672 if (bytes < size) {
673 stream->next_out = buf + bytes;
674 stream->avail_out = size - bytes;
675 while (inflate(stream, Z_FINISH) == Z_OK)
676 /* nothing */;
678 buf[size] = 0;
679 inflateEnd(stream);
680 return buf;
684 * We used to just use "sscanf()", but that's actually way
685 * too permissive for what we want to check. So do an anal
686 * object header parse by hand.
688 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
690 int i;
691 unsigned long size;
694 * The type can be at most ten bytes (including the
695 * terminating '\0' that we add), and is followed by
696 * a space.
698 i = 10;
699 for (;;) {
700 char c = *hdr++;
701 if (c == ' ')
702 break;
703 if (!--i)
704 return -1;
705 *type++ = c;
707 *type = 0;
710 * The length must follow immediately, and be in canonical
711 * decimal format (ie "010" is not valid).
713 size = *hdr++ - '0';
714 if (size > 9)
715 return -1;
716 if (size) {
717 for (;;) {
718 unsigned long c = *hdr - '0';
719 if (c > 9)
720 break;
721 hdr++;
722 size = size * 10 + c;
725 *sizep = size;
728 * The length must be followed by a zero byte
730 return *hdr ? -1 : 0;
733 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
735 int ret;
736 z_stream stream;
737 char hdr[8192];
739 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
740 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
741 return NULL;
743 return unpack_sha1_rest(&stream, hdr, *size);
746 /* forward declaration for a mutually recursive function */
747 static int packed_object_info(struct pack_entry *entry,
748 char *type, unsigned long *sizep);
750 static int packed_delta_info(unsigned char *base_sha1,
751 unsigned long delta_size,
752 unsigned long left,
753 char *type,
754 unsigned long *sizep,
755 struct packed_git *p)
757 struct pack_entry base_ent;
759 if (left < 20)
760 die("truncated pack file");
762 /* The base entry _must_ be in the same pack */
763 if (!find_pack_entry_one(base_sha1, &base_ent, p))
764 die("failed to find delta-pack base object %s",
765 sha1_to_hex(base_sha1));
767 /* We choose to only get the type of the base object and
768 * ignore potentially corrupt pack file that expects the delta
769 * based on a base with a wrong size. This saves tons of
770 * inflate() calls.
773 if (packed_object_info(&base_ent, type, NULL))
774 die("cannot get info for delta-pack base");
776 if (sizep) {
777 const unsigned char *data;
778 unsigned char delta_head[64];
779 unsigned long result_size;
780 z_stream stream;
781 int st;
783 memset(&stream, 0, sizeof(stream));
785 data = stream.next_in = base_sha1 + 20;
786 stream.avail_in = left - 20;
787 stream.next_out = delta_head;
788 stream.avail_out = sizeof(delta_head);
790 inflateInit(&stream);
791 st = inflate(&stream, Z_FINISH);
792 inflateEnd(&stream);
793 if ((st != Z_STREAM_END) &&
794 stream.total_out != sizeof(delta_head))
795 die("delta data unpack-initial failed");
797 /* Examine the initial part of the delta to figure out
798 * the result size.
800 data = delta_head;
801 get_delta_hdr_size(&data); /* ignore base size */
803 /* Read the result size */
804 result_size = get_delta_hdr_size(&data);
805 *sizep = result_size;
807 return 0;
810 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
811 enum object_type *type, unsigned long *sizep)
813 unsigned shift;
814 unsigned char *pack, c;
815 unsigned long size;
817 if (offset >= p->pack_size)
818 die("object offset outside of pack file");
820 pack = p->pack_base + offset;
821 c = *pack++;
822 offset++;
823 *type = (c >> 4) & 7;
824 size = c & 15;
825 shift = 4;
826 while (c & 0x80) {
827 if (offset >= p->pack_size)
828 die("object offset outside of pack file");
829 c = *pack++;
830 offset++;
831 size += (c & 0x7f) << shift;
832 shift += 7;
834 *sizep = size;
835 return offset;
838 void packed_object_info_detail(struct pack_entry *e,
839 char *type,
840 unsigned long *size,
841 unsigned long *store_size,
842 int *delta_chain_length,
843 unsigned char *base_sha1)
845 struct packed_git *p = e->p;
846 unsigned long offset, left;
847 unsigned char *pack;
848 enum object_type kind;
850 offset = unpack_object_header(p, e->offset, &kind, size);
851 pack = p->pack_base + offset;
852 left = p->pack_size - offset;
853 if (kind != OBJ_DELTA)
854 *delta_chain_length = 0;
855 else {
856 int chain_length = 0;
857 memcpy(base_sha1, pack, 20);
858 do {
859 struct pack_entry base_ent;
860 unsigned long junk;
862 find_pack_entry_one(pack, &base_ent, p);
863 offset = unpack_object_header(p, base_ent.offset,
864 &kind, &junk);
865 pack = p->pack_base + offset;
866 chain_length++;
867 } while (kind == OBJ_DELTA);
868 *delta_chain_length = chain_length;
870 switch (kind) {
871 case OBJ_COMMIT:
872 strcpy(type, "commit");
873 break;
874 case OBJ_TREE:
875 strcpy(type, "tree");
876 break;
877 case OBJ_BLOB:
878 strcpy(type, "blob");
879 break;
880 case OBJ_TAG:
881 strcpy(type, "tag");
882 break;
883 default:
884 die("corrupted pack file %s containing object of kind %d",
885 p->pack_name, kind);
887 *store_size = 0; /* notyet */
890 static int packed_object_info(struct pack_entry *entry,
891 char *type, unsigned long *sizep)
893 struct packed_git *p = entry->p;
894 unsigned long offset, size, left;
895 unsigned char *pack;
896 enum object_type kind;
897 int retval;
899 if (use_packed_git(p))
900 die("cannot map packed file");
902 offset = unpack_object_header(p, entry->offset, &kind, &size);
903 pack = p->pack_base + offset;
904 left = p->pack_size - offset;
906 switch (kind) {
907 case OBJ_DELTA:
908 retval = packed_delta_info(pack, size, left, type, sizep, p);
909 unuse_packed_git(p);
910 return retval;
911 case OBJ_COMMIT:
912 strcpy(type, "commit");
913 break;
914 case OBJ_TREE:
915 strcpy(type, "tree");
916 break;
917 case OBJ_BLOB:
918 strcpy(type, "blob");
919 break;
920 case OBJ_TAG:
921 strcpy(type, "tag");
922 break;
923 default:
924 die("corrupted pack file %s containing object of kind %d",
925 p->pack_name, kind);
927 if (sizep)
928 *sizep = size;
929 unuse_packed_git(p);
930 return 0;
933 /* forward declaration for a mutually recursive function */
934 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
936 static void *unpack_delta_entry(unsigned char *base_sha1,
937 unsigned long delta_size,
938 unsigned long left,
939 char *type,
940 unsigned long *sizep,
941 struct packed_git *p)
943 struct pack_entry base_ent;
944 void *data, *delta_data, *result, *base;
945 unsigned long data_size, result_size, base_size;
946 z_stream stream;
947 int st;
949 if (left < 20)
950 die("truncated pack file");
951 data = base_sha1 + 20;
952 data_size = left - 20;
953 delta_data = xmalloc(delta_size);
955 memset(&stream, 0, sizeof(stream));
957 stream.next_in = data;
958 stream.avail_in = data_size;
959 stream.next_out = delta_data;
960 stream.avail_out = delta_size;
962 inflateInit(&stream);
963 st = inflate(&stream, Z_FINISH);
964 inflateEnd(&stream);
965 if ((st != Z_STREAM_END) || stream.total_out != delta_size)
966 die("delta data unpack failed");
968 /* The base entry _must_ be in the same pack */
969 if (!find_pack_entry_one(base_sha1, &base_ent, p))
970 die("failed to find delta-pack base object %s",
971 sha1_to_hex(base_sha1));
972 base = unpack_entry_gently(&base_ent, type, &base_size);
973 if (!base)
974 die("failed to read delta-pack base object %s",
975 sha1_to_hex(base_sha1));
976 result = patch_delta(base, base_size,
977 delta_data, delta_size,
978 &result_size);
979 if (!result)
980 die("failed to apply delta");
981 free(delta_data);
982 free(base);
983 *sizep = result_size;
984 return result;
987 static void *unpack_non_delta_entry(unsigned char *data,
988 unsigned long size,
989 unsigned long left)
991 int st;
992 z_stream stream;
993 unsigned char *buffer;
995 buffer = xmalloc(size + 1);
996 buffer[size] = 0;
997 memset(&stream, 0, sizeof(stream));
998 stream.next_in = data;
999 stream.avail_in = left;
1000 stream.next_out = buffer;
1001 stream.avail_out = size;
1003 inflateInit(&stream);
1004 st = inflate(&stream, Z_FINISH);
1005 inflateEnd(&stream);
1006 if ((st != Z_STREAM_END) || stream.total_out != size) {
1007 free(buffer);
1008 return NULL;
1011 return buffer;
1014 static void *unpack_entry(struct pack_entry *entry,
1015 char *type, unsigned long *sizep)
1017 struct packed_git *p = entry->p;
1018 void *retval;
1020 if (use_packed_git(p))
1021 die("cannot map packed file");
1022 retval = unpack_entry_gently(entry, type, sizep);
1023 unuse_packed_git(p);
1024 if (!retval)
1025 die("corrupted pack file %s", p->pack_name);
1026 return retval;
1029 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
1030 void *unpack_entry_gently(struct pack_entry *entry,
1031 char *type, unsigned long *sizep)
1033 struct packed_git *p = entry->p;
1034 unsigned long offset, size, left;
1035 unsigned char *pack;
1036 enum object_type kind;
1037 void *retval;
1039 offset = unpack_object_header(p, entry->offset, &kind, &size);
1040 pack = p->pack_base + offset;
1041 left = p->pack_size - offset;
1042 switch (kind) {
1043 case OBJ_DELTA:
1044 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
1045 return retval;
1046 case OBJ_COMMIT:
1047 strcpy(type, "commit");
1048 break;
1049 case OBJ_TREE:
1050 strcpy(type, "tree");
1051 break;
1052 case OBJ_BLOB:
1053 strcpy(type, "blob");
1054 break;
1055 case OBJ_TAG:
1056 strcpy(type, "tag");
1057 break;
1058 default:
1059 return NULL;
1061 *sizep = size;
1062 retval = unpack_non_delta_entry(pack, size, left);
1063 return retval;
1066 int num_packed_objects(const struct packed_git *p)
1068 /* See check_packed_git_idx() */
1069 return (p->index_size - 20 - 20 - 4*256) / 24;
1072 int nth_packed_object_sha1(const struct packed_git *p, int n,
1073 unsigned char* sha1)
1075 void *index = p->index_base + 256;
1076 if (n < 0 || num_packed_objects(p) <= n)
1077 return -1;
1078 memcpy(sha1, (index + 24 * n + 4), 20);
1079 return 0;
1082 int find_pack_entry_one(const unsigned char *sha1,
1083 struct pack_entry *e, struct packed_git *p)
1085 unsigned int *level1_ofs = p->index_base;
1086 int hi = ntohl(level1_ofs[*sha1]);
1087 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1088 void *index = p->index_base + 256;
1090 do {
1091 int mi = (lo + hi) / 2;
1092 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
1093 if (!cmp) {
1094 e->offset = ntohl(*((int*)(index + 24 * mi)));
1095 memcpy(e->sha1, sha1, 20);
1096 e->p = p;
1097 return 1;
1099 if (cmp > 0)
1100 hi = mi;
1101 else
1102 lo = mi+1;
1103 } while (lo < hi);
1104 return 0;
1107 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1109 struct packed_git *p;
1110 prepare_packed_git();
1112 for (p = packed_git; p; p = p->next) {
1113 if (find_pack_entry_one(sha1, e, p))
1114 return 1;
1116 return 0;
1119 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1120 struct packed_git *packs)
1122 struct packed_git *p;
1123 struct pack_entry e;
1125 for (p = packs; p; p = p->next) {
1126 if (find_pack_entry_one(sha1, &e, p))
1127 return p;
1129 return NULL;
1133 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1135 int status;
1136 unsigned long mapsize, size;
1137 void *map;
1138 z_stream stream;
1139 char hdr[128];
1141 map = map_sha1_file_internal(sha1, &mapsize);
1142 if (!map) {
1143 struct pack_entry e;
1145 if (!find_pack_entry(sha1, &e))
1146 return error("unable to find %s", sha1_to_hex(sha1));
1147 return packed_object_info(&e, type, sizep);
1149 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1150 status = error("unable to unpack %s header",
1151 sha1_to_hex(sha1));
1152 if (parse_sha1_header(hdr, type, &size) < 0)
1153 status = error("unable to parse %s header", sha1_to_hex(sha1));
1154 else {
1155 status = 0;
1156 if (sizep)
1157 *sizep = size;
1159 inflateEnd(&stream);
1160 munmap(map, mapsize);
1161 return status;
1164 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1166 struct pack_entry e;
1168 if (!find_pack_entry(sha1, &e)) {
1169 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1170 return NULL;
1172 return unpack_entry(&e, type, size);
1175 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1177 unsigned long mapsize;
1178 void *map, *buf;
1179 struct pack_entry e;
1181 if (find_pack_entry(sha1, &e))
1182 return read_packed_sha1(sha1, type, size);
1183 map = map_sha1_file_internal(sha1, &mapsize);
1184 if (map) {
1185 buf = unpack_sha1_file(map, mapsize, type, size);
1186 munmap(map, mapsize);
1187 return buf;
1189 return NULL;
1192 void *read_object_with_reference(const unsigned char *sha1,
1193 const char *required_type,
1194 unsigned long *size,
1195 unsigned char *actual_sha1_return)
1197 char type[20];
1198 void *buffer;
1199 unsigned long isize;
1200 unsigned char actual_sha1[20];
1202 memcpy(actual_sha1, sha1, 20);
1203 while (1) {
1204 int ref_length = -1;
1205 const char *ref_type = NULL;
1207 buffer = read_sha1_file(actual_sha1, type, &isize);
1208 if (!buffer)
1209 return NULL;
1210 if (!strcmp(type, required_type)) {
1211 *size = isize;
1212 if (actual_sha1_return)
1213 memcpy(actual_sha1_return, actual_sha1, 20);
1214 return buffer;
1216 /* Handle references */
1217 else if (!strcmp(type, "commit"))
1218 ref_type = "tree ";
1219 else if (!strcmp(type, "tag"))
1220 ref_type = "object ";
1221 else {
1222 free(buffer);
1223 return NULL;
1225 ref_length = strlen(ref_type);
1227 if (memcmp(buffer, ref_type, ref_length) ||
1228 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1229 free(buffer);
1230 return NULL;
1232 free(buffer);
1233 /* Now we have the ID of the referred-to object in
1234 * actual_sha1. Check again. */
1238 char *write_sha1_file_prepare(void *buf,
1239 unsigned long len,
1240 const char *type,
1241 unsigned char *sha1,
1242 unsigned char *hdr,
1243 int *hdrlen)
1245 SHA_CTX c;
1247 /* Generate the header */
1248 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1250 /* Sha1.. */
1251 SHA1_Init(&c);
1252 SHA1_Update(&c, hdr, *hdrlen);
1253 SHA1_Update(&c, buf, len);
1254 SHA1_Final(sha1, &c);
1256 return sha1_file_name(sha1);
1260 * Link the tempfile to the final place, possibly creating the
1261 * last directory level as you do so.
1263 * Returns the errno on failure, 0 on success.
1265 static int link_temp_to_file(const char *tmpfile, char *filename)
1267 int ret;
1269 if (!link(tmpfile, filename))
1270 return 0;
1273 * Try to mkdir the last path component if that failed
1274 * with an ENOENT.
1276 * Re-try the "link()" regardless of whether the mkdir
1277 * succeeds, since a race might mean that somebody
1278 * else succeeded.
1280 ret = errno;
1281 if (ret == ENOENT) {
1282 char *dir = strrchr(filename, '/');
1283 if (dir) {
1284 *dir = 0;
1285 mkdir(filename, 0777);
1286 if (adjust_shared_perm(filename))
1287 return -2;
1288 *dir = '/';
1289 if (!link(tmpfile, filename))
1290 return 0;
1291 ret = errno;
1294 return ret;
1298 * Move the just written object into its final resting place
1300 int move_temp_to_file(const char *tmpfile, char *filename)
1302 int ret = link_temp_to_file(tmpfile, filename);
1305 * Coda hack - coda doesn't like cross-directory links,
1306 * so we fall back to a rename, which will mean that it
1307 * won't be able to check collisions, but that's not a
1308 * big deal.
1310 * The same holds for FAT formatted media.
1312 * When this succeeds, we just return 0. We have nothing
1313 * left to unlink.
1315 if (ret && ret != EEXIST) {
1316 if (!rename(tmpfile, filename))
1317 return 0;
1318 ret = errno;
1320 unlink(tmpfile);
1321 if (ret) {
1322 if (ret != EEXIST) {
1323 fprintf(stderr, "unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1324 return -1;
1326 /* FIXME!!! Collision check here ? */
1329 return 0;
1332 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1334 int size;
1335 unsigned char *compressed;
1336 z_stream stream;
1337 unsigned char sha1[20];
1338 char *filename;
1339 static char tmpfile[PATH_MAX];
1340 unsigned char hdr[50];
1341 int fd, hdrlen;
1343 /* Normally if we have it in the pack then we do not bother writing
1344 * it out into .git/objects/??/?{38} file.
1346 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1347 if (returnsha1)
1348 memcpy(returnsha1, sha1, 20);
1349 if (has_sha1_file(sha1))
1350 return 0;
1351 fd = open(filename, O_RDONLY);
1352 if (fd >= 0) {
1354 * FIXME!!! We might do collision checking here, but we'd
1355 * need to uncompress the old file and check it. Later.
1357 close(fd);
1358 return 0;
1361 if (errno != ENOENT) {
1362 fprintf(stderr, "sha1 file %s: %s\n", filename, strerror(errno));
1363 return -1;
1366 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1368 fd = mkstemp(tmpfile);
1369 if (fd < 0) {
1370 fprintf(stderr, "unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
1371 return -1;
1374 /* Set it up */
1375 memset(&stream, 0, sizeof(stream));
1376 deflateInit(&stream, Z_BEST_COMPRESSION);
1377 size = deflateBound(&stream, len+hdrlen);
1378 compressed = xmalloc(size);
1380 /* Compress it */
1381 stream.next_out = compressed;
1382 stream.avail_out = size;
1384 /* First header.. */
1385 stream.next_in = hdr;
1386 stream.avail_in = hdrlen;
1387 while (deflate(&stream, 0) == Z_OK)
1388 /* nothing */;
1390 /* Then the data itself.. */
1391 stream.next_in = buf;
1392 stream.avail_in = len;
1393 while (deflate(&stream, Z_FINISH) == Z_OK)
1394 /* nothing */;
1395 deflateEnd(&stream);
1396 size = stream.total_out;
1398 if (write(fd, compressed, size) != size)
1399 die("unable to write file");
1400 fchmod(fd, 0444);
1401 close(fd);
1402 free(compressed);
1404 return move_temp_to_file(tmpfile, filename);
1407 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1409 ssize_t size;
1410 unsigned long objsize;
1411 int posn = 0;
1412 void *map = map_sha1_file_internal(sha1, &objsize);
1413 void *buf = map;
1414 void *temp_obj = NULL;
1415 z_stream stream;
1417 if (!buf) {
1418 unsigned char *unpacked;
1419 unsigned long len;
1420 char type[20];
1421 char hdr[50];
1422 int hdrlen;
1423 // need to unpack and recompress it by itself
1424 unpacked = read_packed_sha1(sha1, type, &len);
1426 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1428 /* Set it up */
1429 memset(&stream, 0, sizeof(stream));
1430 deflateInit(&stream, Z_BEST_COMPRESSION);
1431 size = deflateBound(&stream, len + hdrlen);
1432 temp_obj = buf = xmalloc(size);
1434 /* Compress it */
1435 stream.next_out = buf;
1436 stream.avail_out = size;
1438 /* First header.. */
1439 stream.next_in = (void *)hdr;
1440 stream.avail_in = hdrlen;
1441 while (deflate(&stream, 0) == Z_OK)
1442 /* nothing */;
1444 /* Then the data itself.. */
1445 stream.next_in = unpacked;
1446 stream.avail_in = len;
1447 while (deflate(&stream, Z_FINISH) == Z_OK)
1448 /* nothing */;
1449 deflateEnd(&stream);
1450 free(unpacked);
1452 objsize = stream.total_out;
1455 do {
1456 size = write(fd, buf + posn, objsize - posn);
1457 if (size <= 0) {
1458 if (!size) {
1459 fprintf(stderr, "write closed\n");
1460 } else {
1461 perror("write ");
1463 return -1;
1465 posn += size;
1466 } while (posn < objsize);
1468 if (map)
1469 munmap(map, objsize);
1470 if (temp_obj)
1471 free(temp_obj);
1473 return 0;
1476 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1477 size_t bufsize, size_t *bufposn)
1479 char tmpfile[PATH_MAX];
1480 int local;
1481 z_stream stream;
1482 unsigned char real_sha1[20];
1483 unsigned char discard[4096];
1484 int ret;
1485 SHA_CTX c;
1487 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1489 local = mkstemp(tmpfile);
1490 if (local < 0)
1491 return error("Couldn't open %s for %s\n", tmpfile, sha1_to_hex(sha1));
1493 memset(&stream, 0, sizeof(stream));
1495 inflateInit(&stream);
1497 SHA1_Init(&c);
1499 do {
1500 ssize_t size;
1501 if (*bufposn) {
1502 stream.avail_in = *bufposn;
1503 stream.next_in = (unsigned char *) buffer;
1504 do {
1505 stream.next_out = discard;
1506 stream.avail_out = sizeof(discard);
1507 ret = inflate(&stream, Z_SYNC_FLUSH);
1508 SHA1_Update(&c, discard, sizeof(discard) -
1509 stream.avail_out);
1510 } while (stream.avail_in && ret == Z_OK);
1511 write(local, buffer, *bufposn - stream.avail_in);
1512 memmove(buffer, buffer + *bufposn - stream.avail_in,
1513 stream.avail_in);
1514 *bufposn = stream.avail_in;
1515 if (ret != Z_OK)
1516 break;
1518 size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1519 if (size <= 0) {
1520 close(local);
1521 unlink(tmpfile);
1522 if (!size)
1523 return error("Connection closed?");
1524 perror("Reading from connection");
1525 return -1;
1527 *bufposn += size;
1528 } while (1);
1529 inflateEnd(&stream);
1531 close(local);
1532 SHA1_Final(real_sha1, &c);
1533 if (ret != Z_STREAM_END) {
1534 unlink(tmpfile);
1535 return error("File %s corrupted", sha1_to_hex(sha1));
1537 if (memcmp(sha1, real_sha1, 20)) {
1538 unlink(tmpfile);
1539 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1542 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1545 int has_pack_index(const unsigned char *sha1)
1547 struct stat st;
1548 if (stat(sha1_pack_index_name(sha1), &st))
1549 return 0;
1550 return 1;
1553 int has_pack_file(const unsigned char *sha1)
1555 struct stat st;
1556 if (stat(sha1_pack_name(sha1), &st))
1557 return 0;
1558 return 1;
1561 int has_sha1_pack(const unsigned char *sha1)
1563 struct pack_entry e;
1564 return find_pack_entry(sha1, &e);
1567 int has_sha1_file(const unsigned char *sha1)
1569 struct stat st;
1570 struct pack_entry e;
1572 if (find_pack_entry(sha1, &e))
1573 return 1;
1574 return find_sha1_file(sha1, &st) ? 1 : 0;
1577 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
1579 unsigned long size = 4096;
1580 char *buf = malloc(size);
1581 int iret, ret;
1582 unsigned long off = 0;
1583 unsigned char hdr[50];
1584 int hdrlen;
1585 do {
1586 iret = read(fd, buf + off, size - off);
1587 if (iret > 0) {
1588 off += iret;
1589 if (off == size) {
1590 size *= 2;
1591 buf = realloc(buf, size);
1594 } while (iret > 0);
1595 if (iret < 0) {
1596 free(buf);
1597 return -1;
1599 if (!type)
1600 type = "blob";
1601 if (write_object)
1602 ret = write_sha1_file(buf, off, type, sha1);
1603 else {
1604 write_sha1_file_prepare(buf, off, type, sha1, hdr, &hdrlen);
1605 ret = 0;
1607 free(buf);
1608 return ret;
1611 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1613 unsigned long size = st->st_size;
1614 void *buf;
1615 int ret;
1616 unsigned char hdr[50];
1617 int hdrlen;
1619 buf = "";
1620 if (size)
1621 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1622 close(fd);
1623 if (buf == MAP_FAILED)
1624 return -1;
1626 if (!type)
1627 type = "blob";
1628 if (write_object)
1629 ret = write_sha1_file(buf, size, type, sha1);
1630 else {
1631 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1632 ret = 0;
1634 if (size)
1635 munmap(buf, size);
1636 return ret;
1639 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1641 int fd;
1642 char *target;
1644 switch (st->st_mode & S_IFMT) {
1645 case S_IFREG:
1646 fd = open(path, O_RDONLY);
1647 if (fd < 0)
1648 return error("open(\"%s\"): %s", path,
1649 strerror(errno));
1650 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1651 return error("%s: failed to insert into database",
1652 path);
1653 break;
1654 case S_IFLNK:
1655 target = xmalloc(st->st_size+1);
1656 if (readlink(path, target, st->st_size+1) != st->st_size) {
1657 char *errstr = strerror(errno);
1658 free(target);
1659 return error("readlink(\"%s\"): %s", path,
1660 errstr);
1662 if (!write_object) {
1663 unsigned char hdr[50];
1664 int hdrlen;
1665 write_sha1_file_prepare(target, st->st_size, "blob",
1666 sha1, hdr, &hdrlen);
1667 } else if (write_sha1_file(target, st->st_size, "blob", sha1))
1668 return error("%s: failed to insert into database",
1669 path);
1670 free(target);
1671 break;
1672 default:
1673 return error("%s: unsupported file type", path);
1675 return 0;