Fix PRIuMAX definition for MinGW.
[git/dscho.git] / sha1_file.c
blob6bcbdcf55c94fdfd43a921e2db643ed7c4437b2e
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 #ifdef NO_C99_FORMAT
26 #define SZ_FMT "lu"
27 #else
28 #define SZ_FMT "zu"
29 #endif
31 const unsigned char null_sha1[20];
33 static unsigned int sha1_file_open_flag = O_NOATIME;
35 signed char hexval_table[256] = {
36 -1, -1, -1, -1, -1, -1, -1, -1, /* 00-07 */
37 -1, -1, -1, -1, -1, -1, -1, -1, /* 08-0f */
38 -1, -1, -1, -1, -1, -1, -1, -1, /* 10-17 */
39 -1, -1, -1, -1, -1, -1, -1, -1, /* 18-1f */
40 -1, -1, -1, -1, -1, -1, -1, -1, /* 20-27 */
41 -1, -1, -1, -1, -1, -1, -1, -1, /* 28-2f */
42 0, 1, 2, 3, 4, 5, 6, 7, /* 30-37 */
43 8, 9, -1, -1, -1, -1, -1, -1, /* 38-3f */
44 -1, 10, 11, 12, 13, 14, 15, -1, /* 40-47 */
45 -1, -1, -1, -1, -1, -1, -1, -1, /* 48-4f */
46 -1, -1, -1, -1, -1, -1, -1, -1, /* 50-57 */
47 -1, -1, -1, -1, -1, -1, -1, -1, /* 58-5f */
48 -1, 10, 11, 12, 13, 14, 15, -1, /* 60-67 */
49 -1, -1, -1, -1, -1, -1, -1, -1, /* 68-67 */
50 -1, -1, -1, -1, -1, -1, -1, -1, /* 70-77 */
51 -1, -1, -1, -1, -1, -1, -1, -1, /* 78-7f */
52 -1, -1, -1, -1, -1, -1, -1, -1, /* 80-87 */
53 -1, -1, -1, -1, -1, -1, -1, -1, /* 88-8f */
54 -1, -1, -1, -1, -1, -1, -1, -1, /* 90-97 */
55 -1, -1, -1, -1, -1, -1, -1, -1, /* 98-9f */
56 -1, -1, -1, -1, -1, -1, -1, -1, /* a0-a7 */
57 -1, -1, -1, -1, -1, -1, -1, -1, /* a8-af */
58 -1, -1, -1, -1, -1, -1, -1, -1, /* b0-b7 */
59 -1, -1, -1, -1, -1, -1, -1, -1, /* b8-bf */
60 -1, -1, -1, -1, -1, -1, -1, -1, /* c0-c7 */
61 -1, -1, -1, -1, -1, -1, -1, -1, /* c8-cf */
62 -1, -1, -1, -1, -1, -1, -1, -1, /* d0-d7 */
63 -1, -1, -1, -1, -1, -1, -1, -1, /* d8-df */
64 -1, -1, -1, -1, -1, -1, -1, -1, /* e0-e7 */
65 -1, -1, -1, -1, -1, -1, -1, -1, /* e8-ef */
66 -1, -1, -1, -1, -1, -1, -1, -1, /* f0-f7 */
67 -1, -1, -1, -1, -1, -1, -1, -1, /* f8-ff */
70 int get_sha1_hex(const char *hex, unsigned char *sha1)
72 int i;
73 for (i = 0; i < 20; i++) {
74 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
75 if (val & ~0xff)
76 return -1;
77 *sha1++ = val;
78 hex += 2;
80 return 0;
83 /* returns the number of chars to skip to first component */
84 static inline int is_path_absolute(const char *path)
86 #ifdef __MINGW32__
87 if (isalpha(path[0]) && path[1] == ':')
88 return 2 + (path[2] == '/');
89 /* TODO: C:dir/file 'relative' paths are not catered for */
90 #endif
91 return *path == '/';
94 int safe_create_leading_directories(char *path)
96 char *pos = path + is_path_absolute(path);
97 struct stat st;
99 while (pos) {
100 pos = strchr(pos, '/');
101 if (!pos)
102 break;
103 *pos = 0;
104 if (!stat(path, &st)) {
105 /* path exists */
106 if (!S_ISDIR(st.st_mode)) {
107 *pos = '/';
108 return -3;
111 else if (mkdir(path, 0777)) {
112 *pos = '/';
113 return -1;
115 else if (adjust_shared_perm(path)) {
116 *pos = '/';
117 return -2;
119 *pos++ = '/';
121 return 0;
124 char * sha1_to_hex(const unsigned char *sha1)
126 static int bufno;
127 static char hexbuffer[4][50];
128 static const char hex[] = "0123456789abcdef";
129 char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
130 int i;
132 for (i = 0; i < 20; i++) {
133 unsigned int val = *sha1++;
134 *buf++ = hex[val >> 4];
135 *buf++ = hex[val & 0xf];
137 *buf = '\0';
139 return buffer;
142 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
144 int i;
145 for (i = 0; i < 20; i++) {
146 static char hex[] = "0123456789abcdef";
147 unsigned int val = sha1[i];
148 char *pos = pathbuf + i*2 + (i > 0);
149 *pos++ = hex[val >> 4];
150 *pos = hex[val & 0xf];
155 * NOTE! This returns a statically allocated buffer, so you have to be
156 * careful about using it. Do a "xstrdup()" if you need to save the
157 * filename.
159 * Also note that this returns the location for creating. Reading
160 * SHA1 file can happen from any alternate directory listed in the
161 * DB_ENVIRONMENT environment variable if it is not found in
162 * the primary object database.
164 char *sha1_file_name(const unsigned char *sha1)
166 static char *name, *base;
168 if (!base) {
169 const char *sha1_file_directory = get_object_directory();
170 int len = strlen(sha1_file_directory);
171 base = xmalloc(len + 60);
172 memcpy(base, sha1_file_directory, len);
173 memset(base+len, 0, 60);
174 base[len] = '/';
175 base[len+3] = '/';
176 name = base + len + 1;
178 fill_sha1_path(name, sha1);
179 return base;
182 char *sha1_pack_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.pack", 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 char *sha1_pack_index_name(const unsigned char *sha1)
209 static const char hex[] = "0123456789abcdef";
210 static char *name, *base, *buf;
211 int i;
213 if (!base) {
214 const char *sha1_file_directory = get_object_directory();
215 int len = strlen(sha1_file_directory);
216 base = xmalloc(len + 60);
217 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
218 name = base + len + 11;
221 buf = name;
223 for (i = 0; i < 20; i++) {
224 unsigned int val = *sha1++;
225 *buf++ = hex[val >> 4];
226 *buf++ = hex[val & 0xf];
229 return base;
232 struct alternate_object_database *alt_odb_list;
233 static struct alternate_object_database **alt_odb_tail;
235 static void read_info_alternates(const char * alternates, int depth);
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 similar to that environment variable but can be
245 * LF separated. 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 int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
254 struct stat st;
255 const char *objdir = get_object_directory();
256 struct alternate_object_database *ent;
257 struct alternate_object_database *alt;
258 /* 43 = 40-byte + 2 '/' + terminating NUL */
259 int pfxlen = len;
260 int entlen = pfxlen + 43;
261 int base_len = -1;
263 if (!is_path_absolute(entry) && relative_base) {
264 /* Relative alt-odb */
265 if (base_len < 0)
266 base_len = strlen(relative_base) + 1;
267 entlen += base_len;
268 pfxlen += base_len;
270 ent = xmalloc(sizeof(*ent) + entlen);
272 if (!is_path_absolute(entry) && relative_base) {
273 memcpy(ent->base, relative_base, base_len - 1);
274 ent->base[base_len - 1] = '/';
275 memcpy(ent->base + base_len, entry, len);
277 else
278 memcpy(ent->base, entry, pfxlen);
280 ent->name = ent->base + pfxlen + 1;
281 ent->base[pfxlen + 3] = '/';
282 ent->base[pfxlen] = ent->base[entlen-1] = 0;
284 /* Detect cases where alternate disappeared */
285 if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
286 error("object directory %s does not exist; "
287 "check .git/objects/info/alternates.",
288 ent->base);
289 free(ent);
290 return -1;
293 /* Prevent the common mistake of listing the same
294 * thing twice, or object directory itself.
296 for (alt = alt_odb_list; alt; alt = alt->next) {
297 if (!memcmp(ent->base, alt->base, pfxlen)) {
298 free(ent);
299 return -1;
302 if (!memcmp(ent->base, objdir, pfxlen)) {
303 free(ent);
304 return -1;
307 /* add the alternate entry */
308 *alt_odb_tail = ent;
309 alt_odb_tail = &(ent->next);
310 ent->next = NULL;
312 /* recursively add alternates */
313 read_info_alternates(ent->base, depth + 1);
315 ent->base[pfxlen] = '/';
317 return 0;
320 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
321 const char *relative_base, int depth)
323 const char *cp, *last;
325 if (depth > 5) {
326 error("%s: ignoring alternate object stores, nesting too deep.",
327 relative_base);
328 return;
331 last = alt;
332 while (last < ep) {
333 cp = last;
334 if (cp < ep && *cp == '#') {
335 while (cp < ep && *cp != sep)
336 cp++;
337 last = cp + 1;
338 continue;
340 while (cp < ep && *cp != sep)
341 cp++;
342 if (last != cp) {
343 if (!is_path_absolute(last) && depth) {
344 error("%s: ignoring relative alternate object store %s",
345 relative_base, last);
346 } else {
347 link_alt_odb_entry(last, cp - last,
348 relative_base, depth);
351 while (cp < ep && *cp == sep)
352 cp++;
353 last = cp;
357 static void read_info_alternates(const char * relative_base, int depth)
359 char *map;
360 size_t mapsz;
361 struct stat st;
362 char path[PATH_MAX];
363 int fd;
365 sprintf(path, "%s/info/alternates", relative_base);
366 fd = open(path, O_RDONLY);
367 if (fd < 0)
368 return;
369 if (fstat(fd, &st) || (st.st_size == 0)) {
370 close(fd);
371 return;
373 mapsz = xsize_t(st.st_size);
374 map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
375 close(fd);
377 link_alt_odb_entries(map, map + mapsz, '\n', relative_base, depth);
379 munmap(map, mapsz);
382 void prepare_alt_odb(void)
384 const char *alt;
386 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
387 if (!alt) alt = "";
389 if (alt_odb_tail)
390 return;
391 alt_odb_tail = &alt_odb_list;
392 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL, 0);
394 read_info_alternates(get_object_directory(), 0);
397 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
399 char *name = sha1_file_name(sha1);
400 struct alternate_object_database *alt;
402 if (!stat(name, st))
403 return name;
404 prepare_alt_odb();
405 for (alt = alt_odb_list; alt; alt = alt->next) {
406 name = alt->name;
407 fill_sha1_path(name, sha1);
408 if (!stat(alt->base, st))
409 return alt->base;
411 return NULL;
414 static unsigned int pack_used_ctr;
415 static unsigned int pack_mmap_calls;
416 static unsigned int peak_pack_open_windows;
417 static unsigned int pack_open_windows;
418 static size_t peak_pack_mapped;
419 static size_t pack_mapped;
420 struct packed_git *packed_git;
422 void pack_report()
424 fprintf(stderr,
425 "pack_report: getpagesize() = %10" SZ_FMT "\n"
426 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
427 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
428 (size_t) getpagesize(),
429 packed_git_window_size,
430 packed_git_limit);
431 fprintf(stderr,
432 "pack_report: pack_used_ctr = %10u\n"
433 "pack_report: pack_mmap_calls = %10u\n"
434 "pack_report: pack_open_windows = %10u / %10u\n"
435 "pack_report: pack_mapped = "
436 "%10" SZ_FMT " / %10" SZ_FMT "\n",
437 pack_used_ctr,
438 pack_mmap_calls,
439 pack_open_windows, peak_pack_open_windows,
440 pack_mapped, peak_pack_mapped);
443 static int check_packed_git_idx(const char *path, struct packed_git *p)
445 void *idx_map;
446 struct pack_idx_header *hdr;
447 size_t idx_size;
448 uint32_t nr, i, *index;
449 int fd = open(path, O_RDONLY);
450 struct stat st;
452 if (fd < 0)
453 return -1;
454 if (fstat(fd, &st)) {
455 close(fd);
456 return -1;
458 idx_size = xsize_t(st.st_size);
459 if (idx_size < 4 * 256 + 20 + 20) {
460 close(fd);
461 return error("index file %s is too small", path);
463 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
464 close(fd);
466 /* a future index format would start with this, as older git
467 * binaries would fail the non-monotonic index check below.
468 * give a nicer warning to the user if we can.
470 hdr = idx_map;
471 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
472 munmap(idx_map, idx_size);
473 return error("index file %s is a newer version"
474 " and is not supported by this binary"
475 " (try upgrading GIT to a newer version)",
476 path);
479 nr = 0;
480 index = idx_map;
481 for (i = 0; i < 256; i++) {
482 uint32_t n = ntohl(index[i]);
483 if (n < nr) {
484 munmap(idx_map, idx_size);
485 return error("non-monotonic index %s", path);
487 nr = n;
491 * Total size:
492 * - 256 index entries 4 bytes each
493 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
494 * - 20-byte SHA1 of the packfile
495 * - 20-byte SHA1 file checksum
497 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
498 munmap(idx_map, idx_size);
499 return error("wrong index file size in %s", path);
502 p->index_version = 1;
503 p->index_data = idx_map;
504 p->index_size = idx_size;
505 return 0;
508 static void scan_windows(struct packed_git *p,
509 struct packed_git **lru_p,
510 struct pack_window **lru_w,
511 struct pack_window **lru_l)
513 struct pack_window *w, *w_l;
515 for (w_l = NULL, w = p->windows; w; w = w->next) {
516 if (!w->inuse_cnt) {
517 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
518 *lru_p = p;
519 *lru_w = w;
520 *lru_l = w_l;
523 w_l = w;
527 static int unuse_one_window(struct packed_git *current)
529 struct packed_git *p, *lru_p = NULL;
530 struct pack_window *lru_w = NULL, *lru_l = NULL;
532 if (current)
533 scan_windows(current, &lru_p, &lru_w, &lru_l);
534 for (p = packed_git; p; p = p->next)
535 scan_windows(p, &lru_p, &lru_w, &lru_l);
536 if (lru_p) {
537 munmap(lru_w->base, lru_w->len);
538 pack_mapped -= lru_w->len;
539 if (lru_l)
540 lru_l->next = lru_w->next;
541 else {
542 lru_p->windows = lru_w->next;
543 if (!lru_p->windows && lru_p != current) {
544 close(lru_p->pack_fd);
545 lru_p->pack_fd = -1;
548 free(lru_w);
549 pack_open_windows--;
550 return 1;
552 return 0;
555 void release_pack_memory(size_t need)
557 size_t cur = pack_mapped;
558 while (need >= (cur - pack_mapped) && unuse_one_window(NULL))
559 ; /* nothing */
562 void unuse_pack(struct pack_window **w_cursor)
564 struct pack_window *w = *w_cursor;
565 if (w) {
566 w->inuse_cnt--;
567 *w_cursor = NULL;
572 * Do not call this directly as this leaks p->pack_fd on error return;
573 * call open_packed_git() instead.
575 static int open_packed_git_1(struct packed_git *p)
577 struct stat st;
578 struct pack_header hdr;
579 unsigned char sha1[20];
580 unsigned char *idx_sha1;
581 long fd_flag;
583 p->pack_fd = open(p->pack_name, O_RDONLY);
584 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
585 return -1;
587 /* If we created the struct before we had the pack we lack size. */
588 if (!p->pack_size) {
589 if (!S_ISREG(st.st_mode))
590 return error("packfile %s not a regular file", p->pack_name);
591 p->pack_size = st.st_size;
592 } else if (p->pack_size != st.st_size)
593 return error("packfile %s size changed", p->pack_name);
595 #ifndef __MINGW32__
596 /* We leave these file descriptors open with sliding mmap;
597 * there is no point keeping them open across exec(), though.
599 fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
600 if (fd_flag < 0)
601 return error("cannot determine file descriptor flags");
602 fd_flag |= FD_CLOEXEC;
603 if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
604 return error("cannot set FD_CLOEXEC");
605 #endif
607 /* Verify we recognize this pack file format. */
608 if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
609 return error("file %s is far too short to be a packfile", p->pack_name);
610 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
611 return error("file %s is not a GIT packfile", p->pack_name);
612 if (!pack_version_ok(hdr.hdr_version))
613 return error("packfile %s is version %u and not supported"
614 " (try upgrading GIT to a newer version)",
615 p->pack_name, ntohl(hdr.hdr_version));
617 /* Verify the pack matches its index. */
618 if (num_packed_objects(p) != ntohl(hdr.hdr_entries))
619 return error("packfile %s claims to have %u objects"
620 " while index size indicates %u objects",
621 p->pack_name, ntohl(hdr.hdr_entries),
622 num_packed_objects(p));
623 if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
624 return error("end of packfile %s is unavailable", p->pack_name);
625 if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
626 return error("packfile %s signature is unavailable", p->pack_name);
627 idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
628 if (hashcmp(sha1, idx_sha1))
629 return error("packfile %s does not match index", p->pack_name);
630 return 0;
633 static int open_packed_git(struct packed_git *p)
635 if (!open_packed_git_1(p))
636 return 0;
637 if (p->pack_fd != -1) {
638 close(p->pack_fd);
639 p->pack_fd = -1;
641 return -1;
644 static int in_window(struct pack_window *win, off_t offset)
646 /* We must promise at least 20 bytes (one hash) after the
647 * offset is available from this window, otherwise the offset
648 * is not actually in this window and a different window (which
649 * has that one hash excess) must be used. This is to support
650 * the object header and delta base parsing routines below.
652 off_t win_off = win->offset;
653 return win_off <= offset
654 && (offset + 20) <= (win_off + win->len);
657 unsigned char* use_pack(struct packed_git *p,
658 struct pack_window **w_cursor,
659 off_t offset,
660 unsigned int *left)
662 struct pack_window *win = *w_cursor;
664 if (p->pack_fd == -1 && open_packed_git(p))
665 die("packfile %s cannot be accessed", p->pack_name);
667 /* Since packfiles end in a hash of their content and its
668 * pointless to ask for an offset into the middle of that
669 * hash, and the in_window function above wouldn't match
670 * don't allow an offset too close to the end of the file.
672 if (offset > (p->pack_size - 20))
673 die("offset beyond end of packfile (truncated pack?)");
675 if (!win || !in_window(win, offset)) {
676 if (win)
677 win->inuse_cnt--;
678 for (win = p->windows; win; win = win->next) {
679 if (in_window(win, offset))
680 break;
682 if (!win) {
683 size_t window_align = packed_git_window_size / 2;
684 off_t len;
685 win = xcalloc(1, sizeof(*win));
686 win->offset = (offset / window_align) * window_align;
687 len = p->pack_size - win->offset;
688 if (len > packed_git_window_size)
689 len = packed_git_window_size;
690 win->len = (size_t)len;
691 pack_mapped += win->len;
692 while (packed_git_limit < pack_mapped
693 && unuse_one_window(p))
694 ; /* nothing */
695 win->base = xmmap(NULL, win->len,
696 PROT_READ, MAP_PRIVATE,
697 p->pack_fd, win->offset);
698 if (win->base == MAP_FAILED)
699 die("packfile %s cannot be mapped: %s",
700 p->pack_name,
701 strerror(errno));
702 pack_mmap_calls++;
703 pack_open_windows++;
704 if (pack_mapped > peak_pack_mapped)
705 peak_pack_mapped = pack_mapped;
706 if (pack_open_windows > peak_pack_open_windows)
707 peak_pack_open_windows = pack_open_windows;
708 win->next = p->windows;
709 p->windows = win;
712 if (win != *w_cursor) {
713 win->last_used = pack_used_ctr++;
714 win->inuse_cnt++;
715 *w_cursor = win;
717 offset -= win->offset;
718 if (left)
719 *left = win->len - xsize_t(offset);
720 return win->base + offset;
723 struct packed_git *add_packed_git(const char *path, int path_len, int local)
725 struct stat st;
726 struct packed_git *p = xmalloc(sizeof(*p) + path_len + 2);
729 * Make sure a corresponding .pack file exists and that
730 * the index looks sane.
732 path_len -= strlen(".idx");
733 if (path_len < 1)
734 return NULL;
735 memcpy(p->pack_name, path, path_len);
736 strcpy(p->pack_name + path_len, ".pack");
737 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode) ||
738 check_packed_git_idx(path, p)) {
739 free(p);
740 return NULL;
743 /* ok, it looks sane as far as we can check without
744 * actually mapping the pack file.
746 p->pack_size = st.st_size;
747 p->next = NULL;
748 p->windows = NULL;
749 p->pack_fd = -1;
750 p->pack_local = local;
751 p->mtime = st.st_mtime;
752 if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
753 hashclr(p->sha1);
754 return p;
757 struct packed_git *parse_pack_index(unsigned char *sha1)
759 char *path = sha1_pack_index_name(sha1);
760 return parse_pack_index_file(sha1, path);
763 struct packed_git *parse_pack_index_file(const unsigned char *sha1,
764 const char *idx_path)
766 const char *path = sha1_pack_name(sha1);
767 struct packed_git *p = xmalloc(sizeof(*p) + strlen(path) + 2);
769 if (check_packed_git_idx(idx_path, p)) {
770 free(p);
771 return NULL;
774 strcpy(p->pack_name, path);
775 p->pack_size = 0;
776 p->next = NULL;
777 p->windows = NULL;
778 p->pack_fd = -1;
779 hashcpy(p->sha1, sha1);
780 return p;
783 void install_packed_git(struct packed_git *pack)
785 pack->next = packed_git;
786 packed_git = pack;
789 static void prepare_packed_git_one(char *objdir, int local)
791 char path[PATH_MAX];
792 int len;
793 DIR *dir;
794 struct dirent *de;
796 sprintf(path, "%s/pack", objdir);
797 len = strlen(path);
798 dir = opendir(path);
799 if (!dir) {
800 if (errno != ENOENT)
801 error("unable to open object pack directory: %s: %s",
802 path, strerror(errno));
803 return;
805 path[len++] = '/';
806 while ((de = readdir(dir)) != NULL) {
807 int namelen = strlen(de->d_name);
808 struct packed_git *p;
810 if (!has_extension(de->d_name, ".idx"))
811 continue;
813 /* Don't reopen a pack we already have. */
814 strcpy(path + len, de->d_name);
815 for (p = packed_git; p; p = p->next) {
816 if (!memcmp(path, p->pack_name, len + namelen - 4))
817 break;
819 if (p)
820 continue;
821 /* See if it really is a valid .idx file with corresponding
822 * .pack file that we can map.
824 p = add_packed_git(path, len + namelen, local);
825 if (!p)
826 continue;
827 install_packed_git(p);
829 closedir(dir);
832 static int sort_pack(const void *a_, const void *b_)
834 struct packed_git *a = *((struct packed_git **)a_);
835 struct packed_git *b = *((struct packed_git **)b_);
836 int st;
839 * Local packs tend to contain objects specific to our
840 * variant of the project than remote ones. In addition,
841 * remote ones could be on a network mounted filesystem.
842 * Favor local ones for these reasons.
844 st = a->pack_local - b->pack_local;
845 if (st)
846 return -st;
849 * Younger packs tend to contain more recent objects,
850 * and more recent objects tend to get accessed more
851 * often.
853 if (a->mtime < b->mtime)
854 return 1;
855 else if (a->mtime == b->mtime)
856 return 0;
857 return -1;
860 static void rearrange_packed_git(void)
862 struct packed_git **ary, *p;
863 int i, n;
865 for (n = 0, p = packed_git; p; p = p->next)
866 n++;
867 if (n < 2)
868 return;
870 /* prepare an array of packed_git for easier sorting */
871 ary = xcalloc(n, sizeof(struct packed_git *));
872 for (n = 0, p = packed_git; p; p = p->next)
873 ary[n++] = p;
875 qsort(ary, n, sizeof(struct packed_git *), sort_pack);
877 /* link them back again */
878 for (i = 0; i < n - 1; i++)
879 ary[i]->next = ary[i + 1];
880 ary[n - 1]->next = NULL;
881 packed_git = ary[0];
883 free(ary);
886 static int prepare_packed_git_run_once = 0;
887 void prepare_packed_git(void)
889 struct alternate_object_database *alt;
891 if (prepare_packed_git_run_once)
892 return;
893 prepare_packed_git_one(get_object_directory(), 1);
894 prepare_alt_odb();
895 for (alt = alt_odb_list; alt; alt = alt->next) {
896 alt->name[-1] = 0;
897 prepare_packed_git_one(alt->base, 0);
898 alt->name[-1] = '/';
900 rearrange_packed_git();
901 prepare_packed_git_run_once = 1;
904 void reprepare_packed_git(void)
906 prepare_packed_git_run_once = 0;
907 prepare_packed_git();
910 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
912 unsigned char real_sha1[20];
913 hash_sha1_file(map, size, type, real_sha1);
914 return hashcmp(sha1, real_sha1) ? -1 : 0;
917 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
919 struct stat st;
920 void *map;
921 int fd;
922 char *filename = find_sha1_file(sha1, &st);
924 if (!filename) {
925 return NULL;
928 fd = open(filename, O_RDONLY | sha1_file_open_flag);
929 if (fd < 0) {
930 /* See if it works without O_NOATIME */
931 switch (sha1_file_open_flag) {
932 default:
933 fd = open(filename, O_RDONLY);
934 if (fd >= 0)
935 break;
936 /* Fallthrough */
937 case 0:
938 return NULL;
941 /* If it failed once, it will probably fail again.
942 * Stop using O_NOATIME
944 sha1_file_open_flag = 0;
946 *size = xsize_t(st.st_size);
947 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
948 close(fd);
949 return map;
952 int legacy_loose_object(unsigned char *map)
954 unsigned int word;
957 * Is it a zlib-compressed buffer? If so, the first byte
958 * must be 0x78 (15-bit window size, deflated), and the
959 * first 16-bit word is evenly divisible by 31
961 word = (map[0] << 8) + map[1];
962 if (map[0] == 0x78 && !(word % 31))
963 return 1;
964 else
965 return 0;
968 unsigned long unpack_object_header_gently(const unsigned char *buf, unsigned long len, enum object_type *type, unsigned long *sizep)
970 unsigned shift;
971 unsigned char c;
972 unsigned long size;
973 unsigned long used = 0;
975 c = buf[used++];
976 *type = (c >> 4) & 7;
977 size = c & 15;
978 shift = 4;
979 while (c & 0x80) {
980 if (len <= used)
981 return 0;
982 if (sizeof(long) * 8 <= shift)
983 return 0;
984 c = buf[used++];
985 size += (c & 0x7f) << shift;
986 shift += 7;
988 *sizep = size;
989 return used;
992 static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
994 unsigned long size, used;
995 static const char valid_loose_object_type[8] = {
996 0, /* OBJ_EXT */
997 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
998 0, /* "delta" and others are invalid in a loose object */
1000 enum object_type type;
1002 /* Get the data stream */
1003 memset(stream, 0, sizeof(*stream));
1004 stream->next_in = map;
1005 stream->avail_in = mapsize;
1006 stream->next_out = buffer;
1007 stream->avail_out = bufsiz;
1009 if (legacy_loose_object(map)) {
1010 inflateInit(stream);
1011 return inflate(stream, 0);
1014 used = unpack_object_header_gently(map, mapsize, &type, &size);
1015 if (!used || !valid_loose_object_type[type])
1016 return -1;
1017 map += used;
1018 mapsize -= used;
1020 /* Set up the stream for the rest.. */
1021 stream->next_in = map;
1022 stream->avail_in = mapsize;
1023 inflateInit(stream);
1025 /* And generate the fake traditional header */
1026 stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1027 typename(type), size);
1028 return 0;
1031 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1033 int bytes = strlen(buffer) + 1;
1034 unsigned char *buf = xmalloc(1+size);
1035 unsigned long n;
1036 int status = Z_OK;
1038 n = stream->total_out - bytes;
1039 if (n > size)
1040 n = size;
1041 memcpy(buf, (char *) buffer + bytes, n);
1042 bytes = n;
1043 if (bytes < size) {
1044 stream->next_out = buf + bytes;
1045 stream->avail_out = size - bytes;
1046 while (status == Z_OK)
1047 status = inflate(stream, Z_FINISH);
1049 buf[size] = 0;
1050 if ((status == Z_OK || status == Z_STREAM_END) && !stream->avail_in) {
1051 inflateEnd(stream);
1052 return buf;
1055 if (status < 0)
1056 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1057 else if (stream->avail_in)
1058 error("garbage at end of loose object '%s'",
1059 sha1_to_hex(sha1));
1060 free(buf);
1061 return NULL;
1065 * We used to just use "sscanf()", but that's actually way
1066 * too permissive for what we want to check. So do an anal
1067 * object header parse by hand.
1069 static int parse_sha1_header(const char *hdr, unsigned long *sizep)
1071 char type[10];
1072 int i;
1073 unsigned long size;
1076 * The type can be at most ten bytes (including the
1077 * terminating '\0' that we add), and is followed by
1078 * a space.
1080 i = 0;
1081 for (;;) {
1082 char c = *hdr++;
1083 if (c == ' ')
1084 break;
1085 type[i++] = c;
1086 if (i >= sizeof(type))
1087 return -1;
1089 type[i] = 0;
1092 * The length must follow immediately, and be in canonical
1093 * decimal format (ie "010" is not valid).
1095 size = *hdr++ - '0';
1096 if (size > 9)
1097 return -1;
1098 if (size) {
1099 for (;;) {
1100 unsigned long c = *hdr - '0';
1101 if (c > 9)
1102 break;
1103 hdr++;
1104 size = size * 10 + c;
1107 *sizep = size;
1110 * The length must be followed by a zero byte
1112 return *hdr ? -1 : type_from_string(type);
1115 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1117 int ret;
1118 z_stream stream;
1119 char hdr[8192];
1121 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1122 if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1123 return NULL;
1125 return unpack_sha1_rest(&stream, hdr, *size, sha1);
1128 static off_t get_delta_base(struct packed_git *p,
1129 struct pack_window **w_curs,
1130 off_t *curpos,
1131 enum object_type type,
1132 off_t delta_obj_offset)
1134 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1135 off_t base_offset;
1137 /* use_pack() assured us we have [base_info, base_info + 20)
1138 * as a range that we can look at without walking off the
1139 * end of the mapped window. Its actually the hash size
1140 * that is assured. An OFS_DELTA longer than the hash size
1141 * is stupid, as then a REF_DELTA would be smaller to store.
1143 if (type == OBJ_OFS_DELTA) {
1144 unsigned used = 0;
1145 unsigned char c = base_info[used++];
1146 base_offset = c & 127;
1147 while (c & 128) {
1148 base_offset += 1;
1149 if (!base_offset || base_offset & ~(~0UL >> 7))
1150 die("offset value overflow for delta base object");
1151 c = base_info[used++];
1152 base_offset = (base_offset << 7) + (c & 127);
1154 base_offset = delta_obj_offset - base_offset;
1155 if (base_offset >= delta_obj_offset)
1156 die("delta base offset out of bound");
1157 *curpos += used;
1158 } else if (type == OBJ_REF_DELTA) {
1159 /* The base entry _must_ be in the same pack */
1160 base_offset = find_pack_entry_one(base_info, p);
1161 if (!base_offset)
1162 die("failed to find delta-pack base object %s",
1163 sha1_to_hex(base_info));
1164 *curpos += 20;
1165 } else
1166 die("I am totally screwed");
1167 return base_offset;
1170 /* forward declaration for a mutually recursive function */
1171 static int packed_object_info(struct packed_git *p, off_t offset,
1172 unsigned long *sizep);
1174 static int packed_delta_info(struct packed_git *p,
1175 struct pack_window **w_curs,
1176 off_t curpos,
1177 enum object_type type,
1178 off_t obj_offset,
1179 unsigned long *sizep)
1181 off_t base_offset;
1183 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1184 type = packed_object_info(p, base_offset, NULL);
1186 /* We choose to only get the type of the base object and
1187 * ignore potentially corrupt pack file that expects the delta
1188 * based on a base with a wrong size. This saves tons of
1189 * inflate() calls.
1191 if (sizep) {
1192 const unsigned char *data;
1193 unsigned char delta_head[20], *in;
1194 z_stream stream;
1195 int st;
1197 memset(&stream, 0, sizeof(stream));
1198 stream.next_out = delta_head;
1199 stream.avail_out = sizeof(delta_head);
1201 inflateInit(&stream);
1202 do {
1203 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1204 stream.next_in = in;
1205 st = inflate(&stream, Z_FINISH);
1206 curpos += stream.next_in - in;
1207 } while ((st == Z_OK || st == Z_BUF_ERROR)
1208 && stream.total_out < sizeof(delta_head));
1209 inflateEnd(&stream);
1210 if ((st != Z_STREAM_END) &&
1211 stream.total_out != sizeof(delta_head))
1212 die("delta data unpack-initial failed");
1214 /* Examine the initial part of the delta to figure out
1215 * the result size.
1217 data = delta_head;
1219 /* ignore base size */
1220 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1222 /* Read the result size */
1223 *sizep = get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1226 return type;
1229 static int unpack_object_header(struct packed_git *p,
1230 struct pack_window **w_curs,
1231 off_t *curpos,
1232 unsigned long *sizep)
1234 unsigned char *base;
1235 unsigned int left;
1236 unsigned long used;
1237 enum object_type type;
1239 /* use_pack() assures us we have [base, base + 20) available
1240 * as a range that we can look at at. (Its actually the hash
1241 * size that is assured.) With our object header encoding
1242 * the maximum deflated object size is 2^137, which is just
1243 * insane, so we know won't exceed what we have been given.
1245 base = use_pack(p, w_curs, *curpos, &left);
1246 used = unpack_object_header_gently(base, left, &type, sizep);
1247 if (!used)
1248 die("object offset outside of pack file");
1249 *curpos += used;
1251 return type;
1254 const char *packed_object_info_detail(struct packed_git *p,
1255 off_t obj_offset,
1256 unsigned long *size,
1257 unsigned long *store_size,
1258 unsigned int *delta_chain_length,
1259 unsigned char *base_sha1)
1261 struct pack_window *w_curs = NULL;
1262 off_t curpos;
1263 unsigned long dummy;
1264 unsigned char *next_sha1;
1265 enum object_type type;
1267 *delta_chain_length = 0;
1268 curpos = obj_offset;
1269 type = unpack_object_header(p, &w_curs, &curpos, size);
1271 for (;;) {
1272 switch (type) {
1273 default:
1274 die("pack %s contains unknown object type %d",
1275 p->pack_name, type);
1276 case OBJ_COMMIT:
1277 case OBJ_TREE:
1278 case OBJ_BLOB:
1279 case OBJ_TAG:
1280 *store_size = 0; /* notyet */
1281 unuse_pack(&w_curs);
1282 return typename(type);
1283 case OBJ_OFS_DELTA:
1284 obj_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1285 if (*delta_chain_length == 0) {
1286 /* TODO: find base_sha1 as pointed by curpos */
1287 hashclr(base_sha1);
1289 break;
1290 case OBJ_REF_DELTA:
1291 next_sha1 = use_pack(p, &w_curs, curpos, NULL);
1292 if (*delta_chain_length == 0)
1293 hashcpy(base_sha1, next_sha1);
1294 obj_offset = find_pack_entry_one(next_sha1, p);
1295 break;
1297 (*delta_chain_length)++;
1298 curpos = obj_offset;
1299 type = unpack_object_header(p, &w_curs, &curpos, &dummy);
1303 static int packed_object_info(struct packed_git *p, off_t obj_offset,
1304 unsigned long *sizep)
1306 struct pack_window *w_curs = NULL;
1307 unsigned long size;
1308 off_t curpos = obj_offset;
1309 enum object_type type;
1311 type = unpack_object_header(p, &w_curs, &curpos, &size);
1313 switch (type) {
1314 case OBJ_OFS_DELTA:
1315 case OBJ_REF_DELTA:
1316 type = packed_delta_info(p, &w_curs, curpos,
1317 type, obj_offset, sizep);
1318 break;
1319 case OBJ_COMMIT:
1320 case OBJ_TREE:
1321 case OBJ_BLOB:
1322 case OBJ_TAG:
1323 if (sizep)
1324 *sizep = size;
1325 break;
1326 default:
1327 die("pack %s contains unknown object type %d",
1328 p->pack_name, type);
1330 unuse_pack(&w_curs);
1331 return type;
1334 static void *unpack_compressed_entry(struct packed_git *p,
1335 struct pack_window **w_curs,
1336 off_t curpos,
1337 unsigned long size)
1339 int st;
1340 z_stream stream;
1341 unsigned char *buffer, *in;
1343 buffer = xmalloc(size + 1);
1344 buffer[size] = 0;
1345 memset(&stream, 0, sizeof(stream));
1346 stream.next_out = buffer;
1347 stream.avail_out = size;
1349 inflateInit(&stream);
1350 do {
1351 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1352 stream.next_in = in;
1353 st = inflate(&stream, Z_FINISH);
1354 curpos += stream.next_in - in;
1355 } while (st == Z_OK || st == Z_BUF_ERROR);
1356 inflateEnd(&stream);
1357 if ((st != Z_STREAM_END) || stream.total_out != size) {
1358 free(buffer);
1359 return NULL;
1362 return buffer;
1365 #define MAX_DELTA_CACHE (256)
1367 static size_t delta_base_cached;
1368 static struct delta_base_cache_entry {
1369 struct packed_git *p;
1370 off_t base_offset;
1371 unsigned long size;
1372 void *data;
1373 enum object_type type;
1374 } delta_base_cache[MAX_DELTA_CACHE];
1376 static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1378 unsigned long hash;
1380 hash = (unsigned long)p + (unsigned long)base_offset;
1381 hash += (hash >> 8) + (hash >> 16);
1382 return hash & 0xff;
1385 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1386 unsigned long *base_size, enum object_type *type, int keep_cache)
1388 void *ret;
1389 unsigned long hash = pack_entry_hash(p, base_offset);
1390 struct delta_base_cache_entry *ent = delta_base_cache + hash;
1392 ret = ent->data;
1393 if (ret && ent->p == p && ent->base_offset == base_offset)
1394 goto found_cache_entry;
1395 return unpack_entry(p, base_offset, type, base_size);
1397 found_cache_entry:
1398 if (!keep_cache) {
1399 ent->data = NULL;
1400 delta_base_cached -= ent->size;
1402 else {
1403 ret = xmalloc(ent->size + 1);
1404 memcpy(ret, ent->data, ent->size);
1405 ((char *)ret)[ent->size] = 0;
1407 *type = ent->type;
1408 *base_size = ent->size;
1409 return ret;
1412 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1414 if (ent->data) {
1415 free(ent->data);
1416 ent->data = NULL;
1417 delta_base_cached -= ent->size;
1421 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1422 void *base, unsigned long base_size, enum object_type type)
1424 unsigned long i, hash = pack_entry_hash(p, base_offset);
1425 struct delta_base_cache_entry *ent = delta_base_cache + hash;
1427 release_delta_base_cache(ent);
1428 delta_base_cached += base_size;
1429 for (i = 0; delta_base_cached > delta_base_cache_limit
1430 && i < ARRAY_SIZE(delta_base_cache); i++) {
1431 struct delta_base_cache_entry *f = delta_base_cache + i;
1432 if (f->type == OBJ_BLOB)
1433 release_delta_base_cache(f);
1435 for (i = 0; delta_base_cached > delta_base_cache_limit
1436 && i < ARRAY_SIZE(delta_base_cache); i++)
1437 release_delta_base_cache(delta_base_cache + i);
1439 ent->p = p;
1440 ent->base_offset = base_offset;
1441 ent->type = type;
1442 ent->data = base;
1443 ent->size = base_size;
1446 static void *unpack_delta_entry(struct packed_git *p,
1447 struct pack_window **w_curs,
1448 off_t curpos,
1449 unsigned long delta_size,
1450 off_t obj_offset,
1451 enum object_type *type,
1452 unsigned long *sizep)
1454 void *delta_data, *result, *base;
1455 unsigned long base_size;
1456 off_t base_offset;
1458 base_offset = get_delta_base(p, w_curs, &curpos, *type, obj_offset);
1459 base = cache_or_unpack_entry(p, base_offset, &base_size, type, 0);
1460 if (!base)
1461 die("failed to read delta base object"
1462 " at %"PRIuMAX" from %s",
1463 (uintmax_t)base_offset, p->pack_name);
1465 delta_data = unpack_compressed_entry(p, w_curs, curpos, delta_size);
1466 result = patch_delta(base, base_size,
1467 delta_data, delta_size,
1468 sizep);
1469 if (!result)
1470 die("failed to apply delta");
1471 free(delta_data);
1472 add_delta_base_cache(p, base_offset, base, base_size, *type);
1473 return result;
1476 void *unpack_entry(struct packed_git *p, off_t obj_offset,
1477 enum object_type *type, unsigned long *sizep)
1479 struct pack_window *w_curs = NULL;
1480 off_t curpos = obj_offset;
1481 void *data;
1483 *type = unpack_object_header(p, &w_curs, &curpos, sizep);
1484 switch (*type) {
1485 case OBJ_OFS_DELTA:
1486 case OBJ_REF_DELTA:
1487 data = unpack_delta_entry(p, &w_curs, curpos, *sizep,
1488 obj_offset, type, sizep);
1489 break;
1490 case OBJ_COMMIT:
1491 case OBJ_TREE:
1492 case OBJ_BLOB:
1493 case OBJ_TAG:
1494 data = unpack_compressed_entry(p, &w_curs, curpos, *sizep);
1495 break;
1496 default:
1497 die("unknown object type %i in %s", *type, p->pack_name);
1499 unuse_pack(&w_curs);
1500 return data;
1503 uint32_t num_packed_objects(const struct packed_git *p)
1505 /* See check_packed_git_idx() */
1506 return (uint32_t)((p->index_size - 20 - 20 - 4*256) / 24);
1509 int nth_packed_object_sha1(const struct packed_git *p, uint32_t n,
1510 unsigned char* sha1)
1512 const unsigned char *index = p->index_data;
1513 index += 4 * 256;
1514 if (num_packed_objects(p) <= n)
1515 return -1;
1516 hashcpy(sha1, index + 24 * n + 4);
1517 return 0;
1520 off_t find_pack_entry_one(const unsigned char *sha1,
1521 struct packed_git *p)
1523 const uint32_t *level1_ofs = p->index_data;
1524 int hi = ntohl(level1_ofs[*sha1]);
1525 int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1526 const unsigned char *index = p->index_data;
1528 index += 4 * 256;
1530 do {
1531 int mi = (lo + hi) / 2;
1532 int cmp = hashcmp(index + 24 * mi + 4, sha1);
1533 if (!cmp)
1534 return ntohl(*((uint32_t *)((char *)index + (24 * mi))));
1535 if (cmp > 0)
1536 hi = mi;
1537 else
1538 lo = mi+1;
1539 } while (lo < hi);
1540 return 0;
1543 static int matches_pack_name(struct packed_git *p, const char *ig)
1545 const char *last_c, *c;
1547 if (!strcmp(p->pack_name, ig))
1548 return 0;
1550 for (c = p->pack_name, last_c = c; *c;)
1551 if (*c == '/')
1552 last_c = ++c;
1553 else
1554 ++c;
1555 if (!strcmp(last_c, ig))
1556 return 0;
1558 return 1;
1561 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e, const char **ignore_packed)
1563 struct packed_git *p;
1564 off_t offset;
1566 prepare_packed_git();
1568 for (p = packed_git; p; p = p->next) {
1569 if (ignore_packed) {
1570 const char **ig;
1571 for (ig = ignore_packed; *ig; ig++)
1572 if (!matches_pack_name(p, *ig))
1573 break;
1574 if (*ig)
1575 continue;
1577 offset = find_pack_entry_one(sha1, p);
1578 if (offset) {
1580 * We are about to tell the caller where they can
1581 * locate the requested object. We better make
1582 * sure the packfile is still here and can be
1583 * accessed before supplying that answer, as
1584 * it may have been deleted since the index
1585 * was loaded!
1587 if (p->pack_fd == -1 && open_packed_git(p)) {
1588 error("packfile %s cannot be accessed", p->pack_name);
1589 continue;
1591 e->offset = offset;
1592 e->p = p;
1593 hashcpy(e->sha1, sha1);
1594 return 1;
1597 return 0;
1600 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1601 struct packed_git *packs)
1603 struct packed_git *p;
1605 for (p = packs; p; p = p->next) {
1606 if (find_pack_entry_one(sha1, p))
1607 return p;
1609 return NULL;
1613 static int sha1_loose_object_info(const unsigned char *sha1, unsigned long *sizep)
1615 int status;
1616 unsigned long mapsize, size;
1617 void *map;
1618 z_stream stream;
1619 char hdr[32];
1621 map = map_sha1_file(sha1, &mapsize);
1622 if (!map)
1623 return error("unable to find %s", sha1_to_hex(sha1));
1624 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1625 status = error("unable to unpack %s header",
1626 sha1_to_hex(sha1));
1627 else if ((status = parse_sha1_header(hdr, &size)) < 0)
1628 status = error("unable to parse %s header", sha1_to_hex(sha1));
1629 else if (sizep)
1630 *sizep = size;
1631 inflateEnd(&stream);
1632 munmap(map, mapsize);
1633 return status;
1636 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
1638 struct pack_entry e;
1640 if (!find_pack_entry(sha1, &e, NULL)) {
1641 reprepare_packed_git();
1642 if (!find_pack_entry(sha1, &e, NULL))
1643 return sha1_loose_object_info(sha1, sizep);
1645 return packed_object_info(e.p, e.offset, sizep);
1648 static void *read_packed_sha1(const unsigned char *sha1,
1649 enum object_type *type, unsigned long *size)
1651 struct pack_entry e;
1653 if (!find_pack_entry(sha1, &e, NULL))
1654 return NULL;
1655 else
1656 return cache_or_unpack_entry(e.p, e.offset, size, type, 1);
1660 * This is meant to hold a *small* number of objects that you would
1661 * want read_sha1_file() to be able to return, but yet you do not want
1662 * to write them into the object store (e.g. a browse-only
1663 * application).
1665 static struct cached_object {
1666 unsigned char sha1[20];
1667 enum object_type type;
1668 void *buf;
1669 unsigned long size;
1670 } *cached_objects;
1671 static int cached_object_nr, cached_object_alloc;
1673 static struct cached_object *find_cached_object(const unsigned char *sha1)
1675 int i;
1676 struct cached_object *co = cached_objects;
1678 for (i = 0; i < cached_object_nr; i++, co++) {
1679 if (!hashcmp(co->sha1, sha1))
1680 return co;
1682 return NULL;
1685 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
1686 unsigned char *sha1)
1688 struct cached_object *co;
1690 hash_sha1_file(buf, len, typename(type), sha1);
1691 if (has_sha1_file(sha1) || find_cached_object(sha1))
1692 return 0;
1693 if (cached_object_alloc <= cached_object_nr) {
1694 cached_object_alloc = alloc_nr(cached_object_alloc);
1695 cached_objects = xrealloc(cached_objects,
1696 sizeof(*cached_objects) *
1697 cached_object_alloc);
1699 co = &cached_objects[cached_object_nr++];
1700 co->size = len;
1701 co->type = type;
1702 co->buf = xmalloc(len);
1703 memcpy(co->buf, buf, len);
1704 hashcpy(co->sha1, sha1);
1705 return 0;
1708 void *read_sha1_file(const unsigned char *sha1, enum object_type *type,
1709 unsigned long *size)
1711 unsigned long mapsize;
1712 void *map, *buf;
1713 struct cached_object *co;
1715 co = find_cached_object(sha1);
1716 if (co) {
1717 buf = xmalloc(co->size + 1);
1718 memcpy(buf, co->buf, co->size);
1719 ((char*)buf)[co->size] = 0;
1720 *type = co->type;
1721 *size = co->size;
1722 return buf;
1725 buf = read_packed_sha1(sha1, type, size);
1726 if (buf)
1727 return buf;
1728 map = map_sha1_file(sha1, &mapsize);
1729 if (map) {
1730 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
1731 munmap(map, mapsize);
1732 return buf;
1734 reprepare_packed_git();
1735 return read_packed_sha1(sha1, type, size);
1738 void *read_object_with_reference(const unsigned char *sha1,
1739 const char *required_type_name,
1740 unsigned long *size,
1741 unsigned char *actual_sha1_return)
1743 enum object_type type, required_type;
1744 void *buffer;
1745 unsigned long isize;
1746 unsigned char actual_sha1[20];
1748 required_type = type_from_string(required_type_name);
1749 hashcpy(actual_sha1, sha1);
1750 while (1) {
1751 int ref_length = -1;
1752 const char *ref_type = NULL;
1754 buffer = read_sha1_file(actual_sha1, &type, &isize);
1755 if (!buffer)
1756 return NULL;
1757 if (type == required_type) {
1758 *size = isize;
1759 if (actual_sha1_return)
1760 hashcpy(actual_sha1_return, actual_sha1);
1761 return buffer;
1763 /* Handle references */
1764 else if (type == OBJ_COMMIT)
1765 ref_type = "tree ";
1766 else if (type == OBJ_TAG)
1767 ref_type = "object ";
1768 else {
1769 free(buffer);
1770 return NULL;
1772 ref_length = strlen(ref_type);
1774 if (memcmp(buffer, ref_type, ref_length) ||
1775 get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
1776 free(buffer);
1777 return NULL;
1779 free(buffer);
1780 /* Now we have the ID of the referred-to object in
1781 * actual_sha1. Check again. */
1785 static void write_sha1_file_prepare(void *buf, unsigned long len,
1786 const char *type, unsigned char *sha1,
1787 char *hdr, int *hdrlen)
1789 SHA_CTX c;
1791 /* Generate the header */
1792 *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
1794 /* Sha1.. */
1795 SHA1_Init(&c);
1796 SHA1_Update(&c, hdr, *hdrlen);
1797 SHA1_Update(&c, buf, len);
1798 SHA1_Final(sha1, &c);
1802 * Link the tempfile to the final place, possibly creating the
1803 * last directory level as you do so.
1805 * Returns the errno on failure, 0 on success.
1807 static int link_temp_to_file(const char *tmpfile, const char *filename)
1809 int ret;
1810 char *dir;
1812 if (!link(tmpfile, filename))
1813 return 0;
1816 * Try to mkdir the last path component if that failed.
1818 * Re-try the "link()" regardless of whether the mkdir
1819 * succeeds, since a race might mean that somebody
1820 * else succeeded.
1822 ret = errno;
1823 dir = strrchr(filename, '/');
1824 if (dir) {
1825 *dir = 0;
1826 if (!mkdir(filename, 0777) && adjust_shared_perm(filename)) {
1827 *dir = '/';
1828 return -2;
1830 *dir = '/';
1831 if (!link(tmpfile, filename))
1832 return 0;
1833 ret = errno;
1835 return ret;
1839 * Move the just written object into its final resting place
1841 int move_temp_to_file(const char *tmpfile, const char *filename)
1843 int ret = link_temp_to_file(tmpfile, filename);
1846 * Coda hack - coda doesn't like cross-directory links,
1847 * so we fall back to a rename, which will mean that it
1848 * won't be able to check collisions, but that's not a
1849 * big deal.
1851 * The same holds for FAT formatted media.
1853 * When this succeeds, we just return 0. We have nothing
1854 * left to unlink.
1856 if (ret && ret != EEXIST) {
1857 if (!rename(tmpfile, filename))
1858 return 0;
1859 ret = errno;
1861 unlink(tmpfile);
1862 if (ret) {
1863 if (ret != EEXIST) {
1864 return error("unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1866 /* FIXME!!! Collision check here ? */
1869 return 0;
1872 static int write_buffer(int fd, const void *buf, size_t len)
1874 if (write_in_full(fd, buf, len) < 0)
1875 return error("file write error (%s)", strerror(errno));
1876 return 0;
1879 static int write_binary_header(unsigned char *hdr, enum object_type type, unsigned long len)
1881 int hdr_len;
1882 unsigned char c;
1884 c = (type << 4) | (len & 15);
1885 len >>= 4;
1886 hdr_len = 1;
1887 while (len) {
1888 *hdr++ = c | 0x80;
1889 hdr_len++;
1890 c = (len & 0x7f);
1891 len >>= 7;
1893 *hdr = c;
1894 return hdr_len;
1897 static void setup_object_header(z_stream *stream, const char *type, unsigned long len)
1899 int obj_type, hdrlen;
1901 if (use_legacy_headers) {
1902 while (deflate(stream, 0) == Z_OK)
1903 /* nothing */;
1904 return;
1906 obj_type = type_from_string(type);
1907 hdrlen = write_binary_header(stream->next_out, obj_type, len);
1908 stream->total_out = hdrlen;
1909 stream->next_out += hdrlen;
1910 stream->avail_out -= hdrlen;
1913 int hash_sha1_file(void *buf, unsigned long len, const char *type,
1914 unsigned char *sha1)
1916 char hdr[32];
1917 int hdrlen;
1918 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1919 return 0;
1922 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1924 int size;
1925 unsigned char *compressed;
1926 z_stream stream;
1927 unsigned char sha1[20];
1928 char *filename;
1929 static char tmpfile[PATH_MAX];
1930 char hdr[32];
1931 int fd, hdrlen;
1933 /* Normally if we have it in the pack then we do not bother writing
1934 * it out into .git/objects/??/?{38} file.
1936 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1937 filename = sha1_file_name(sha1);
1938 if (returnsha1)
1939 hashcpy(returnsha1, sha1);
1940 if (has_sha1_file(sha1))
1941 return 0;
1942 fd = open(filename, O_RDONLY);
1943 if (fd >= 0) {
1945 * FIXME!!! We might do collision checking here, but we'd
1946 * need to uncompress the old file and check it. Later.
1948 close(fd);
1949 return 0;
1952 if (errno != ENOENT) {
1953 return error("sha1 file %s: %s\n", filename, strerror(errno));
1956 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1958 fd = mkstemp(tmpfile);
1959 if (fd < 0) {
1960 if (errno == EPERM)
1961 return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
1962 else
1963 return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
1966 /* Set it up */
1967 memset(&stream, 0, sizeof(stream));
1968 deflateInit(&stream, zlib_compression_level);
1969 size = 8 + deflateBound(&stream, len+hdrlen);
1970 compressed = xmalloc(size);
1972 /* Compress it */
1973 stream.next_out = compressed;
1974 stream.avail_out = size;
1976 /* First header.. */
1977 stream.next_in = (unsigned char *)hdr;
1978 stream.avail_in = hdrlen;
1979 setup_object_header(&stream, type, len);
1981 /* Then the data itself.. */
1982 stream.next_in = buf;
1983 stream.avail_in = len;
1984 while (deflate(&stream, Z_FINISH) == Z_OK)
1985 /* nothing */;
1986 deflateEnd(&stream);
1987 size = stream.total_out;
1989 if (write_buffer(fd, compressed, size) < 0)
1990 die("unable to write sha1 file");
1991 fchmod(fd, 0444);
1992 close(fd);
1993 free(compressed);
1995 return move_temp_to_file(tmpfile, filename);
1999 * We need to unpack and recompress the object for writing
2000 * it out to a different file.
2002 static void *repack_object(const unsigned char *sha1, unsigned long *objsize)
2004 size_t size;
2005 z_stream stream;
2006 unsigned char *unpacked;
2007 unsigned long len;
2008 enum object_type type;
2009 char hdr[32];
2010 int hdrlen;
2011 void *buf;
2013 /* need to unpack and recompress it by itself */
2014 unpacked = read_packed_sha1(sha1, &type, &len);
2015 if (!unpacked)
2016 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2018 hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
2020 /* Set it up */
2021 memset(&stream, 0, sizeof(stream));
2022 deflateInit(&stream, zlib_compression_level);
2023 size = deflateBound(&stream, len + hdrlen);
2024 buf = xmalloc(size);
2026 /* Compress it */
2027 stream.next_out = buf;
2028 stream.avail_out = size;
2030 /* First header.. */
2031 stream.next_in = (void *)hdr;
2032 stream.avail_in = hdrlen;
2033 while (deflate(&stream, 0) == Z_OK)
2034 /* nothing */;
2036 /* Then the data itself.. */
2037 stream.next_in = unpacked;
2038 stream.avail_in = len;
2039 while (deflate(&stream, Z_FINISH) == Z_OK)
2040 /* nothing */;
2041 deflateEnd(&stream);
2042 free(unpacked);
2044 *objsize = stream.total_out;
2045 return buf;
2048 int write_sha1_to_fd(int fd, const unsigned char *sha1)
2050 int retval;
2051 unsigned long objsize;
2052 void *buf = map_sha1_file(sha1, &objsize);
2054 if (buf) {
2055 retval = write_buffer(fd, buf, objsize);
2056 munmap(buf, objsize);
2057 return retval;
2060 buf = repack_object(sha1, &objsize);
2061 retval = write_buffer(fd, buf, objsize);
2062 free(buf);
2063 return retval;
2066 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
2067 size_t bufsize, size_t *bufposn)
2069 char tmpfile[PATH_MAX];
2070 int local;
2071 z_stream stream;
2072 unsigned char real_sha1[20];
2073 unsigned char discard[4096];
2074 int ret;
2075 SHA_CTX c;
2077 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
2079 local = mkstemp(tmpfile);
2080 if (local < 0) {
2081 if (errno == EPERM)
2082 return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2083 else
2084 return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2087 memset(&stream, 0, sizeof(stream));
2089 inflateInit(&stream);
2091 SHA1_Init(&c);
2093 do {
2094 ssize_t size;
2095 if (*bufposn) {
2096 stream.avail_in = *bufposn;
2097 stream.next_in = (unsigned char *) buffer;
2098 do {
2099 stream.next_out = discard;
2100 stream.avail_out = sizeof(discard);
2101 ret = inflate(&stream, Z_SYNC_FLUSH);
2102 SHA1_Update(&c, discard, sizeof(discard) -
2103 stream.avail_out);
2104 } while (stream.avail_in && ret == Z_OK);
2105 if (write_buffer(local, buffer, *bufposn - stream.avail_in) < 0)
2106 die("unable to write sha1 file");
2107 memmove(buffer, buffer + *bufposn - stream.avail_in,
2108 stream.avail_in);
2109 *bufposn = stream.avail_in;
2110 if (ret != Z_OK)
2111 break;
2113 size = xread(fd, buffer + *bufposn, bufsize - *bufposn);
2114 if (size <= 0) {
2115 close(local);
2116 unlink(tmpfile);
2117 if (!size)
2118 return error("Connection closed?");
2119 perror("Reading from connection");
2120 return -1;
2122 *bufposn += size;
2123 } while (1);
2124 inflateEnd(&stream);
2126 close(local);
2127 SHA1_Final(real_sha1, &c);
2128 if (ret != Z_STREAM_END) {
2129 unlink(tmpfile);
2130 return error("File %s corrupted", sha1_to_hex(sha1));
2132 if (hashcmp(sha1, real_sha1)) {
2133 unlink(tmpfile);
2134 return error("File %s has bad hash", sha1_to_hex(sha1));
2137 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
2140 int has_pack_index(const unsigned char *sha1)
2142 struct stat st;
2143 if (stat(sha1_pack_index_name(sha1), &st))
2144 return 0;
2145 return 1;
2148 int has_pack_file(const unsigned char *sha1)
2150 struct stat st;
2151 if (stat(sha1_pack_name(sha1), &st))
2152 return 0;
2153 return 1;
2156 int has_sha1_pack(const unsigned char *sha1, const char **ignore_packed)
2158 struct pack_entry e;
2159 return find_pack_entry(sha1, &e, ignore_packed);
2162 int has_sha1_file(const unsigned char *sha1)
2164 struct stat st;
2165 struct pack_entry e;
2167 if (find_pack_entry(sha1, &e, NULL))
2168 return 1;
2169 return find_sha1_file(sha1, &st) ? 1 : 0;
2173 * reads from fd as long as possible into a supplied buffer of size bytes.
2174 * If necessary the buffer's size is increased using realloc()
2176 * returns 0 if anything went fine and -1 otherwise
2178 * NOTE: both buf and size may change, but even when -1 is returned
2179 * you still have to free() it yourself.
2181 int read_pipe(int fd, char** return_buf, unsigned long* return_size)
2183 char* buf = *return_buf;
2184 unsigned long size = *return_size;
2185 int iret;
2186 unsigned long off = 0;
2188 do {
2189 iret = xread(fd, buf + off, size - off);
2190 if (iret > 0) {
2191 off += iret;
2192 if (off == size) {
2193 size *= 2;
2194 buf = xrealloc(buf, size);
2197 } while (iret > 0);
2199 *return_buf = buf;
2200 *return_size = off;
2202 if (iret < 0)
2203 return -1;
2204 return 0;
2207 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
2209 unsigned long size = 4096;
2210 char *buf = xmalloc(size);
2211 int ret;
2213 if (read_pipe(fd, &buf, &size)) {
2214 free(buf);
2215 return -1;
2218 if (!type)
2219 type = blob_type;
2220 if (write_object)
2221 ret = write_sha1_file(buf, size, type, sha1);
2222 else
2223 ret = hash_sha1_file(buf, size, type, sha1);
2224 free(buf);
2225 return ret;
2228 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object,
2229 enum object_type type, const char *path)
2231 size_t size = xsize_t(st->st_size);
2232 void *buf = NULL;
2233 int ret, re_allocated = 0;
2235 if (size)
2236 buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2237 close(fd);
2239 if (!type)
2240 type = OBJ_BLOB;
2243 * Convert blobs to git internal format
2245 if ((type == OBJ_BLOB) && S_ISREG(st->st_mode)) {
2246 unsigned long nsize = size;
2247 char *nbuf = buf;
2248 if (convert_to_git(path, &nbuf, &nsize)) {
2249 if (size)
2250 munmap(buf, size);
2251 size = nsize;
2252 buf = nbuf;
2253 re_allocated = 1;
2257 if (write_object)
2258 ret = write_sha1_file(buf, size, typename(type), sha1);
2259 else
2260 ret = hash_sha1_file(buf, size, typename(type), sha1);
2261 if (re_allocated) {
2262 free(buf);
2263 return ret;
2265 if (size)
2266 munmap(buf, size);
2267 return ret;
2270 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
2272 int fd;
2273 char *target;
2274 size_t len;
2276 switch (st->st_mode & S_IFMT) {
2277 case S_IFREG:
2278 fd = open(path, O_RDONLY);
2279 if (fd < 0)
2280 return error("open(\"%s\"): %s", path,
2281 strerror(errno));
2282 if (index_fd(sha1, fd, st, write_object, OBJ_BLOB, path) < 0)
2283 return error("%s: failed to insert into database",
2284 path);
2285 break;
2286 case S_IFLNK:
2287 len = xsize_t(st->st_size);
2288 target = xmalloc(len + 1);
2289 if (readlink(path, target, len + 1) != st->st_size) {
2290 char *errstr = strerror(errno);
2291 free(target);
2292 return error("readlink(\"%s\"): %s", path,
2293 errstr);
2295 if (!write_object)
2296 hash_sha1_file(target, len, blob_type, sha1);
2297 else if (write_sha1_file(target, len, blob_type, sha1))
2298 return error("%s: failed to insert into database",
2299 path);
2300 free(target);
2301 break;
2302 default:
2303 return error("%s: unsupported file type", path);
2305 return 0;
2308 int read_pack_header(int fd, struct pack_header *header)
2310 char *c = (char*)header;
2311 ssize_t remaining = sizeof(struct pack_header);
2312 do {
2313 ssize_t r = xread(fd, c, remaining);
2314 if (r <= 0)
2315 /* "eof before pack header was fully read" */
2316 return PH_ERROR_EOF;
2317 remaining -= r;
2318 c += r;
2319 } while (remaining > 0);
2320 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2321 /* "protocol error (pack signature mismatch detected)" */
2322 return PH_ERROR_PACK_SIGNATURE;
2323 if (!pack_version_ok(header->hdr_version))
2324 /* "protocol error (pack version unsupported)" */
2325 return PH_ERROR_PROTOCOL;
2326 return 0;