Introduce git_etc_gitconfig() that encapsulates access of ETC_GITCONFIG.
[git/mingw.git] / sha1_file.c
blob8b6f88e249711e04029f14b4b71eaca6a15d40f0
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"
16 #include "refs.h"
18 #ifndef O_NOATIME
19 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
20 #define O_NOATIME 01000000
21 #else
22 #define O_NOATIME 0
23 #endif
24 #endif
26 #ifdef NO_C99_FORMAT
27 #define SZ_FMT "lu"
28 #else
29 #define SZ_FMT "zu"
30 #endif
32 const unsigned char null_sha1[20];
34 static unsigned int sha1_file_open_flag = O_NOATIME;
36 const signed char hexval_table[256] = {
37 -1, -1, -1, -1, -1, -1, -1, -1, /* 00-07 */
38 -1, -1, -1, -1, -1, -1, -1, -1, /* 08-0f */
39 -1, -1, -1, -1, -1, -1, -1, -1, /* 10-17 */
40 -1, -1, -1, -1, -1, -1, -1, -1, /* 18-1f */
41 -1, -1, -1, -1, -1, -1, -1, -1, /* 20-27 */
42 -1, -1, -1, -1, -1, -1, -1, -1, /* 28-2f */
43 0, 1, 2, 3, 4, 5, 6, 7, /* 30-37 */
44 8, 9, -1, -1, -1, -1, -1, -1, /* 38-3f */
45 -1, 10, 11, 12, 13, 14, 15, -1, /* 40-47 */
46 -1, -1, -1, -1, -1, -1, -1, -1, /* 48-4f */
47 -1, -1, -1, -1, -1, -1, -1, -1, /* 50-57 */
48 -1, -1, -1, -1, -1, -1, -1, -1, /* 58-5f */
49 -1, 10, 11, 12, 13, 14, 15, -1, /* 60-67 */
50 -1, -1, -1, -1, -1, -1, -1, -1, /* 68-67 */
51 -1, -1, -1, -1, -1, -1, -1, -1, /* 70-77 */
52 -1, -1, -1, -1, -1, -1, -1, -1, /* 78-7f */
53 -1, -1, -1, -1, -1, -1, -1, -1, /* 80-87 */
54 -1, -1, -1, -1, -1, -1, -1, -1, /* 88-8f */
55 -1, -1, -1, -1, -1, -1, -1, -1, /* 90-97 */
56 -1, -1, -1, -1, -1, -1, -1, -1, /* 98-9f */
57 -1, -1, -1, -1, -1, -1, -1, -1, /* a0-a7 */
58 -1, -1, -1, -1, -1, -1, -1, -1, /* a8-af */
59 -1, -1, -1, -1, -1, -1, -1, -1, /* b0-b7 */
60 -1, -1, -1, -1, -1, -1, -1, -1, /* b8-bf */
61 -1, -1, -1, -1, -1, -1, -1, -1, /* c0-c7 */
62 -1, -1, -1, -1, -1, -1, -1, -1, /* c8-cf */
63 -1, -1, -1, -1, -1, -1, -1, -1, /* d0-d7 */
64 -1, -1, -1, -1, -1, -1, -1, -1, /* d8-df */
65 -1, -1, -1, -1, -1, -1, -1, -1, /* e0-e7 */
66 -1, -1, -1, -1, -1, -1, -1, -1, /* e8-ef */
67 -1, -1, -1, -1, -1, -1, -1, -1, /* f0-f7 */
68 -1, -1, -1, -1, -1, -1, -1, -1, /* f8-ff */
71 int get_sha1_hex(const char *hex, unsigned char *sha1)
73 int i;
74 for (i = 0; i < 20; i++) {
75 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
76 if (val & ~0xff)
77 return -1;
78 *sha1++ = val;
79 hex += 2;
81 return 0;
84 /* returns the number of chars to skip to first component */
85 static inline int is_path_absolute(const char *path)
87 #ifdef __MINGW32__
88 if (isalpha(path[0]) && path[1] == ':')
89 return 2 + (path[2] == '/');
90 /* TODO: C:dir/file 'relative' paths are not catered for */
91 #endif
92 return *path == '/';
95 int safe_create_leading_directories(char *path)
97 char *pos = path + is_path_absolute(path);
98 struct stat st;
100 while (pos) {
101 pos = strchr(pos, '/');
102 if (!pos)
103 break;
104 *pos = 0;
105 if (!stat(path, &st)) {
106 /* path exists */
107 if (!S_ISDIR(st.st_mode)) {
108 *pos = '/';
109 return -3;
112 else if (mkdir(path, 0777)) {
113 *pos = '/';
114 return -1;
116 else if (adjust_shared_perm(path)) {
117 *pos = '/';
118 return -2;
120 *pos++ = '/';
122 return 0;
125 char * sha1_to_hex(const unsigned char *sha1)
127 static int bufno;
128 static char hexbuffer[4][50];
129 static const char hex[] = "0123456789abcdef";
130 char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
131 int i;
133 for (i = 0; i < 20; i++) {
134 unsigned int val = *sha1++;
135 *buf++ = hex[val >> 4];
136 *buf++ = hex[val & 0xf];
138 *buf = '\0';
140 return buffer;
143 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
145 int i;
146 for (i = 0; i < 20; i++) {
147 static char hex[] = "0123456789abcdef";
148 unsigned int val = sha1[i];
149 char *pos = pathbuf + i*2 + (i > 0);
150 *pos++ = hex[val >> 4];
151 *pos = hex[val & 0xf];
156 * NOTE! This returns a statically allocated buffer, so you have to be
157 * careful about using it. Do a "xstrdup()" if you need to save the
158 * filename.
160 * Also note that this returns the location for creating. Reading
161 * SHA1 file can happen from any alternate directory listed in the
162 * DB_ENVIRONMENT environment variable if it is not found in
163 * the primary object database.
165 char *sha1_file_name(const unsigned char *sha1)
167 static char *name, *base;
169 if (!base) {
170 const char *sha1_file_directory = get_object_directory();
171 int len = strlen(sha1_file_directory);
172 base = xmalloc(len + 60);
173 memcpy(base, sha1_file_directory, len);
174 memset(base+len, 0, 60);
175 base[len] = '/';
176 base[len+3] = '/';
177 name = base + len + 1;
179 fill_sha1_path(name, sha1);
180 return base;
183 char *sha1_pack_name(const unsigned char *sha1)
185 static const char hex[] = "0123456789abcdef";
186 static char *name, *base, *buf;
187 int i;
189 if (!base) {
190 const char *sha1_file_directory = get_object_directory();
191 int len = strlen(sha1_file_directory);
192 base = xmalloc(len + 60);
193 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
194 name = base + len + 11;
197 buf = name;
199 for (i = 0; i < 20; i++) {
200 unsigned int val = *sha1++;
201 *buf++ = hex[val >> 4];
202 *buf++ = hex[val & 0xf];
205 return base;
208 char *sha1_pack_index_name(const unsigned char *sha1)
210 static const char hex[] = "0123456789abcdef";
211 static char *name, *base, *buf;
212 int i;
214 if (!base) {
215 const char *sha1_file_directory = get_object_directory();
216 int len = strlen(sha1_file_directory);
217 base = xmalloc(len + 60);
218 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
219 name = base + len + 11;
222 buf = name;
224 for (i = 0; i < 20; i++) {
225 unsigned int val = *sha1++;
226 *buf++ = hex[val >> 4];
227 *buf++ = hex[val & 0xf];
230 return base;
233 struct alternate_object_database *alt_odb_list;
234 static struct alternate_object_database **alt_odb_tail;
236 static void read_info_alternates(const char * alternates, int depth);
239 * Prepare alternate object database registry.
241 * The variable alt_odb_list points at the list of struct
242 * alternate_object_database. The elements on this list come from
243 * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
244 * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
245 * whose contents is similar to that environment variable but can be
246 * LF separated. Its base points at a statically allocated buffer that
247 * contains "/the/directory/corresponding/to/.git/objects/...", while
248 * its name points just after the slash at the end of ".git/objects/"
249 * in the example above, and has enough space to hold 40-byte hex
250 * SHA1, an extra slash for the first level indirection, and the
251 * terminating NUL.
253 static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
255 struct stat st;
256 const char *objdir = get_object_directory();
257 struct alternate_object_database *ent;
258 struct alternate_object_database *alt;
259 /* 43 = 40-byte + 2 '/' + terminating NUL */
260 int pfxlen = len;
261 int entlen = pfxlen + 43;
262 int base_len = -1;
264 if (!is_path_absolute(entry) && relative_base) {
265 /* Relative alt-odb */
266 if (base_len < 0)
267 base_len = strlen(relative_base) + 1;
268 entlen += base_len;
269 pfxlen += base_len;
271 ent = xmalloc(sizeof(*ent) + entlen);
273 if (!is_path_absolute(entry) && relative_base) {
274 memcpy(ent->base, relative_base, base_len - 1);
275 ent->base[base_len - 1] = '/';
276 memcpy(ent->base + base_len, entry, len);
278 else
279 memcpy(ent->base, entry, pfxlen);
281 ent->name = ent->base + pfxlen + 1;
282 ent->base[pfxlen + 3] = '/';
283 ent->base[pfxlen] = ent->base[entlen-1] = 0;
285 /* Detect cases where alternate disappeared */
286 if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
287 error("object directory %s does not exist; "
288 "check .git/objects/info/alternates.",
289 ent->base);
290 free(ent);
291 return -1;
294 /* Prevent the common mistake of listing the same
295 * thing twice, or object directory itself.
297 for (alt = alt_odb_list; alt; alt = alt->next) {
298 if (!memcmp(ent->base, alt->base, pfxlen)) {
299 free(ent);
300 return -1;
303 if (!memcmp(ent->base, objdir, pfxlen)) {
304 free(ent);
305 return -1;
308 /* add the alternate entry */
309 *alt_odb_tail = ent;
310 alt_odb_tail = &(ent->next);
311 ent->next = NULL;
313 /* recursively add alternates */
314 read_info_alternates(ent->base, depth + 1);
316 ent->base[pfxlen] = '/';
318 return 0;
321 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
322 const char *relative_base, int depth)
324 const char *cp, *last;
326 if (depth > 5) {
327 error("%s: ignoring alternate object stores, nesting too deep.",
328 relative_base);
329 return;
332 last = alt;
333 while (last < ep) {
334 cp = last;
335 if (cp < ep && *cp == '#') {
336 while (cp < ep && *cp != sep)
337 cp++;
338 last = cp + 1;
339 continue;
341 while (cp < ep && *cp != sep)
342 cp++;
343 if (last != cp) {
344 if (!is_path_absolute(last) && depth) {
345 error("%s: ignoring relative alternate object store %s",
346 relative_base, last);
347 } else {
348 link_alt_odb_entry(last, cp - last,
349 relative_base, depth);
352 while (cp < ep && *cp == sep)
353 cp++;
354 last = cp;
358 static void read_info_alternates(const char * relative_base, int depth)
360 char *map;
361 size_t mapsz;
362 struct stat st;
363 char path[PATH_MAX];
364 int fd;
366 sprintf(path, "%s/info/alternates", relative_base);
367 fd = open(path, O_RDONLY);
368 if (fd < 0)
369 return;
370 if (fstat(fd, &st) || (st.st_size == 0)) {
371 close(fd);
372 return;
374 mapsz = xsize_t(st.st_size);
375 map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
376 close(fd);
378 link_alt_odb_entries(map, map + mapsz, '\n', relative_base, depth);
380 munmap(map, mapsz);
383 void prepare_alt_odb(void)
385 const char *alt;
387 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
388 if (!alt) alt = "";
390 if (alt_odb_tail)
391 return;
392 alt_odb_tail = &alt_odb_list;
393 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL, 0);
395 read_info_alternates(get_object_directory(), 0);
398 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
400 char *name = sha1_file_name(sha1);
401 struct alternate_object_database *alt;
403 if (!stat(name, st))
404 return name;
405 prepare_alt_odb();
406 for (alt = alt_odb_list; alt; alt = alt->next) {
407 name = alt->name;
408 fill_sha1_path(name, sha1);
409 if (!stat(alt->base, st))
410 return alt->base;
412 return NULL;
415 static unsigned int pack_used_ctr;
416 static unsigned int pack_mmap_calls;
417 static unsigned int peak_pack_open_windows;
418 static unsigned int pack_open_windows;
419 static size_t peak_pack_mapped;
420 static size_t pack_mapped;
421 struct packed_git *packed_git;
423 void pack_report()
425 fprintf(stderr,
426 "pack_report: getpagesize() = %10" SZ_FMT "\n"
427 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
428 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
429 (size_t) getpagesize(),
430 packed_git_window_size,
431 packed_git_limit);
432 fprintf(stderr,
433 "pack_report: pack_used_ctr = %10u\n"
434 "pack_report: pack_mmap_calls = %10u\n"
435 "pack_report: pack_open_windows = %10u / %10u\n"
436 "pack_report: pack_mapped = "
437 "%10" SZ_FMT " / %10" SZ_FMT "\n",
438 pack_used_ctr,
439 pack_mmap_calls,
440 pack_open_windows, peak_pack_open_windows,
441 pack_mapped, peak_pack_mapped);
444 static int check_packed_git_idx(const char *path, struct packed_git *p)
446 void *idx_map;
447 struct pack_idx_header *hdr;
448 size_t idx_size;
449 uint32_t version, nr, i, *index;
450 int fd = open(path, O_RDONLY);
451 struct stat st;
453 if (fd < 0)
454 return -1;
455 if (fstat(fd, &st)) {
456 close(fd);
457 return -1;
459 idx_size = xsize_t(st.st_size);
460 if (idx_size < 4 * 256 + 20 + 20) {
461 close(fd);
462 return error("index file %s is too small", path);
464 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
465 close(fd);
467 hdr = idx_map;
468 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
469 version = ntohl(hdr->idx_version);
470 if (version < 2 || version > 2) {
471 munmap(idx_map, idx_size);
472 return error("index file %s is version %d"
473 " and is not supported by this binary"
474 " (try upgrading GIT to a newer version)",
475 path, version);
477 } else
478 version = 1;
480 nr = 0;
481 index = idx_map;
482 if (version > 1)
483 index += 2; /* skip index header */
484 for (i = 0; i < 256; i++) {
485 uint32_t n = ntohl(index[i]);
486 if (n < nr) {
487 munmap(idx_map, idx_size);
488 return error("non-monotonic index %s", path);
490 nr = n;
493 if (version == 1) {
495 * Total size:
496 * - 256 index entries 4 bytes each
497 * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
498 * - 20-byte SHA1 of the packfile
499 * - 20-byte SHA1 file checksum
501 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
502 munmap(idx_map, idx_size);
503 return error("wrong index file size in %s", path);
505 } else if (version == 2) {
507 * Minimum size:
508 * - 8 bytes of header
509 * - 256 index entries 4 bytes each
510 * - 20-byte sha1 entry * nr
511 * - 4-byte crc entry * nr
512 * - 4-byte offset entry * nr
513 * - 20-byte SHA1 of the packfile
514 * - 20-byte SHA1 file checksum
515 * And after the 4-byte offset table might be a
516 * variable sized table containing 8-byte entries
517 * for offsets larger than 2^31.
519 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
520 if (idx_size < min_size || idx_size > min_size + (nr - 1)*8) {
521 munmap(idx_map, idx_size);
522 return error("wrong index file size in %s", path);
524 if (idx_size != min_size) {
525 /* make sure we can deal with large pack offsets */
526 off_t x = 0x7fffffffUL, y = 0xffffffffUL;
527 if (x > (x + 1) || y > (y + 1)) {
528 munmap(idx_map, idx_size);
529 return error("pack too large for current definition of off_t in %s", path);
534 p->index_version = version;
535 p->index_data = idx_map;
536 p->index_size = idx_size;
537 p->num_objects = nr;
538 return 0;
541 static void scan_windows(struct packed_git *p,
542 struct packed_git **lru_p,
543 struct pack_window **lru_w,
544 struct pack_window **lru_l)
546 struct pack_window *w, *w_l;
548 for (w_l = NULL, w = p->windows; w; w = w->next) {
549 if (!w->inuse_cnt) {
550 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
551 *lru_p = p;
552 *lru_w = w;
553 *lru_l = w_l;
556 w_l = w;
560 static int unuse_one_window(struct packed_git *current, int keep_fd)
562 struct packed_git *p, *lru_p = NULL;
563 struct pack_window *lru_w = NULL, *lru_l = NULL;
565 if (current)
566 scan_windows(current, &lru_p, &lru_w, &lru_l);
567 for (p = packed_git; p; p = p->next)
568 scan_windows(p, &lru_p, &lru_w, &lru_l);
569 if (lru_p) {
570 munmap(lru_w->base, lru_w->len);
571 pack_mapped -= lru_w->len;
572 if (lru_l)
573 lru_l->next = lru_w->next;
574 else {
575 lru_p->windows = lru_w->next;
576 if (!lru_p->windows && lru_p->pack_fd != keep_fd) {
577 close(lru_p->pack_fd);
578 lru_p->pack_fd = -1;
581 free(lru_w);
582 pack_open_windows--;
583 return 1;
585 return 0;
588 void release_pack_memory(size_t need, int fd)
590 size_t cur = pack_mapped;
591 while (need >= (cur - pack_mapped) && unuse_one_window(NULL, fd))
592 ; /* nothing */
595 void unuse_pack(struct pack_window **w_cursor)
597 struct pack_window *w = *w_cursor;
598 if (w) {
599 w->inuse_cnt--;
600 *w_cursor = NULL;
605 * Do not call this directly as this leaks p->pack_fd on error return;
606 * call open_packed_git() instead.
608 static int open_packed_git_1(struct packed_git *p)
610 struct stat st;
611 struct pack_header hdr;
612 unsigned char sha1[20];
613 unsigned char *idx_sha1;
614 long fd_flag;
616 p->pack_fd = open(p->pack_name, O_RDONLY);
617 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
618 return -1;
620 /* If we created the struct before we had the pack we lack size. */
621 if (!p->pack_size) {
622 if (!S_ISREG(st.st_mode))
623 return error("packfile %s not a regular file", p->pack_name);
624 p->pack_size = st.st_size;
625 } else if (p->pack_size != st.st_size)
626 return error("packfile %s size changed", p->pack_name);
628 #ifndef __MINGW32__
629 /* We leave these file descriptors open with sliding mmap;
630 * there is no point keeping them open across exec(), though.
632 fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
633 if (fd_flag < 0)
634 return error("cannot determine file descriptor flags");
635 fd_flag |= FD_CLOEXEC;
636 if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
637 return error("cannot set FD_CLOEXEC");
638 #endif
640 /* Verify we recognize this pack file format. */
641 if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
642 return error("file %s is far too short to be a packfile", p->pack_name);
643 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
644 return error("file %s is not a GIT packfile", p->pack_name);
645 if (!pack_version_ok(hdr.hdr_version))
646 return error("packfile %s is version %u and not supported"
647 " (try upgrading GIT to a newer version)",
648 p->pack_name, ntohl(hdr.hdr_version));
650 /* Verify the pack matches its index. */
651 if (p->num_objects != ntohl(hdr.hdr_entries))
652 return error("packfile %s claims to have %u objects"
653 " while index indicates %u objects",
654 p->pack_name, ntohl(hdr.hdr_entries),
655 p->num_objects);
656 if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
657 return error("end of packfile %s is unavailable", p->pack_name);
658 if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
659 return error("packfile %s signature is unavailable", p->pack_name);
660 idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
661 if (hashcmp(sha1, idx_sha1))
662 return error("packfile %s does not match index", p->pack_name);
663 return 0;
666 static int open_packed_git(struct packed_git *p)
668 if (!open_packed_git_1(p))
669 return 0;
670 if (p->pack_fd != -1) {
671 close(p->pack_fd);
672 p->pack_fd = -1;
674 return -1;
677 static int in_window(struct pack_window *win, off_t offset)
679 /* We must promise at least 20 bytes (one hash) after the
680 * offset is available from this window, otherwise the offset
681 * is not actually in this window and a different window (which
682 * has that one hash excess) must be used. This is to support
683 * the object header and delta base parsing routines below.
685 off_t win_off = win->offset;
686 return win_off <= offset
687 && (offset + 20) <= (win_off + win->len);
690 unsigned char* use_pack(struct packed_git *p,
691 struct pack_window **w_cursor,
692 off_t offset,
693 unsigned int *left)
695 struct pack_window *win = *w_cursor;
697 if (p->pack_fd == -1 && open_packed_git(p))
698 die("packfile %s cannot be accessed", p->pack_name);
700 /* Since packfiles end in a hash of their content and its
701 * pointless to ask for an offset into the middle of that
702 * hash, and the in_window function above wouldn't match
703 * don't allow an offset too close to the end of the file.
705 if (offset > (p->pack_size - 20))
706 die("offset beyond end of packfile (truncated pack?)");
708 if (!win || !in_window(win, offset)) {
709 if (win)
710 win->inuse_cnt--;
711 for (win = p->windows; win; win = win->next) {
712 if (in_window(win, offset))
713 break;
715 if (!win) {
716 size_t window_align = packed_git_window_size / 2;
717 off_t len;
718 win = xcalloc(1, sizeof(*win));
719 win->offset = (offset / window_align) * window_align;
720 len = p->pack_size - win->offset;
721 if (len > packed_git_window_size)
722 len = packed_git_window_size;
723 win->len = (size_t)len;
724 pack_mapped += win->len;
725 while (packed_git_limit < pack_mapped
726 && unuse_one_window(p, p->pack_fd))
727 ; /* nothing */
728 win->base = xmmap(NULL, win->len,
729 PROT_READ, MAP_PRIVATE,
730 p->pack_fd, win->offset);
731 if (win->base == MAP_FAILED)
732 die("packfile %s cannot be mapped: %s",
733 p->pack_name,
734 strerror(errno));
735 pack_mmap_calls++;
736 pack_open_windows++;
737 if (pack_mapped > peak_pack_mapped)
738 peak_pack_mapped = pack_mapped;
739 if (pack_open_windows > peak_pack_open_windows)
740 peak_pack_open_windows = pack_open_windows;
741 win->next = p->windows;
742 p->windows = win;
745 if (win != *w_cursor) {
746 win->last_used = pack_used_ctr++;
747 win->inuse_cnt++;
748 *w_cursor = win;
750 offset -= win->offset;
751 if (left)
752 *left = win->len - xsize_t(offset);
753 return win->base + offset;
756 struct packed_git *add_packed_git(const char *path, int path_len, int local)
758 struct stat st;
759 struct packed_git *p = xmalloc(sizeof(*p) + path_len + 2);
762 * Make sure a corresponding .pack file exists and that
763 * the index looks sane.
765 path_len -= strlen(".idx");
766 if (path_len < 1)
767 return NULL;
768 memcpy(p->pack_name, path, path_len);
769 strcpy(p->pack_name + path_len, ".pack");
770 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode) ||
771 check_packed_git_idx(path, p)) {
772 free(p);
773 return NULL;
776 /* ok, it looks sane as far as we can check without
777 * actually mapping the pack file.
779 p->pack_size = st.st_size;
780 p->next = NULL;
781 p->windows = NULL;
782 p->pack_fd = -1;
783 p->pack_local = local;
784 p->mtime = st.st_mtime;
785 if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
786 hashclr(p->sha1);
787 return p;
790 struct packed_git *parse_pack_index(unsigned char *sha1)
792 char *path = sha1_pack_index_name(sha1);
793 return parse_pack_index_file(sha1, path);
796 struct packed_git *parse_pack_index_file(const unsigned char *sha1,
797 const char *idx_path)
799 const char *path = sha1_pack_name(sha1);
800 struct packed_git *p = xmalloc(sizeof(*p) + strlen(path) + 2);
802 if (check_packed_git_idx(idx_path, p)) {
803 free(p);
804 return NULL;
807 strcpy(p->pack_name, path);
808 p->pack_size = 0;
809 p->next = NULL;
810 p->windows = NULL;
811 p->pack_fd = -1;
812 hashcpy(p->sha1, sha1);
813 return p;
816 void install_packed_git(struct packed_git *pack)
818 pack->next = packed_git;
819 packed_git = pack;
822 static void prepare_packed_git_one(char *objdir, int local)
824 char path[PATH_MAX];
825 int len;
826 DIR *dir;
827 struct dirent *de;
829 sprintf(path, "%s/pack", objdir);
830 len = strlen(path);
831 dir = opendir(path);
832 if (!dir) {
833 if (errno != ENOENT)
834 error("unable to open object pack directory: %s: %s",
835 path, strerror(errno));
836 return;
838 path[len++] = '/';
839 while ((de = readdir(dir)) != NULL) {
840 int namelen = strlen(de->d_name);
841 struct packed_git *p;
843 if (!has_extension(de->d_name, ".idx"))
844 continue;
846 /* Don't reopen a pack we already have. */
847 strcpy(path + len, de->d_name);
848 for (p = packed_git; p; p = p->next) {
849 if (!memcmp(path, p->pack_name, len + namelen - 4))
850 break;
852 if (p)
853 continue;
854 /* See if it really is a valid .idx file with corresponding
855 * .pack file that we can map.
857 p = add_packed_git(path, len + namelen, local);
858 if (!p)
859 continue;
860 install_packed_git(p);
862 closedir(dir);
865 static int sort_pack(const void *a_, const void *b_)
867 struct packed_git *a = *((struct packed_git **)a_);
868 struct packed_git *b = *((struct packed_git **)b_);
869 int st;
872 * Local packs tend to contain objects specific to our
873 * variant of the project than remote ones. In addition,
874 * remote ones could be on a network mounted filesystem.
875 * Favor local ones for these reasons.
877 st = a->pack_local - b->pack_local;
878 if (st)
879 return -st;
882 * Younger packs tend to contain more recent objects,
883 * and more recent objects tend to get accessed more
884 * often.
886 if (a->mtime < b->mtime)
887 return 1;
888 else if (a->mtime == b->mtime)
889 return 0;
890 return -1;
893 static void rearrange_packed_git(void)
895 struct packed_git **ary, *p;
896 int i, n;
898 for (n = 0, p = packed_git; p; p = p->next)
899 n++;
900 if (n < 2)
901 return;
903 /* prepare an array of packed_git for easier sorting */
904 ary = xcalloc(n, sizeof(struct packed_git *));
905 for (n = 0, p = packed_git; p; p = p->next)
906 ary[n++] = p;
908 qsort(ary, n, sizeof(struct packed_git *), sort_pack);
910 /* link them back again */
911 for (i = 0; i < n - 1; i++)
912 ary[i]->next = ary[i + 1];
913 ary[n - 1]->next = NULL;
914 packed_git = ary[0];
916 free(ary);
919 static int prepare_packed_git_run_once = 0;
920 void prepare_packed_git(void)
922 struct alternate_object_database *alt;
924 if (prepare_packed_git_run_once)
925 return;
926 prepare_packed_git_one(get_object_directory(), 1);
927 prepare_alt_odb();
928 for (alt = alt_odb_list; alt; alt = alt->next) {
929 alt->name[-1] = 0;
930 prepare_packed_git_one(alt->base, 0);
931 alt->name[-1] = '/';
933 rearrange_packed_git();
934 prepare_packed_git_run_once = 1;
937 void reprepare_packed_git(void)
939 prepare_packed_git_run_once = 0;
940 prepare_packed_git();
943 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
945 unsigned char real_sha1[20];
946 hash_sha1_file(map, size, type, real_sha1);
947 return hashcmp(sha1, real_sha1) ? -1 : 0;
950 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
952 struct stat st;
953 void *map;
954 int fd;
955 char *filename = find_sha1_file(sha1, &st);
957 if (!filename) {
958 return NULL;
961 fd = open(filename, O_RDONLY | sha1_file_open_flag);
962 if (fd < 0) {
963 /* See if it works without O_NOATIME */
964 switch (sha1_file_open_flag) {
965 default:
966 fd = open(filename, O_RDONLY);
967 if (fd >= 0)
968 break;
969 /* Fallthrough */
970 case 0:
971 return NULL;
974 /* If it failed once, it will probably fail again.
975 * Stop using O_NOATIME
977 sha1_file_open_flag = 0;
979 *size = xsize_t(st.st_size);
980 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
981 close(fd);
982 return map;
985 int legacy_loose_object(unsigned char *map)
987 unsigned int word;
990 * Is it a zlib-compressed buffer? If so, the first byte
991 * must be 0x78 (15-bit window size, deflated), and the
992 * first 16-bit word is evenly divisible by 31
994 word = (map[0] << 8) + map[1];
995 if (map[0] == 0x78 && !(word % 31))
996 return 1;
997 else
998 return 0;
1001 unsigned long unpack_object_header_gently(const unsigned char *buf, unsigned long len, enum object_type *type, unsigned long *sizep)
1003 unsigned shift;
1004 unsigned char c;
1005 unsigned long size;
1006 unsigned long used = 0;
1008 c = buf[used++];
1009 *type = (c >> 4) & 7;
1010 size = c & 15;
1011 shift = 4;
1012 while (c & 0x80) {
1013 if (len <= used)
1014 return 0;
1015 if (sizeof(long) * 8 <= shift)
1016 return 0;
1017 c = buf[used++];
1018 size += (c & 0x7f) << shift;
1019 shift += 7;
1021 *sizep = size;
1022 return used;
1025 static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1027 unsigned long size, used;
1028 static const char valid_loose_object_type[8] = {
1029 0, /* OBJ_EXT */
1030 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1031 0, /* "delta" and others are invalid in a loose object */
1033 enum object_type type;
1035 /* Get the data stream */
1036 memset(stream, 0, sizeof(*stream));
1037 stream->next_in = map;
1038 stream->avail_in = mapsize;
1039 stream->next_out = buffer;
1040 stream->avail_out = bufsiz;
1042 if (legacy_loose_object(map)) {
1043 inflateInit(stream);
1044 return inflate(stream, 0);
1047 used = unpack_object_header_gently(map, mapsize, &type, &size);
1048 if (!used || !valid_loose_object_type[type])
1049 return -1;
1050 map += used;
1051 mapsize -= used;
1053 /* Set up the stream for the rest.. */
1054 stream->next_in = map;
1055 stream->avail_in = mapsize;
1056 inflateInit(stream);
1058 /* And generate the fake traditional header */
1059 stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1060 typename(type), size);
1061 return 0;
1064 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1066 int bytes = strlen(buffer) + 1;
1067 unsigned char *buf = xmalloc(1+size);
1068 unsigned long n;
1069 int status = Z_OK;
1071 n = stream->total_out - bytes;
1072 if (n > size)
1073 n = size;
1074 memcpy(buf, (char *) buffer + bytes, n);
1075 bytes = n;
1076 if (bytes <= size) {
1078 * The above condition must be (bytes <= size), not
1079 * (bytes < size). In other words, even though we
1080 * expect no more output and set avail_out to zer0,
1081 * the input zlib stream may have bytes that express
1082 * "this concludes the stream", and we *do* want to
1083 * eat that input.
1085 * Otherwise we would not be able to test that we
1086 * consumed all the input to reach the expected size;
1087 * we also want to check that zlib tells us that all
1088 * went well with status == Z_STREAM_END at the end.
1090 stream->next_out = buf + bytes;
1091 stream->avail_out = size - bytes;
1092 while (status == Z_OK)
1093 status = inflate(stream, Z_FINISH);
1095 buf[size] = 0;
1096 if (status == Z_STREAM_END && !stream->avail_in) {
1097 inflateEnd(stream);
1098 return buf;
1101 if (status < 0)
1102 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1103 else if (stream->avail_in)
1104 error("garbage at end of loose object '%s'",
1105 sha1_to_hex(sha1));
1106 free(buf);
1107 return NULL;
1111 * We used to just use "sscanf()", but that's actually way
1112 * too permissive for what we want to check. So do an anal
1113 * object header parse by hand.
1115 static int parse_sha1_header(const char *hdr, unsigned long *sizep)
1117 char type[10];
1118 int i;
1119 unsigned long size;
1122 * The type can be at most ten bytes (including the
1123 * terminating '\0' that we add), and is followed by
1124 * a space.
1126 i = 0;
1127 for (;;) {
1128 char c = *hdr++;
1129 if (c == ' ')
1130 break;
1131 type[i++] = c;
1132 if (i >= sizeof(type))
1133 return -1;
1135 type[i] = 0;
1138 * The length must follow immediately, and be in canonical
1139 * decimal format (ie "010" is not valid).
1141 size = *hdr++ - '0';
1142 if (size > 9)
1143 return -1;
1144 if (size) {
1145 for (;;) {
1146 unsigned long c = *hdr - '0';
1147 if (c > 9)
1148 break;
1149 hdr++;
1150 size = size * 10 + c;
1153 *sizep = size;
1156 * The length must be followed by a zero byte
1158 return *hdr ? -1 : type_from_string(type);
1161 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1163 int ret;
1164 z_stream stream;
1165 char hdr[8192];
1167 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1168 if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1169 return NULL;
1171 return unpack_sha1_rest(&stream, hdr, *size, sha1);
1174 unsigned long get_size_from_delta(struct packed_git *p,
1175 struct pack_window **w_curs,
1176 off_t curpos)
1178 const unsigned char *data;
1179 unsigned char delta_head[20], *in;
1180 z_stream stream;
1181 int st;
1183 memset(&stream, 0, sizeof(stream));
1184 stream.next_out = delta_head;
1185 stream.avail_out = sizeof(delta_head);
1187 inflateInit(&stream);
1188 do {
1189 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1190 stream.next_in = in;
1191 st = inflate(&stream, Z_FINISH);
1192 curpos += stream.next_in - in;
1193 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1194 stream.total_out < sizeof(delta_head));
1195 inflateEnd(&stream);
1196 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head))
1197 die("delta data unpack-initial failed");
1199 /* Examine the initial part of the delta to figure out
1200 * the result size.
1202 data = delta_head;
1204 /* ignore base size */
1205 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1207 /* Read the result size */
1208 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1211 static off_t get_delta_base(struct packed_git *p,
1212 struct pack_window **w_curs,
1213 off_t *curpos,
1214 enum object_type type,
1215 off_t delta_obj_offset)
1217 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1218 off_t base_offset;
1220 /* use_pack() assured us we have [base_info, base_info + 20)
1221 * as a range that we can look at without walking off the
1222 * end of the mapped window. Its actually the hash size
1223 * that is assured. An OFS_DELTA longer than the hash size
1224 * is stupid, as then a REF_DELTA would be smaller to store.
1226 if (type == OBJ_OFS_DELTA) {
1227 unsigned used = 0;
1228 unsigned char c = base_info[used++];
1229 base_offset = c & 127;
1230 while (c & 128) {
1231 base_offset += 1;
1232 if (!base_offset || MSB(base_offset, 7))
1233 die("offset value overflow for delta base object");
1234 c = base_info[used++];
1235 base_offset = (base_offset << 7) + (c & 127);
1237 base_offset = delta_obj_offset - base_offset;
1238 if (base_offset >= delta_obj_offset)
1239 die("delta base offset out of bound");
1240 *curpos += used;
1241 } else if (type == OBJ_REF_DELTA) {
1242 /* The base entry _must_ be in the same pack */
1243 base_offset = find_pack_entry_one(base_info, p);
1244 if (!base_offset)
1245 die("failed to find delta-pack base object %s",
1246 sha1_to_hex(base_info));
1247 *curpos += 20;
1248 } else
1249 die("I am totally screwed");
1250 return base_offset;
1253 /* forward declaration for a mutually recursive function */
1254 static int packed_object_info(struct packed_git *p, off_t offset,
1255 unsigned long *sizep);
1257 static int packed_delta_info(struct packed_git *p,
1258 struct pack_window **w_curs,
1259 off_t curpos,
1260 enum object_type type,
1261 off_t obj_offset,
1262 unsigned long *sizep)
1264 off_t base_offset;
1266 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1267 type = packed_object_info(p, base_offset, NULL);
1269 /* We choose to only get the type of the base object and
1270 * ignore potentially corrupt pack file that expects the delta
1271 * based on a base with a wrong size. This saves tons of
1272 * inflate() calls.
1274 if (sizep)
1275 *sizep = get_size_from_delta(p, w_curs, curpos);
1277 return type;
1280 static int unpack_object_header(struct packed_git *p,
1281 struct pack_window **w_curs,
1282 off_t *curpos,
1283 unsigned long *sizep)
1285 unsigned char *base;
1286 unsigned int left;
1287 unsigned long used;
1288 enum object_type type;
1290 /* use_pack() assures us we have [base, base + 20) available
1291 * as a range that we can look at at. (Its actually the hash
1292 * size that is assured.) With our object header encoding
1293 * the maximum deflated object size is 2^137, which is just
1294 * insane, so we know won't exceed what we have been given.
1296 base = use_pack(p, w_curs, *curpos, &left);
1297 used = unpack_object_header_gently(base, left, &type, sizep);
1298 if (!used)
1299 die("object offset outside of pack file");
1300 *curpos += used;
1302 return type;
1305 const char *packed_object_info_detail(struct packed_git *p,
1306 off_t obj_offset,
1307 unsigned long *size,
1308 unsigned long *store_size,
1309 unsigned int *delta_chain_length,
1310 unsigned char *base_sha1)
1312 struct pack_window *w_curs = NULL;
1313 off_t curpos;
1314 unsigned long dummy;
1315 unsigned char *next_sha1;
1316 enum object_type type;
1318 *delta_chain_length = 0;
1319 curpos = obj_offset;
1320 type = unpack_object_header(p, &w_curs, &curpos, size);
1322 for (;;) {
1323 switch (type) {
1324 default:
1325 die("pack %s contains unknown object type %d",
1326 p->pack_name, type);
1327 case OBJ_COMMIT:
1328 case OBJ_TREE:
1329 case OBJ_BLOB:
1330 case OBJ_TAG:
1331 *store_size = 0; /* notyet */
1332 unuse_pack(&w_curs);
1333 return typename(type);
1334 case OBJ_OFS_DELTA:
1335 obj_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1336 if (*delta_chain_length == 0) {
1337 /* TODO: find base_sha1 as pointed by curpos */
1338 hashclr(base_sha1);
1340 break;
1341 case OBJ_REF_DELTA:
1342 next_sha1 = use_pack(p, &w_curs, curpos, NULL);
1343 if (*delta_chain_length == 0)
1344 hashcpy(base_sha1, next_sha1);
1345 obj_offset = find_pack_entry_one(next_sha1, p);
1346 break;
1348 (*delta_chain_length)++;
1349 curpos = obj_offset;
1350 type = unpack_object_header(p, &w_curs, &curpos, &dummy);
1354 static int packed_object_info(struct packed_git *p, off_t obj_offset,
1355 unsigned long *sizep)
1357 struct pack_window *w_curs = NULL;
1358 unsigned long size;
1359 off_t curpos = obj_offset;
1360 enum object_type type;
1362 type = unpack_object_header(p, &w_curs, &curpos, &size);
1364 switch (type) {
1365 case OBJ_OFS_DELTA:
1366 case OBJ_REF_DELTA:
1367 type = packed_delta_info(p, &w_curs, curpos,
1368 type, obj_offset, sizep);
1369 break;
1370 case OBJ_COMMIT:
1371 case OBJ_TREE:
1372 case OBJ_BLOB:
1373 case OBJ_TAG:
1374 if (sizep)
1375 *sizep = size;
1376 break;
1377 default:
1378 die("pack %s contains unknown object type %d",
1379 p->pack_name, type);
1381 unuse_pack(&w_curs);
1382 return type;
1385 static void *unpack_compressed_entry(struct packed_git *p,
1386 struct pack_window **w_curs,
1387 off_t curpos,
1388 unsigned long size)
1390 int st;
1391 z_stream stream;
1392 unsigned char *buffer, *in;
1394 buffer = xmalloc(size + 1);
1395 buffer[size] = 0;
1396 memset(&stream, 0, sizeof(stream));
1397 stream.next_out = buffer;
1398 stream.avail_out = size;
1400 inflateInit(&stream);
1401 do {
1402 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1403 stream.next_in = in;
1404 st = inflate(&stream, Z_FINISH);
1405 curpos += stream.next_in - in;
1406 } while (st == Z_OK || st == Z_BUF_ERROR);
1407 inflateEnd(&stream);
1408 if ((st != Z_STREAM_END) || stream.total_out != size) {
1409 free(buffer);
1410 return NULL;
1413 return buffer;
1416 #define MAX_DELTA_CACHE (256)
1418 static size_t delta_base_cached;
1420 static struct delta_base_cache_lru_list {
1421 struct delta_base_cache_lru_list *prev;
1422 struct delta_base_cache_lru_list *next;
1423 } delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1425 static struct delta_base_cache_entry {
1426 struct delta_base_cache_lru_list lru;
1427 void *data;
1428 struct packed_git *p;
1429 off_t base_offset;
1430 unsigned long size;
1431 enum object_type type;
1432 } delta_base_cache[MAX_DELTA_CACHE];
1434 static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1436 unsigned long hash;
1438 hash = (unsigned long)p + (unsigned long)base_offset;
1439 hash += (hash >> 8) + (hash >> 16);
1440 return hash % MAX_DELTA_CACHE;
1443 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1444 unsigned long *base_size, enum object_type *type, int keep_cache)
1446 void *ret;
1447 unsigned long hash = pack_entry_hash(p, base_offset);
1448 struct delta_base_cache_entry *ent = delta_base_cache + hash;
1450 ret = ent->data;
1451 if (ret && ent->p == p && ent->base_offset == base_offset)
1452 goto found_cache_entry;
1453 return unpack_entry(p, base_offset, type, base_size);
1455 found_cache_entry:
1456 if (!keep_cache) {
1457 ent->data = NULL;
1458 ent->lru.next->prev = ent->lru.prev;
1459 ent->lru.prev->next = ent->lru.next;
1460 delta_base_cached -= ent->size;
1462 else {
1463 ret = xmalloc(ent->size + 1);
1464 memcpy(ret, ent->data, ent->size);
1465 ((char *)ret)[ent->size] = 0;
1467 *type = ent->type;
1468 *base_size = ent->size;
1469 return ret;
1472 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1474 if (ent->data) {
1475 free(ent->data);
1476 ent->data = NULL;
1477 ent->lru.next->prev = ent->lru.prev;
1478 ent->lru.prev->next = ent->lru.next;
1479 delta_base_cached -= ent->size;
1483 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1484 void *base, unsigned long base_size, enum object_type type)
1486 unsigned long hash = pack_entry_hash(p, base_offset);
1487 struct delta_base_cache_entry *ent = delta_base_cache + hash;
1488 struct delta_base_cache_lru_list *lru;
1490 release_delta_base_cache(ent);
1491 delta_base_cached += base_size;
1493 for (lru = delta_base_cache_lru.next;
1494 delta_base_cached > delta_base_cache_limit
1495 && lru != &delta_base_cache_lru;
1496 lru = lru->next) {
1497 struct delta_base_cache_entry *f = (void *)lru;
1498 if (f->type == OBJ_BLOB)
1499 release_delta_base_cache(f);
1501 for (lru = delta_base_cache_lru.next;
1502 delta_base_cached > delta_base_cache_limit
1503 && lru != &delta_base_cache_lru;
1504 lru = lru->next) {
1505 struct delta_base_cache_entry *f = (void *)lru;
1506 release_delta_base_cache(f);
1509 ent->p = p;
1510 ent->base_offset = base_offset;
1511 ent->type = type;
1512 ent->data = base;
1513 ent->size = base_size;
1514 ent->lru.next = &delta_base_cache_lru;
1515 ent->lru.prev = delta_base_cache_lru.prev;
1516 delta_base_cache_lru.prev->next = &ent->lru;
1517 delta_base_cache_lru.prev = &ent->lru;
1520 static void *unpack_delta_entry(struct packed_git *p,
1521 struct pack_window **w_curs,
1522 off_t curpos,
1523 unsigned long delta_size,
1524 off_t obj_offset,
1525 enum object_type *type,
1526 unsigned long *sizep)
1528 void *delta_data, *result, *base;
1529 unsigned long base_size;
1530 off_t base_offset;
1532 base_offset = get_delta_base(p, w_curs, &curpos, *type, obj_offset);
1533 base = cache_or_unpack_entry(p, base_offset, &base_size, type, 0);
1534 if (!base)
1535 die("failed to read delta base object"
1536 " at %"PRIuMAX" from %s",
1537 (uintmax_t)base_offset, p->pack_name);
1539 delta_data = unpack_compressed_entry(p, w_curs, curpos, delta_size);
1540 result = patch_delta(base, base_size,
1541 delta_data, delta_size,
1542 sizep);
1543 if (!result)
1544 die("failed to apply delta");
1545 free(delta_data);
1546 add_delta_base_cache(p, base_offset, base, base_size, *type);
1547 return result;
1550 void *unpack_entry(struct packed_git *p, off_t obj_offset,
1551 enum object_type *type, unsigned long *sizep)
1553 struct pack_window *w_curs = NULL;
1554 off_t curpos = obj_offset;
1555 void *data;
1557 *type = unpack_object_header(p, &w_curs, &curpos, sizep);
1558 switch (*type) {
1559 case OBJ_OFS_DELTA:
1560 case OBJ_REF_DELTA:
1561 data = unpack_delta_entry(p, &w_curs, curpos, *sizep,
1562 obj_offset, type, sizep);
1563 break;
1564 case OBJ_COMMIT:
1565 case OBJ_TREE:
1566 case OBJ_BLOB:
1567 case OBJ_TAG:
1568 data = unpack_compressed_entry(p, &w_curs, curpos, *sizep);
1569 break;
1570 default:
1571 die("unknown object type %i in %s", *type, p->pack_name);
1573 unuse_pack(&w_curs);
1574 return data;
1577 const unsigned char *nth_packed_object_sha1(const struct packed_git *p,
1578 uint32_t n)
1580 const unsigned char *index = p->index_data;
1581 if (n >= p->num_objects)
1582 return NULL;
1583 index += 4 * 256;
1584 if (p->index_version == 1) {
1585 return index + 24 * n + 4;
1586 } else {
1587 index += 8;
1588 return index + 20 * n;
1592 static off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1594 const unsigned char *index = p->index_data;
1595 index += 4 * 256;
1596 if (p->index_version == 1) {
1597 return ntohl(*((uint32_t *)(index + 24 * n)));
1598 } else {
1599 uint32_t off;
1600 index += 8 + p->num_objects * (20 + 4);
1601 off = ntohl(*((uint32_t *)(index + 4 * n)));
1602 if (!(off & 0x80000000))
1603 return off;
1604 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1605 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
1606 ntohl(*((uint32_t *)(index + 4)));
1610 off_t find_pack_entry_one(const unsigned char *sha1,
1611 struct packed_git *p)
1613 const uint32_t *level1_ofs = p->index_data;
1614 const unsigned char *index = p->index_data;
1615 unsigned hi, lo;
1617 if (p->index_version > 1) {
1618 level1_ofs += 2;
1619 index += 8;
1621 index += 4 * 256;
1622 hi = ntohl(level1_ofs[*sha1]);
1623 lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1625 do {
1626 unsigned mi = (lo + hi) / 2;
1627 unsigned x = (p->index_version > 1) ? (mi * 20) : (mi * 24 + 4);
1628 int cmp = hashcmp(index + x, sha1);
1629 if (!cmp)
1630 return nth_packed_object_offset(p, mi);
1631 if (cmp > 0)
1632 hi = mi;
1633 else
1634 lo = mi+1;
1635 } while (lo < hi);
1636 return 0;
1639 static int matches_pack_name(struct packed_git *p, const char *ig)
1641 const char *last_c, *c;
1643 if (!strcmp(p->pack_name, ig))
1644 return 0;
1646 for (c = p->pack_name, last_c = c; *c;)
1647 if (*c == '/')
1648 last_c = ++c;
1649 else
1650 ++c;
1651 if (!strcmp(last_c, ig))
1652 return 0;
1654 return 1;
1657 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e, const char **ignore_packed)
1659 struct packed_git *p;
1660 off_t offset;
1662 prepare_packed_git();
1664 for (p = packed_git; p; p = p->next) {
1665 if (ignore_packed) {
1666 const char **ig;
1667 for (ig = ignore_packed; *ig; ig++)
1668 if (!matches_pack_name(p, *ig))
1669 break;
1670 if (*ig)
1671 continue;
1673 offset = find_pack_entry_one(sha1, p);
1674 if (offset) {
1676 * We are about to tell the caller where they can
1677 * locate the requested object. We better make
1678 * sure the packfile is still here and can be
1679 * accessed before supplying that answer, as
1680 * it may have been deleted since the index
1681 * was loaded!
1683 if (p->pack_fd == -1 && open_packed_git(p)) {
1684 error("packfile %s cannot be accessed", p->pack_name);
1685 continue;
1687 e->offset = offset;
1688 e->p = p;
1689 hashcpy(e->sha1, sha1);
1690 return 1;
1693 return 0;
1696 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1697 struct packed_git *packs)
1699 struct packed_git *p;
1701 for (p = packs; p; p = p->next) {
1702 if (find_pack_entry_one(sha1, p))
1703 return p;
1705 return NULL;
1709 static int sha1_loose_object_info(const unsigned char *sha1, unsigned long *sizep)
1711 int status;
1712 unsigned long mapsize, size;
1713 void *map;
1714 z_stream stream;
1715 char hdr[32];
1717 map = map_sha1_file(sha1, &mapsize);
1718 if (!map)
1719 return error("unable to find %s", sha1_to_hex(sha1));
1720 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1721 status = error("unable to unpack %s header",
1722 sha1_to_hex(sha1));
1723 else if ((status = parse_sha1_header(hdr, &size)) < 0)
1724 status = error("unable to parse %s header", sha1_to_hex(sha1));
1725 else if (sizep)
1726 *sizep = size;
1727 inflateEnd(&stream);
1728 munmap(map, mapsize);
1729 return status;
1732 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
1734 struct pack_entry e;
1736 if (!find_pack_entry(sha1, &e, NULL)) {
1737 reprepare_packed_git();
1738 if (!find_pack_entry(sha1, &e, NULL))
1739 return sha1_loose_object_info(sha1, sizep);
1741 return packed_object_info(e.p, e.offset, sizep);
1744 static void *read_packed_sha1(const unsigned char *sha1,
1745 enum object_type *type, unsigned long *size)
1747 struct pack_entry e;
1749 if (!find_pack_entry(sha1, &e, NULL))
1750 return NULL;
1751 else
1752 return cache_or_unpack_entry(e.p, e.offset, size, type, 1);
1756 * This is meant to hold a *small* number of objects that you would
1757 * want read_sha1_file() to be able to return, but yet you do not want
1758 * to write them into the object store (e.g. a browse-only
1759 * application).
1761 static struct cached_object {
1762 unsigned char sha1[20];
1763 enum object_type type;
1764 void *buf;
1765 unsigned long size;
1766 } *cached_objects;
1767 static int cached_object_nr, cached_object_alloc;
1769 static struct cached_object *find_cached_object(const unsigned char *sha1)
1771 int i;
1772 struct cached_object *co = cached_objects;
1774 for (i = 0; i < cached_object_nr; i++, co++) {
1775 if (!hashcmp(co->sha1, sha1))
1776 return co;
1778 return NULL;
1781 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
1782 unsigned char *sha1)
1784 struct cached_object *co;
1786 hash_sha1_file(buf, len, typename(type), sha1);
1787 if (has_sha1_file(sha1) || find_cached_object(sha1))
1788 return 0;
1789 if (cached_object_alloc <= cached_object_nr) {
1790 cached_object_alloc = alloc_nr(cached_object_alloc);
1791 cached_objects = xrealloc(cached_objects,
1792 sizeof(*cached_objects) *
1793 cached_object_alloc);
1795 co = &cached_objects[cached_object_nr++];
1796 co->size = len;
1797 co->type = type;
1798 co->buf = xmalloc(len);
1799 memcpy(co->buf, buf, len);
1800 hashcpy(co->sha1, sha1);
1801 return 0;
1804 void *read_sha1_file(const unsigned char *sha1, enum object_type *type,
1805 unsigned long *size)
1807 unsigned long mapsize;
1808 void *map, *buf;
1809 struct cached_object *co;
1811 co = find_cached_object(sha1);
1812 if (co) {
1813 buf = xmalloc(co->size + 1);
1814 memcpy(buf, co->buf, co->size);
1815 ((char*)buf)[co->size] = 0;
1816 *type = co->type;
1817 *size = co->size;
1818 return buf;
1821 buf = read_packed_sha1(sha1, type, size);
1822 if (buf)
1823 return buf;
1824 map = map_sha1_file(sha1, &mapsize);
1825 if (map) {
1826 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
1827 munmap(map, mapsize);
1828 return buf;
1830 reprepare_packed_git();
1831 return read_packed_sha1(sha1, type, size);
1834 void *read_object_with_reference(const unsigned char *sha1,
1835 const char *required_type_name,
1836 unsigned long *size,
1837 unsigned char *actual_sha1_return)
1839 enum object_type type, required_type;
1840 void *buffer;
1841 unsigned long isize;
1842 unsigned char actual_sha1[20];
1844 required_type = type_from_string(required_type_name);
1845 hashcpy(actual_sha1, sha1);
1846 while (1) {
1847 int ref_length = -1;
1848 const char *ref_type = NULL;
1850 buffer = read_sha1_file(actual_sha1, &type, &isize);
1851 if (!buffer)
1852 return NULL;
1853 if (type == required_type) {
1854 *size = isize;
1855 if (actual_sha1_return)
1856 hashcpy(actual_sha1_return, actual_sha1);
1857 return buffer;
1859 /* Handle references */
1860 else if (type == OBJ_COMMIT)
1861 ref_type = "tree ";
1862 else if (type == OBJ_TAG)
1863 ref_type = "object ";
1864 else {
1865 free(buffer);
1866 return NULL;
1868 ref_length = strlen(ref_type);
1870 if (memcmp(buffer, ref_type, ref_length) ||
1871 get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
1872 free(buffer);
1873 return NULL;
1875 free(buffer);
1876 /* Now we have the ID of the referred-to object in
1877 * actual_sha1. Check again. */
1881 static void write_sha1_file_prepare(const void *buf, unsigned long len,
1882 const char *type, unsigned char *sha1,
1883 char *hdr, int *hdrlen)
1885 SHA_CTX c;
1887 /* Generate the header */
1888 *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
1890 /* Sha1.. */
1891 SHA1_Init(&c);
1892 SHA1_Update(&c, hdr, *hdrlen);
1893 SHA1_Update(&c, buf, len);
1894 SHA1_Final(sha1, &c);
1898 * Link the tempfile to the final place, possibly creating the
1899 * last directory level as you do so.
1901 * Returns the errno on failure, 0 on success.
1903 static int link_temp_to_file(const char *tmpfile, const char *filename)
1905 int ret;
1906 char *dir;
1908 if (!link(tmpfile, filename))
1909 return 0;
1912 * Try to mkdir the last path component if that failed.
1914 * Re-try the "link()" regardless of whether the mkdir
1915 * succeeds, since a race might mean that somebody
1916 * else succeeded.
1918 ret = errno;
1919 dir = strrchr(filename, '/');
1920 if (dir) {
1921 *dir = 0;
1922 if (!mkdir(filename, 0777) && adjust_shared_perm(filename)) {
1923 *dir = '/';
1924 return -2;
1926 *dir = '/';
1927 if (!link(tmpfile, filename))
1928 return 0;
1929 ret = errno;
1931 return ret;
1935 * Move the just written object into its final resting place
1937 int move_temp_to_file(const char *tmpfile, const char *filename)
1939 int ret = link_temp_to_file(tmpfile, filename);
1942 * Coda hack - coda doesn't like cross-directory links,
1943 * so we fall back to a rename, which will mean that it
1944 * won't be able to check collisions, but that's not a
1945 * big deal.
1947 * The same holds for FAT formatted media.
1949 * When this succeeds, we just return 0. We have nothing
1950 * left to unlink.
1952 if (ret && ret != EEXIST) {
1953 if (!rename(tmpfile, filename))
1954 return 0;
1955 ret = errno;
1957 unlink(tmpfile);
1958 if (ret) {
1959 if (ret != EEXIST) {
1960 return error("unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1962 /* FIXME!!! Collision check here ? */
1965 return 0;
1968 static int write_buffer(int fd, const void *buf, size_t len)
1970 if (write_in_full(fd, buf, len) < 0)
1971 return error("file write error (%s)", strerror(errno));
1972 return 0;
1975 static int write_binary_header(unsigned char *hdr, enum object_type type, unsigned long len)
1977 int hdr_len;
1978 unsigned char c;
1980 c = (type << 4) | (len & 15);
1981 len >>= 4;
1982 hdr_len = 1;
1983 while (len) {
1984 *hdr++ = c | 0x80;
1985 hdr_len++;
1986 c = (len & 0x7f);
1987 len >>= 7;
1989 *hdr = c;
1990 return hdr_len;
1993 static void setup_object_header(z_stream *stream, const char *type, unsigned long len)
1995 int obj_type, hdrlen;
1997 if (use_legacy_headers) {
1998 while (deflate(stream, 0) == Z_OK)
1999 /* nothing */;
2000 return;
2002 obj_type = type_from_string(type);
2003 hdrlen = write_binary_header(stream->next_out, obj_type, len);
2004 stream->total_out = hdrlen;
2005 stream->next_out += hdrlen;
2006 stream->avail_out -= hdrlen;
2009 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2010 unsigned char *sha1)
2012 char hdr[32];
2013 int hdrlen;
2014 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2015 return 0;
2018 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
2020 int size, ret;
2021 unsigned char *compressed;
2022 z_stream stream;
2023 unsigned char sha1[20];
2024 char *filename;
2025 static char tmpfile[PATH_MAX];
2026 char hdr[32];
2027 int fd, hdrlen;
2029 /* Normally if we have it in the pack then we do not bother writing
2030 * it out into .git/objects/??/?{38} file.
2032 write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2033 filename = sha1_file_name(sha1);
2034 if (returnsha1)
2035 hashcpy(returnsha1, sha1);
2036 if (has_sha1_file(sha1))
2037 return 0;
2038 fd = open(filename, O_RDONLY);
2039 if (fd >= 0) {
2041 * FIXME!!! We might do collision checking here, but we'd
2042 * need to uncompress the old file and check it. Later.
2044 close(fd);
2045 return 0;
2048 if (errno != ENOENT) {
2049 return error("sha1 file %s: %s\n", filename, strerror(errno));
2052 snprintf(tmpfile, sizeof(tmpfile), "%s/tmp_obj_XXXXXX", get_object_directory());
2054 fd = mkstemp(tmpfile);
2055 if (fd < 0) {
2056 if (errno == EPERM)
2057 return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2058 else
2059 return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2062 /* Set it up */
2063 memset(&stream, 0, sizeof(stream));
2064 deflateInit(&stream, zlib_compression_level);
2065 size = 8 + deflateBound(&stream, len+hdrlen);
2066 compressed = xmalloc(size);
2068 /* Compress it */
2069 stream.next_out = compressed;
2070 stream.avail_out = size;
2072 /* First header.. */
2073 stream.next_in = (unsigned char *)hdr;
2074 stream.avail_in = hdrlen;
2075 setup_object_header(&stream, type, len);
2077 /* Then the data itself.. */
2078 stream.next_in = buf;
2079 stream.avail_in = len;
2080 ret = deflate(&stream, Z_FINISH);
2081 if (ret != Z_STREAM_END)
2082 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2084 ret = deflateEnd(&stream);
2085 if (ret != Z_OK)
2086 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2088 size = stream.total_out;
2090 if (write_buffer(fd, compressed, size) < 0)
2091 die("unable to write sha1 file");
2092 fchmod(fd, 0444);
2093 if (close(fd))
2094 die("unable to write sha1 file");
2095 free(compressed);
2097 return move_temp_to_file(tmpfile, filename);
2101 * We need to unpack and recompress the object for writing
2102 * it out to a different file.
2104 static void *repack_object(const unsigned char *sha1, unsigned long *objsize)
2106 size_t size;
2107 z_stream stream;
2108 unsigned char *unpacked;
2109 unsigned long len;
2110 enum object_type type;
2111 char hdr[32];
2112 int hdrlen;
2113 void *buf;
2115 /* need to unpack and recompress it by itself */
2116 unpacked = read_packed_sha1(sha1, &type, &len);
2117 if (!unpacked)
2118 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2120 hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
2122 /* Set it up */
2123 memset(&stream, 0, sizeof(stream));
2124 deflateInit(&stream, zlib_compression_level);
2125 size = deflateBound(&stream, len + hdrlen);
2126 buf = xmalloc(size);
2128 /* Compress it */
2129 stream.next_out = buf;
2130 stream.avail_out = size;
2132 /* First header.. */
2133 stream.next_in = (void *)hdr;
2134 stream.avail_in = hdrlen;
2135 while (deflate(&stream, 0) == Z_OK)
2136 /* nothing */;
2138 /* Then the data itself.. */
2139 stream.next_in = unpacked;
2140 stream.avail_in = len;
2141 while (deflate(&stream, Z_FINISH) == Z_OK)
2142 /* nothing */;
2143 deflateEnd(&stream);
2144 free(unpacked);
2146 *objsize = stream.total_out;
2147 return buf;
2150 int write_sha1_to_fd(int fd, const unsigned char *sha1)
2152 int retval;
2153 unsigned long objsize;
2154 void *buf = map_sha1_file(sha1, &objsize);
2156 if (buf) {
2157 retval = write_buffer(fd, buf, objsize);
2158 munmap(buf, objsize);
2159 return retval;
2162 buf = repack_object(sha1, &objsize);
2163 retval = write_buffer(fd, buf, objsize);
2164 free(buf);
2165 return retval;
2168 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
2169 size_t bufsize, size_t *bufposn)
2171 char tmpfile[PATH_MAX];
2172 int local;
2173 z_stream stream;
2174 unsigned char real_sha1[20];
2175 unsigned char discard[4096];
2176 int ret;
2177 SHA_CTX c;
2179 snprintf(tmpfile, sizeof(tmpfile), "%s/tmp_obj_XXXXXX", get_object_directory());
2181 local = mkstemp(tmpfile);
2182 if (local < 0) {
2183 if (errno == EPERM)
2184 return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2185 else
2186 return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2189 memset(&stream, 0, sizeof(stream));
2191 inflateInit(&stream);
2193 SHA1_Init(&c);
2195 do {
2196 ssize_t size;
2197 if (*bufposn) {
2198 stream.avail_in = *bufposn;
2199 stream.next_in = (unsigned char *) buffer;
2200 do {
2201 stream.next_out = discard;
2202 stream.avail_out = sizeof(discard);
2203 ret = inflate(&stream, Z_SYNC_FLUSH);
2204 SHA1_Update(&c, discard, sizeof(discard) -
2205 stream.avail_out);
2206 } while (stream.avail_in && ret == Z_OK);
2207 if (write_buffer(local, buffer, *bufposn - stream.avail_in) < 0)
2208 die("unable to write sha1 file");
2209 memmove(buffer, buffer + *bufposn - stream.avail_in,
2210 stream.avail_in);
2211 *bufposn = stream.avail_in;
2212 if (ret != Z_OK)
2213 break;
2215 size = xread(fd, buffer + *bufposn, bufsize - *bufposn);
2216 if (size <= 0) {
2217 close(local);
2218 unlink(tmpfile);
2219 if (!size)
2220 return error("Connection closed?");
2221 perror("Reading from connection");
2222 return -1;
2224 *bufposn += size;
2225 } while (1);
2226 inflateEnd(&stream);
2228 fchmod(local, 0444);
2229 if (close(local) != 0)
2230 die("unable to write sha1 file");
2231 SHA1_Final(real_sha1, &c);
2232 if (ret != Z_STREAM_END) {
2233 unlink(tmpfile);
2234 return error("File %s corrupted", sha1_to_hex(sha1));
2236 if (hashcmp(sha1, real_sha1)) {
2237 unlink(tmpfile);
2238 return error("File %s has bad hash", sha1_to_hex(sha1));
2241 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
2244 int has_pack_index(const unsigned char *sha1)
2246 struct stat st;
2247 if (stat(sha1_pack_index_name(sha1), &st))
2248 return 0;
2249 return 1;
2252 int has_pack_file(const unsigned char *sha1)
2254 struct stat st;
2255 if (stat(sha1_pack_name(sha1), &st))
2256 return 0;
2257 return 1;
2260 int has_sha1_pack(const unsigned char *sha1, const char **ignore_packed)
2262 struct pack_entry e;
2263 return find_pack_entry(sha1, &e, ignore_packed);
2266 int has_sha1_file(const unsigned char *sha1)
2268 struct stat st;
2269 struct pack_entry e;
2271 if (find_pack_entry(sha1, &e, NULL))
2272 return 1;
2273 return find_sha1_file(sha1, &st) ? 1 : 0;
2277 * reads from fd as long as possible into a supplied buffer of size bytes.
2278 * If necessary the buffer's size is increased using realloc()
2280 * returns 0 if anything went fine and -1 otherwise
2282 * NOTE: both buf and size may change, but even when -1 is returned
2283 * you still have to free() it yourself.
2285 int read_pipe(int fd, char** return_buf, unsigned long* return_size)
2287 char* buf = *return_buf;
2288 unsigned long size = *return_size;
2289 ssize_t iret;
2290 unsigned long off = 0;
2292 do {
2293 iret = xread(fd, buf + off, size - off);
2294 if (iret > 0) {
2295 off += iret;
2296 if (off == size) {
2297 size *= 2;
2298 buf = xrealloc(buf, size);
2301 } while (iret > 0);
2303 *return_buf = buf;
2304 *return_size = off;
2306 if (iret < 0)
2307 return -1;
2308 return 0;
2311 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
2313 unsigned long size = 4096;
2314 char *buf = xmalloc(size);
2315 int ret;
2317 if (read_pipe(fd, &buf, &size)) {
2318 free(buf);
2319 return -1;
2322 if (!type)
2323 type = blob_type;
2324 if (write_object)
2325 ret = write_sha1_file(buf, size, type, sha1);
2326 else
2327 ret = hash_sha1_file(buf, size, type, sha1);
2328 free(buf);
2329 return ret;
2332 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object,
2333 enum object_type type, const char *path)
2335 size_t size = xsize_t(st->st_size);
2336 void *buf = NULL;
2337 int ret, re_allocated = 0;
2339 if (size)
2340 buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2341 close(fd);
2343 if (!type)
2344 type = OBJ_BLOB;
2347 * Convert blobs to git internal format
2349 if ((type == OBJ_BLOB) && S_ISREG(st->st_mode)) {
2350 unsigned long nsize = size;
2351 char *nbuf = convert_to_git(path, buf, &nsize);
2352 if (nbuf) {
2353 munmap(buf, size);
2354 size = nsize;
2355 buf = nbuf;
2356 re_allocated = 1;
2360 if (write_object)
2361 ret = write_sha1_file(buf, size, typename(type), sha1);
2362 else
2363 ret = hash_sha1_file(buf, size, typename(type), sha1);
2364 if (re_allocated) {
2365 free(buf);
2366 return ret;
2368 if (size)
2369 munmap(buf, size);
2370 return ret;
2373 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
2375 int fd;
2376 char *target;
2377 size_t len;
2379 switch (st->st_mode & S_IFMT) {
2380 case S_IFREG:
2381 fd = open(path, O_RDONLY);
2382 if (fd < 0)
2383 return error("open(\"%s\"): %s", path,
2384 strerror(errno));
2385 if (index_fd(sha1, fd, st, write_object, OBJ_BLOB, path) < 0)
2386 return error("%s: failed to insert into database",
2387 path);
2388 break;
2389 case S_IFLNK:
2390 len = xsize_t(st->st_size);
2391 target = xmalloc(len + 1);
2392 if (readlink(path, target, len + 1) != st->st_size) {
2393 char *errstr = strerror(errno);
2394 free(target);
2395 return error("readlink(\"%s\"): %s", path,
2396 errstr);
2398 if (!write_object)
2399 hash_sha1_file(target, len, blob_type, sha1);
2400 else if (write_sha1_file(target, len, blob_type, sha1))
2401 return error("%s: failed to insert into database",
2402 path);
2403 free(target);
2404 break;
2405 case S_IFDIR:
2406 return resolve_gitlink_ref(path, "HEAD", sha1);
2407 default:
2408 return error("%s: unsupported file type", path);
2410 return 0;
2413 int read_pack_header(int fd, struct pack_header *header)
2415 char *c = (char*)header;
2416 ssize_t remaining = sizeof(struct pack_header);
2417 do {
2418 ssize_t r = xread(fd, c, remaining);
2419 if (r <= 0)
2420 /* "eof before pack header was fully read" */
2421 return PH_ERROR_EOF;
2422 remaining -= r;
2423 c += r;
2424 } while (remaining > 0);
2425 if (header->hdr_signature != htonl(PACK_SIGNATURE))
2426 /* "protocol error (pack signature mismatch detected)" */
2427 return PH_ERROR_PACK_SIGNATURE;
2428 if (!pack_version_ok(header->hdr_version))
2429 /* "protocol error (pack version unsupported)" */
2430 return PH_ERROR_PROTOCOL;
2431 return 0;