Code

GIT 1.5.5.4
[git.git] / sha1_file.c
1 /*
2  * GIT - The information manager from hell
3  *
4  * Copyright (C) Linus Torvalds, 2005
5  *
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"
17 #include "pack-revindex.h"
19 #ifndef O_NOATIME
20 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
21 #define O_NOATIME 01000000
22 #else
23 #define O_NOATIME 0
24 #endif
25 #endif
27 #ifdef NO_C99_FORMAT
28 #define SZ_FMT "lu"
29 static unsigned long sz_fmt(size_t s) { return (unsigned long)s; }
30 #else
31 #define SZ_FMT "zu"
32 static size_t sz_fmt(size_t s) { return s; }
33 #endif
35 const unsigned char null_sha1[20];
37 static unsigned int sha1_file_open_flag = O_NOATIME;
39 const signed char hexval_table[256] = {
40          -1, -1, -1, -1, -1, -1, -1, -1,                /* 00-07 */
41          -1, -1, -1, -1, -1, -1, -1, -1,                /* 08-0f */
42          -1, -1, -1, -1, -1, -1, -1, -1,                /* 10-17 */
43          -1, -1, -1, -1, -1, -1, -1, -1,                /* 18-1f */
44          -1, -1, -1, -1, -1, -1, -1, -1,                /* 20-27 */
45          -1, -1, -1, -1, -1, -1, -1, -1,                /* 28-2f */
46           0,  1,  2,  3,  4,  5,  6,  7,                /* 30-37 */
47           8,  9, -1, -1, -1, -1, -1, -1,                /* 38-3f */
48          -1, 10, 11, 12, 13, 14, 15, -1,                /* 40-47 */
49          -1, -1, -1, -1, -1, -1, -1, -1,                /* 48-4f */
50          -1, -1, -1, -1, -1, -1, -1, -1,                /* 50-57 */
51          -1, -1, -1, -1, -1, -1, -1, -1,                /* 58-5f */
52          -1, 10, 11, 12, 13, 14, 15, -1,                /* 60-67 */
53          -1, -1, -1, -1, -1, -1, -1, -1,                /* 68-67 */
54          -1, -1, -1, -1, -1, -1, -1, -1,                /* 70-77 */
55          -1, -1, -1, -1, -1, -1, -1, -1,                /* 78-7f */
56          -1, -1, -1, -1, -1, -1, -1, -1,                /* 80-87 */
57          -1, -1, -1, -1, -1, -1, -1, -1,                /* 88-8f */
58          -1, -1, -1, -1, -1, -1, -1, -1,                /* 90-97 */
59          -1, -1, -1, -1, -1, -1, -1, -1,                /* 98-9f */
60          -1, -1, -1, -1, -1, -1, -1, -1,                /* a0-a7 */
61          -1, -1, -1, -1, -1, -1, -1, -1,                /* a8-af */
62          -1, -1, -1, -1, -1, -1, -1, -1,                /* b0-b7 */
63          -1, -1, -1, -1, -1, -1, -1, -1,                /* b8-bf */
64          -1, -1, -1, -1, -1, -1, -1, -1,                /* c0-c7 */
65          -1, -1, -1, -1, -1, -1, -1, -1,                /* c8-cf */
66          -1, -1, -1, -1, -1, -1, -1, -1,                /* d0-d7 */
67          -1, -1, -1, -1, -1, -1, -1, -1,                /* d8-df */
68          -1, -1, -1, -1, -1, -1, -1, -1,                /* e0-e7 */
69          -1, -1, -1, -1, -1, -1, -1, -1,                /* e8-ef */
70          -1, -1, -1, -1, -1, -1, -1, -1,                /* f0-f7 */
71          -1, -1, -1, -1, -1, -1, -1, -1,                /* f8-ff */
72 };
74 int get_sha1_hex(const char *hex, unsigned char *sha1)
75 {
76         int i;
77         for (i = 0; i < 20; i++) {
78                 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
79                 if (val & ~0xff)
80                         return -1;
81                 *sha1++ = val;
82                 hex += 2;
83         }
84         return 0;
85 }
87 int safe_create_leading_directories(char *path)
88 {
89         char *pos = path;
90         struct stat st;
92         if (is_absolute_path(path))
93                 pos++;
95         while (pos) {
96                 pos = strchr(pos, '/');
97                 if (!pos)
98                         break;
99                 *pos = 0;
100                 if (!stat(path, &st)) {
101                         /* path exists */
102                         if (!S_ISDIR(st.st_mode)) {
103                                 *pos = '/';
104                                 return -3;
105                         }
106                 }
107                 else if (mkdir(path, 0777)) {
108                         *pos = '/';
109                         return -1;
110                 }
111                 else if (adjust_shared_perm(path)) {
112                         *pos = '/';
113                         return -2;
114                 }
115                 *pos++ = '/';
116         }
117         return 0;
120 char * sha1_to_hex(const unsigned char *sha1)
122         static int bufno;
123         static char hexbuffer[4][50];
124         static const char hex[] = "0123456789abcdef";
125         char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
126         int i;
128         for (i = 0; i < 20; i++) {
129                 unsigned int val = *sha1++;
130                 *buf++ = hex[val >> 4];
131                 *buf++ = hex[val & 0xf];
132         }
133         *buf = '\0';
135         return buffer;
138 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
140         int i;
141         for (i = 0; i < 20; i++) {
142                 static char hex[] = "0123456789abcdef";
143                 unsigned int val = sha1[i];
144                 char *pos = pathbuf + i*2 + (i > 0);
145                 *pos++ = hex[val >> 4];
146                 *pos = hex[val & 0xf];
147         }
150 /*
151  * NOTE! This returns a statically allocated buffer, so you have to be
152  * careful about using it. Do an "xstrdup()" if you need to save the
153  * filename.
154  *
155  * Also note that this returns the location for creating.  Reading
156  * SHA1 file can happen from any alternate directory listed in the
157  * DB_ENVIRONMENT environment variable if it is not found in
158  * the primary object database.
159  */
160 char *sha1_file_name(const unsigned char *sha1)
162         static char *name, *base;
164         if (!base) {
165                 const char *sha1_file_directory = get_object_directory();
166                 int len = strlen(sha1_file_directory);
167                 base = xmalloc(len + 60);
168                 memcpy(base, sha1_file_directory, len);
169                 memset(base+len, 0, 60);
170                 base[len] = '/';
171                 base[len+3] = '/';
172                 name = base + len + 1;
173         }
174         fill_sha1_path(name, sha1);
175         return base;
178 char *sha1_pack_name(const unsigned char *sha1)
180         static const char hex[] = "0123456789abcdef";
181         static char *name, *base, *buf;
182         int i;
184         if (!base) {
185                 const char *sha1_file_directory = get_object_directory();
186                 int len = strlen(sha1_file_directory);
187                 base = xmalloc(len + 60);
188                 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
189                 name = base + len + 11;
190         }
192         buf = name;
194         for (i = 0; i < 20; i++) {
195                 unsigned int val = *sha1++;
196                 *buf++ = hex[val >> 4];
197                 *buf++ = hex[val & 0xf];
198         }
200         return base;
203 char *sha1_pack_index_name(const unsigned char *sha1)
205         static const char hex[] = "0123456789abcdef";
206         static char *name, *base, *buf;
207         int i;
209         if (!base) {
210                 const char *sha1_file_directory = get_object_directory();
211                 int len = strlen(sha1_file_directory);
212                 base = xmalloc(len + 60);
213                 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
214                 name = base + len + 11;
215         }
217         buf = name;
219         for (i = 0; i < 20; i++) {
220                 unsigned int val = *sha1++;
221                 *buf++ = hex[val >> 4];
222                 *buf++ = hex[val & 0xf];
223         }
225         return base;
228 struct alternate_object_database *alt_odb_list;
229 static struct alternate_object_database **alt_odb_tail;
231 static void read_info_alternates(const char * alternates, int depth);
233 /*
234  * Prepare alternate object database registry.
235  *
236  * The variable alt_odb_list points at the list of struct
237  * alternate_object_database.  The elements on this list come from
238  * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
239  * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
240  * whose contents is similar to that environment variable but can be
241  * LF separated.  Its base points at a statically allocated buffer that
242  * contains "/the/directory/corresponding/to/.git/objects/...", while
243  * its name points just after the slash at the end of ".git/objects/"
244  * in the example above, and has enough space to hold 40-byte hex
245  * SHA1, an extra slash for the first level indirection, and the
246  * terminating NUL.
247  */
248 static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
250         struct stat st;
251         const char *objdir = get_object_directory();
252         struct alternate_object_database *ent;
253         struct alternate_object_database *alt;
254         /* 43 = 40-byte + 2 '/' + terminating NUL */
255         int pfxlen = len;
256         int entlen = pfxlen + 43;
257         int base_len = -1;
259         if (!is_absolute_path(entry) && relative_base) {
260                 /* Relative alt-odb */
261                 if (base_len < 0)
262                         base_len = strlen(relative_base) + 1;
263                 entlen += base_len;
264                 pfxlen += base_len;
265         }
266         ent = xmalloc(sizeof(*ent) + entlen);
268         if (!is_absolute_path(entry) && relative_base) {
269                 memcpy(ent->base, relative_base, base_len - 1);
270                 ent->base[base_len - 1] = '/';
271                 memcpy(ent->base + base_len, entry, len);
272         }
273         else
274                 memcpy(ent->base, entry, pfxlen);
276         ent->name = ent->base + pfxlen + 1;
277         ent->base[pfxlen + 3] = '/';
278         ent->base[pfxlen] = ent->base[entlen-1] = 0;
280         /* Detect cases where alternate disappeared */
281         if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
282                 error("object directory %s does not exist; "
283                       "check .git/objects/info/alternates.",
284                       ent->base);
285                 free(ent);
286                 return -1;
287         }
289         /* Prevent the common mistake of listing the same
290          * thing twice, or object directory itself.
291          */
292         for (alt = alt_odb_list; alt; alt = alt->next) {
293                 if (!memcmp(ent->base, alt->base, pfxlen)) {
294                         free(ent);
295                         return -1;
296                 }
297         }
298         if (!memcmp(ent->base, objdir, pfxlen)) {
299                 free(ent);
300                 return -1;
301         }
303         /* add the alternate entry */
304         *alt_odb_tail = ent;
305         alt_odb_tail = &(ent->next);
306         ent->next = NULL;
308         /* recursively add alternates */
309         read_info_alternates(ent->base, depth + 1);
311         ent->base[pfxlen] = '/';
313         return 0;
316 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
317                                  const char *relative_base, int depth)
319         const char *cp, *last;
321         if (depth > 5) {
322                 error("%s: ignoring alternate object stores, nesting too deep.",
323                                 relative_base);
324                 return;
325         }
327         last = alt;
328         while (last < ep) {
329                 cp = last;
330                 if (cp < ep && *cp == '#') {
331                         while (cp < ep && *cp != sep)
332                                 cp++;
333                         last = cp + 1;
334                         continue;
335                 }
336                 while (cp < ep && *cp != sep)
337                         cp++;
338                 if (last != cp) {
339                         if (!is_absolute_path(last) && depth) {
340                                 error("%s: ignoring relative alternate object store %s",
341                                                 relative_base, last);
342                         } else {
343                                 link_alt_odb_entry(last, cp - last,
344                                                 relative_base, depth);
345                         }
346                 }
347                 while (cp < ep && *cp == sep)
348                         cp++;
349                 last = cp;
350         }
353 static void read_info_alternates(const char * relative_base, int depth)
355         char *map;
356         size_t mapsz;
357         struct stat st;
358         const char alt_file_name[] = "info/alternates";
359         /* Given that relative_base is no longer than PATH_MAX,
360            ensure that "path" has enough space to append "/", the
361            file name, "info/alternates", and a trailing NUL.  */
362         char path[PATH_MAX + 1 + sizeof alt_file_name];
363         int fd;
365         sprintf(path, "%s/%s", relative_base, alt_file_name);
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;
372         }
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         if (alt_odb_tail)
387                 return;
389         alt = getenv(ALTERNATE_DB_ENVIRONMENT);
390         if (!alt) alt = "";
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;
411         }
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(void)
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                 sz_fmt(getpagesize()),
430                 sz_fmt(packed_git_window_size),
431                 sz_fmt(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                 sz_fmt(pack_mapped), sz_fmt(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;
458         }
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);
463         }
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);
476                 }
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);
489                 }
490                 nr = n;
491         }
493         if (version == 1) {
494                 /*
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
500                  */
501                 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
502                         munmap(idx_map, idx_size);
503                         return error("wrong index v1 file size in %s", path);
504                 }
505         } else if (version == 2) {
506                 /*
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.
518                  */
519                 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
520                 unsigned long max_size = min_size;
521                 if (nr)
522                         max_size += (nr - 1)*8;
523                 if (idx_size < min_size || idx_size > max_size) {
524                         munmap(idx_map, idx_size);
525                         return error("wrong index v2 file size in %s", path);
526                 }
527                 if (idx_size != min_size &&
528                     /*
529                      * make sure we can deal with large pack offsets.
530                      * 31-bit signed offset won't be enough, neither
531                      * 32-bit unsigned one will be.
532                      */
533                     (sizeof(off_t) <= 4)) {
534                         munmap(idx_map, idx_size);
535                         return error("pack too large for current definition of off_t in %s", path);
536                 }
537         }
539         p->index_version = version;
540         p->index_data = idx_map;
541         p->index_size = idx_size;
542         p->num_objects = nr;
543         return 0;
546 int open_pack_index(struct packed_git *p)
548         char *idx_name;
549         int ret;
551         if (p->index_data)
552                 return 0;
554         idx_name = xstrdup(p->pack_name);
555         strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
556         ret = check_packed_git_idx(idx_name, p);
557         free(idx_name);
558         return ret;
561 static void scan_windows(struct packed_git *p,
562         struct packed_git **lru_p,
563         struct pack_window **lru_w,
564         struct pack_window **lru_l)
566         struct pack_window *w, *w_l;
568         for (w_l = NULL, w = p->windows; w; w = w->next) {
569                 if (!w->inuse_cnt) {
570                         if (!*lru_w || w->last_used < (*lru_w)->last_used) {
571                                 *lru_p = p;
572                                 *lru_w = w;
573                                 *lru_l = w_l;
574                         }
575                 }
576                 w_l = w;
577         }
580 static int unuse_one_window(struct packed_git *current, int keep_fd)
582         struct packed_git *p, *lru_p = NULL;
583         struct pack_window *lru_w = NULL, *lru_l = NULL;
585         if (current)
586                 scan_windows(current, &lru_p, &lru_w, &lru_l);
587         for (p = packed_git; p; p = p->next)
588                 scan_windows(p, &lru_p, &lru_w, &lru_l);
589         if (lru_p) {
590                 munmap(lru_w->base, lru_w->len);
591                 pack_mapped -= lru_w->len;
592                 if (lru_l)
593                         lru_l->next = lru_w->next;
594                 else {
595                         lru_p->windows = lru_w->next;
596                         if (!lru_p->windows && lru_p->pack_fd != keep_fd) {
597                                 close(lru_p->pack_fd);
598                                 lru_p->pack_fd = -1;
599                         }
600                 }
601                 free(lru_w);
602                 pack_open_windows--;
603                 return 1;
604         }
605         return 0;
608 void release_pack_memory(size_t need, int fd)
610         size_t cur = pack_mapped;
611         while (need >= (cur - pack_mapped) && unuse_one_window(NULL, fd))
612                 ; /* nothing */
615 void close_pack_windows(struct packed_git *p)
617         while (p->windows) {
618                 struct pack_window *w = p->windows;
620                 if (w->inuse_cnt)
621                         die("pack '%s' still has open windows to it",
622                             p->pack_name);
623                 munmap(w->base, w->len);
624                 pack_mapped -= w->len;
625                 pack_open_windows--;
626                 p->windows = w->next;
627                 free(w);
628         }
631 void unuse_pack(struct pack_window **w_cursor)
633         struct pack_window *w = *w_cursor;
634         if (w) {
635                 w->inuse_cnt--;
636                 *w_cursor = NULL;
637         }
640 /*
641  * Do not call this directly as this leaks p->pack_fd on error return;
642  * call open_packed_git() instead.
643  */
644 static int open_packed_git_1(struct packed_git *p)
646         struct stat st;
647         struct pack_header hdr;
648         unsigned char sha1[20];
649         unsigned char *idx_sha1;
650         long fd_flag;
652         if (!p->index_data && open_pack_index(p))
653                 return error("packfile %s index unavailable", p->pack_name);
655         p->pack_fd = open(p->pack_name, O_RDONLY);
656         if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
657                 return -1;
659         /* If we created the struct before we had the pack we lack size. */
660         if (!p->pack_size) {
661                 if (!S_ISREG(st.st_mode))
662                         return error("packfile %s not a regular file", p->pack_name);
663                 p->pack_size = st.st_size;
664         } else if (p->pack_size != st.st_size)
665                 return error("packfile %s size changed", p->pack_name);
667         /* We leave these file descriptors open with sliding mmap;
668          * there is no point keeping them open across exec(), though.
669          */
670         fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
671         if (fd_flag < 0)
672                 return error("cannot determine file descriptor flags");
673         fd_flag |= FD_CLOEXEC;
674         if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
675                 return error("cannot set FD_CLOEXEC");
677         /* Verify we recognize this pack file format. */
678         if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
679                 return error("file %s is far too short to be a packfile", p->pack_name);
680         if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
681                 return error("file %s is not a GIT packfile", p->pack_name);
682         if (!pack_version_ok(hdr.hdr_version))
683                 return error("packfile %s is version %u and not supported"
684                         " (try upgrading GIT to a newer version)",
685                         p->pack_name, ntohl(hdr.hdr_version));
687         /* Verify the pack matches its index. */
688         if (p->num_objects != ntohl(hdr.hdr_entries))
689                 return error("packfile %s claims to have %u objects"
690                              " while index indicates %u objects",
691                              p->pack_name, ntohl(hdr.hdr_entries),
692                              p->num_objects);
693         if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
694                 return error("end of packfile %s is unavailable", p->pack_name);
695         if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
696                 return error("packfile %s signature is unavailable", p->pack_name);
697         idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
698         if (hashcmp(sha1, idx_sha1))
699                 return error("packfile %s does not match index", p->pack_name);
700         return 0;
703 static int open_packed_git(struct packed_git *p)
705         if (!open_packed_git_1(p))
706                 return 0;
707         if (p->pack_fd != -1) {
708                 close(p->pack_fd);
709                 p->pack_fd = -1;
710         }
711         return -1;
714 static int in_window(struct pack_window *win, off_t offset)
716         /* We must promise at least 20 bytes (one hash) after the
717          * offset is available from this window, otherwise the offset
718          * is not actually in this window and a different window (which
719          * has that one hash excess) must be used.  This is to support
720          * the object header and delta base parsing routines below.
721          */
722         off_t win_off = win->offset;
723         return win_off <= offset
724                 && (offset + 20) <= (win_off + win->len);
727 unsigned char* use_pack(struct packed_git *p,
728                 struct pack_window **w_cursor,
729                 off_t offset,
730                 unsigned int *left)
732         struct pack_window *win = *w_cursor;
734         if (p->pack_fd == -1 && open_packed_git(p))
735                 die("packfile %s cannot be accessed", p->pack_name);
737         /* Since packfiles end in a hash of their content and its
738          * pointless to ask for an offset into the middle of that
739          * hash, and the in_window function above wouldn't match
740          * don't allow an offset too close to the end of the file.
741          */
742         if (offset > (p->pack_size - 20))
743                 die("offset beyond end of packfile (truncated pack?)");
745         if (!win || !in_window(win, offset)) {
746                 if (win)
747                         win->inuse_cnt--;
748                 for (win = p->windows; win; win = win->next) {
749                         if (in_window(win, offset))
750                                 break;
751                 }
752                 if (!win) {
753                         size_t window_align = packed_git_window_size / 2;
754                         off_t len;
755                         win = xcalloc(1, sizeof(*win));
756                         win->offset = (offset / window_align) * window_align;
757                         len = p->pack_size - win->offset;
758                         if (len > packed_git_window_size)
759                                 len = packed_git_window_size;
760                         win->len = (size_t)len;
761                         pack_mapped += win->len;
762                         while (packed_git_limit < pack_mapped
763                                 && unuse_one_window(p, p->pack_fd))
764                                 ; /* nothing */
765                         win->base = xmmap(NULL, win->len,
766                                 PROT_READ, MAP_PRIVATE,
767                                 p->pack_fd, win->offset);
768                         if (win->base == MAP_FAILED)
769                                 die("packfile %s cannot be mapped: %s",
770                                         p->pack_name,
771                                         strerror(errno));
772                         pack_mmap_calls++;
773                         pack_open_windows++;
774                         if (pack_mapped > peak_pack_mapped)
775                                 peak_pack_mapped = pack_mapped;
776                         if (pack_open_windows > peak_pack_open_windows)
777                                 peak_pack_open_windows = pack_open_windows;
778                         win->next = p->windows;
779                         p->windows = win;
780                 }
781         }
782         if (win != *w_cursor) {
783                 win->last_used = pack_used_ctr++;
784                 win->inuse_cnt++;
785                 *w_cursor = win;
786         }
787         offset -= win->offset;
788         if (left)
789                 *left = win->len - xsize_t(offset);
790         return win->base + offset;
793 struct packed_git *add_packed_git(const char *path, int path_len, int local)
795         struct stat st;
796         struct packed_git *p = xmalloc(sizeof(*p) + path_len + 2);
798         /*
799          * Make sure a corresponding .pack file exists and that
800          * the index looks sane.
801          */
802         path_len -= strlen(".idx");
803         if (path_len < 1)
804                 return NULL;
805         memcpy(p->pack_name, path, path_len);
806         strcpy(p->pack_name + path_len, ".pack");
807         if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
808                 free(p);
809                 return NULL;
810         }
812         /* ok, it looks sane as far as we can check without
813          * actually mapping the pack file.
814          */
815         p->index_version = 0;
816         p->index_data = NULL;
817         p->index_size = 0;
818         p->num_objects = 0;
819         p->pack_size = st.st_size;
820         p->next = NULL;
821         p->windows = NULL;
822         p->pack_fd = -1;
823         p->pack_local = local;
824         p->mtime = st.st_mtime;
825         if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
826                 hashclr(p->sha1);
827         return p;
830 struct packed_git *parse_pack_index(unsigned char *sha1)
832         char *path = sha1_pack_index_name(sha1);
833         return parse_pack_index_file(sha1, path);
836 struct packed_git *parse_pack_index_file(const unsigned char *sha1,
837                                          const char *idx_path)
839         const char *path = sha1_pack_name(sha1);
840         struct packed_git *p = xmalloc(sizeof(*p) + strlen(path) + 2);
842         if (check_packed_git_idx(idx_path, p)) {
843                 free(p);
844                 return NULL;
845         }
847         strcpy(p->pack_name, path);
848         p->pack_size = 0;
849         p->next = NULL;
850         p->windows = NULL;
851         p->pack_fd = -1;
852         hashcpy(p->sha1, sha1);
853         return p;
856 void install_packed_git(struct packed_git *pack)
858         pack->next = packed_git;
859         packed_git = pack;
862 static void prepare_packed_git_one(char *objdir, int local)
864         /* Ensure that this buffer is large enough so that we can
865            append "/pack/" without clobbering the stack even if
866            strlen(objdir) were PATH_MAX.  */
867         char path[PATH_MAX + 1 + 4 + 1 + 1];
868         int len;
869         DIR *dir;
870         struct dirent *de;
872         sprintf(path, "%s/pack", objdir);
873         len = strlen(path);
874         dir = opendir(path);
875         if (!dir) {
876                 if (errno != ENOENT)
877                         error("unable to open object pack directory: %s: %s",
878                               path, strerror(errno));
879                 return;
880         }
881         path[len++] = '/';
882         while ((de = readdir(dir)) != NULL) {
883                 int namelen = strlen(de->d_name);
884                 struct packed_git *p;
886                 if (!has_extension(de->d_name, ".idx"))
887                         continue;
889                 if (len + namelen + 1 > sizeof(path))
890                         continue;
892                 /* Don't reopen a pack we already have. */
893                 strcpy(path + len, de->d_name);
894                 for (p = packed_git; p; p = p->next) {
895                         if (!memcmp(path, p->pack_name, len + namelen - 4))
896                                 break;
897                 }
898                 if (p)
899                         continue;
900                 /* See if it really is a valid .idx file with corresponding
901                  * .pack file that we can map.
902                  */
903                 p = add_packed_git(path, len + namelen, local);
904                 if (!p)
905                         continue;
906                 install_packed_git(p);
907         }
908         closedir(dir);
911 static int sort_pack(const void *a_, const void *b_)
913         struct packed_git *a = *((struct packed_git **)a_);
914         struct packed_git *b = *((struct packed_git **)b_);
915         int st;
917         /*
918          * Local packs tend to contain objects specific to our
919          * variant of the project than remote ones.  In addition,
920          * remote ones could be on a network mounted filesystem.
921          * Favor local ones for these reasons.
922          */
923         st = a->pack_local - b->pack_local;
924         if (st)
925                 return -st;
927         /*
928          * Younger packs tend to contain more recent objects,
929          * and more recent objects tend to get accessed more
930          * often.
931          */
932         if (a->mtime < b->mtime)
933                 return 1;
934         else if (a->mtime == b->mtime)
935                 return 0;
936         return -1;
939 static void rearrange_packed_git(void)
941         struct packed_git **ary, *p;
942         int i, n;
944         for (n = 0, p = packed_git; p; p = p->next)
945                 n++;
946         if (n < 2)
947                 return;
949         /* prepare an array of packed_git for easier sorting */
950         ary = xcalloc(n, sizeof(struct packed_git *));
951         for (n = 0, p = packed_git; p; p = p->next)
952                 ary[n++] = p;
954         qsort(ary, n, sizeof(struct packed_git *), sort_pack);
956         /* link them back again */
957         for (i = 0; i < n - 1; i++)
958                 ary[i]->next = ary[i + 1];
959         ary[n - 1]->next = NULL;
960         packed_git = ary[0];
962         free(ary);
965 static int prepare_packed_git_run_once = 0;
966 void prepare_packed_git(void)
968         struct alternate_object_database *alt;
970         if (prepare_packed_git_run_once)
971                 return;
972         prepare_packed_git_one(get_object_directory(), 1);
973         prepare_alt_odb();
974         for (alt = alt_odb_list; alt; alt = alt->next) {
975                 alt->name[-1] = 0;
976                 prepare_packed_git_one(alt->base, 0);
977                 alt->name[-1] = '/';
978         }
979         rearrange_packed_git();
980         prepare_packed_git_run_once = 1;
983 void reprepare_packed_git(void)
985         prepare_packed_git_run_once = 0;
986         prepare_packed_git();
989 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
991         unsigned char real_sha1[20];
992         hash_sha1_file(map, size, type, real_sha1);
993         return hashcmp(sha1, real_sha1) ? -1 : 0;
996 static void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
998         struct stat st;
999         void *map;
1000         int fd;
1001         char *filename = find_sha1_file(sha1, &st);
1003         if (!filename) {
1004                 return NULL;
1005         }
1007         fd = open(filename, O_RDONLY | sha1_file_open_flag);
1008         if (fd < 0) {
1009                 /* See if it works without O_NOATIME */
1010                 switch (sha1_file_open_flag) {
1011                 default:
1012                         fd = open(filename, O_RDONLY);
1013                         if (fd >= 0)
1014                                 break;
1015                 /* Fallthrough */
1016                 case 0:
1017                         return NULL;
1018                 }
1020                 /* If it failed once, it will probably fail again.
1021                  * Stop using O_NOATIME
1022                  */
1023                 sha1_file_open_flag = 0;
1024         }
1025         *size = xsize_t(st.st_size);
1026         map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1027         close(fd);
1028         return map;
1031 static int legacy_loose_object(unsigned char *map)
1033         unsigned int word;
1035         /*
1036          * Is it a zlib-compressed buffer? If so, the first byte
1037          * must be 0x78 (15-bit window size, deflated), and the
1038          * first 16-bit word is evenly divisible by 31
1039          */
1040         word = (map[0] << 8) + map[1];
1041         if (map[0] == 0x78 && !(word % 31))
1042                 return 1;
1043         else
1044                 return 0;
1047 unsigned long unpack_object_header_gently(const unsigned char *buf, unsigned long len, enum object_type *type, unsigned long *sizep)
1049         unsigned shift;
1050         unsigned char c;
1051         unsigned long size;
1052         unsigned long used = 0;
1054         c = buf[used++];
1055         *type = (c >> 4) & 7;
1056         size = c & 15;
1057         shift = 4;
1058         while (c & 0x80) {
1059                 if (len <= used)
1060                         return 0;
1061                 if (sizeof(long) * 8 <= shift)
1062                         return 0;
1063                 c = buf[used++];
1064                 size += (c & 0x7f) << shift;
1065                 shift += 7;
1066         }
1067         *sizep = size;
1068         return used;
1071 static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1073         unsigned long size, used;
1074         static const char valid_loose_object_type[8] = {
1075                 0, /* OBJ_EXT */
1076                 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1077                 0, /* "delta" and others are invalid in a loose object */
1078         };
1079         enum object_type type;
1081         /* Get the data stream */
1082         memset(stream, 0, sizeof(*stream));
1083         stream->next_in = map;
1084         stream->avail_in = mapsize;
1085         stream->next_out = buffer;
1086         stream->avail_out = bufsiz;
1088         if (legacy_loose_object(map)) {
1089                 inflateInit(stream);
1090                 return inflate(stream, 0);
1091         }
1094         /*
1095          * There used to be a second loose object header format which
1096          * was meant to mimic the in-pack format, allowing for direct
1097          * copy of the object data.  This format turned up not to be
1098          * really worth it and we don't write it any longer.  But we
1099          * can still read it.
1100          */
1101         used = unpack_object_header_gently(map, mapsize, &type, &size);
1102         if (!used || !valid_loose_object_type[type])
1103                 return -1;
1104         map += used;
1105         mapsize -= used;
1107         /* Set up the stream for the rest.. */
1108         stream->next_in = map;
1109         stream->avail_in = mapsize;
1110         inflateInit(stream);
1112         /* And generate the fake traditional header */
1113         stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1114                                          typename(type), size);
1115         return 0;
1118 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1120         int bytes = strlen(buffer) + 1;
1121         unsigned char *buf = xmalloc(1+size);
1122         unsigned long n;
1123         int status = Z_OK;
1125         n = stream->total_out - bytes;
1126         if (n > size)
1127                 n = size;
1128         memcpy(buf, (char *) buffer + bytes, n);
1129         bytes = n;
1130         if (bytes <= size) {
1131                 /*
1132                  * The above condition must be (bytes <= size), not
1133                  * (bytes < size).  In other words, even though we
1134                  * expect no more output and set avail_out to zer0,
1135                  * the input zlib stream may have bytes that express
1136                  * "this concludes the stream", and we *do* want to
1137                  * eat that input.
1138                  *
1139                  * Otherwise we would not be able to test that we
1140                  * consumed all the input to reach the expected size;
1141                  * we also want to check that zlib tells us that all
1142                  * went well with status == Z_STREAM_END at the end.
1143                  */
1144                 stream->next_out = buf + bytes;
1145                 stream->avail_out = size - bytes;
1146                 while (status == Z_OK)
1147                         status = inflate(stream, Z_FINISH);
1148         }
1149         buf[size] = 0;
1150         if (status == Z_STREAM_END && !stream->avail_in) {
1151                 inflateEnd(stream);
1152                 return buf;
1153         }
1155         if (status < 0)
1156                 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1157         else if (stream->avail_in)
1158                 error("garbage at end of loose object '%s'",
1159                       sha1_to_hex(sha1));
1160         free(buf);
1161         return NULL;
1164 /*
1165  * We used to just use "sscanf()", but that's actually way
1166  * too permissive for what we want to check. So do an anal
1167  * object header parse by hand.
1168  */
1169 static int parse_sha1_header(const char *hdr, unsigned long *sizep)
1171         char type[10];
1172         int i;
1173         unsigned long size;
1175         /*
1176          * The type can be at most ten bytes (including the
1177          * terminating '\0' that we add), and is followed by
1178          * a space.
1179          */
1180         i = 0;
1181         for (;;) {
1182                 char c = *hdr++;
1183                 if (c == ' ')
1184                         break;
1185                 type[i++] = c;
1186                 if (i >= sizeof(type))
1187                         return -1;
1188         }
1189         type[i] = 0;
1191         /*
1192          * The length must follow immediately, and be in canonical
1193          * decimal format (ie "010" is not valid).
1194          */
1195         size = *hdr++ - '0';
1196         if (size > 9)
1197                 return -1;
1198         if (size) {
1199                 for (;;) {
1200                         unsigned long c = *hdr - '0';
1201                         if (c > 9)
1202                                 break;
1203                         hdr++;
1204                         size = size * 10 + c;
1205                 }
1206         }
1207         *sizep = size;
1209         /*
1210          * The length must be followed by a zero byte
1211          */
1212         return *hdr ? -1 : type_from_string(type);
1215 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1217         int ret;
1218         z_stream stream;
1219         char hdr[8192];
1221         ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1222         if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1223                 return NULL;
1225         return unpack_sha1_rest(&stream, hdr, *size, sha1);
1228 unsigned long get_size_from_delta(struct packed_git *p,
1229                                   struct pack_window **w_curs,
1230                                   off_t curpos)
1232         const unsigned char *data;
1233         unsigned char delta_head[20], *in;
1234         z_stream stream;
1235         int st;
1237         memset(&stream, 0, sizeof(stream));
1238         stream.next_out = delta_head;
1239         stream.avail_out = sizeof(delta_head);
1241         inflateInit(&stream);
1242         do {
1243                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1244                 stream.next_in = in;
1245                 st = inflate(&stream, Z_FINISH);
1246                 curpos += stream.next_in - in;
1247         } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1248                  stream.total_out < sizeof(delta_head));
1249         inflateEnd(&stream);
1250         if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head))
1251                 die("delta data unpack-initial failed");
1253         /* Examine the initial part of the delta to figure out
1254          * the result size.
1255          */
1256         data = delta_head;
1258         /* ignore base size */
1259         get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1261         /* Read the result size */
1262         return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1265 static off_t get_delta_base(struct packed_git *p,
1266                                     struct pack_window **w_curs,
1267                                     off_t *curpos,
1268                                     enum object_type type,
1269                                     off_t delta_obj_offset)
1271         unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1272         off_t base_offset;
1274         /* use_pack() assured us we have [base_info, base_info + 20)
1275          * as a range that we can look at without walking off the
1276          * end of the mapped window.  Its actually the hash size
1277          * that is assured.  An OFS_DELTA longer than the hash size
1278          * is stupid, as then a REF_DELTA would be smaller to store.
1279          */
1280         if (type == OBJ_OFS_DELTA) {
1281                 unsigned used = 0;
1282                 unsigned char c = base_info[used++];
1283                 base_offset = c & 127;
1284                 while (c & 128) {
1285                         base_offset += 1;
1286                         if (!base_offset || MSB(base_offset, 7))
1287                                 die("offset value overflow for delta base object");
1288                         c = base_info[used++];
1289                         base_offset = (base_offset << 7) + (c & 127);
1290                 }
1291                 base_offset = delta_obj_offset - base_offset;
1292                 if (base_offset >= delta_obj_offset)
1293                         die("delta base offset out of bound");
1294                 *curpos += used;
1295         } else if (type == OBJ_REF_DELTA) {
1296                 /* The base entry _must_ be in the same pack */
1297                 base_offset = find_pack_entry_one(base_info, p);
1298                 if (!base_offset)
1299                         die("failed to find delta-pack base object %s",
1300                                 sha1_to_hex(base_info));
1301                 *curpos += 20;
1302         } else
1303                 die("I am totally screwed");
1304         return base_offset;
1307 /* forward declaration for a mutually recursive function */
1308 static int packed_object_info(struct packed_git *p, off_t offset,
1309                               unsigned long *sizep);
1311 static int packed_delta_info(struct packed_git *p,
1312                              struct pack_window **w_curs,
1313                              off_t curpos,
1314                              enum object_type type,
1315                              off_t obj_offset,
1316                              unsigned long *sizep)
1318         off_t base_offset;
1320         base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1321         type = packed_object_info(p, base_offset, NULL);
1323         /* We choose to only get the type of the base object and
1324          * ignore potentially corrupt pack file that expects the delta
1325          * based on a base with a wrong size.  This saves tons of
1326          * inflate() calls.
1327          */
1328         if (sizep)
1329                 *sizep = get_size_from_delta(p, w_curs, curpos);
1331         return type;
1334 static int unpack_object_header(struct packed_git *p,
1335                                 struct pack_window **w_curs,
1336                                 off_t *curpos,
1337                                 unsigned long *sizep)
1339         unsigned char *base;
1340         unsigned int left;
1341         unsigned long used;
1342         enum object_type type;
1344         /* use_pack() assures us we have [base, base + 20) available
1345          * as a range that we can look at at.  (Its actually the hash
1346          * size that is assured.)  With our object header encoding
1347          * the maximum deflated object size is 2^137, which is just
1348          * insane, so we know won't exceed what we have been given.
1349          */
1350         base = use_pack(p, w_curs, *curpos, &left);
1351         used = unpack_object_header_gently(base, left, &type, sizep);
1352         if (!used)
1353                 die("object offset outside of pack file");
1354         *curpos += used;
1356         return type;
1359 const char *packed_object_info_detail(struct packed_git *p,
1360                                       off_t obj_offset,
1361                                       unsigned long *size,
1362                                       unsigned long *store_size,
1363                                       unsigned int *delta_chain_length,
1364                                       unsigned char *base_sha1)
1366         struct pack_window *w_curs = NULL;
1367         off_t curpos;
1368         unsigned long dummy;
1369         unsigned char *next_sha1;
1370         enum object_type type;
1371         struct revindex_entry *revidx;
1373         *delta_chain_length = 0;
1374         curpos = obj_offset;
1375         type = unpack_object_header(p, &w_curs, &curpos, size);
1377         revidx = find_pack_revindex(p, obj_offset);
1378         *store_size = revidx[1].offset - obj_offset;
1380         for (;;) {
1381                 switch (type) {
1382                 default:
1383                         die("pack %s contains unknown object type %d",
1384                             p->pack_name, type);
1385                 case OBJ_COMMIT:
1386                 case OBJ_TREE:
1387                 case OBJ_BLOB:
1388                 case OBJ_TAG:
1389                         unuse_pack(&w_curs);
1390                         return typename(type);
1391                 case OBJ_OFS_DELTA:
1392                         obj_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1393                         if (*delta_chain_length == 0) {
1394                                 revidx = find_pack_revindex(p, obj_offset);
1395                                 hashcpy(base_sha1, nth_packed_object_sha1(p, revidx->nr));
1396                         }
1397                         break;
1398                 case OBJ_REF_DELTA:
1399                         next_sha1 = use_pack(p, &w_curs, curpos, NULL);
1400                         if (*delta_chain_length == 0)
1401                                 hashcpy(base_sha1, next_sha1);
1402                         obj_offset = find_pack_entry_one(next_sha1, p);
1403                         break;
1404                 }
1405                 (*delta_chain_length)++;
1406                 curpos = obj_offset;
1407                 type = unpack_object_header(p, &w_curs, &curpos, &dummy);
1408         }
1411 static int packed_object_info(struct packed_git *p, off_t obj_offset,
1412                               unsigned long *sizep)
1414         struct pack_window *w_curs = NULL;
1415         unsigned long size;
1416         off_t curpos = obj_offset;
1417         enum object_type type;
1419         type = unpack_object_header(p, &w_curs, &curpos, &size);
1421         switch (type) {
1422         case OBJ_OFS_DELTA:
1423         case OBJ_REF_DELTA:
1424                 type = packed_delta_info(p, &w_curs, curpos,
1425                                          type, obj_offset, sizep);
1426                 break;
1427         case OBJ_COMMIT:
1428         case OBJ_TREE:
1429         case OBJ_BLOB:
1430         case OBJ_TAG:
1431                 if (sizep)
1432                         *sizep = size;
1433                 break;
1434         default:
1435                 die("pack %s contains unknown object type %d",
1436                     p->pack_name, type);
1437         }
1438         unuse_pack(&w_curs);
1439         return type;
1442 static void *unpack_compressed_entry(struct packed_git *p,
1443                                     struct pack_window **w_curs,
1444                                     off_t curpos,
1445                                     unsigned long size)
1447         int st;
1448         z_stream stream;
1449         unsigned char *buffer, *in;
1451         buffer = xmalloc(size + 1);
1452         buffer[size] = 0;
1453         memset(&stream, 0, sizeof(stream));
1454         stream.next_out = buffer;
1455         stream.avail_out = size;
1457         inflateInit(&stream);
1458         do {
1459                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1460                 stream.next_in = in;
1461                 st = inflate(&stream, Z_FINISH);
1462                 curpos += stream.next_in - in;
1463         } while (st == Z_OK || st == Z_BUF_ERROR);
1464         inflateEnd(&stream);
1465         if ((st != Z_STREAM_END) || stream.total_out != size) {
1466                 free(buffer);
1467                 return NULL;
1468         }
1470         return buffer;
1473 #define MAX_DELTA_CACHE (256)
1475 static size_t delta_base_cached;
1477 static struct delta_base_cache_lru_list {
1478         struct delta_base_cache_lru_list *prev;
1479         struct delta_base_cache_lru_list *next;
1480 } delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1482 static struct delta_base_cache_entry {
1483         struct delta_base_cache_lru_list lru;
1484         void *data;
1485         struct packed_git *p;
1486         off_t base_offset;
1487         unsigned long size;
1488         enum object_type type;
1489 } delta_base_cache[MAX_DELTA_CACHE];
1491 static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1493         unsigned long hash;
1495         hash = (unsigned long)p + (unsigned long)base_offset;
1496         hash += (hash >> 8) + (hash >> 16);
1497         return hash % MAX_DELTA_CACHE;
1500 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1501         unsigned long *base_size, enum object_type *type, int keep_cache)
1503         void *ret;
1504         unsigned long hash = pack_entry_hash(p, base_offset);
1505         struct delta_base_cache_entry *ent = delta_base_cache + hash;
1507         ret = ent->data;
1508         if (ret && ent->p == p && ent->base_offset == base_offset)
1509                 goto found_cache_entry;
1510         return unpack_entry(p, base_offset, type, base_size);
1512 found_cache_entry:
1513         if (!keep_cache) {
1514                 ent->data = NULL;
1515                 ent->lru.next->prev = ent->lru.prev;
1516                 ent->lru.prev->next = ent->lru.next;
1517                 delta_base_cached -= ent->size;
1518         } else {
1519                 ret = xmemdupz(ent->data, ent->size);
1520         }
1521         *type = ent->type;
1522         *base_size = ent->size;
1523         return ret;
1526 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1528         if (ent->data) {
1529                 free(ent->data);
1530                 ent->data = NULL;
1531                 ent->lru.next->prev = ent->lru.prev;
1532                 ent->lru.prev->next = ent->lru.next;
1533                 delta_base_cached -= ent->size;
1534         }
1537 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1538         void *base, unsigned long base_size, enum object_type type)
1540         unsigned long hash = pack_entry_hash(p, base_offset);
1541         struct delta_base_cache_entry *ent = delta_base_cache + hash;
1542         struct delta_base_cache_lru_list *lru;
1544         release_delta_base_cache(ent);
1545         delta_base_cached += base_size;
1547         for (lru = delta_base_cache_lru.next;
1548              delta_base_cached > delta_base_cache_limit
1549              && lru != &delta_base_cache_lru;
1550              lru = lru->next) {
1551                 struct delta_base_cache_entry *f = (void *)lru;
1552                 if (f->type == OBJ_BLOB)
1553                         release_delta_base_cache(f);
1554         }
1555         for (lru = delta_base_cache_lru.next;
1556              delta_base_cached > delta_base_cache_limit
1557              && lru != &delta_base_cache_lru;
1558              lru = lru->next) {
1559                 struct delta_base_cache_entry *f = (void *)lru;
1560                 release_delta_base_cache(f);
1561         }
1563         ent->p = p;
1564         ent->base_offset = base_offset;
1565         ent->type = type;
1566         ent->data = base;
1567         ent->size = base_size;
1568         ent->lru.next = &delta_base_cache_lru;
1569         ent->lru.prev = delta_base_cache_lru.prev;
1570         delta_base_cache_lru.prev->next = &ent->lru;
1571         delta_base_cache_lru.prev = &ent->lru;
1574 static void *unpack_delta_entry(struct packed_git *p,
1575                                 struct pack_window **w_curs,
1576                                 off_t curpos,
1577                                 unsigned long delta_size,
1578                                 off_t obj_offset,
1579                                 enum object_type *type,
1580                                 unsigned long *sizep)
1582         void *delta_data, *result, *base;
1583         unsigned long base_size;
1584         off_t base_offset;
1586         base_offset = get_delta_base(p, w_curs, &curpos, *type, obj_offset);
1587         base = cache_or_unpack_entry(p, base_offset, &base_size, type, 0);
1588         if (!base)
1589                 die("failed to read delta base object"
1590                     " at %"PRIuMAX" from %s",
1591                     (uintmax_t)base_offset, p->pack_name);
1593         delta_data = unpack_compressed_entry(p, w_curs, curpos, delta_size);
1594         if (!delta_data)
1595                 die("failed to unpack compressed delta"
1596                     " at %"PRIuMAX" from %s",
1597                     (uintmax_t)curpos, p->pack_name);
1598         result = patch_delta(base, base_size,
1599                              delta_data, delta_size,
1600                              sizep);
1601         if (!result)
1602                 die("failed to apply delta");
1603         free(delta_data);
1604         add_delta_base_cache(p, base_offset, base, base_size, *type);
1605         return result;
1608 void *unpack_entry(struct packed_git *p, off_t obj_offset,
1609                    enum object_type *type, unsigned long *sizep)
1611         struct pack_window *w_curs = NULL;
1612         off_t curpos = obj_offset;
1613         void *data;
1615         *type = unpack_object_header(p, &w_curs, &curpos, sizep);
1616         switch (*type) {
1617         case OBJ_OFS_DELTA:
1618         case OBJ_REF_DELTA:
1619                 data = unpack_delta_entry(p, &w_curs, curpos, *sizep,
1620                                           obj_offset, type, sizep);
1621                 break;
1622         case OBJ_COMMIT:
1623         case OBJ_TREE:
1624         case OBJ_BLOB:
1625         case OBJ_TAG:
1626                 data = unpack_compressed_entry(p, &w_curs, curpos, *sizep);
1627                 break;
1628         default:
1629                 die("unknown object type %i in %s", *type, p->pack_name);
1630         }
1631         unuse_pack(&w_curs);
1632         return data;
1635 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1636                                             uint32_t n)
1638         const unsigned char *index = p->index_data;
1639         if (!index) {
1640                 if (open_pack_index(p))
1641                         return NULL;
1642                 index = p->index_data;
1643         }
1644         if (n >= p->num_objects)
1645                 return NULL;
1646         index += 4 * 256;
1647         if (p->index_version == 1) {
1648                 return index + 24 * n + 4;
1649         } else {
1650                 index += 8;
1651                 return index + 20 * n;
1652         }
1655 static off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1657         const unsigned char *index = p->index_data;
1658         index += 4 * 256;
1659         if (p->index_version == 1) {
1660                 return ntohl(*((uint32_t *)(index + 24 * n)));
1661         } else {
1662                 uint32_t off;
1663                 index += 8 + p->num_objects * (20 + 4);
1664                 off = ntohl(*((uint32_t *)(index + 4 * n)));
1665                 if (!(off & 0x80000000))
1666                         return off;
1667                 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1668                 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
1669                                    ntohl(*((uint32_t *)(index + 4)));
1670         }
1673 off_t find_pack_entry_one(const unsigned char *sha1,
1674                                   struct packed_git *p)
1676         const uint32_t *level1_ofs = p->index_data;
1677         const unsigned char *index = p->index_data;
1678         unsigned hi, lo;
1680         if (!index) {
1681                 if (open_pack_index(p))
1682                         return 0;
1683                 level1_ofs = p->index_data;
1684                 index = p->index_data;
1685         }
1686         if (p->index_version > 1) {
1687                 level1_ofs += 2;
1688                 index += 8;
1689         }
1690         index += 4 * 256;
1691         hi = ntohl(level1_ofs[*sha1]);
1692         lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1694         do {
1695                 unsigned mi = (lo + hi) / 2;
1696                 unsigned x = (p->index_version > 1) ? (mi * 20) : (mi * 24 + 4);
1697                 int cmp = hashcmp(index + x, sha1);
1698                 if (!cmp)
1699                         return nth_packed_object_offset(p, mi);
1700                 if (cmp > 0)
1701                         hi = mi;
1702                 else
1703                         lo = mi+1;
1704         } while (lo < hi);
1705         return 0;
1708 int matches_pack_name(struct packed_git *p, const char *name)
1710         const char *last_c, *c;
1712         if (!strcmp(p->pack_name, name))
1713                 return 1;
1715         for (c = p->pack_name, last_c = c; *c;)
1716                 if (*c == '/')
1717                         last_c = ++c;
1718                 else
1719                         ++c;
1720         if (!strcmp(last_c, name))
1721                 return 1;
1723         return 0;
1726 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e, const char **ignore_packed)
1728         static struct packed_git *last_found = (void *)1;
1729         struct packed_git *p;
1730         off_t offset;
1732         prepare_packed_git();
1733         if (!packed_git)
1734                 return 0;
1735         p = (last_found == (void *)1) ? packed_git : last_found;
1737         do {
1738                 if (ignore_packed) {
1739                         const char **ig;
1740                         for (ig = ignore_packed; *ig; ig++)
1741                                 if (matches_pack_name(p, *ig))
1742                                         break;
1743                         if (*ig)
1744                                 goto next;
1745                 }
1747                 offset = find_pack_entry_one(sha1, p);
1748                 if (offset) {
1749                         /*
1750                          * We are about to tell the caller where they can
1751                          * locate the requested object.  We better make
1752                          * sure the packfile is still here and can be
1753                          * accessed before supplying that answer, as
1754                          * it may have been deleted since the index
1755                          * was loaded!
1756                          */
1757                         if (p->pack_fd == -1 && open_packed_git(p)) {
1758                                 error("packfile %s cannot be accessed", p->pack_name);
1759                                 goto next;
1760                         }
1761                         e->offset = offset;
1762                         e->p = p;
1763                         hashcpy(e->sha1, sha1);
1764                         last_found = p;
1765                         return 1;
1766                 }
1768                 next:
1769                 if (p == last_found)
1770                         p = packed_git;
1771                 else
1772                         p = p->next;
1773                 if (p == last_found)
1774                         p = p->next;
1775         } while (p);
1776         return 0;
1779 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1780                                   struct packed_git *packs)
1782         struct packed_git *p;
1784         for (p = packs; p; p = p->next) {
1785                 if (find_pack_entry_one(sha1, p))
1786                         return p;
1787         }
1788         return NULL;
1792 static int sha1_loose_object_info(const unsigned char *sha1, unsigned long *sizep)
1794         int status;
1795         unsigned long mapsize, size;
1796         void *map;
1797         z_stream stream;
1798         char hdr[32];
1800         map = map_sha1_file(sha1, &mapsize);
1801         if (!map)
1802                 return error("unable to find %s", sha1_to_hex(sha1));
1803         if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1804                 status = error("unable to unpack %s header",
1805                                sha1_to_hex(sha1));
1806         else if ((status = parse_sha1_header(hdr, &size)) < 0)
1807                 status = error("unable to parse %s header", sha1_to_hex(sha1));
1808         else if (sizep)
1809                 *sizep = size;
1810         inflateEnd(&stream);
1811         munmap(map, mapsize);
1812         return status;
1815 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
1817         struct pack_entry e;
1819         if (!find_pack_entry(sha1, &e, NULL)) {
1820                 reprepare_packed_git();
1821                 if (!find_pack_entry(sha1, &e, NULL))
1822                         return sha1_loose_object_info(sha1, sizep);
1823         }
1824         return packed_object_info(e.p, e.offset, sizep);
1827 static void *read_packed_sha1(const unsigned char *sha1,
1828                               enum object_type *type, unsigned long *size)
1830         struct pack_entry e;
1832         if (!find_pack_entry(sha1, &e, NULL))
1833                 return NULL;
1834         else
1835                 return cache_or_unpack_entry(e.p, e.offset, size, type, 1);
1838 /*
1839  * This is meant to hold a *small* number of objects that you would
1840  * want read_sha1_file() to be able to return, but yet you do not want
1841  * to write them into the object store (e.g. a browse-only
1842  * application).
1843  */
1844 static struct cached_object {
1845         unsigned char sha1[20];
1846         enum object_type type;
1847         void *buf;
1848         unsigned long size;
1849 } *cached_objects;
1850 static int cached_object_nr, cached_object_alloc;
1852 static struct cached_object empty_tree = {
1853         /* empty tree sha1: 4b825dc642cb6eb9a060e54bf8d69288fbee4904 */
1854         "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60"
1855         "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04",
1856         OBJ_TREE,
1857         "",
1858         0
1859 };
1861 static struct cached_object *find_cached_object(const unsigned char *sha1)
1863         int i;
1864         struct cached_object *co = cached_objects;
1866         for (i = 0; i < cached_object_nr; i++, co++) {
1867                 if (!hashcmp(co->sha1, sha1))
1868                         return co;
1869         }
1870         if (!hashcmp(sha1, empty_tree.sha1))
1871                 return &empty_tree;
1872         return NULL;
1875 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
1876                       unsigned char *sha1)
1878         struct cached_object *co;
1880         hash_sha1_file(buf, len, typename(type), sha1);
1881         if (has_sha1_file(sha1) || find_cached_object(sha1))
1882                 return 0;
1883         if (cached_object_alloc <= cached_object_nr) {
1884                 cached_object_alloc = alloc_nr(cached_object_alloc);
1885                 cached_objects = xrealloc(cached_objects,
1886                                           sizeof(*cached_objects) *
1887                                           cached_object_alloc);
1888         }
1889         co = &cached_objects[cached_object_nr++];
1890         co->size = len;
1891         co->type = type;
1892         co->buf = xmalloc(len);
1893         memcpy(co->buf, buf, len);
1894         hashcpy(co->sha1, sha1);
1895         return 0;
1898 void *read_sha1_file(const unsigned char *sha1, enum object_type *type,
1899                      unsigned long *size)
1901         unsigned long mapsize;
1902         void *map, *buf;
1903         struct cached_object *co;
1905         co = find_cached_object(sha1);
1906         if (co) {
1907                 *type = co->type;
1908                 *size = co->size;
1909                 return xmemdupz(co->buf, co->size);
1910         }
1912         buf = read_packed_sha1(sha1, type, size);
1913         if (buf)
1914                 return buf;
1915         map = map_sha1_file(sha1, &mapsize);
1916         if (map) {
1917                 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
1918                 munmap(map, mapsize);
1919                 return buf;
1920         }
1921         reprepare_packed_git();
1922         return read_packed_sha1(sha1, type, size);
1925 void *read_object_with_reference(const unsigned char *sha1,
1926                                  const char *required_type_name,
1927                                  unsigned long *size,
1928                                  unsigned char *actual_sha1_return)
1930         enum object_type type, required_type;
1931         void *buffer;
1932         unsigned long isize;
1933         unsigned char actual_sha1[20];
1935         required_type = type_from_string(required_type_name);
1936         hashcpy(actual_sha1, sha1);
1937         while (1) {
1938                 int ref_length = -1;
1939                 const char *ref_type = NULL;
1941                 buffer = read_sha1_file(actual_sha1, &type, &isize);
1942                 if (!buffer)
1943                         return NULL;
1944                 if (type == required_type) {
1945                         *size = isize;
1946                         if (actual_sha1_return)
1947                                 hashcpy(actual_sha1_return, actual_sha1);
1948                         return buffer;
1949                 }
1950                 /* Handle references */
1951                 else if (type == OBJ_COMMIT)
1952                         ref_type = "tree ";
1953                 else if (type == OBJ_TAG)
1954                         ref_type = "object ";
1955                 else {
1956                         free(buffer);
1957                         return NULL;
1958                 }
1959                 ref_length = strlen(ref_type);
1961                 if (ref_length + 40 > isize ||
1962                     memcmp(buffer, ref_type, ref_length) ||
1963                     get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
1964                         free(buffer);
1965                         return NULL;
1966                 }
1967                 free(buffer);
1968                 /* Now we have the ID of the referred-to object in
1969                  * actual_sha1.  Check again. */
1970         }
1973 static void write_sha1_file_prepare(const void *buf, unsigned long len,
1974                                     const char *type, unsigned char *sha1,
1975                                     char *hdr, int *hdrlen)
1977         SHA_CTX c;
1979         /* Generate the header */
1980         *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
1982         /* Sha1.. */
1983         SHA1_Init(&c);
1984         SHA1_Update(&c, hdr, *hdrlen);
1985         SHA1_Update(&c, buf, len);
1986         SHA1_Final(sha1, &c);
1989 /*
1990  * Link the tempfile to the final place, possibly creating the
1991  * last directory level as you do so.
1992  *
1993  * Returns the errno on failure, 0 on success.
1994  */
1995 static int link_temp_to_file(const char *tmpfile, const char *filename)
1997         int ret;
1998         char *dir;
2000         if (!link(tmpfile, filename))
2001                 return 0;
2003         /*
2004          * Try to mkdir the last path component if that failed.
2005          *
2006          * Re-try the "link()" regardless of whether the mkdir
2007          * succeeds, since a race might mean that somebody
2008          * else succeeded.
2009          */
2010         ret = errno;
2011         dir = strrchr(filename, '/');
2012         if (dir) {
2013                 *dir = 0;
2014                 if (!mkdir(filename, 0777) && adjust_shared_perm(filename)) {
2015                         *dir = '/';
2016                         return -2;
2017                 }
2018                 *dir = '/';
2019                 if (!link(tmpfile, filename))
2020                         return 0;
2021                 ret = errno;
2022         }
2023         return ret;
2026 /*
2027  * Move the just written object into its final resting place
2028  */
2029 int move_temp_to_file(const char *tmpfile, const char *filename)
2031         int ret = link_temp_to_file(tmpfile, filename);
2033         /*
2034          * Coda hack - coda doesn't like cross-directory links,
2035          * so we fall back to a rename, which will mean that it
2036          * won't be able to check collisions, but that's not a
2037          * big deal.
2038          *
2039          * The same holds for FAT formatted media.
2040          *
2041          * When this succeeds, we just return 0. We have nothing
2042          * left to unlink.
2043          */
2044         if (ret && ret != EEXIST) {
2045                 if (!rename(tmpfile, filename))
2046                         return 0;
2047                 ret = errno;
2048         }
2049         unlink(tmpfile);
2050         if (ret) {
2051                 if (ret != EEXIST) {
2052                         return error("unable to write sha1 filename %s: %s\n", filename, strerror(ret));
2053                 }
2054                 /* FIXME!!! Collision check here ? */
2055         }
2057         return 0;
2060 static int write_buffer(int fd, const void *buf, size_t len)
2062         if (write_in_full(fd, buf, len) < 0)
2063                 return error("file write error (%s)", strerror(errno));
2064         return 0;
2067 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2068                    unsigned char *sha1)
2070         char hdr[32];
2071         int hdrlen;
2072         write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2073         return 0;
2076 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
2078         int size, ret;
2079         unsigned char *compressed;
2080         z_stream stream;
2081         unsigned char sha1[20];
2082         char *filename;
2083         static char tmpfile[PATH_MAX];
2084         char hdr[32];
2085         int fd, hdrlen;
2087         /* Normally if we have it in the pack then we do not bother writing
2088          * it out into .git/objects/??/?{38} file.
2089          */
2090         write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2091         filename = sha1_file_name(sha1);
2092         if (returnsha1)
2093                 hashcpy(returnsha1, sha1);
2094         if (has_sha1_file(sha1))
2095                 return 0;
2096         fd = open(filename, O_RDONLY);
2097         if (fd >= 0) {
2098                 /*
2099                  * FIXME!!! We might do collision checking here, but we'd
2100                  * need to uncompress the old file and check it. Later.
2101                  */
2102                 close(fd);
2103                 return 0;
2104         }
2106         if (errno != ENOENT) {
2107                 return error("sha1 file %s: %s\n", filename, strerror(errno));
2108         }
2110         snprintf(tmpfile, sizeof(tmpfile), "%s/tmp_obj_XXXXXX", get_object_directory());
2112         fd = mkstemp(tmpfile);
2113         if (fd < 0) {
2114                 if (errno == EPERM)
2115                         return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2116                 else
2117                         return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2118         }
2120         /* Set it up */
2121         memset(&stream, 0, sizeof(stream));
2122         deflateInit(&stream, zlib_compression_level);
2123         size = 8 + deflateBound(&stream, len+hdrlen);
2124         compressed = xmalloc(size);
2126         /* Compress it */
2127         stream.next_out = compressed;
2128         stream.avail_out = size;
2130         /* First header.. */
2131         stream.next_in = (unsigned char *)hdr;
2132         stream.avail_in = hdrlen;
2133         while (deflate(&stream, 0) == Z_OK)
2134                 /* nothing */;
2136         /* Then the data itself.. */
2137         stream.next_in = buf;
2138         stream.avail_in = len;
2139         ret = deflate(&stream, Z_FINISH);
2140         if (ret != Z_STREAM_END)
2141                 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2143         ret = deflateEnd(&stream);
2144         if (ret != Z_OK)
2145                 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2147         size = stream.total_out;
2149         if (write_buffer(fd, compressed, size) < 0)
2150                 die("unable to write sha1 file");
2151         fchmod(fd, 0444);
2152         if (close(fd))
2153                 die("unable to write sha1 file");
2154         free(compressed);
2156         return move_temp_to_file(tmpfile, filename);
2159 /*
2160  * We need to unpack and recompress the object for writing
2161  * it out to a different file.
2162  */
2163 static void *repack_object(const unsigned char *sha1, unsigned long *objsize)
2165         size_t size;
2166         z_stream stream;
2167         unsigned char *unpacked;
2168         unsigned long len;
2169         enum object_type type;
2170         char hdr[32];
2171         int hdrlen;
2172         void *buf;
2174         /* need to unpack and recompress it by itself */
2175         unpacked = read_packed_sha1(sha1, &type, &len);
2176         if (!unpacked)
2177                 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2179         hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
2181         /* Set it up */
2182         memset(&stream, 0, sizeof(stream));
2183         deflateInit(&stream, zlib_compression_level);
2184         size = deflateBound(&stream, len + hdrlen);
2185         buf = xmalloc(size);
2187         /* Compress it */
2188         stream.next_out = buf;
2189         stream.avail_out = size;
2191         /* First header.. */
2192         stream.next_in = (void *)hdr;
2193         stream.avail_in = hdrlen;
2194         while (deflate(&stream, 0) == Z_OK)
2195                 /* nothing */;
2197         /* Then the data itself.. */
2198         stream.next_in = unpacked;
2199         stream.avail_in = len;
2200         while (deflate(&stream, Z_FINISH) == Z_OK)
2201                 /* nothing */;
2202         deflateEnd(&stream);
2203         free(unpacked);
2205         *objsize = stream.total_out;
2206         return buf;
2209 int write_sha1_to_fd(int fd, const unsigned char *sha1)
2211         int retval;
2212         unsigned long objsize;
2213         void *buf = map_sha1_file(sha1, &objsize);
2215         if (buf) {
2216                 retval = write_buffer(fd, buf, objsize);
2217                 munmap(buf, objsize);
2218                 return retval;
2219         }
2221         buf = repack_object(sha1, &objsize);
2222         retval = write_buffer(fd, buf, objsize);
2223         free(buf);
2224         return retval;
2227 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
2228                        size_t bufsize, size_t *bufposn)
2230         char tmpfile[PATH_MAX];
2231         int local;
2232         z_stream stream;
2233         unsigned char real_sha1[20];
2234         unsigned char discard[4096];
2235         int ret;
2236         SHA_CTX c;
2238         snprintf(tmpfile, sizeof(tmpfile), "%s/tmp_obj_XXXXXX", get_object_directory());
2240         local = mkstemp(tmpfile);
2241         if (local < 0) {
2242                 if (errno == EPERM)
2243                         return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2244                 else
2245                         return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2246         }
2248         memset(&stream, 0, sizeof(stream));
2250         inflateInit(&stream);
2252         SHA1_Init(&c);
2254         do {
2255                 ssize_t size;
2256                 if (*bufposn) {
2257                         stream.avail_in = *bufposn;
2258                         stream.next_in = (unsigned char *) buffer;
2259                         do {
2260                                 stream.next_out = discard;
2261                                 stream.avail_out = sizeof(discard);
2262                                 ret = inflate(&stream, Z_SYNC_FLUSH);
2263                                 SHA1_Update(&c, discard, sizeof(discard) -
2264                                             stream.avail_out);
2265                         } while (stream.avail_in && ret == Z_OK);
2266                         if (write_buffer(local, buffer, *bufposn - stream.avail_in) < 0)
2267                                 die("unable to write sha1 file");
2268                         memmove(buffer, buffer + *bufposn - stream.avail_in,
2269                                 stream.avail_in);
2270                         *bufposn = stream.avail_in;
2271                         if (ret != Z_OK)
2272                                 break;
2273                 }
2274                 size = xread(fd, buffer + *bufposn, bufsize - *bufposn);
2275                 if (size <= 0) {
2276                         close(local);
2277                         unlink(tmpfile);
2278                         if (!size)
2279                                 return error("Connection closed?");
2280                         perror("Reading from connection");
2281                         return -1;
2282                 }
2283                 *bufposn += size;
2284         } while (1);
2285         inflateEnd(&stream);
2287         fchmod(local, 0444);
2288         if (close(local) != 0)
2289                 die("unable to write sha1 file");
2290         SHA1_Final(real_sha1, &c);
2291         if (ret != Z_STREAM_END) {
2292                 unlink(tmpfile);
2293                 return error("File %s corrupted", sha1_to_hex(sha1));
2294         }
2295         if (hashcmp(sha1, real_sha1)) {
2296                 unlink(tmpfile);
2297                 return error("File %s has bad hash", sha1_to_hex(sha1));
2298         }
2300         return move_temp_to_file(tmpfile, sha1_file_name(sha1));
2303 int has_pack_index(const unsigned char *sha1)
2305         struct stat st;
2306         if (stat(sha1_pack_index_name(sha1), &st))
2307                 return 0;
2308         return 1;
2311 int has_pack_file(const unsigned char *sha1)
2313         struct stat st;
2314         if (stat(sha1_pack_name(sha1), &st))
2315                 return 0;
2316         return 1;
2319 int has_sha1_pack(const unsigned char *sha1, const char **ignore_packed)
2321         struct pack_entry e;
2322         return find_pack_entry(sha1, &e, ignore_packed);
2325 int has_sha1_file(const unsigned char *sha1)
2327         struct stat st;
2328         struct pack_entry e;
2330         if (find_pack_entry(sha1, &e, NULL))
2331                 return 1;
2332         return find_sha1_file(sha1, &st) ? 1 : 0;
2335 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
2337         struct strbuf buf;
2338         int ret;
2340         strbuf_init(&buf, 0);
2341         if (strbuf_read(&buf, fd, 4096) < 0) {
2342                 strbuf_release(&buf);
2343                 return -1;
2344         }
2346         if (!type)
2347                 type = blob_type;
2348         if (write_object)
2349                 ret = write_sha1_file(buf.buf, buf.len, type, sha1);
2350         else
2351                 ret = hash_sha1_file(buf.buf, buf.len, type, sha1);
2352         strbuf_release(&buf);
2354         return ret;
2357 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object,
2358              enum object_type type, const char *path)
2360         size_t size = xsize_t(st->st_size);
2361         void *buf = NULL;
2362         int ret, re_allocated = 0;
2364         if (size)
2365                 buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2366         close(fd);
2368         if (!type)
2369                 type = OBJ_BLOB;
2371         /*
2372          * Convert blobs to git internal format
2373          */
2374         if ((type == OBJ_BLOB) && S_ISREG(st->st_mode)) {
2375                 struct strbuf nbuf;
2376                 strbuf_init(&nbuf, 0);
2377                 if (convert_to_git(path, buf, size, &nbuf,
2378                                    write_object ? safe_crlf : 0)) {
2379                         munmap(buf, size);
2380                         buf = strbuf_detach(&nbuf, &size);
2381                         re_allocated = 1;
2382                 }
2383         }
2385         if (write_object)
2386                 ret = write_sha1_file(buf, size, typename(type), sha1);
2387         else
2388                 ret = hash_sha1_file(buf, size, typename(type), sha1);
2389         if (re_allocated) {
2390                 free(buf);
2391                 return ret;
2392         }
2393         if (size)
2394                 munmap(buf, size);
2395         return ret;
2398 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
2400         int fd;
2401         char *target;
2402         size_t len;
2404         switch (st->st_mode & S_IFMT) {
2405         case S_IFREG:
2406                 fd = open(path, O_RDONLY);
2407                 if (fd < 0)
2408                         return error("open(\"%s\"): %s", path,
2409                                      strerror(errno));
2410                 if (index_fd(sha1, fd, st, write_object, OBJ_BLOB, path) < 0)
2411                         return error("%s: failed to insert into database",
2412                                      path);
2413                 break;
2414         case S_IFLNK:
2415                 len = xsize_t(st->st_size);
2416                 target = xmalloc(len + 1);
2417                 if (readlink(path, target, len + 1) != st->st_size) {
2418                         char *errstr = strerror(errno);
2419                         free(target);
2420                         return error("readlink(\"%s\"): %s", path,
2421                                      errstr);
2422                 }
2423                 if (!write_object)
2424                         hash_sha1_file(target, len, blob_type, sha1);
2425                 else if (write_sha1_file(target, len, blob_type, sha1))
2426                         return error("%s: failed to insert into database",
2427                                      path);
2428                 free(target);
2429                 break;
2430         case S_IFDIR:
2431                 return resolve_gitlink_ref(path, "HEAD", sha1);
2432         default:
2433                 return error("%s: unsupported file type", path);
2434         }
2435         return 0;
2438 int read_pack_header(int fd, struct pack_header *header)
2440         char *c = (char*)header;
2441         ssize_t remaining = sizeof(struct pack_header);
2442         do {
2443                 ssize_t r = xread(fd, c, remaining);
2444                 if (r <= 0)
2445                         /* "eof before pack header was fully read" */
2446                         return PH_ERROR_EOF;
2447                 remaining -= r;
2448                 c += r;
2449         } while (remaining > 0);
2450         if (header->hdr_signature != htonl(PACK_SIGNATURE))
2451                 /* "protocol error (pack signature mismatch detected)" */
2452                 return PH_ERROR_PACK_SIGNATURE;
2453         if (!pack_version_ok(header->hdr_version))
2454                 /* "protocol error (pack version unsupported)" */
2455                 return PH_ERROR_PROTOCOL;
2456         return 0;