Support custom build options in config.mak
[git/jrn.git] / sha1_file.c
blob6e3ea232eecc0f190925568ecb86fb24c93e6c94
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 static char *git_dir, *git_object_dir, *git_index_file, *git_refs_dir,
52 *git_graft_file;
53 static void setup_git_env(void)
55 git_dir = getenv(GIT_DIR_ENVIRONMENT);
56 if (!git_dir)
57 git_dir = DEFAULT_GIT_DIR_ENVIRONMENT;
58 git_object_dir = getenv(DB_ENVIRONMENT);
59 if (!git_object_dir) {
60 git_object_dir = xmalloc(strlen(git_dir) + 9);
61 sprintf(git_object_dir, "%s/objects", git_dir);
63 git_refs_dir = xmalloc(strlen(git_dir) + 6);
64 sprintf(git_refs_dir, "%s/refs", git_dir);
65 git_index_file = getenv(INDEX_ENVIRONMENT);
66 if (!git_index_file) {
67 git_index_file = xmalloc(strlen(git_dir) + 7);
68 sprintf(git_index_file, "%s/index", git_dir);
70 git_graft_file = getenv(GRAFT_ENVIRONMENT);
71 if (!git_graft_file)
72 git_graft_file = strdup(git_path("info/grafts"));
75 char *get_git_dir(void)
77 if (!git_dir)
78 setup_git_env();
79 return git_dir;
82 char *get_object_directory(void)
84 if (!git_object_dir)
85 setup_git_env();
86 return git_object_dir;
89 char *get_refs_directory(void)
91 if (!git_refs_dir)
92 setup_git_env();
93 return git_refs_dir;
96 char *get_index_file(void)
98 if (!git_index_file)
99 setup_git_env();
100 return git_index_file;
103 char *get_graft_file(void)
105 if (!git_graft_file)
106 setup_git_env();
107 return git_graft_file;
110 int safe_create_leading_directories(char *path)
112 char *pos = path;
114 while (pos) {
115 pos = strchr(pos, '/');
116 if (!pos)
117 break;
118 *pos = 0;
119 if (mkdir(path, 0777) < 0)
120 if (errno != EEXIST) {
121 *pos = '/';
122 return -1;
124 *pos++ = '/';
126 return 0;
129 char * sha1_to_hex(const unsigned char *sha1)
131 static char buffer[50];
132 static const char hex[] = "0123456789abcdef";
133 char *buf = buffer;
134 int i;
136 for (i = 0; i < 20; i++) {
137 unsigned int val = *sha1++;
138 *buf++ = hex[val >> 4];
139 *buf++ = hex[val & 0xf];
141 return buffer;
144 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
146 int i;
147 for (i = 0; i < 20; i++) {
148 static char hex[] = "0123456789abcdef";
149 unsigned int val = sha1[i];
150 char *pos = pathbuf + i*2 + (i > 0);
151 *pos++ = hex[val >> 4];
152 *pos = hex[val & 0xf];
157 * NOTE! This returns a statically allocated buffer, so you have to be
158 * careful about using it. Do a "strdup()" if you need to save the
159 * filename.
161 * Also note that this returns the location for creating. Reading
162 * SHA1 file can happen from any alternate directory listed in the
163 * DB_ENVIRONMENT environment variable if it is not found in
164 * the primary object database.
166 char *sha1_file_name(const unsigned char *sha1)
168 static char *name, *base;
170 if (!base) {
171 const char *sha1_file_directory = get_object_directory();
172 int len = strlen(sha1_file_directory);
173 base = xmalloc(len + 60);
174 memcpy(base, sha1_file_directory, len);
175 memset(base+len, 0, 60);
176 base[len] = '/';
177 base[len+3] = '/';
178 name = base + len + 1;
180 fill_sha1_path(name, sha1);
181 return base;
184 char *sha1_pack_name(const unsigned char *sha1)
186 static const char hex[] = "0123456789abcdef";
187 static char *name, *base, *buf;
188 int i;
190 if (!base) {
191 const char *sha1_file_directory = get_object_directory();
192 int len = strlen(sha1_file_directory);
193 base = xmalloc(len + 60);
194 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
195 name = base + len + 11;
198 buf = name;
200 for (i = 0; i < 20; i++) {
201 unsigned int val = *sha1++;
202 *buf++ = hex[val >> 4];
203 *buf++ = hex[val & 0xf];
206 return base;
209 char *sha1_pack_index_name(const unsigned char *sha1)
211 static const char hex[] = "0123456789abcdef";
212 static char *name, *base, *buf;
213 int i;
215 if (!base) {
216 const char *sha1_file_directory = get_object_directory();
217 int len = strlen(sha1_file_directory);
218 base = xmalloc(len + 60);
219 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
220 name = base + len + 11;
223 buf = name;
225 for (i = 0; i < 20; i++) {
226 unsigned int val = *sha1++;
227 *buf++ = hex[val >> 4];
228 *buf++ = hex[val & 0xf];
231 return base;
234 struct alternate_object_database *alt_odb_list;
235 static struct alternate_object_database **alt_odb_tail;
238 * Prepare alternate object database registry.
240 * The variable alt_odb_list points at the list of struct
241 * alternate_object_database. The elements on this list come from
242 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
243 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
244 * whose contents is exactly in the same format as that environment
245 * variable. Its base points at a statically allocated buffer that
246 * contains "/the/directory/corresponding/to/.git/objects/...", while
247 * its name points just after the slash at the end of ".git/objects/"
248 * in the example above, and has enough space to hold 40-byte hex
249 * SHA1, an extra slash for the first level indirection, and the
250 * terminating NUL.
252 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
253 const char *relative_base)
255 const char *cp, *last;
256 struct alternate_object_database *ent;
257 int base_len = -1;
259 last = alt;
260 while (last < ep) {
261 cp = last;
262 if (cp < ep && *cp == '#') {
263 while (cp < ep && *cp != sep)
264 cp++;
265 last = cp + 1;
266 continue;
268 for ( ; cp < ep && *cp != sep; cp++)
270 if (last != cp) {
271 /* 43 = 40-byte + 2 '/' + terminating NUL */
272 int pfxlen = cp - last;
273 int entlen = pfxlen + 43;
275 if (*last != '/' && relative_base) {
276 /* Relative alt-odb */
277 if (base_len < 0)
278 base_len = strlen(relative_base) + 1;
279 entlen += base_len;
280 pfxlen += base_len;
282 ent = xmalloc(sizeof(*ent) + entlen);
283 *alt_odb_tail = ent;
284 alt_odb_tail = &(ent->next);
285 ent->next = NULL;
286 if (*last != '/' && relative_base) {
287 memcpy(ent->base, relative_base, base_len - 1);
288 ent->base[base_len - 1] = '/';
289 memcpy(ent->base + base_len,
290 last, cp - last);
292 else
293 memcpy(ent->base, last, pfxlen);
294 ent->name = ent->base + pfxlen + 1;
295 ent->base[pfxlen] = ent->base[pfxlen + 3] = '/';
296 ent->base[entlen-1] = 0;
298 while (cp < ep && *cp == sep)
299 cp++;
300 last = cp;
304 void prepare_alt_odb(void)
306 char path[PATH_MAX];
307 char *map;
308 int fd;
309 struct stat st;
310 char *alt;
312 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
313 if (!alt) alt = "";
315 if (alt_odb_tail)
316 return;
317 alt_odb_tail = &alt_odb_list;
318 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL);
320 sprintf(path, "%s/info/alternates", get_object_directory());
321 fd = open(path, O_RDONLY);
322 if (fd < 0)
323 return;
324 if (fstat(fd, &st) || (st.st_size == 0)) {
325 close(fd);
326 return;
328 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
329 close(fd);
330 if (map == MAP_FAILED)
331 return;
333 link_alt_odb_entries(map, map + st.st_size, '\n',
334 get_object_directory());
335 munmap(map, st.st_size);
338 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
340 char *name = sha1_file_name(sha1);
341 struct alternate_object_database *alt;
343 if (!stat(name, st))
344 return name;
345 prepare_alt_odb();
346 for (alt = alt_odb_list; alt; alt = alt->next) {
347 name = alt->name;
348 fill_sha1_path(name, sha1);
349 if (!stat(alt->base, st))
350 return alt->base;
352 return NULL;
355 #define PACK_MAX_SZ (1<<26)
356 static int pack_used_ctr;
357 static unsigned long pack_mapped;
358 struct packed_git *packed_git;
360 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
361 void **idx_map_)
363 void *idx_map;
364 unsigned int *index;
365 unsigned long idx_size;
366 int nr, i;
367 int fd = open(path, O_RDONLY);
368 struct stat st;
369 if (fd < 0)
370 return -1;
371 if (fstat(fd, &st)) {
372 close(fd);
373 return -1;
375 idx_size = st.st_size;
376 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
377 close(fd);
378 if (idx_map == MAP_FAILED)
379 return -1;
381 index = idx_map;
382 *idx_map_ = idx_map;
383 *idx_size_ = idx_size;
385 /* check index map */
386 if (idx_size < 4*256 + 20 + 20)
387 return error("index file too small");
388 nr = 0;
389 for (i = 0; i < 256; i++) {
390 unsigned int n = ntohl(index[i]);
391 if (n < nr)
392 return error("non-monotonic index");
393 nr = n;
397 * Total size:
398 * - 256 index entries 4 bytes each
399 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
400 * - 20-byte SHA1 of the packfile
401 * - 20-byte SHA1 file checksum
403 if (idx_size != 4*256 + nr * 24 + 20 + 20)
404 return error("wrong index file size");
406 return 0;
409 static int unuse_one_packed_git(void)
411 struct packed_git *p, *lru = NULL;
413 for (p = packed_git; p; p = p->next) {
414 if (p->pack_use_cnt || !p->pack_base)
415 continue;
416 if (!lru || p->pack_last_used < lru->pack_last_used)
417 lru = p;
419 if (!lru)
420 return 0;
421 munmap(lru->pack_base, lru->pack_size);
422 lru->pack_base = NULL;
423 return 1;
426 void unuse_packed_git(struct packed_git *p)
428 p->pack_use_cnt--;
431 int use_packed_git(struct packed_git *p)
433 if (!p->pack_size) {
434 struct stat st;
435 // We created the struct before we had the pack
436 stat(p->pack_name, &st);
437 if (!S_ISREG(st.st_mode))
438 die("packfile %s not a regular file", p->pack_name);
439 p->pack_size = st.st_size;
441 if (!p->pack_base) {
442 int fd;
443 struct stat st;
444 void *map;
446 pack_mapped += p->pack_size;
447 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
448 ; /* nothing */
449 fd = open(p->pack_name, O_RDONLY);
450 if (fd < 0)
451 die("packfile %s cannot be opened", p->pack_name);
452 if (fstat(fd, &st)) {
453 close(fd);
454 die("packfile %s cannot be opened", p->pack_name);
456 if (st.st_size != p->pack_size)
457 die("packfile %s size mismatch.", p->pack_name);
458 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
459 close(fd);
460 if (map == MAP_FAILED)
461 die("packfile %s cannot be mapped.", p->pack_name);
462 p->pack_base = map;
464 /* Check if the pack file matches with the index file.
465 * this is cheap.
467 if (memcmp((char*)(p->index_base) + p->index_size - 40,
468 p->pack_base + p->pack_size - 20, 20)) {
470 die("packfile %s does not match index.", p->pack_name);
473 p->pack_last_used = pack_used_ctr++;
474 p->pack_use_cnt++;
475 return 0;
478 struct packed_git *add_packed_git(char *path, int path_len)
480 struct stat st;
481 struct packed_git *p;
482 unsigned long idx_size;
483 void *idx_map;
485 if (check_packed_git_idx(path, &idx_size, &idx_map))
486 return NULL;
488 /* do we have a corresponding .pack file? */
489 strcpy(path + path_len - 4, ".pack");
490 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
491 munmap(idx_map, idx_size);
492 return NULL;
494 /* ok, it looks sane as far as we can check without
495 * actually mapping the pack file.
497 p = xmalloc(sizeof(*p) + path_len + 2);
498 strcpy(p->pack_name, path);
499 p->index_size = idx_size;
500 p->pack_size = st.st_size;
501 p->index_base = idx_map;
502 p->next = NULL;
503 p->pack_base = NULL;
504 p->pack_last_used = 0;
505 p->pack_use_cnt = 0;
506 return p;
509 struct packed_git *parse_pack_index(unsigned char *sha1)
511 char *path = sha1_pack_index_name(sha1);
512 return parse_pack_index_file(sha1, path);
515 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
517 struct packed_git *p;
518 unsigned long idx_size;
519 void *idx_map;
520 char *path;
522 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
523 return NULL;
525 path = sha1_pack_name(sha1);
527 p = xmalloc(sizeof(*p) + strlen(path) + 2);
528 strcpy(p->pack_name, path);
529 p->index_size = idx_size;
530 p->pack_size = 0;
531 p->index_base = idx_map;
532 p->next = NULL;
533 p->pack_base = NULL;
534 p->pack_last_used = 0;
535 p->pack_use_cnt = 0;
536 memcpy(p->sha1, sha1, 20);
537 return p;
540 void install_packed_git(struct packed_git *pack)
542 pack->next = packed_git;
543 packed_git = pack;
546 static void prepare_packed_git_one(char *objdir)
548 char path[PATH_MAX];
549 int len;
550 DIR *dir;
551 struct dirent *de;
553 sprintf(path, "%s/pack", objdir);
554 len = strlen(path);
555 dir = opendir(path);
556 if (!dir)
557 return;
558 path[len++] = '/';
559 while ((de = readdir(dir)) != NULL) {
560 int namelen = strlen(de->d_name);
561 struct packed_git *p;
563 if (strcmp(de->d_name + namelen - 4, ".idx"))
564 continue;
566 /* we have .idx. Is it a file we can map? */
567 strcpy(path + len, de->d_name);
568 p = add_packed_git(path, len + namelen);
569 if (!p)
570 continue;
571 p->next = packed_git;
572 packed_git = p;
574 closedir(dir);
577 void prepare_packed_git(void)
579 static int run_once = 0;
580 struct alternate_object_database *alt;
582 if (run_once)
583 return;
584 prepare_packed_git_one(get_object_directory());
585 prepare_alt_odb();
586 for (alt = alt_odb_list; alt; alt = alt->next) {
587 alt->name[0] = 0;
588 prepare_packed_git_one(alt->base);
590 run_once = 1;
593 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
595 char header[100];
596 unsigned char real_sha1[20];
597 SHA_CTX c;
599 SHA1_Init(&c);
600 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
601 SHA1_Update(&c, map, size);
602 SHA1_Final(real_sha1, &c);
603 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
606 static void *map_sha1_file_internal(const unsigned char *sha1,
607 unsigned long *size)
609 struct stat st;
610 void *map;
611 int fd;
612 char *filename = find_sha1_file(sha1, &st);
614 if (!filename) {
615 return NULL;
618 fd = open(filename, O_RDONLY | sha1_file_open_flag);
619 if (fd < 0) {
620 /* See if it works without O_NOATIME */
621 switch (sha1_file_open_flag) {
622 default:
623 fd = open(filename, O_RDONLY);
624 if (fd >= 0)
625 break;
626 /* Fallthrough */
627 case 0:
628 return NULL;
631 /* If it failed once, it will probably fail again.
632 * Stop using O_NOATIME
634 sha1_file_open_flag = 0;
636 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
637 close(fd);
638 if (map == MAP_FAILED)
639 return NULL;
640 *size = st.st_size;
641 return map;
644 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
646 /* Get the data stream */
647 memset(stream, 0, sizeof(*stream));
648 stream->next_in = map;
649 stream->avail_in = mapsize;
650 stream->next_out = buffer;
651 stream->avail_out = size;
653 inflateInit(stream);
654 return inflate(stream, 0);
657 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
659 int bytes = strlen(buffer) + 1;
660 unsigned char *buf = xmalloc(1+size);
662 memcpy(buf, buffer + bytes, stream->total_out - bytes);
663 bytes = stream->total_out - bytes;
664 if (bytes < size) {
665 stream->next_out = buf + bytes;
666 stream->avail_out = size - bytes;
667 while (inflate(stream, Z_FINISH) == Z_OK)
668 /* nothing */;
670 buf[size] = 0;
671 inflateEnd(stream);
672 return buf;
676 * We used to just use "sscanf()", but that's actually way
677 * too permissive for what we want to check. So do an anal
678 * object header parse by hand.
680 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
682 int i;
683 unsigned long size;
686 * The type can be at most ten bytes (including the
687 * terminating '\0' that we add), and is followed by
688 * a space.
690 i = 10;
691 for (;;) {
692 char c = *hdr++;
693 if (c == ' ')
694 break;
695 if (!--i)
696 return -1;
697 *type++ = c;
699 *type = 0;
702 * The length must follow immediately, and be in canonical
703 * decimal format (ie "010" is not valid).
705 size = *hdr++ - '0';
706 if (size > 9)
707 return -1;
708 if (size) {
709 for (;;) {
710 unsigned long c = *hdr - '0';
711 if (c > 9)
712 break;
713 hdr++;
714 size = size * 10 + c;
717 *sizep = size;
720 * The length must be followed by a zero byte
722 return *hdr ? -1 : 0;
725 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
727 int ret;
728 z_stream stream;
729 char hdr[8192];
731 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
732 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
733 return NULL;
735 return unpack_sha1_rest(&stream, hdr, *size);
738 /* forward declaration for a mutually recursive function */
739 static int packed_object_info(struct pack_entry *entry,
740 char *type, unsigned long *sizep);
742 static int packed_delta_info(unsigned char *base_sha1,
743 unsigned long delta_size,
744 unsigned long left,
745 char *type,
746 unsigned long *sizep,
747 struct packed_git *p)
749 struct pack_entry base_ent;
751 if (left < 20)
752 die("truncated pack file");
754 /* The base entry _must_ be in the same pack */
755 if (!find_pack_entry_one(base_sha1, &base_ent, p))
756 die("failed to find delta-pack base object %s",
757 sha1_to_hex(base_sha1));
759 /* We choose to only get the type of the base object and
760 * ignore potentially corrupt pack file that expects the delta
761 * based on a base with a wrong size. This saves tons of
762 * inflate() calls.
765 if (packed_object_info(&base_ent, type, NULL))
766 die("cannot get info for delta-pack base");
768 if (sizep) {
769 const unsigned char *data;
770 unsigned char delta_head[64];
771 unsigned long result_size;
772 z_stream stream;
773 int st;
775 memset(&stream, 0, sizeof(stream));
777 data = stream.next_in = base_sha1 + 20;
778 stream.avail_in = left - 20;
779 stream.next_out = delta_head;
780 stream.avail_out = sizeof(delta_head);
782 inflateInit(&stream);
783 st = inflate(&stream, Z_FINISH);
784 inflateEnd(&stream);
785 if ((st != Z_STREAM_END) &&
786 stream.total_out != sizeof(delta_head))
787 die("delta data unpack-initial failed");
789 /* Examine the initial part of the delta to figure out
790 * the result size.
792 data = delta_head;
793 get_delta_hdr_size(&data); /* ignore base size */
795 /* Read the result size */
796 result_size = get_delta_hdr_size(&data);
797 *sizep = result_size;
799 return 0;
802 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
803 enum object_type *type, unsigned long *sizep)
805 unsigned shift;
806 unsigned char *pack, c;
807 unsigned long size;
809 if (offset >= p->pack_size)
810 die("object offset outside of pack file");
812 pack = p->pack_base + offset;
813 c = *pack++;
814 offset++;
815 *type = (c >> 4) & 7;
816 size = c & 15;
817 shift = 4;
818 while (c & 0x80) {
819 if (offset >= p->pack_size)
820 die("object offset outside of pack file");
821 c = *pack++;
822 offset++;
823 size += (c & 0x7f) << shift;
824 shift += 7;
826 *sizep = size;
827 return offset;
830 void packed_object_info_detail(struct pack_entry *e,
831 char *type,
832 unsigned long *size,
833 unsigned long *store_size,
834 int *delta_chain_length,
835 unsigned char *base_sha1)
837 struct packed_git *p = e->p;
838 unsigned long offset, left;
839 unsigned char *pack;
840 enum object_type kind;
842 offset = unpack_object_header(p, e->offset, &kind, size);
843 pack = p->pack_base + offset;
844 left = p->pack_size - offset;
845 if (kind != OBJ_DELTA)
846 *delta_chain_length = 0;
847 else {
848 int chain_length = 0;
849 memcpy(base_sha1, pack, 20);
850 do {
851 struct pack_entry base_ent;
852 unsigned long junk;
854 find_pack_entry_one(pack, &base_ent, p);
855 offset = unpack_object_header(p, base_ent.offset,
856 &kind, &junk);
857 pack = p->pack_base + offset;
858 chain_length++;
859 } while (kind == OBJ_DELTA);
860 *delta_chain_length = chain_length;
862 switch (kind) {
863 case OBJ_COMMIT:
864 strcpy(type, "commit");
865 break;
866 case OBJ_TREE:
867 strcpy(type, "tree");
868 break;
869 case OBJ_BLOB:
870 strcpy(type, "blob");
871 break;
872 case OBJ_TAG:
873 strcpy(type, "tag");
874 break;
875 default:
876 die("corrupted pack file %s containing object of kind %d",
877 p->pack_name, kind);
879 *store_size = 0; /* notyet */
882 static int packed_object_info(struct pack_entry *entry,
883 char *type, unsigned long *sizep)
885 struct packed_git *p = entry->p;
886 unsigned long offset, size, left;
887 unsigned char *pack;
888 enum object_type kind;
889 int retval;
891 if (use_packed_git(p))
892 die("cannot map packed file");
894 offset = unpack_object_header(p, entry->offset, &kind, &size);
895 pack = p->pack_base + offset;
896 left = p->pack_size - offset;
898 switch (kind) {
899 case OBJ_DELTA:
900 retval = packed_delta_info(pack, size, left, type, sizep, p);
901 unuse_packed_git(p);
902 return retval;
903 case OBJ_COMMIT:
904 strcpy(type, "commit");
905 break;
906 case OBJ_TREE:
907 strcpy(type, "tree");
908 break;
909 case OBJ_BLOB:
910 strcpy(type, "blob");
911 break;
912 case OBJ_TAG:
913 strcpy(type, "tag");
914 break;
915 default:
916 die("corrupted pack file %s containing object of kind %d",
917 p->pack_name, kind);
919 if (sizep)
920 *sizep = size;
921 unuse_packed_git(p);
922 return 0;
925 /* forward declaration for a mutually recursive function */
926 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
928 static void *unpack_delta_entry(unsigned char *base_sha1,
929 unsigned long delta_size,
930 unsigned long left,
931 char *type,
932 unsigned long *sizep,
933 struct packed_git *p)
935 struct pack_entry base_ent;
936 void *data, *delta_data, *result, *base;
937 unsigned long data_size, result_size, base_size;
938 z_stream stream;
939 int st;
941 if (left < 20)
942 die("truncated pack file");
943 data = base_sha1 + 20;
944 data_size = left - 20;
945 delta_data = xmalloc(delta_size);
947 memset(&stream, 0, sizeof(stream));
949 stream.next_in = data;
950 stream.avail_in = data_size;
951 stream.next_out = delta_data;
952 stream.avail_out = delta_size;
954 inflateInit(&stream);
955 st = inflate(&stream, Z_FINISH);
956 inflateEnd(&stream);
957 if ((st != Z_STREAM_END) || stream.total_out != delta_size)
958 die("delta data unpack failed");
960 /* The base entry _must_ be in the same pack */
961 if (!find_pack_entry_one(base_sha1, &base_ent, p))
962 die("failed to find delta-pack base object %s",
963 sha1_to_hex(base_sha1));
964 base = unpack_entry_gently(&base_ent, type, &base_size);
965 if (!base)
966 die("failed to read delta-pack base object %s",
967 sha1_to_hex(base_sha1));
968 result = patch_delta(base, base_size,
969 delta_data, delta_size,
970 &result_size);
971 if (!result)
972 die("failed to apply delta");
973 free(delta_data);
974 free(base);
975 *sizep = result_size;
976 return result;
979 static void *unpack_non_delta_entry(unsigned char *data,
980 unsigned long size,
981 unsigned long left)
983 int st;
984 z_stream stream;
985 unsigned char *buffer;
987 buffer = xmalloc(size + 1);
988 buffer[size] = 0;
989 memset(&stream, 0, sizeof(stream));
990 stream.next_in = data;
991 stream.avail_in = left;
992 stream.next_out = buffer;
993 stream.avail_out = size;
995 inflateInit(&stream);
996 st = inflate(&stream, Z_FINISH);
997 inflateEnd(&stream);
998 if ((st != Z_STREAM_END) || stream.total_out != size) {
999 free(buffer);
1000 return NULL;
1003 return buffer;
1006 static void *unpack_entry(struct pack_entry *entry,
1007 char *type, unsigned long *sizep)
1009 struct packed_git *p = entry->p;
1010 void *retval;
1012 if (use_packed_git(p))
1013 die("cannot map packed file");
1014 retval = unpack_entry_gently(entry, type, sizep);
1015 unuse_packed_git(p);
1016 if (!retval)
1017 die("corrupted pack file %s", p->pack_name);
1018 return retval;
1021 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
1022 void *unpack_entry_gently(struct pack_entry *entry,
1023 char *type, unsigned long *sizep)
1025 struct packed_git *p = entry->p;
1026 unsigned long offset, size, left;
1027 unsigned char *pack;
1028 enum object_type kind;
1029 void *retval;
1031 offset = unpack_object_header(p, entry->offset, &kind, &size);
1032 pack = p->pack_base + offset;
1033 left = p->pack_size - offset;
1034 switch (kind) {
1035 case OBJ_DELTA:
1036 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
1037 return retval;
1038 case OBJ_COMMIT:
1039 strcpy(type, "commit");
1040 break;
1041 case OBJ_TREE:
1042 strcpy(type, "tree");
1043 break;
1044 case OBJ_BLOB:
1045 strcpy(type, "blob");
1046 break;
1047 case OBJ_TAG:
1048 strcpy(type, "tag");
1049 break;
1050 default:
1051 return NULL;
1053 *sizep = size;
1054 retval = unpack_non_delta_entry(pack, size, left);
1055 return retval;
1058 int num_packed_objects(const struct packed_git *p)
1060 /* See check_packed_git_idx() */
1061 return (p->index_size - 20 - 20 - 4*256) / 24;
1064 int nth_packed_object_sha1(const struct packed_git *p, int n,
1065 unsigned char* sha1)
1067 void *index = p->index_base + 256;
1068 if (n < 0 || num_packed_objects(p) <= n)
1069 return -1;
1070 memcpy(sha1, (index + 24 * n + 4), 20);
1071 return 0;
1074 int find_pack_entry_one(const unsigned char *sha1,
1075 struct pack_entry *e, struct packed_git *p)
1077 unsigned int *level1_ofs = p->index_base;
1078 int hi = ntohl(level1_ofs[*sha1]);
1079 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1080 void *index = p->index_base + 256;
1082 do {
1083 int mi = (lo + hi) / 2;
1084 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
1085 if (!cmp) {
1086 e->offset = ntohl(*((int*)(index + 24 * mi)));
1087 memcpy(e->sha1, sha1, 20);
1088 e->p = p;
1089 return 1;
1091 if (cmp > 0)
1092 hi = mi;
1093 else
1094 lo = mi+1;
1095 } while (lo < hi);
1096 return 0;
1099 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1101 struct packed_git *p;
1102 prepare_packed_git();
1104 for (p = packed_git; p; p = p->next) {
1105 if (find_pack_entry_one(sha1, e, p))
1106 return 1;
1108 return 0;
1111 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1112 struct packed_git *packs)
1114 struct packed_git *p;
1115 struct pack_entry e;
1117 for (p = packs; p; p = p->next) {
1118 if (find_pack_entry_one(sha1, &e, p))
1119 return p;
1121 return NULL;
1125 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1127 int status;
1128 unsigned long mapsize, size;
1129 void *map;
1130 z_stream stream;
1131 char hdr[128];
1133 map = map_sha1_file_internal(sha1, &mapsize);
1134 if (!map) {
1135 struct pack_entry e;
1137 if (!find_pack_entry(sha1, &e))
1138 return error("unable to find %s", sha1_to_hex(sha1));
1139 return packed_object_info(&e, type, sizep);
1141 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1142 status = error("unable to unpack %s header",
1143 sha1_to_hex(sha1));
1144 if (parse_sha1_header(hdr, type, &size) < 0)
1145 status = error("unable to parse %s header", sha1_to_hex(sha1));
1146 else {
1147 status = 0;
1148 if (sizep)
1149 *sizep = size;
1151 inflateEnd(&stream);
1152 munmap(map, mapsize);
1153 return status;
1156 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1158 struct pack_entry e;
1160 if (!find_pack_entry(sha1, &e)) {
1161 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1162 return NULL;
1164 return unpack_entry(&e, type, size);
1167 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1169 unsigned long mapsize;
1170 void *map, *buf;
1171 struct pack_entry e;
1173 if (find_pack_entry(sha1, &e))
1174 return read_packed_sha1(sha1, type, size);
1175 map = map_sha1_file_internal(sha1, &mapsize);
1176 if (map) {
1177 buf = unpack_sha1_file(map, mapsize, type, size);
1178 munmap(map, mapsize);
1179 return buf;
1181 return NULL;
1184 void *read_object_with_reference(const unsigned char *sha1,
1185 const char *required_type,
1186 unsigned long *size,
1187 unsigned char *actual_sha1_return)
1189 char type[20];
1190 void *buffer;
1191 unsigned long isize;
1192 unsigned char actual_sha1[20];
1194 memcpy(actual_sha1, sha1, 20);
1195 while (1) {
1196 int ref_length = -1;
1197 const char *ref_type = NULL;
1199 buffer = read_sha1_file(actual_sha1, type, &isize);
1200 if (!buffer)
1201 return NULL;
1202 if (!strcmp(type, required_type)) {
1203 *size = isize;
1204 if (actual_sha1_return)
1205 memcpy(actual_sha1_return, actual_sha1, 20);
1206 return buffer;
1208 /* Handle references */
1209 else if (!strcmp(type, "commit"))
1210 ref_type = "tree ";
1211 else if (!strcmp(type, "tag"))
1212 ref_type = "object ";
1213 else {
1214 free(buffer);
1215 return NULL;
1217 ref_length = strlen(ref_type);
1219 if (memcmp(buffer, ref_type, ref_length) ||
1220 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1221 free(buffer);
1222 return NULL;
1224 free(buffer);
1225 /* Now we have the ID of the referred-to object in
1226 * actual_sha1. Check again. */
1230 char *write_sha1_file_prepare(void *buf,
1231 unsigned long len,
1232 const char *type,
1233 unsigned char *sha1,
1234 unsigned char *hdr,
1235 int *hdrlen)
1237 SHA_CTX c;
1239 /* Generate the header */
1240 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1242 /* Sha1.. */
1243 SHA1_Init(&c);
1244 SHA1_Update(&c, hdr, *hdrlen);
1245 SHA1_Update(&c, buf, len);
1246 SHA1_Final(sha1, &c);
1248 return sha1_file_name(sha1);
1252 * Link the tempfile to the final place, possibly creating the
1253 * last directory level as you do so.
1255 * Returns the errno on failure, 0 on success.
1257 static int link_temp_to_file(const char *tmpfile, char *filename)
1259 int ret;
1261 if (!link(tmpfile, filename))
1262 return 0;
1265 * Try to mkdir the last path component if that failed
1266 * with an ENOENT.
1268 * Re-try the "link()" regardless of whether the mkdir
1269 * succeeds, since a race might mean that somebody
1270 * else succeeded.
1272 ret = errno;
1273 if (ret == ENOENT) {
1274 char *dir = strrchr(filename, '/');
1275 if (dir) {
1276 *dir = 0;
1277 mkdir(filename, 0777);
1278 *dir = '/';
1279 if (!link(tmpfile, filename))
1280 return 0;
1281 ret = errno;
1284 return ret;
1288 * Move the just written object into its final resting place
1290 int move_temp_to_file(const char *tmpfile, char *filename)
1292 int ret = link_temp_to_file(tmpfile, filename);
1293 if (ret) {
1295 * Coda hack - coda doesn't like cross-directory links,
1296 * so we fall back to a rename, which will mean that it
1297 * won't be able to check collisions, but that's not a
1298 * big deal.
1300 * When this succeeds, we just return 0. We have nothing
1301 * left to unlink.
1303 if (ret == EXDEV && !rename(tmpfile, filename))
1304 return 0;
1306 unlink(tmpfile);
1307 if (ret) {
1308 if (ret != EEXIST) {
1309 fprintf(stderr, "unable to write sha1 filename %s: %s", 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", 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", 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");
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_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1565 unsigned long size = st->st_size;
1566 void *buf;
1567 int ret;
1568 unsigned char hdr[50];
1569 int hdrlen;
1571 buf = "";
1572 if (size)
1573 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1574 close(fd);
1575 if (buf == MAP_FAILED)
1576 return -1;
1578 if (!type)
1579 type = "blob";
1580 if (write_object)
1581 ret = write_sha1_file(buf, size, type, sha1);
1582 else {
1583 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1584 ret = 0;
1586 if (size)
1587 munmap(buf, size);
1588 return ret;
1591 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1593 int fd;
1594 char *target;
1596 switch (st->st_mode & S_IFMT) {
1597 case S_IFREG:
1598 fd = open(path, O_RDONLY);
1599 if (fd < 0)
1600 return error("open(\"%s\"): %s", path,
1601 strerror(errno));
1602 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1603 return error("%s: failed to insert into database",
1604 path);
1605 break;
1606 case S_IFLNK:
1607 target = xmalloc(st->st_size+1);
1608 if (readlink(path, target, st->st_size+1) != st->st_size) {
1609 char *errstr = strerror(errno);
1610 free(target);
1611 return error("readlink(\"%s\"): %s", path,
1612 errstr);
1614 if (!write_object) {
1615 unsigned char hdr[50];
1616 int hdrlen;
1617 write_sha1_file_prepare(target, st->st_size, "blob",
1618 sha1, hdr, &hdrlen);
1619 } else if (write_sha1_file(target, st->st_size, "blob", sha1))
1620 return error("%s: failed to insert into database",
1621 path);
1622 free(target);
1623 break;
1624 default:
1625 return error("%s: unsupported file type", path);
1627 return 0;