gitweb: Make git_print_log generic; git_print_simplified_log uses it
[git/jnareb-git.git] / sha1_file.c
blob01aa745031b6fa152fcdeb71f7b43aecd7b669b9
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
6 * This handles basic git sha1 object files - packing, unpacking,
7 * creation etc.
8 */
9 #include "cache.h"
10 #include "delta.h"
11 #include "pack.h"
12 #include "blob.h"
13 #include "commit.h"
14 #include "tag.h"
15 #include "tree.h"
17 #ifndef O_NOATIME
18 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
19 #define O_NOATIME 01000000
20 #else
21 #define O_NOATIME 0
22 #endif
23 #endif
25 const unsigned char null_sha1[20];
27 static unsigned int sha1_file_open_flag = O_NOATIME;
29 static unsigned hexval(char c)
31 if (c >= '0' && c <= '9')
32 return c - '0';
33 if (c >= 'a' && c <= 'f')
34 return c - 'a' + 10;
35 if (c >= 'A' && c <= 'F')
36 return c - 'A' + 10;
37 return ~0;
40 int get_sha1_hex(const char *hex, unsigned char *sha1)
42 int i;
43 for (i = 0; i < 20; i++) {
44 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
45 if (val & ~0xff)
46 return -1;
47 *sha1++ = val;
48 hex += 2;
50 return 0;
53 int safe_create_leading_directories(char *path)
55 char *pos = path;
56 struct stat st;
58 if (*pos == '/')
59 pos++;
61 while (pos) {
62 pos = strchr(pos, '/');
63 if (!pos)
64 break;
65 *pos = 0;
66 if (!stat(path, &st)) {
67 /* path exists */
68 if (!S_ISDIR(st.st_mode)) {
69 *pos = '/';
70 return -3;
73 else if (mkdir(path, 0777)) {
74 *pos = '/';
75 return -1;
77 else if (adjust_shared_perm(path)) {
78 *pos = '/';
79 return -2;
81 *pos++ = '/';
83 return 0;
86 char * sha1_to_hex(const unsigned char *sha1)
88 static int bufno;
89 static char hexbuffer[4][50];
90 static const char hex[] = "0123456789abcdef";
91 char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
92 int i;
94 for (i = 0; i < 20; i++) {
95 unsigned int val = *sha1++;
96 *buf++ = hex[val >> 4];
97 *buf++ = hex[val & 0xf];
99 *buf = '\0';
101 return buffer;
104 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
106 int i;
107 for (i = 0; i < 20; i++) {
108 static char hex[] = "0123456789abcdef";
109 unsigned int val = sha1[i];
110 char *pos = pathbuf + i*2 + (i > 0);
111 *pos++ = hex[val >> 4];
112 *pos = hex[val & 0xf];
117 * NOTE! This returns a statically allocated buffer, so you have to be
118 * careful about using it. Do a "strdup()" if you need to save the
119 * filename.
121 * Also note that this returns the location for creating. Reading
122 * SHA1 file can happen from any alternate directory listed in the
123 * DB_ENVIRONMENT environment variable if it is not found in
124 * the primary object database.
126 char *sha1_file_name(const unsigned char *sha1)
128 static char *name, *base;
129 static const char *last_objdir;
130 const char *sha1_file_directory = get_object_directory();
132 if (!last_objdir || strcmp(last_objdir, sha1_file_directory)) {
133 int len = strlen(sha1_file_directory);
134 if (base)
135 free(base);
136 base = xmalloc(len + 60);
137 memcpy(base, sha1_file_directory, len);
138 memset(base+len, 0, 60);
139 base[len] = '/';
140 base[len+3] = '/';
141 name = base + len + 1;
142 if (last_objdir)
143 free((char *) last_objdir);
144 last_objdir = strdup(sha1_file_directory);
146 fill_sha1_path(name, sha1);
147 return base;
150 char *sha1_pack_name(const unsigned char *sha1)
152 static const char hex[] = "0123456789abcdef";
153 static char *name, *base, *buf;
154 static const char *last_objdir;
155 const char *sha1_file_directory = get_object_directory();
156 int i;
158 if (!last_objdir || strcmp(last_objdir, sha1_file_directory)) {
159 int len = strlen(sha1_file_directory);
160 if (base)
161 free(base);
162 base = xmalloc(len + 60);
163 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
164 name = base + len + 11;
165 if (last_objdir)
166 free((char *) last_objdir);
167 last_objdir = strdup(sha1_file_directory);
170 buf = name;
172 for (i = 0; i < 20; i++) {
173 unsigned int val = *sha1++;
174 *buf++ = hex[val >> 4];
175 *buf++ = hex[val & 0xf];
178 return base;
181 char *sha1_pack_index_name(const unsigned char *sha1)
183 static const char hex[] = "0123456789abcdef";
184 static char *name, *base, *buf;
185 static const char *last_objdir;
186 const char *sha1_file_directory = get_object_directory();
187 int i;
189 if (!last_objdir || strcmp(last_objdir, sha1_file_directory)) {
190 int len = strlen(sha1_file_directory);
191 if (base)
192 free(base);
193 base = xmalloc(len + 60);
194 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
195 name = base + len + 11;
196 if (last_objdir)
197 free((char *) last_objdir);
198 last_objdir = strdup(sha1_file_directory);
201 buf = name;
203 for (i = 0; i < 20; i++) {
204 unsigned int val = *sha1++;
205 *buf++ = hex[val >> 4];
206 *buf++ = hex[val & 0xf];
209 return base;
212 struct alternate_object_database *alt_odb_list;
213 static struct alternate_object_database **alt_odb_tail;
215 static void read_info_alternates(const char * alternates, int depth);
218 * Prepare alternate object database registry.
220 * The variable alt_odb_list points at the list of struct
221 * alternate_object_database. The elements on this list come from
222 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
223 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
224 * whose contents is similar to that environment variable but can be
225 * LF separated. Its base points at a statically allocated buffer that
226 * contains "/the/directory/corresponding/to/.git/objects/...", while
227 * its name points just after the slash at the end of ".git/objects/"
228 * in the example above, and has enough space to hold 40-byte hex
229 * SHA1, an extra slash for the first level indirection, and the
230 * terminating NUL.
232 static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
234 struct stat st;
235 const char *objdir = get_object_directory();
236 struct alternate_object_database *ent;
237 struct alternate_object_database *alt;
238 /* 43 = 40-byte + 2 '/' + terminating NUL */
239 int pfxlen = len;
240 int entlen = pfxlen + 43;
241 int base_len = -1;
243 if (*entry != '/' && relative_base) {
244 /* Relative alt-odb */
245 if (base_len < 0)
246 base_len = strlen(relative_base) + 1;
247 entlen += base_len;
248 pfxlen += base_len;
250 ent = xmalloc(sizeof(*ent) + entlen);
252 if (*entry != '/' && relative_base) {
253 memcpy(ent->base, relative_base, base_len - 1);
254 ent->base[base_len - 1] = '/';
255 memcpy(ent->base + base_len, entry, len);
257 else
258 memcpy(ent->base, entry, pfxlen);
260 ent->name = ent->base + pfxlen + 1;
261 ent->base[pfxlen + 3] = '/';
262 ent->base[pfxlen] = ent->base[entlen-1] = 0;
264 /* Detect cases where alternate disappeared */
265 if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
266 error("object directory %s does not exist; "
267 "check .git/objects/info/alternates.",
268 ent->base);
269 free(ent);
270 return -1;
273 /* Prevent the common mistake of listing the same
274 * thing twice, or object directory itself.
276 for (alt = alt_odb_list; alt; alt = alt->next) {
277 if (!memcmp(ent->base, alt->base, pfxlen)) {
278 free(ent);
279 return -1;
282 if (!memcmp(ent->base, objdir, pfxlen)) {
283 free(ent);
284 return -1;
287 /* add the alternate entry */
288 *alt_odb_tail = ent;
289 alt_odb_tail = &(ent->next);
290 ent->next = NULL;
292 /* recursively add alternates */
293 read_info_alternates(ent->base, depth + 1);
295 ent->base[pfxlen] = '/';
297 return 0;
300 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
301 const char *relative_base, int depth)
303 const char *cp, *last;
305 if (depth > 5) {
306 error("%s: ignoring alternate object stores, nesting too deep.",
307 relative_base);
308 return;
311 last = alt;
312 while (last < ep) {
313 cp = last;
314 if (cp < ep && *cp == '#') {
315 while (cp < ep && *cp != sep)
316 cp++;
317 last = cp + 1;
318 continue;
320 while (cp < ep && *cp != sep)
321 cp++;
322 if (last != cp) {
323 if ((*last != '/') && depth) {
324 error("%s: ignoring relative alternate object store %s",
325 relative_base, last);
326 } else {
327 link_alt_odb_entry(last, cp - last,
328 relative_base, depth);
331 while (cp < ep && *cp == sep)
332 cp++;
333 last = cp;
337 static void read_info_alternates(const char * relative_base, int depth)
339 char *map;
340 struct stat st;
341 char path[PATH_MAX];
342 int fd;
344 sprintf(path, "%s/info/alternates", relative_base);
345 fd = open(path, O_RDONLY);
346 if (fd < 0)
347 return;
348 if (fstat(fd, &st) || (st.st_size == 0)) {
349 close(fd);
350 return;
352 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
353 close(fd);
354 if (map == MAP_FAILED)
355 return;
357 link_alt_odb_entries(map, map + st.st_size, '\n', relative_base, depth);
359 munmap(map, st.st_size);
362 void prepare_alt_odb(void)
364 const char *alt;
366 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
367 if (!alt) alt = "";
369 if (alt_odb_tail)
370 return;
371 alt_odb_tail = &alt_odb_list;
372 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL, 0);
374 read_info_alternates(get_object_directory(), 0);
377 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
379 char *name = sha1_file_name(sha1);
380 struct alternate_object_database *alt;
382 if (!stat(name, st))
383 return name;
384 prepare_alt_odb();
385 for (alt = alt_odb_list; alt; alt = alt->next) {
386 name = alt->name;
387 fill_sha1_path(name, sha1);
388 if (!stat(alt->base, st))
389 return alt->base;
391 return NULL;
394 #define PACK_MAX_SZ (1<<26)
395 static int pack_used_ctr;
396 static unsigned long pack_mapped;
397 struct packed_git *packed_git;
399 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
400 void **idx_map_)
402 void *idx_map;
403 unsigned int *index;
404 unsigned long idx_size;
405 int nr, i;
406 int fd = open(path, O_RDONLY);
407 struct stat st;
408 if (fd < 0)
409 return -1;
410 if (fstat(fd, &st)) {
411 close(fd);
412 return -1;
414 idx_size = st.st_size;
415 idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
416 close(fd);
417 if (idx_map == MAP_FAILED)
418 return -1;
420 index = idx_map;
421 *idx_map_ = idx_map;
422 *idx_size_ = idx_size;
424 /* check index map */
425 if (idx_size < 4*256 + 20 + 20)
426 return error("index file too small");
427 nr = 0;
428 for (i = 0; i < 256; i++) {
429 unsigned int n = ntohl(index[i]);
430 if (n < nr)
431 return error("non-monotonic index");
432 nr = n;
436 * Total size:
437 * - 256 index entries 4 bytes each
438 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
439 * - 20-byte SHA1 of the packfile
440 * - 20-byte SHA1 file checksum
442 if (idx_size != 4*256 + nr * 24 + 20 + 20)
443 return error("wrong index file size");
445 return 0;
448 static int unuse_one_packed_git(void)
450 struct packed_git *p, *lru = NULL;
452 for (p = packed_git; p; p = p->next) {
453 if (p->pack_use_cnt || !p->pack_base)
454 continue;
455 if (!lru || p->pack_last_used < lru->pack_last_used)
456 lru = p;
458 if (!lru)
459 return 0;
460 munmap(lru->pack_base, lru->pack_size);
461 lru->pack_base = NULL;
462 return 1;
465 void unuse_packed_git(struct packed_git *p)
467 p->pack_use_cnt--;
470 int use_packed_git(struct packed_git *p)
472 if (!p->pack_size) {
473 struct stat st;
474 /* We created the struct before we had the pack */
475 stat(p->pack_name, &st);
476 if (!S_ISREG(st.st_mode))
477 die("packfile %s not a regular file", p->pack_name);
478 p->pack_size = st.st_size;
480 if (!p->pack_base) {
481 int fd;
482 struct stat st;
483 void *map;
484 struct pack_header *hdr;
486 pack_mapped += p->pack_size;
487 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
488 ; /* nothing */
489 fd = open(p->pack_name, O_RDONLY);
490 if (fd < 0)
491 die("packfile %s cannot be opened", p->pack_name);
492 if (fstat(fd, &st)) {
493 close(fd);
494 die("packfile %s cannot be opened", p->pack_name);
496 if (st.st_size != p->pack_size)
497 die("packfile %s size mismatch.", p->pack_name);
498 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
499 close(fd);
500 if (map == MAP_FAILED)
501 die("packfile %s cannot be mapped.", p->pack_name);
502 p->pack_base = map;
504 /* Check if we understand this pack file. If we don't we're
505 * likely too old to handle it.
507 hdr = map;
508 if (hdr->hdr_signature != htonl(PACK_SIGNATURE))
509 die("packfile %s isn't actually a pack.", p->pack_name);
510 if (!pack_version_ok(hdr->hdr_version))
511 die("packfile %s is version %i and not supported"
512 " (try upgrading GIT to a newer version)",
513 p->pack_name, ntohl(hdr->hdr_version));
515 /* Check if the pack file matches with the index file.
516 * this is cheap.
518 if (hashcmp((unsigned char *)(p->index_base) +
519 p->index_size - 40,
520 (unsigned char *)p->pack_base +
521 p->pack_size - 20)) {
522 die("packfile %s does not match index.", p->pack_name);
525 p->pack_last_used = pack_used_ctr++;
526 p->pack_use_cnt++;
527 return 0;
530 struct packed_git *add_packed_git(char *path, int path_len, int local)
532 struct stat st;
533 struct packed_git *p;
534 unsigned long idx_size;
535 void *idx_map;
536 unsigned char sha1[20];
538 if (check_packed_git_idx(path, &idx_size, &idx_map))
539 return NULL;
541 /* do we have a corresponding .pack file? */
542 strcpy(path + path_len - 4, ".pack");
543 if (stat(path, &st) || !S_ISREG(st.st_mode)) {
544 munmap(idx_map, idx_size);
545 return NULL;
547 /* ok, it looks sane as far as we can check without
548 * actually mapping the pack file.
550 p = xmalloc(sizeof(*p) + path_len + 2);
551 strcpy(p->pack_name, path);
552 p->index_size = idx_size;
553 p->pack_size = st.st_size;
554 p->index_base = idx_map;
555 p->next = NULL;
556 p->pack_base = NULL;
557 p->pack_last_used = 0;
558 p->pack_use_cnt = 0;
559 p->pack_local = local;
560 if ((path_len > 44) && !get_sha1_hex(path + path_len - 44, sha1))
561 hashcpy(p->sha1, sha1);
562 return p;
565 struct packed_git *parse_pack_index(unsigned char *sha1)
567 char *path = sha1_pack_index_name(sha1);
568 return parse_pack_index_file(sha1, path);
571 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
573 struct packed_git *p;
574 unsigned long idx_size;
575 void *idx_map;
576 char *path;
578 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
579 return NULL;
581 path = sha1_pack_name(sha1);
583 p = xmalloc(sizeof(*p) + strlen(path) + 2);
584 strcpy(p->pack_name, path);
585 p->index_size = idx_size;
586 p->pack_size = 0;
587 p->index_base = idx_map;
588 p->next = NULL;
589 p->pack_base = NULL;
590 p->pack_last_used = 0;
591 p->pack_use_cnt = 0;
592 hashcpy(p->sha1, sha1);
593 return p;
596 void install_packed_git(struct packed_git *pack)
598 pack->next = packed_git;
599 packed_git = pack;
602 static void prepare_packed_git_one(char *objdir, int local)
604 char path[PATH_MAX];
605 int len;
606 DIR *dir;
607 struct dirent *de;
609 sprintf(path, "%s/pack", objdir);
610 len = strlen(path);
611 dir = opendir(path);
612 if (!dir) {
613 if (errno != ENOENT)
614 error("unable to open object pack directory: %s: %s",
615 path, strerror(errno));
616 return;
618 path[len++] = '/';
619 while ((de = readdir(dir)) != NULL) {
620 int namelen = strlen(de->d_name);
621 struct packed_git *p;
623 if (!has_extension(de->d_name, ".idx"))
624 continue;
626 /* we have .idx. Is it a file we can map? */
627 strcpy(path + len, de->d_name);
628 for (p = packed_git; p; p = p->next) {
629 if (!memcmp(path, p->pack_name, len + namelen - 4))
630 break;
632 if (p)
633 continue;
634 p = add_packed_git(path, len + namelen, local);
635 if (!p)
636 continue;
637 p->next = packed_git;
638 packed_git = p;
640 closedir(dir);
643 static int prepare_packed_git_run_once = 0;
644 void prepare_packed_git(void)
646 struct alternate_object_database *alt;
648 if (prepare_packed_git_run_once)
649 return;
650 prepare_packed_git_one(get_object_directory(), 1);
651 prepare_alt_odb();
652 for (alt = alt_odb_list; alt; alt = alt->next) {
653 alt->name[-1] = 0;
654 prepare_packed_git_one(alt->base, 0);
655 alt->name[-1] = '/';
657 prepare_packed_git_run_once = 1;
660 static void reprepare_packed_git(void)
662 prepare_packed_git_run_once = 0;
663 prepare_packed_git();
666 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
668 char header[100];
669 unsigned char real_sha1[20];
670 SHA_CTX c;
672 SHA1_Init(&c);
673 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
674 SHA1_Update(&c, map, size);
675 SHA1_Final(real_sha1, &c);
676 return hashcmp(sha1, real_sha1) ? -1 : 0;
679 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
681 struct stat st;
682 void *map;
683 int fd;
684 char *filename = find_sha1_file(sha1, &st);
686 if (!filename) {
687 return NULL;
690 fd = open(filename, O_RDONLY | sha1_file_open_flag);
691 if (fd < 0) {
692 /* See if it works without O_NOATIME */
693 switch (sha1_file_open_flag) {
694 default:
695 fd = open(filename, O_RDONLY);
696 if (fd >= 0)
697 break;
698 /* Fallthrough */
699 case 0:
700 return NULL;
703 /* If it failed once, it will probably fail again.
704 * Stop using O_NOATIME
706 sha1_file_open_flag = 0;
708 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
709 close(fd);
710 if (map == MAP_FAILED)
711 return NULL;
712 *size = st.st_size;
713 return map;
716 int legacy_loose_object(unsigned char *map)
718 unsigned int word;
721 * Is it a zlib-compressed buffer? If so, the first byte
722 * must be 0x78 (15-bit window size, deflated), and the
723 * first 16-bit word is evenly divisible by 31
725 word = (map[0] << 8) + map[1];
726 if (map[0] == 0x78 && !(word % 31))
727 return 1;
728 else
729 return 0;
732 static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
734 unsigned char c;
735 unsigned int bits;
736 unsigned long size;
737 static const char *typename[8] = {
738 NULL, /* OBJ_EXT */
739 "commit", "tree", "blob", "tag",
740 NULL, NULL, NULL
742 const char *type;
744 /* Get the data stream */
745 memset(stream, 0, sizeof(*stream));
746 stream->next_in = map;
747 stream->avail_in = mapsize;
748 stream->next_out = buffer;
749 stream->avail_out = bufsiz;
751 if (legacy_loose_object(map)) {
752 inflateInit(stream);
753 return inflate(stream, 0);
756 c = *map++;
757 mapsize--;
758 type = typename[(c >> 4) & 7];
759 if (!type)
760 return -1;
762 bits = 4;
763 size = c & 0xf;
764 while ((c & 0x80)) {
765 if (bits >= 8*sizeof(long))
766 return -1;
767 c = *map++;
768 size += (c & 0x7f) << bits;
769 bits += 7;
770 mapsize--;
773 /* Set up the stream for the rest.. */
774 stream->next_in = map;
775 stream->avail_in = mapsize;
776 inflateInit(stream);
778 /* And generate the fake traditional header */
779 stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu", type, size);
780 return 0;
783 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
785 int bytes = strlen(buffer) + 1;
786 unsigned char *buf = xmalloc(1+size);
787 unsigned long n;
789 n = stream->total_out - bytes;
790 if (n > size)
791 n = size;
792 memcpy(buf, (char *) buffer + bytes, n);
793 bytes = n;
794 if (bytes < size) {
795 stream->next_out = buf + bytes;
796 stream->avail_out = size - bytes;
797 while (inflate(stream, Z_FINISH) == Z_OK)
798 /* nothing */;
800 buf[size] = 0;
801 inflateEnd(stream);
802 return buf;
806 * We used to just use "sscanf()", but that's actually way
807 * too permissive for what we want to check. So do an anal
808 * object header parse by hand.
810 static int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
812 int i;
813 unsigned long size;
816 * The type can be at most ten bytes (including the
817 * terminating '\0' that we add), and is followed by
818 * a space.
820 i = 10;
821 for (;;) {
822 char c = *hdr++;
823 if (c == ' ')
824 break;
825 if (!--i)
826 return -1;
827 *type++ = c;
829 *type = 0;
832 * The length must follow immediately, and be in canonical
833 * decimal format (ie "010" is not valid).
835 size = *hdr++ - '0';
836 if (size > 9)
837 return -1;
838 if (size) {
839 for (;;) {
840 unsigned long c = *hdr - '0';
841 if (c > 9)
842 break;
843 hdr++;
844 size = size * 10 + c;
847 *sizep = size;
850 * The length must be followed by a zero byte
852 return *hdr ? -1 : 0;
855 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
857 int ret;
858 z_stream stream;
859 char hdr[8192];
861 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
862 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
863 return NULL;
865 return unpack_sha1_rest(&stream, hdr, *size);
868 /* forward declaration for a mutually recursive function */
869 static int packed_object_info(struct pack_entry *entry,
870 char *type, unsigned long *sizep);
872 static int packed_delta_info(unsigned char *base_sha1,
873 unsigned long delta_size,
874 unsigned long left,
875 char *type,
876 unsigned long *sizep,
877 struct packed_git *p)
879 struct pack_entry base_ent;
881 if (left < 20)
882 die("truncated pack file");
884 /* The base entry _must_ be in the same pack */
885 if (!find_pack_entry_one(base_sha1, &base_ent, p))
886 die("failed to find delta-pack base object %s",
887 sha1_to_hex(base_sha1));
889 /* We choose to only get the type of the base object and
890 * ignore potentially corrupt pack file that expects the delta
891 * based on a base with a wrong size. This saves tons of
892 * inflate() calls.
895 if (packed_object_info(&base_ent, type, NULL))
896 die("cannot get info for delta-pack base");
898 if (sizep) {
899 const unsigned char *data;
900 unsigned char delta_head[64];
901 unsigned long result_size;
902 z_stream stream;
903 int st;
905 memset(&stream, 0, sizeof(stream));
907 data = stream.next_in = base_sha1 + 20;
908 stream.avail_in = left - 20;
909 stream.next_out = delta_head;
910 stream.avail_out = sizeof(delta_head);
912 inflateInit(&stream);
913 st = inflate(&stream, Z_FINISH);
914 inflateEnd(&stream);
915 if ((st != Z_STREAM_END) &&
916 stream.total_out != sizeof(delta_head))
917 die("delta data unpack-initial failed");
919 /* Examine the initial part of the delta to figure out
920 * the result size.
922 data = delta_head;
924 /* ignore base size */
925 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
927 /* Read the result size */
928 result_size = get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
929 *sizep = result_size;
931 return 0;
934 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
935 enum object_type *type, unsigned long *sizep)
937 unsigned shift;
938 unsigned char c;
939 unsigned long size;
941 if (offset >= p->pack_size)
942 die("object offset outside of pack file");
943 c = *((unsigned char *)p->pack_base + offset++);
944 *type = (c >> 4) & 7;
945 size = c & 15;
946 shift = 4;
947 while (c & 0x80) {
948 if (offset >= p->pack_size)
949 die("object offset outside of pack file");
950 c = *((unsigned char *)p->pack_base + offset++);
951 size += (c & 0x7f) << shift;
952 shift += 7;
954 *sizep = size;
955 return offset;
958 int check_reuse_pack_delta(struct packed_git *p, unsigned long offset,
959 unsigned char *base, unsigned long *sizep,
960 enum object_type *kindp)
962 unsigned long ptr;
963 int status = -1;
965 use_packed_git(p);
966 ptr = offset;
967 ptr = unpack_object_header(p, ptr, kindp, sizep);
968 if (*kindp != OBJ_DELTA)
969 goto done;
970 hashcpy(base, (unsigned char *) p->pack_base + ptr);
971 status = 0;
972 done:
973 unuse_packed_git(p);
974 return status;
977 void packed_object_info_detail(struct pack_entry *e,
978 char *type,
979 unsigned long *size,
980 unsigned long *store_size,
981 unsigned int *delta_chain_length,
982 unsigned char *base_sha1)
984 struct packed_git *p = e->p;
985 unsigned long offset;
986 unsigned char *pack;
987 enum object_type kind;
989 offset = unpack_object_header(p, e->offset, &kind, size);
990 pack = (unsigned char *) p->pack_base + offset;
991 if (kind != OBJ_DELTA)
992 *delta_chain_length = 0;
993 else {
994 unsigned int chain_length = 0;
995 if (p->pack_size <= offset + 20)
996 die("pack file %s records an incomplete delta base",
997 p->pack_name);
998 hashcpy(base_sha1, pack);
999 do {
1000 struct pack_entry base_ent;
1001 unsigned long junk;
1003 find_pack_entry_one(pack, &base_ent, p);
1004 offset = unpack_object_header(p, base_ent.offset,
1005 &kind, &junk);
1006 pack = (unsigned char *) p->pack_base + offset;
1007 chain_length++;
1008 } while (kind == OBJ_DELTA);
1009 *delta_chain_length = chain_length;
1011 switch (kind) {
1012 case OBJ_COMMIT:
1013 case OBJ_TREE:
1014 case OBJ_BLOB:
1015 case OBJ_TAG:
1016 strcpy(type, type_names[kind]);
1017 break;
1018 default:
1019 die("corrupted pack file %s containing object of kind %d",
1020 p->pack_name, kind);
1022 *store_size = 0; /* notyet */
1025 static int packed_object_info(struct pack_entry *entry,
1026 char *type, unsigned long *sizep)
1028 struct packed_git *p = entry->p;
1029 unsigned long offset, size, left;
1030 unsigned char *pack;
1031 enum object_type kind;
1032 int retval;
1034 if (use_packed_git(p))
1035 die("cannot map packed file");
1037 offset = unpack_object_header(p, entry->offset, &kind, &size);
1038 pack = (unsigned char *) p->pack_base + offset;
1039 left = p->pack_size - offset;
1041 switch (kind) {
1042 case OBJ_DELTA:
1043 retval = packed_delta_info(pack, size, left, type, sizep, p);
1044 unuse_packed_git(p);
1045 return retval;
1046 case OBJ_COMMIT:
1047 case OBJ_TREE:
1048 case OBJ_BLOB:
1049 case OBJ_TAG:
1050 strcpy(type, type_names[kind]);
1051 break;
1052 default:
1053 die("corrupted pack file %s containing object of kind %d",
1054 p->pack_name, kind);
1056 if (sizep)
1057 *sizep = size;
1058 unuse_packed_git(p);
1059 return 0;
1062 static void *unpack_compressed_entry(struct packed_git *p,
1063 unsigned long offset,
1064 unsigned long size)
1066 int st;
1067 z_stream stream;
1068 unsigned char *buffer;
1070 buffer = xmalloc(size + 1);
1071 buffer[size] = 0;
1072 memset(&stream, 0, sizeof(stream));
1073 stream.next_in = (unsigned char*)p->pack_base + offset;
1074 stream.avail_in = p->pack_size - offset;
1075 stream.next_out = buffer;
1076 stream.avail_out = size;
1078 inflateInit(&stream);
1079 st = inflate(&stream, Z_FINISH);
1080 inflateEnd(&stream);
1081 if ((st != Z_STREAM_END) || stream.total_out != size) {
1082 free(buffer);
1083 return NULL;
1086 return buffer;
1089 static void *unpack_delta_entry(struct packed_git *p,
1090 unsigned long offset,
1091 unsigned long delta_size,
1092 char *type,
1093 unsigned long *sizep)
1095 struct pack_entry base_ent;
1096 void *delta_data, *result, *base;
1097 unsigned long result_size, base_size;
1098 unsigned char* base_sha1;
1100 if ((offset + 20) >= p->pack_size)
1101 die("truncated pack file");
1103 /* The base entry _must_ be in the same pack */
1104 base_sha1 = (unsigned char*)p->pack_base + offset;
1105 if (!find_pack_entry_one(base_sha1, &base_ent, p))
1106 die("failed to find delta-pack base object %s",
1107 sha1_to_hex(base_sha1));
1108 base = unpack_entry_gently(&base_ent, type, &base_size);
1109 if (!base)
1110 die("failed to read delta-pack base object %s",
1111 sha1_to_hex(base_sha1));
1113 delta_data = unpack_compressed_entry(p, offset + 20, delta_size);
1114 result = patch_delta(base, base_size,
1115 delta_data, delta_size,
1116 &result_size);
1117 if (!result)
1118 die("failed to apply delta");
1119 free(delta_data);
1120 free(base);
1121 *sizep = result_size;
1122 return result;
1125 static void *unpack_entry(struct pack_entry *entry,
1126 char *type, unsigned long *sizep)
1128 struct packed_git *p = entry->p;
1129 void *retval;
1131 if (use_packed_git(p))
1132 die("cannot map packed file");
1133 retval = unpack_entry_gently(entry, type, sizep);
1134 unuse_packed_git(p);
1135 if (!retval)
1136 die("corrupted pack file %s", p->pack_name);
1137 return retval;
1140 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
1141 void *unpack_entry_gently(struct pack_entry *entry,
1142 char *type, unsigned long *sizep)
1144 struct packed_git *p = entry->p;
1145 unsigned long offset, size;
1146 enum object_type kind;
1148 offset = unpack_object_header(p, entry->offset, &kind, &size);
1149 switch (kind) {
1150 case OBJ_DELTA:
1151 return unpack_delta_entry(p, offset, size, type, sizep);
1152 case OBJ_COMMIT:
1153 case OBJ_TREE:
1154 case OBJ_BLOB:
1155 case OBJ_TAG:
1156 strcpy(type, type_names[kind]);
1157 *sizep = size;
1158 return unpack_compressed_entry(p, offset, size);
1159 default:
1160 return NULL;
1164 int num_packed_objects(const struct packed_git *p)
1166 /* See check_packed_git_idx() */
1167 return (p->index_size - 20 - 20 - 4*256) / 24;
1170 int nth_packed_object_sha1(const struct packed_git *p, int n,
1171 unsigned char* sha1)
1173 void *index = p->index_base + 256;
1174 if (n < 0 || num_packed_objects(p) <= n)
1175 return -1;
1176 hashcpy(sha1, (unsigned char *) index + (24 * n) + 4);
1177 return 0;
1180 int find_pack_entry_one(const unsigned char *sha1,
1181 struct pack_entry *e, struct packed_git *p)
1183 unsigned int *level1_ofs = p->index_base;
1184 int hi = ntohl(level1_ofs[*sha1]);
1185 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1186 void *index = p->index_base + 256;
1188 do {
1189 int mi = (lo + hi) / 2;
1190 int cmp = hashcmp((unsigned char *)index + (24 * mi) + 4, sha1);
1191 if (!cmp) {
1192 e->offset = ntohl(*((unsigned int *) ((char *) index + (24 * mi))));
1193 hashcpy(e->sha1, sha1);
1194 e->p = p;
1195 return 1;
1197 if (cmp > 0)
1198 hi = mi;
1199 else
1200 lo = mi+1;
1201 } while (lo < hi);
1202 return 0;
1205 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1207 struct packed_git *p;
1208 prepare_packed_git();
1210 for (p = packed_git; p; p = p->next) {
1211 if (find_pack_entry_one(sha1, e, p))
1212 return 1;
1214 return 0;
1217 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1218 struct packed_git *packs)
1220 struct packed_git *p;
1221 struct pack_entry e;
1223 for (p = packs; p; p = p->next) {
1224 if (find_pack_entry_one(sha1, &e, p))
1225 return p;
1227 return NULL;
1231 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1233 int status;
1234 unsigned long mapsize, size;
1235 void *map;
1236 z_stream stream;
1237 char hdr[128];
1239 map = map_sha1_file(sha1, &mapsize);
1240 if (!map) {
1241 struct pack_entry e;
1243 if (find_pack_entry(sha1, &e))
1244 return packed_object_info(&e, type, sizep);
1245 reprepare_packed_git();
1246 if (find_pack_entry(sha1, &e))
1247 return packed_object_info(&e, type, sizep);
1248 return error("unable to find %s", sha1_to_hex(sha1));
1250 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1251 status = error("unable to unpack %s header",
1252 sha1_to_hex(sha1));
1253 if (parse_sha1_header(hdr, type, &size) < 0)
1254 status = error("unable to parse %s header", sha1_to_hex(sha1));
1255 else {
1256 status = 0;
1257 if (sizep)
1258 *sizep = size;
1260 inflateEnd(&stream);
1261 munmap(map, mapsize);
1262 return status;
1265 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1267 struct pack_entry e;
1269 if (!find_pack_entry(sha1, &e)) {
1270 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1271 return NULL;
1273 return unpack_entry(&e, type, size);
1276 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1278 unsigned long mapsize;
1279 void *map, *buf;
1280 struct pack_entry e;
1282 if (find_pack_entry(sha1, &e))
1283 return read_packed_sha1(sha1, type, size);
1284 map = map_sha1_file(sha1, &mapsize);
1285 if (map) {
1286 buf = unpack_sha1_file(map, mapsize, type, size);
1287 munmap(map, mapsize);
1288 return buf;
1290 reprepare_packed_git();
1291 if (find_pack_entry(sha1, &e))
1292 return read_packed_sha1(sha1, type, size);
1293 return NULL;
1296 void *read_object_with_reference(const unsigned char *sha1,
1297 const char *required_type,
1298 unsigned long *size,
1299 unsigned char *actual_sha1_return)
1301 char type[20];
1302 void *buffer;
1303 unsigned long isize;
1304 unsigned char actual_sha1[20];
1306 hashcpy(actual_sha1, sha1);
1307 while (1) {
1308 int ref_length = -1;
1309 const char *ref_type = NULL;
1311 buffer = read_sha1_file(actual_sha1, type, &isize);
1312 if (!buffer)
1313 return NULL;
1314 if (!strcmp(type, required_type)) {
1315 *size = isize;
1316 if (actual_sha1_return)
1317 hashcpy(actual_sha1_return, actual_sha1);
1318 return buffer;
1320 /* Handle references */
1321 else if (!strcmp(type, commit_type))
1322 ref_type = "tree ";
1323 else if (!strcmp(type, tag_type))
1324 ref_type = "object ";
1325 else {
1326 free(buffer);
1327 return NULL;
1329 ref_length = strlen(ref_type);
1331 if (memcmp(buffer, ref_type, ref_length) ||
1332 get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
1333 free(buffer);
1334 return NULL;
1336 free(buffer);
1337 /* Now we have the ID of the referred-to object in
1338 * actual_sha1. Check again. */
1342 char *write_sha1_file_prepare(void *buf,
1343 unsigned long len,
1344 const char *type,
1345 unsigned char *sha1,
1346 unsigned char *hdr,
1347 int *hdrlen)
1349 SHA_CTX c;
1351 /* Generate the header */
1352 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1354 /* Sha1.. */
1355 SHA1_Init(&c);
1356 SHA1_Update(&c, hdr, *hdrlen);
1357 SHA1_Update(&c, buf, len);
1358 SHA1_Final(sha1, &c);
1360 return sha1_file_name(sha1);
1364 * Link the tempfile to the final place, possibly creating the
1365 * last directory level as you do so.
1367 * Returns the errno on failure, 0 on success.
1369 static int link_temp_to_file(const char *tmpfile, char *filename)
1371 int ret;
1372 char *dir;
1374 if (!link(tmpfile, filename))
1375 return 0;
1378 * Try to mkdir the last path component if that failed.
1380 * Re-try the "link()" regardless of whether the mkdir
1381 * succeeds, since a race might mean that somebody
1382 * else succeeded.
1384 ret = errno;
1385 dir = strrchr(filename, '/');
1386 if (dir) {
1387 *dir = 0;
1388 mkdir(filename, 0777);
1389 if (adjust_shared_perm(filename))
1390 return -2;
1391 *dir = '/';
1392 if (!link(tmpfile, filename))
1393 return 0;
1394 ret = errno;
1396 return ret;
1400 * Move the just written object into its final resting place
1402 int move_temp_to_file(const char *tmpfile, char *filename)
1404 int ret = link_temp_to_file(tmpfile, filename);
1407 * Coda hack - coda doesn't like cross-directory links,
1408 * so we fall back to a rename, which will mean that it
1409 * won't be able to check collisions, but that's not a
1410 * big deal.
1412 * The same holds for FAT formatted media.
1414 * When this succeeds, we just return 0. We have nothing
1415 * left to unlink.
1417 if (ret && ret != EEXIST) {
1418 if (!rename(tmpfile, filename))
1419 return 0;
1420 ret = errno;
1422 unlink(tmpfile);
1423 if (ret) {
1424 if (ret != EEXIST) {
1425 fprintf(stderr, "unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1426 return -1;
1428 /* FIXME!!! Collision check here ? */
1431 return 0;
1434 static int write_buffer(int fd, const void *buf, size_t len)
1436 while (len) {
1437 ssize_t size;
1439 size = write(fd, buf, len);
1440 if (!size)
1441 return error("file write: disk full");
1442 if (size < 0) {
1443 if (errno == EINTR || errno == EAGAIN)
1444 continue;
1445 return error("file write error (%s)", strerror(errno));
1447 len -= size;
1448 buf = (char *) buf + size;
1450 return 0;
1453 static int write_binary_header(unsigned char *hdr, enum object_type type, unsigned long len)
1455 int hdr_len;
1456 unsigned char c;
1458 c = (type << 4) | (len & 15);
1459 len >>= 4;
1460 hdr_len = 1;
1461 while (len) {
1462 *hdr++ = c | 0x80;
1463 hdr_len++;
1464 c = (len & 0x7f);
1465 len >>= 7;
1467 *hdr = c;
1468 return hdr_len;
1471 static void setup_object_header(z_stream *stream, const char *type, unsigned long len)
1473 int obj_type, hdr;
1475 if (use_legacy_headers) {
1476 while (deflate(stream, 0) == Z_OK)
1477 /* nothing */;
1478 return;
1480 if (!strcmp(type, blob_type))
1481 obj_type = OBJ_BLOB;
1482 else if (!strcmp(type, tree_type))
1483 obj_type = OBJ_TREE;
1484 else if (!strcmp(type, commit_type))
1485 obj_type = OBJ_COMMIT;
1486 else if (!strcmp(type, tag_type))
1487 obj_type = OBJ_TAG;
1488 else
1489 die("trying to generate bogus object of type '%s'", type);
1490 hdr = write_binary_header(stream->next_out, obj_type, len);
1491 stream->total_out = hdr;
1492 stream->next_out += hdr;
1493 stream->avail_out -= hdr;
1496 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1498 int size;
1499 unsigned char *compressed;
1500 z_stream stream;
1501 unsigned char sha1[20];
1502 char *filename;
1503 static char tmpfile[PATH_MAX];
1504 unsigned char hdr[50];
1505 int fd, hdrlen;
1507 /* Normally if we have it in the pack then we do not bother writing
1508 * it out into .git/objects/??/?{38} file.
1510 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1511 if (returnsha1)
1512 hashcpy(returnsha1, sha1);
1513 if (has_sha1_file(sha1))
1514 return 0;
1515 fd = open(filename, O_RDONLY);
1516 if (fd >= 0) {
1518 * FIXME!!! We might do collision checking here, but we'd
1519 * need to uncompress the old file and check it. Later.
1521 close(fd);
1522 return 0;
1525 if (errno != ENOENT) {
1526 fprintf(stderr, "sha1 file %s: %s\n", filename, strerror(errno));
1527 return -1;
1530 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1532 fd = mkstemp(tmpfile);
1533 if (fd < 0) {
1534 fprintf(stderr, "unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
1535 return -1;
1538 /* Set it up */
1539 memset(&stream, 0, sizeof(stream));
1540 deflateInit(&stream, zlib_compression_level);
1541 size = 8 + deflateBound(&stream, len+hdrlen);
1542 compressed = xmalloc(size);
1544 /* Compress it */
1545 stream.next_out = compressed;
1546 stream.avail_out = size;
1548 /* First header.. */
1549 stream.next_in = hdr;
1550 stream.avail_in = hdrlen;
1551 setup_object_header(&stream, type, len);
1553 /* Then the data itself.. */
1554 stream.next_in = buf;
1555 stream.avail_in = len;
1556 while (deflate(&stream, Z_FINISH) == Z_OK)
1557 /* nothing */;
1558 deflateEnd(&stream);
1559 size = stream.total_out;
1561 if (write_buffer(fd, compressed, size) < 0)
1562 die("unable to write sha1 file");
1563 fchmod(fd, 0444);
1564 close(fd);
1565 free(compressed);
1567 return move_temp_to_file(tmpfile, filename);
1571 * We need to unpack and recompress the object for writing
1572 * it out to a different file.
1574 static void *repack_object(const unsigned char *sha1, unsigned long *objsize)
1576 size_t size;
1577 z_stream stream;
1578 unsigned char *unpacked;
1579 unsigned long len;
1580 char type[20];
1581 char hdr[50];
1582 int hdrlen;
1583 void *buf;
1585 /* need to unpack and recompress it by itself */
1586 unpacked = read_packed_sha1(sha1, type, &len);
1588 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1590 /* Set it up */
1591 memset(&stream, 0, sizeof(stream));
1592 deflateInit(&stream, zlib_compression_level);
1593 size = deflateBound(&stream, len + hdrlen);
1594 buf = xmalloc(size);
1596 /* Compress it */
1597 stream.next_out = buf;
1598 stream.avail_out = size;
1600 /* First header.. */
1601 stream.next_in = (void *)hdr;
1602 stream.avail_in = hdrlen;
1603 while (deflate(&stream, 0) == Z_OK)
1604 /* nothing */;
1606 /* Then the data itself.. */
1607 stream.next_in = unpacked;
1608 stream.avail_in = len;
1609 while (deflate(&stream, Z_FINISH) == Z_OK)
1610 /* nothing */;
1611 deflateEnd(&stream);
1612 free(unpacked);
1614 *objsize = stream.total_out;
1615 return buf;
1618 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1620 int retval;
1621 unsigned long objsize;
1622 void *buf = map_sha1_file(sha1, &objsize);
1624 if (buf) {
1625 retval = write_buffer(fd, buf, objsize);
1626 munmap(buf, objsize);
1627 return retval;
1630 buf = repack_object(sha1, &objsize);
1631 retval = write_buffer(fd, buf, objsize);
1632 free(buf);
1633 return retval;
1636 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1637 size_t bufsize, size_t *bufposn)
1639 char tmpfile[PATH_MAX];
1640 int local;
1641 z_stream stream;
1642 unsigned char real_sha1[20];
1643 unsigned char discard[4096];
1644 int ret;
1645 SHA_CTX c;
1647 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1649 local = mkstemp(tmpfile);
1650 if (local < 0)
1651 return error("Couldn't open %s for %s",
1652 tmpfile, sha1_to_hex(sha1));
1654 memset(&stream, 0, sizeof(stream));
1656 inflateInit(&stream);
1658 SHA1_Init(&c);
1660 do {
1661 ssize_t size;
1662 if (*bufposn) {
1663 stream.avail_in = *bufposn;
1664 stream.next_in = (unsigned char *) buffer;
1665 do {
1666 stream.next_out = discard;
1667 stream.avail_out = sizeof(discard);
1668 ret = inflate(&stream, Z_SYNC_FLUSH);
1669 SHA1_Update(&c, discard, sizeof(discard) -
1670 stream.avail_out);
1671 } while (stream.avail_in && ret == Z_OK);
1672 if (write_buffer(local, buffer, *bufposn - stream.avail_in) < 0)
1673 die("unable to write sha1 file");
1674 memmove(buffer, buffer + *bufposn - stream.avail_in,
1675 stream.avail_in);
1676 *bufposn = stream.avail_in;
1677 if (ret != Z_OK)
1678 break;
1680 size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1681 if (size <= 0) {
1682 close(local);
1683 unlink(tmpfile);
1684 if (!size)
1685 return error("Connection closed?");
1686 perror("Reading from connection");
1687 return -1;
1689 *bufposn += size;
1690 } while (1);
1691 inflateEnd(&stream);
1693 close(local);
1694 SHA1_Final(real_sha1, &c);
1695 if (ret != Z_STREAM_END) {
1696 unlink(tmpfile);
1697 return error("File %s corrupted", sha1_to_hex(sha1));
1699 if (hashcmp(sha1, real_sha1)) {
1700 unlink(tmpfile);
1701 return error("File %s has bad hash", sha1_to_hex(sha1));
1704 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1707 int has_pack_index(const unsigned char *sha1)
1709 struct stat st;
1710 if (stat(sha1_pack_index_name(sha1), &st))
1711 return 0;
1712 return 1;
1715 int has_pack_file(const unsigned char *sha1)
1717 struct stat st;
1718 if (stat(sha1_pack_name(sha1), &st))
1719 return 0;
1720 return 1;
1723 int has_sha1_pack(const unsigned char *sha1)
1725 struct pack_entry e;
1726 return find_pack_entry(sha1, &e);
1729 int has_sha1_file(const unsigned char *sha1)
1731 struct stat st;
1732 struct pack_entry e;
1734 if (find_pack_entry(sha1, &e))
1735 return 1;
1736 return find_sha1_file(sha1, &st) ? 1 : 0;
1740 * reads from fd as long as possible into a supplied buffer of size bytes.
1741 * If necessary the buffer's size is increased using realloc()
1743 * returns 0 if anything went fine and -1 otherwise
1745 * NOTE: both buf and size may change, but even when -1 is returned
1746 * you still have to free() it yourself.
1748 int read_pipe(int fd, char** return_buf, unsigned long* return_size)
1750 char* buf = *return_buf;
1751 unsigned long size = *return_size;
1752 int iret;
1753 unsigned long off = 0;
1755 do {
1756 iret = xread(fd, buf + off, size - off);
1757 if (iret > 0) {
1758 off += iret;
1759 if (off == size) {
1760 size *= 2;
1761 buf = xrealloc(buf, size);
1764 } while (iret > 0);
1766 *return_buf = buf;
1767 *return_size = off;
1769 if (iret < 0)
1770 return -1;
1771 return 0;
1774 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
1776 unsigned long size = 4096;
1777 char *buf = malloc(size);
1778 int ret;
1779 unsigned char hdr[50];
1780 int hdrlen;
1782 if (read_pipe(fd, &buf, &size)) {
1783 free(buf);
1784 return -1;
1787 if (!type)
1788 type = blob_type;
1789 if (write_object)
1790 ret = write_sha1_file(buf, size, type, sha1);
1791 else {
1792 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1793 ret = 0;
1795 free(buf);
1796 return ret;
1799 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1801 unsigned long size = st->st_size;
1802 void *buf;
1803 int ret;
1804 unsigned char hdr[50];
1805 int hdrlen;
1807 buf = "";
1808 if (size)
1809 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1810 close(fd);
1811 if (buf == MAP_FAILED)
1812 return -1;
1814 if (!type)
1815 type = blob_type;
1816 if (write_object)
1817 ret = write_sha1_file(buf, size, type, sha1);
1818 else {
1819 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1820 ret = 0;
1822 if (size)
1823 munmap(buf, size);
1824 return ret;
1827 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1829 int fd;
1830 char *target;
1832 switch (st->st_mode & S_IFMT) {
1833 case S_IFREG:
1834 fd = open(path, O_RDONLY);
1835 if (fd < 0)
1836 return error("open(\"%s\"): %s", path,
1837 strerror(errno));
1838 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1839 return error("%s: failed to insert into database",
1840 path);
1841 break;
1842 case S_IFLNK:
1843 target = xmalloc(st->st_size+1);
1844 if (readlink(path, target, st->st_size+1) != st->st_size) {
1845 char *errstr = strerror(errno);
1846 free(target);
1847 return error("readlink(\"%s\"): %s", path,
1848 errstr);
1850 if (!write_object) {
1851 unsigned char hdr[50];
1852 int hdrlen;
1853 write_sha1_file_prepare(target, st->st_size, blob_type,
1854 sha1, hdr, &hdrlen);
1855 } else if (write_sha1_file(target, st->st_size, blob_type, sha1))
1856 return error("%s: failed to insert into database",
1857 path);
1858 free(target);
1859 break;
1860 default:
1861 return error("%s: unsupported file type", path);
1863 return 0;