]> asedeno.scripts.mit.edu Git - git.git/blob - sha1_file.c
push: receiver end advertises refs from alternate repositories
[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"
18 #include "sha1-lookup.h"
19
20 #ifndef O_NOATIME
21 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
22 #define O_NOATIME 01000000
23 #else
24 #define O_NOATIME 0
25 #endif
26 #endif
27
28 #ifdef NO_C99_FORMAT
29 #define SZ_FMT "lu"
30 static unsigned long sz_fmt(size_t s) { return (unsigned long)s; }
31 #else
32 #define SZ_FMT "zu"
33 static size_t sz_fmt(size_t s) { return s; }
34 #endif
35
36 const unsigned char null_sha1[20];
37
38 const signed char hexval_table[256] = {
39          -1, -1, -1, -1, -1, -1, -1, -1,                /* 00-07 */
40          -1, -1, -1, -1, -1, -1, -1, -1,                /* 08-0f */
41          -1, -1, -1, -1, -1, -1, -1, -1,                /* 10-17 */
42          -1, -1, -1, -1, -1, -1, -1, -1,                /* 18-1f */
43          -1, -1, -1, -1, -1, -1, -1, -1,                /* 20-27 */
44          -1, -1, -1, -1, -1, -1, -1, -1,                /* 28-2f */
45           0,  1,  2,  3,  4,  5,  6,  7,                /* 30-37 */
46           8,  9, -1, -1, -1, -1, -1, -1,                /* 38-3f */
47          -1, 10, 11, 12, 13, 14, 15, -1,                /* 40-47 */
48          -1, -1, -1, -1, -1, -1, -1, -1,                /* 48-4f */
49          -1, -1, -1, -1, -1, -1, -1, -1,                /* 50-57 */
50          -1, -1, -1, -1, -1, -1, -1, -1,                /* 58-5f */
51          -1, 10, 11, 12, 13, 14, 15, -1,                /* 60-67 */
52          -1, -1, -1, -1, -1, -1, -1, -1,                /* 68-67 */
53          -1, -1, -1, -1, -1, -1, -1, -1,                /* 70-77 */
54          -1, -1, -1, -1, -1, -1, -1, -1,                /* 78-7f */
55          -1, -1, -1, -1, -1, -1, -1, -1,                /* 80-87 */
56          -1, -1, -1, -1, -1, -1, -1, -1,                /* 88-8f */
57          -1, -1, -1, -1, -1, -1, -1, -1,                /* 90-97 */
58          -1, -1, -1, -1, -1, -1, -1, -1,                /* 98-9f */
59          -1, -1, -1, -1, -1, -1, -1, -1,                /* a0-a7 */
60          -1, -1, -1, -1, -1, -1, -1, -1,                /* a8-af */
61          -1, -1, -1, -1, -1, -1, -1, -1,                /* b0-b7 */
62          -1, -1, -1, -1, -1, -1, -1, -1,                /* b8-bf */
63          -1, -1, -1, -1, -1, -1, -1, -1,                /* c0-c7 */
64          -1, -1, -1, -1, -1, -1, -1, -1,                /* c8-cf */
65          -1, -1, -1, -1, -1, -1, -1, -1,                /* d0-d7 */
66          -1, -1, -1, -1, -1, -1, -1, -1,                /* d8-df */
67          -1, -1, -1, -1, -1, -1, -1, -1,                /* e0-e7 */
68          -1, -1, -1, -1, -1, -1, -1, -1,                /* e8-ef */
69          -1, -1, -1, -1, -1, -1, -1, -1,                /* f0-f7 */
70          -1, -1, -1, -1, -1, -1, -1, -1,                /* f8-ff */
71 };
72
73 int get_sha1_hex(const char *hex, unsigned char *sha1)
74 {
75         int i;
76         for (i = 0; i < 20; i++) {
77                 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
78                 if (val & ~0xff)
79                         return -1;
80                 *sha1++ = val;
81                 hex += 2;
82         }
83         return 0;
84 }
85
86 static inline int offset_1st_component(const char *path)
87 {
88         if (has_dos_drive_prefix(path))
89                 return 2 + (path[2] == '/');
90         return *path == '/';
91 }
92
93 int safe_create_leading_directories(char *path)
94 {
95         char *pos = path + offset_1st_component(path);
96         struct stat st;
97
98         while (pos) {
99                 pos = strchr(pos, '/');
100                 if (!pos)
101                         break;
102                 *pos = 0;
103                 if (!stat(path, &st)) {
104                         /* path exists */
105                         if (!S_ISDIR(st.st_mode)) {
106                                 *pos = '/';
107                                 return -3;
108                         }
109                 }
110                 else if (mkdir(path, 0777)) {
111                         *pos = '/';
112                         return -1;
113                 }
114                 else if (adjust_shared_perm(path)) {
115                         *pos = '/';
116                         return -2;
117                 }
118                 *pos++ = '/';
119         }
120         return 0;
121 }
122
123 int safe_create_leading_directories_const(const char *path)
124 {
125         /* path points to cache entries, so xstrdup before messing with it */
126         char *buf = xstrdup(path);
127         int result = safe_create_leading_directories(buf);
128         free(buf);
129         return result;
130 }
131
132 char *sha1_to_hex(const unsigned char *sha1)
133 {
134         static int bufno;
135         static char hexbuffer[4][50];
136         static const char hex[] = "0123456789abcdef";
137         char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
138         int i;
139
140         for (i = 0; i < 20; i++) {
141                 unsigned int val = *sha1++;
142                 *buf++ = hex[val >> 4];
143                 *buf++ = hex[val & 0xf];
144         }
145         *buf = '\0';
146
147         return buffer;
148 }
149
150 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
151 {
152         int i;
153         for (i = 0; i < 20; i++) {
154                 static char hex[] = "0123456789abcdef";
155                 unsigned int val = sha1[i];
156                 char *pos = pathbuf + i*2 + (i > 0);
157                 *pos++ = hex[val >> 4];
158                 *pos = hex[val & 0xf];
159         }
160 }
161
162 /*
163  * NOTE! This returns a statically allocated buffer, so you have to be
164  * careful about using it. Do an "xstrdup()" if you need to save the
165  * filename.
166  *
167  * Also note that this returns the location for creating.  Reading
168  * SHA1 file can happen from any alternate directory listed in the
169  * DB_ENVIRONMENT environment variable if it is not found in
170  * the primary object database.
171  */
172 char *sha1_file_name(const unsigned char *sha1)
173 {
174         static char *name, *base;
175
176         if (!base) {
177                 const char *sha1_file_directory = get_object_directory();
178                 int len = strlen(sha1_file_directory);
179                 base = xmalloc(len + 60);
180                 memcpy(base, sha1_file_directory, len);
181                 memset(base+len, 0, 60);
182                 base[len] = '/';
183                 base[len+3] = '/';
184                 name = base + len + 1;
185         }
186         fill_sha1_path(name, sha1);
187         return base;
188 }
189
190 static char *sha1_get_pack_name(const unsigned char *sha1,
191                                 char **name, char **base, const char *which)
192 {
193         static const char hex[] = "0123456789abcdef";
194         char *buf;
195         int i;
196
197         if (!*base) {
198                 const char *sha1_file_directory = get_object_directory();
199                 int len = strlen(sha1_file_directory);
200                 *base = xmalloc(len + 60);
201                 sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
202                         sha1_file_directory, which);
203                 *name = *base + len + 11;
204         }
205
206         buf = *name;
207
208         for (i = 0; i < 20; i++) {
209                 unsigned int val = *sha1++;
210                 *buf++ = hex[val >> 4];
211                 *buf++ = hex[val & 0xf];
212         }
213
214         return *base;
215 }
216
217 char *sha1_pack_name(const unsigned char *sha1)
218 {
219         static char *name, *base;
220
221         return sha1_get_pack_name(sha1, &name, &base, "pack");
222 }
223
224 char *sha1_pack_index_name(const unsigned char *sha1)
225 {
226         static char *name, *base;
227
228         return sha1_get_pack_name(sha1, &name, &base, "idx");
229 }
230
231 struct alternate_object_database *alt_odb_list;
232 static struct alternate_object_database **alt_odb_tail;
233
234 static void read_info_alternates(const char * alternates, int depth);
235
236 /*
237  * Prepare alternate object database registry.
238  *
239  * The variable alt_odb_list points at the list of struct
240  * alternate_object_database.  The elements on this list come from
241  * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
242  * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
243  * whose contents is similar to that environment variable but can be
244  * LF separated.  Its base points at a statically allocated buffer that
245  * contains "/the/directory/corresponding/to/.git/objects/...", while
246  * its name points just after the slash at the end of ".git/objects/"
247  * in the example above, and has enough space to hold 40-byte hex
248  * SHA1, an extra slash for the first level indirection, and the
249  * terminating NUL.
250  */
251 static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth)
252 {
253         const char *objdir = get_object_directory();
254         struct alternate_object_database *ent;
255         struct alternate_object_database *alt;
256         /* 43 = 40-byte + 2 '/' + terminating NUL */
257         int pfxlen = len;
258         int entlen = pfxlen + 43;
259         int base_len = -1;
260
261         if (!is_absolute_path(entry) && relative_base) {
262                 /* Relative alt-odb */
263                 if (base_len < 0)
264                         base_len = strlen(relative_base) + 1;
265                 entlen += base_len;
266                 pfxlen += base_len;
267         }
268         ent = xmalloc(sizeof(*ent) + entlen);
269
270         if (!is_absolute_path(entry) && relative_base) {
271                 memcpy(ent->base, relative_base, base_len - 1);
272                 ent->base[base_len - 1] = '/';
273                 memcpy(ent->base + base_len, entry, len);
274         }
275         else
276                 memcpy(ent->base, entry, pfxlen);
277
278         ent->name = ent->base + pfxlen + 1;
279         ent->base[pfxlen + 3] = '/';
280         ent->base[pfxlen] = ent->base[entlen-1] = 0;
281
282         /* Detect cases where alternate disappeared */
283         if (!is_directory(ent->base)) {
284                 error("object directory %s does not exist; "
285                       "check .git/objects/info/alternates.",
286                       ent->base);
287                 free(ent);
288                 return -1;
289         }
290
291         /* Prevent the common mistake of listing the same
292          * thing twice, or object directory itself.
293          */
294         for (alt = alt_odb_list; alt; alt = alt->next) {
295                 if (!memcmp(ent->base, alt->base, pfxlen)) {
296                         free(ent);
297                         return -1;
298                 }
299         }
300         if (!memcmp(ent->base, objdir, pfxlen)) {
301                 free(ent);
302                 return -1;
303         }
304
305         /* add the alternate entry */
306         *alt_odb_tail = ent;
307         alt_odb_tail = &(ent->next);
308         ent->next = NULL;
309
310         /* recursively add alternates */
311         read_info_alternates(ent->base, depth + 1);
312
313         ent->base[pfxlen] = '/';
314
315         return 0;
316 }
317
318 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
319                                  const char *relative_base, int depth)
320 {
321         const char *cp, *last;
322
323         if (depth > 5) {
324                 error("%s: ignoring alternate object stores, nesting too deep.",
325                                 relative_base);
326                 return;
327         }
328
329         last = alt;
330         while (last < ep) {
331                 cp = last;
332                 if (cp < ep && *cp == '#') {
333                         while (cp < ep && *cp != sep)
334                                 cp++;
335                         last = cp + 1;
336                         continue;
337                 }
338                 while (cp < ep && *cp != sep)
339                         cp++;
340                 if (last != cp) {
341                         if (!is_absolute_path(last) && depth) {
342                                 error("%s: ignoring relative alternate object store %s",
343                                                 relative_base, last);
344                         } else {
345                                 link_alt_odb_entry(last, cp - last,
346                                                 relative_base, depth);
347                         }
348                 }
349                 while (cp < ep && *cp == sep)
350                         cp++;
351                 last = cp;
352         }
353 }
354
355 static void read_info_alternates(const char * relative_base, int depth)
356 {
357         char *map;
358         size_t mapsz;
359         struct stat st;
360         const char alt_file_name[] = "info/alternates";
361         /* Given that relative_base is no longer than PATH_MAX,
362            ensure that "path" has enough space to append "/", the
363            file name, "info/alternates", and a trailing NUL.  */
364         char path[PATH_MAX + 1 + sizeof alt_file_name];
365         int fd;
366
367         sprintf(path, "%s/%s", relative_base, alt_file_name);
368         fd = open(path, O_RDONLY);
369         if (fd < 0)
370                 return;
371         if (fstat(fd, &st) || (st.st_size == 0)) {
372                 close(fd);
373                 return;
374         }
375         mapsz = xsize_t(st.st_size);
376         map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
377         close(fd);
378
379         link_alt_odb_entries(map, map + mapsz, '\n', relative_base, depth);
380
381         munmap(map, mapsz);
382 }
383
384 void add_to_alternates_file(const char *reference)
385 {
386         struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
387         int fd = hold_lock_file_for_append(lock, git_path("objects/info/alternates"), 1);
388         char *alt = mkpath("%s/objects\n", reference);
389         write_or_die(fd, alt, strlen(alt));
390         if (commit_lock_file(lock))
391                 die("could not close alternates file");
392         if (alt_odb_tail)
393                 link_alt_odb_entries(alt, alt + strlen(alt), '\n', NULL, 0);
394 }
395
396 void foreach_alt_odb(alt_odb_fn fn, void *cb)
397 {
398         struct alternate_object_database *ent;
399
400         prepare_alt_odb();
401         for (ent = alt_odb_list; ent; ent = ent->next)
402                 if (fn(ent, cb))
403                         return;
404 }
405
406 void prepare_alt_odb(void)
407 {
408         const char *alt;
409
410         if (alt_odb_tail)
411                 return;
412
413         alt = getenv(ALTERNATE_DB_ENVIRONMENT);
414         if (!alt) alt = "";
415
416         alt_odb_tail = &alt_odb_list;
417         link_alt_odb_entries(alt, alt + strlen(alt), PATH_SEP, NULL, 0);
418
419         read_info_alternates(get_object_directory(), 0);
420 }
421
422 static int has_loose_object(const unsigned char *sha1)
423 {
424         char *name = sha1_file_name(sha1);
425         struct alternate_object_database *alt;
426
427         if (!access(name, F_OK))
428                 return 1;
429         prepare_alt_odb();
430         for (alt = alt_odb_list; alt; alt = alt->next) {
431                 name = alt->name;
432                 fill_sha1_path(name, sha1);
433                 if (!access(alt->base, F_OK))
434                         return 1;
435         }
436         return 0;
437 }
438
439 static unsigned int pack_used_ctr;
440 static unsigned int pack_mmap_calls;
441 static unsigned int peak_pack_open_windows;
442 static unsigned int pack_open_windows;
443 static size_t peak_pack_mapped;
444 static size_t pack_mapped;
445 struct packed_git *packed_git;
446
447 void pack_report(void)
448 {
449         fprintf(stderr,
450                 "pack_report: getpagesize()            = %10" SZ_FMT "\n"
451                 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
452                 "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n",
453                 sz_fmt(getpagesize()),
454                 sz_fmt(packed_git_window_size),
455                 sz_fmt(packed_git_limit));
456         fprintf(stderr,
457                 "pack_report: pack_used_ctr            = %10u\n"
458                 "pack_report: pack_mmap_calls          = %10u\n"
459                 "pack_report: pack_open_windows        = %10u / %10u\n"
460                 "pack_report: pack_mapped              = "
461                         "%10" SZ_FMT " / %10" SZ_FMT "\n",
462                 pack_used_ctr,
463                 pack_mmap_calls,
464                 pack_open_windows, peak_pack_open_windows,
465                 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
466 }
467
468 static int check_packed_git_idx(const char *path,  struct packed_git *p)
469 {
470         void *idx_map;
471         struct pack_idx_header *hdr;
472         size_t idx_size;
473         uint32_t version, nr, i, *index;
474         int fd = open(path, O_RDONLY);
475         struct stat st;
476
477         if (fd < 0)
478                 return -1;
479         if (fstat(fd, &st)) {
480                 close(fd);
481                 return -1;
482         }
483         idx_size = xsize_t(st.st_size);
484         if (idx_size < 4 * 256 + 20 + 20) {
485                 close(fd);
486                 return error("index file %s is too small", path);
487         }
488         idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
489         close(fd);
490
491         hdr = idx_map;
492         if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
493                 version = ntohl(hdr->idx_version);
494                 if (version < 2 || version > 2) {
495                         munmap(idx_map, idx_size);
496                         return error("index file %s is version %"PRIu32
497                                      " and is not supported by this binary"
498                                      " (try upgrading GIT to a newer version)",
499                                      path, version);
500                 }
501         } else
502                 version = 1;
503
504         nr = 0;
505         index = idx_map;
506         if (version > 1)
507                 index += 2;  /* skip index header */
508         for (i = 0; i < 256; i++) {
509                 uint32_t n = ntohl(index[i]);
510                 if (n < nr) {
511                         munmap(idx_map, idx_size);
512                         return error("non-monotonic index %s", path);
513                 }
514                 nr = n;
515         }
516
517         if (version == 1) {
518                 /*
519                  * Total size:
520                  *  - 256 index entries 4 bytes each
521                  *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
522                  *  - 20-byte SHA1 of the packfile
523                  *  - 20-byte SHA1 file checksum
524                  */
525                 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
526                         munmap(idx_map, idx_size);
527                         return error("wrong index v1 file size in %s", path);
528                 }
529         } else if (version == 2) {
530                 /*
531                  * Minimum size:
532                  *  - 8 bytes of header
533                  *  - 256 index entries 4 bytes each
534                  *  - 20-byte sha1 entry * nr
535                  *  - 4-byte crc entry * nr
536                  *  - 4-byte offset entry * nr
537                  *  - 20-byte SHA1 of the packfile
538                  *  - 20-byte SHA1 file checksum
539                  * And after the 4-byte offset table might be a
540                  * variable sized table containing 8-byte entries
541                  * for offsets larger than 2^31.
542                  */
543                 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
544                 unsigned long max_size = min_size;
545                 if (nr)
546                         max_size += (nr - 1)*8;
547                 if (idx_size < min_size || idx_size > max_size) {
548                         munmap(idx_map, idx_size);
549                         return error("wrong index v2 file size in %s", path);
550                 }
551                 if (idx_size != min_size &&
552                     /*
553                      * make sure we can deal with large pack offsets.
554                      * 31-bit signed offset won't be enough, neither
555                      * 32-bit unsigned one will be.
556                      */
557                     (sizeof(off_t) <= 4)) {
558                         munmap(idx_map, idx_size);
559                         return error("pack too large for current definition of off_t in %s", path);
560                 }
561         }
562
563         p->index_version = version;
564         p->index_data = idx_map;
565         p->index_size = idx_size;
566         p->num_objects = nr;
567         return 0;
568 }
569
570 int open_pack_index(struct packed_git *p)
571 {
572         char *idx_name;
573         int ret;
574
575         if (p->index_data)
576                 return 0;
577
578         idx_name = xstrdup(p->pack_name);
579         strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
580         ret = check_packed_git_idx(idx_name, p);
581         free(idx_name);
582         return ret;
583 }
584
585 static void scan_windows(struct packed_git *p,
586         struct packed_git **lru_p,
587         struct pack_window **lru_w,
588         struct pack_window **lru_l)
589 {
590         struct pack_window *w, *w_l;
591
592         for (w_l = NULL, w = p->windows; w; w = w->next) {
593                 if (!w->inuse_cnt) {
594                         if (!*lru_w || w->last_used < (*lru_w)->last_used) {
595                                 *lru_p = p;
596                                 *lru_w = w;
597                                 *lru_l = w_l;
598                         }
599                 }
600                 w_l = w;
601         }
602 }
603
604 static int unuse_one_window(struct packed_git *current, int keep_fd)
605 {
606         struct packed_git *p, *lru_p = NULL;
607         struct pack_window *lru_w = NULL, *lru_l = NULL;
608
609         if (current)
610                 scan_windows(current, &lru_p, &lru_w, &lru_l);
611         for (p = packed_git; p; p = p->next)
612                 scan_windows(p, &lru_p, &lru_w, &lru_l);
613         if (lru_p) {
614                 munmap(lru_w->base, lru_w->len);
615                 pack_mapped -= lru_w->len;
616                 if (lru_l)
617                         lru_l->next = lru_w->next;
618                 else {
619                         lru_p->windows = lru_w->next;
620                         if (!lru_p->windows && lru_p->pack_fd != keep_fd) {
621                                 close(lru_p->pack_fd);
622                                 lru_p->pack_fd = -1;
623                         }
624                 }
625                 free(lru_w);
626                 pack_open_windows--;
627                 return 1;
628         }
629         return 0;
630 }
631
632 void release_pack_memory(size_t need, int fd)
633 {
634         size_t cur = pack_mapped;
635         while (need >= (cur - pack_mapped) && unuse_one_window(NULL, fd))
636                 ; /* nothing */
637 }
638
639 void close_pack_windows(struct packed_git *p)
640 {
641         while (p->windows) {
642                 struct pack_window *w = p->windows;
643
644                 if (w->inuse_cnt)
645                         die("pack '%s' still has open windows to it",
646                             p->pack_name);
647                 munmap(w->base, w->len);
648                 pack_mapped -= w->len;
649                 pack_open_windows--;
650                 p->windows = w->next;
651                 free(w);
652         }
653 }
654
655 void unuse_pack(struct pack_window **w_cursor)
656 {
657         struct pack_window *w = *w_cursor;
658         if (w) {
659                 w->inuse_cnt--;
660                 *w_cursor = NULL;
661         }
662 }
663
664 /*
665  * Do not call this directly as this leaks p->pack_fd on error return;
666  * call open_packed_git() instead.
667  */
668 static int open_packed_git_1(struct packed_git *p)
669 {
670         struct stat st;
671         struct pack_header hdr;
672         unsigned char sha1[20];
673         unsigned char *idx_sha1;
674         long fd_flag;
675
676         if (!p->index_data && open_pack_index(p))
677                 return error("packfile %s index unavailable", p->pack_name);
678
679         p->pack_fd = open(p->pack_name, O_RDONLY);
680         if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
681                 return -1;
682
683         /* If we created the struct before we had the pack we lack size. */
684         if (!p->pack_size) {
685                 if (!S_ISREG(st.st_mode))
686                         return error("packfile %s not a regular file", p->pack_name);
687                 p->pack_size = st.st_size;
688         } else if (p->pack_size != st.st_size)
689                 return error("packfile %s size changed", p->pack_name);
690
691         /* We leave these file descriptors open with sliding mmap;
692          * there is no point keeping them open across exec(), though.
693          */
694         fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
695         if (fd_flag < 0)
696                 return error("cannot determine file descriptor flags");
697         fd_flag |= FD_CLOEXEC;
698         if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
699                 return error("cannot set FD_CLOEXEC");
700
701         /* Verify we recognize this pack file format. */
702         if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
703                 return error("file %s is far too short to be a packfile", p->pack_name);
704         if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
705                 return error("file %s is not a GIT packfile", p->pack_name);
706         if (!pack_version_ok(hdr.hdr_version))
707                 return error("packfile %s is version %"PRIu32" and not"
708                         " supported (try upgrading GIT to a newer version)",
709                         p->pack_name, ntohl(hdr.hdr_version));
710
711         /* Verify the pack matches its index. */
712         if (p->num_objects != ntohl(hdr.hdr_entries))
713                 return error("packfile %s claims to have %"PRIu32" objects"
714                              " while index indicates %"PRIu32" objects",
715                              p->pack_name, ntohl(hdr.hdr_entries),
716                              p->num_objects);
717         if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
718                 return error("end of packfile %s is unavailable", p->pack_name);
719         if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
720                 return error("packfile %s signature is unavailable", p->pack_name);
721         idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
722         if (hashcmp(sha1, idx_sha1))
723                 return error("packfile %s does not match index", p->pack_name);
724         return 0;
725 }
726
727 static int open_packed_git(struct packed_git *p)
728 {
729         if (!open_packed_git_1(p))
730                 return 0;
731         if (p->pack_fd != -1) {
732                 close(p->pack_fd);
733                 p->pack_fd = -1;
734         }
735         return -1;
736 }
737
738 static int in_window(struct pack_window *win, off_t offset)
739 {
740         /* We must promise at least 20 bytes (one hash) after the
741          * offset is available from this window, otherwise the offset
742          * is not actually in this window and a different window (which
743          * has that one hash excess) must be used.  This is to support
744          * the object header and delta base parsing routines below.
745          */
746         off_t win_off = win->offset;
747         return win_off <= offset
748                 && (offset + 20) <= (win_off + win->len);
749 }
750
751 unsigned char* use_pack(struct packed_git *p,
752                 struct pack_window **w_cursor,
753                 off_t offset,
754                 unsigned int *left)
755 {
756         struct pack_window *win = *w_cursor;
757
758         if (p->pack_fd == -1 && open_packed_git(p))
759                 die("packfile %s cannot be accessed", p->pack_name);
760
761         /* Since packfiles end in a hash of their content and its
762          * pointless to ask for an offset into the middle of that
763          * hash, and the in_window function above wouldn't match
764          * don't allow an offset too close to the end of the file.
765          */
766         if (offset > (p->pack_size - 20))
767                 die("offset beyond end of packfile (truncated pack?)");
768
769         if (!win || !in_window(win, offset)) {
770                 if (win)
771                         win->inuse_cnt--;
772                 for (win = p->windows; win; win = win->next) {
773                         if (in_window(win, offset))
774                                 break;
775                 }
776                 if (!win) {
777                         size_t window_align = packed_git_window_size / 2;
778                         off_t len;
779                         win = xcalloc(1, sizeof(*win));
780                         win->offset = (offset / window_align) * window_align;
781                         len = p->pack_size - win->offset;
782                         if (len > packed_git_window_size)
783                                 len = packed_git_window_size;
784                         win->len = (size_t)len;
785                         pack_mapped += win->len;
786                         while (packed_git_limit < pack_mapped
787                                 && unuse_one_window(p, p->pack_fd))
788                                 ; /* nothing */
789                         win->base = xmmap(NULL, win->len,
790                                 PROT_READ, MAP_PRIVATE,
791                                 p->pack_fd, win->offset);
792                         if (win->base == MAP_FAILED)
793                                 die("packfile %s cannot be mapped: %s",
794                                         p->pack_name,
795                                         strerror(errno));
796                         pack_mmap_calls++;
797                         pack_open_windows++;
798                         if (pack_mapped > peak_pack_mapped)
799                                 peak_pack_mapped = pack_mapped;
800                         if (pack_open_windows > peak_pack_open_windows)
801                                 peak_pack_open_windows = pack_open_windows;
802                         win->next = p->windows;
803                         p->windows = win;
804                 }
805         }
806         if (win != *w_cursor) {
807                 win->last_used = pack_used_ctr++;
808                 win->inuse_cnt++;
809                 *w_cursor = win;
810         }
811         offset -= win->offset;
812         if (left)
813                 *left = win->len - xsize_t(offset);
814         return win->base + offset;
815 }
816
817 static struct packed_git *alloc_packed_git(int extra)
818 {
819         struct packed_git *p = xmalloc(sizeof(*p) + extra);
820         memset(p, 0, sizeof(*p));
821         p->pack_fd = -1;
822         return p;
823 }
824
825 struct packed_git *add_packed_git(const char *path, int path_len, int local)
826 {
827         struct stat st;
828         struct packed_git *p = alloc_packed_git(path_len + 2);
829
830         /*
831          * Make sure a corresponding .pack file exists and that
832          * the index looks sane.
833          */
834         path_len -= strlen(".idx");
835         if (path_len < 1) {
836                 free(p);
837                 return NULL;
838         }
839         memcpy(p->pack_name, path, path_len);
840         strcpy(p->pack_name + path_len, ".pack");
841         if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
842                 free(p);
843                 return NULL;
844         }
845
846         /* ok, it looks sane as far as we can check without
847          * actually mapping the pack file.
848          */
849         p->pack_size = st.st_size;
850         p->pack_local = local;
851         p->mtime = st.st_mtime;
852         if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
853                 hashclr(p->sha1);
854         return p;
855 }
856
857 struct packed_git *parse_pack_index(unsigned char *sha1)
858 {
859         const char *idx_path = sha1_pack_index_name(sha1);
860         const char *path = sha1_pack_name(sha1);
861         struct packed_git *p = alloc_packed_git(strlen(path) + 1);
862
863         strcpy(p->pack_name, path);
864         hashcpy(p->sha1, sha1);
865         if (check_packed_git_idx(idx_path, p)) {
866                 free(p);
867                 return NULL;
868         }
869
870         return p;
871 }
872
873 void install_packed_git(struct packed_git *pack)
874 {
875         pack->next = packed_git;
876         packed_git = pack;
877 }
878
879 static void prepare_packed_git_one(char *objdir, int local)
880 {
881         /* Ensure that this buffer is large enough so that we can
882            append "/pack/" without clobbering the stack even if
883            strlen(objdir) were PATH_MAX.  */
884         char path[PATH_MAX + 1 + 4 + 1 + 1];
885         int len;
886         DIR *dir;
887         struct dirent *de;
888
889         sprintf(path, "%s/pack", objdir);
890         len = strlen(path);
891         dir = opendir(path);
892         if (!dir) {
893                 if (errno != ENOENT)
894                         error("unable to open object pack directory: %s: %s",
895                               path, strerror(errno));
896                 return;
897         }
898         path[len++] = '/';
899         while ((de = readdir(dir)) != NULL) {
900                 int namelen = strlen(de->d_name);
901                 struct packed_git *p;
902
903                 if (!has_extension(de->d_name, ".idx"))
904                         continue;
905
906                 if (len + namelen + 1 > sizeof(path))
907                         continue;
908
909                 /* Don't reopen a pack we already have. */
910                 strcpy(path + len, de->d_name);
911                 for (p = packed_git; p; p = p->next) {
912                         if (!memcmp(path, p->pack_name, len + namelen - 4))
913                                 break;
914                 }
915                 if (p)
916                         continue;
917                 /* See if it really is a valid .idx file with corresponding
918                  * .pack file that we can map.
919                  */
920                 p = add_packed_git(path, len + namelen, local);
921                 if (!p)
922                         continue;
923                 install_packed_git(p);
924         }
925         closedir(dir);
926 }
927
928 static int sort_pack(const void *a_, const void *b_)
929 {
930         struct packed_git *a = *((struct packed_git **)a_);
931         struct packed_git *b = *((struct packed_git **)b_);
932         int st;
933
934         /*
935          * Local packs tend to contain objects specific to our
936          * variant of the project than remote ones.  In addition,
937          * remote ones could be on a network mounted filesystem.
938          * Favor local ones for these reasons.
939          */
940         st = a->pack_local - b->pack_local;
941         if (st)
942                 return -st;
943
944         /*
945          * Younger packs tend to contain more recent objects,
946          * and more recent objects tend to get accessed more
947          * often.
948          */
949         if (a->mtime < b->mtime)
950                 return 1;
951         else if (a->mtime == b->mtime)
952                 return 0;
953         return -1;
954 }
955
956 static void rearrange_packed_git(void)
957 {
958         struct packed_git **ary, *p;
959         int i, n;
960
961         for (n = 0, p = packed_git; p; p = p->next)
962                 n++;
963         if (n < 2)
964                 return;
965
966         /* prepare an array of packed_git for easier sorting */
967         ary = xcalloc(n, sizeof(struct packed_git *));
968         for (n = 0, p = packed_git; p; p = p->next)
969                 ary[n++] = p;
970
971         qsort(ary, n, sizeof(struct packed_git *), sort_pack);
972
973         /* link them back again */
974         for (i = 0; i < n - 1; i++)
975                 ary[i]->next = ary[i + 1];
976         ary[n - 1]->next = NULL;
977         packed_git = ary[0];
978
979         free(ary);
980 }
981
982 static int prepare_packed_git_run_once = 0;
983 void prepare_packed_git(void)
984 {
985         struct alternate_object_database *alt;
986
987         if (prepare_packed_git_run_once)
988                 return;
989         prepare_packed_git_one(get_object_directory(), 1);
990         prepare_alt_odb();
991         for (alt = alt_odb_list; alt; alt = alt->next) {
992                 alt->name[-1] = 0;
993                 prepare_packed_git_one(alt->base, 0);
994                 alt->name[-1] = '/';
995         }
996         rearrange_packed_git();
997         prepare_packed_git_run_once = 1;
998 }
999
1000 void reprepare_packed_git(void)
1001 {
1002         discard_revindex();
1003         prepare_packed_git_run_once = 0;
1004         prepare_packed_git();
1005 }
1006
1007 static void mark_bad_packed_object(struct packed_git *p,
1008                                    const unsigned char *sha1)
1009 {
1010         unsigned i;
1011         for (i = 0; i < p->num_bad_objects; i++)
1012                 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1013                         return;
1014         p->bad_object_sha1 = xrealloc(p->bad_object_sha1, 20 * (p->num_bad_objects + 1));
1015         hashcpy(p->bad_object_sha1 + 20 * p->num_bad_objects, sha1);
1016         p->num_bad_objects++;
1017 }
1018
1019 static int has_packed_and_bad(const unsigned char *sha1)
1020 {
1021         struct packed_git *p;
1022         unsigned i;
1023
1024         for (p = packed_git; p; p = p->next)
1025                 for (i = 0; i < p->num_bad_objects; i++)
1026                         if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1027                                 return 1;
1028         return 0;
1029 }
1030
1031 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
1032 {
1033         unsigned char real_sha1[20];
1034         hash_sha1_file(map, size, type, real_sha1);
1035         return hashcmp(sha1, real_sha1) ? -1 : 0;
1036 }
1037
1038 static int git_open_noatime(const char *name)
1039 {
1040         static int sha1_file_open_flag = O_NOATIME;
1041         int fd = open(name, O_RDONLY | sha1_file_open_flag);
1042
1043         /* Might the failure be due to O_NOATIME? */
1044         if (fd < 0 && errno != ENOENT && sha1_file_open_flag) {
1045                 fd = open(name, O_RDONLY);
1046                 if (fd >= 0)
1047                         sha1_file_open_flag = 0;
1048         }
1049         return fd;
1050 }
1051
1052 static int open_sha1_file(const unsigned char *sha1)
1053 {
1054         int fd;
1055         char *name = sha1_file_name(sha1);
1056         struct alternate_object_database *alt;
1057
1058         fd = git_open_noatime(name);
1059         if (fd >= 0)
1060                 return fd;
1061
1062         prepare_alt_odb();
1063         errno = ENOENT;
1064         for (alt = alt_odb_list; alt; alt = alt->next) {
1065                 name = alt->name;
1066                 fill_sha1_path(name, sha1);
1067                 fd = git_open_noatime(alt->base);
1068                 if (fd >= 0)
1069                         return fd;
1070         }
1071         return -1;
1072 }
1073
1074 static void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1075 {
1076         void *map;
1077         int fd;
1078
1079         fd = open_sha1_file(sha1);
1080         map = NULL;
1081         if (fd >= 0) {
1082                 struct stat st;
1083
1084                 if (!fstat(fd, &st)) {
1085                         *size = xsize_t(st.st_size);
1086                         map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1087                 }
1088                 close(fd);
1089         }
1090         return map;
1091 }
1092
1093 static int legacy_loose_object(unsigned char *map)
1094 {
1095         unsigned int word;
1096
1097         /*
1098          * Is it a zlib-compressed buffer? If so, the first byte
1099          * must be 0x78 (15-bit window size, deflated), and the
1100          * first 16-bit word is evenly divisible by 31
1101          */
1102         word = (map[0] << 8) + map[1];
1103         if (map[0] == 0x78 && !(word % 31))
1104                 return 1;
1105         else
1106                 return 0;
1107 }
1108
1109 unsigned long unpack_object_header_gently(const unsigned char *buf, unsigned long len, enum object_type *type, unsigned long *sizep)
1110 {
1111         unsigned shift;
1112         unsigned char c;
1113         unsigned long size;
1114         unsigned long used = 0;
1115
1116         c = buf[used++];
1117         *type = (c >> 4) & 7;
1118         size = c & 15;
1119         shift = 4;
1120         while (c & 0x80) {
1121                 if (len <= used)
1122                         return 0;
1123                 if (sizeof(long) * 8 <= shift)
1124                         return 0;
1125                 c = buf[used++];
1126                 size += (c & 0x7f) << shift;
1127                 shift += 7;
1128         }
1129         *sizep = size;
1130         return used;
1131 }
1132
1133 static int unpack_sha1_header(z_stream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1134 {
1135         unsigned long size, used;
1136         static const char valid_loose_object_type[8] = {
1137                 0, /* OBJ_EXT */
1138                 1, 1, 1, 1, /* "commit", "tree", "blob", "tag" */
1139                 0, /* "delta" and others are invalid in a loose object */
1140         };
1141         enum object_type type;
1142
1143         /* Get the data stream */
1144         memset(stream, 0, sizeof(*stream));
1145         stream->next_in = map;
1146         stream->avail_in = mapsize;
1147         stream->next_out = buffer;
1148         stream->avail_out = bufsiz;
1149
1150         if (legacy_loose_object(map)) {
1151                 inflateInit(stream);
1152                 return inflate(stream, 0);
1153         }
1154
1155
1156         /*
1157          * There used to be a second loose object header format which
1158          * was meant to mimic the in-pack format, allowing for direct
1159          * copy of the object data.  This format turned up not to be
1160          * really worth it and we don't write it any longer.  But we
1161          * can still read it.
1162          */
1163         used = unpack_object_header_gently(map, mapsize, &type, &size);
1164         if (!used || !valid_loose_object_type[type])
1165                 return -1;
1166         map += used;
1167         mapsize -= used;
1168
1169         /* Set up the stream for the rest.. */
1170         stream->next_in = map;
1171         stream->avail_in = mapsize;
1172         inflateInit(stream);
1173
1174         /* And generate the fake traditional header */
1175         stream->total_out = 1 + snprintf(buffer, bufsiz, "%s %lu",
1176                                          typename(type), size);
1177         return 0;
1178 }
1179
1180 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1181 {
1182         int bytes = strlen(buffer) + 1;
1183         unsigned char *buf = xmalloc(1+size);
1184         unsigned long n;
1185         int status = Z_OK;
1186
1187         n = stream->total_out - bytes;
1188         if (n > size)
1189                 n = size;
1190         memcpy(buf, (char *) buffer + bytes, n);
1191         bytes = n;
1192         if (bytes <= size) {
1193                 /*
1194                  * The above condition must be (bytes <= size), not
1195                  * (bytes < size).  In other words, even though we
1196                  * expect no more output and set avail_out to zer0,
1197                  * the input zlib stream may have bytes that express
1198                  * "this concludes the stream", and we *do* want to
1199                  * eat that input.
1200                  *
1201                  * Otherwise we would not be able to test that we
1202                  * consumed all the input to reach the expected size;
1203                  * we also want to check that zlib tells us that all
1204                  * went well with status == Z_STREAM_END at the end.
1205                  */
1206                 stream->next_out = buf + bytes;
1207                 stream->avail_out = size - bytes;
1208                 while (status == Z_OK)
1209                         status = inflate(stream, Z_FINISH);
1210         }
1211         buf[size] = 0;
1212         if (status == Z_STREAM_END && !stream->avail_in) {
1213                 inflateEnd(stream);
1214                 return buf;
1215         }
1216
1217         if (status < 0)
1218                 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1219         else if (stream->avail_in)
1220                 error("garbage at end of loose object '%s'",
1221                       sha1_to_hex(sha1));
1222         free(buf);
1223         return NULL;
1224 }
1225
1226 /*
1227  * We used to just use "sscanf()", but that's actually way
1228  * too permissive for what we want to check. So do an anal
1229  * object header parse by hand.
1230  */
1231 static int parse_sha1_header(const char *hdr, unsigned long *sizep)
1232 {
1233         char type[10];
1234         int i;
1235         unsigned long size;
1236
1237         /*
1238          * The type can be at most ten bytes (including the
1239          * terminating '\0' that we add), and is followed by
1240          * a space.
1241          */
1242         i = 0;
1243         for (;;) {
1244                 char c = *hdr++;
1245                 if (c == ' ')
1246                         break;
1247                 type[i++] = c;
1248                 if (i >= sizeof(type))
1249                         return -1;
1250         }
1251         type[i] = 0;
1252
1253         /*
1254          * The length must follow immediately, and be in canonical
1255          * decimal format (ie "010" is not valid).
1256          */
1257         size = *hdr++ - '0';
1258         if (size > 9)
1259                 return -1;
1260         if (size) {
1261                 for (;;) {
1262                         unsigned long c = *hdr - '0';
1263                         if (c > 9)
1264                                 break;
1265                         hdr++;
1266                         size = size * 10 + c;
1267                 }
1268         }
1269         *sizep = size;
1270
1271         /*
1272          * The length must be followed by a zero byte
1273          */
1274         return *hdr ? -1 : type_from_string(type);
1275 }
1276
1277 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1278 {
1279         int ret;
1280         z_stream stream;
1281         char hdr[8192];
1282
1283         ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1284         if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1285                 return NULL;
1286
1287         return unpack_sha1_rest(&stream, hdr, *size, sha1);
1288 }
1289
1290 unsigned long get_size_from_delta(struct packed_git *p,
1291                                   struct pack_window **w_curs,
1292                                   off_t curpos)
1293 {
1294         const unsigned char *data;
1295         unsigned char delta_head[20], *in;
1296         z_stream stream;
1297         int st;
1298
1299         memset(&stream, 0, sizeof(stream));
1300         stream.next_out = delta_head;
1301         stream.avail_out = sizeof(delta_head);
1302
1303         inflateInit(&stream);
1304         do {
1305                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1306                 stream.next_in = in;
1307                 st = inflate(&stream, Z_FINISH);
1308                 curpos += stream.next_in - in;
1309         } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1310                  stream.total_out < sizeof(delta_head));
1311         inflateEnd(&stream);
1312         if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head))
1313                 die("delta data unpack-initial failed");
1314
1315         /* Examine the initial part of the delta to figure out
1316          * the result size.
1317          */
1318         data = delta_head;
1319
1320         /* ignore base size */
1321         get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1322
1323         /* Read the result size */
1324         return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1325 }
1326
1327 static off_t get_delta_base(struct packed_git *p,
1328                                     struct pack_window **w_curs,
1329                                     off_t *curpos,
1330                                     enum object_type type,
1331                                     off_t delta_obj_offset)
1332 {
1333         unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1334         off_t base_offset;
1335
1336         /* use_pack() assured us we have [base_info, base_info + 20)
1337          * as a range that we can look at without walking off the
1338          * end of the mapped window.  Its actually the hash size
1339          * that is assured.  An OFS_DELTA longer than the hash size
1340          * is stupid, as then a REF_DELTA would be smaller to store.
1341          */
1342         if (type == OBJ_OFS_DELTA) {
1343                 unsigned used = 0;
1344                 unsigned char c = base_info[used++];
1345                 base_offset = c & 127;
1346                 while (c & 128) {
1347                         base_offset += 1;
1348                         if (!base_offset || MSB(base_offset, 7))
1349                                 return 0;  /* overflow */
1350                         c = base_info[used++];
1351                         base_offset = (base_offset << 7) + (c & 127);
1352                 }
1353                 base_offset = delta_obj_offset - base_offset;
1354                 if (base_offset >= delta_obj_offset)
1355                         return 0;  /* out of bound */
1356                 *curpos += used;
1357         } else if (type == OBJ_REF_DELTA) {
1358                 /* The base entry _must_ be in the same pack */
1359                 base_offset = find_pack_entry_one(base_info, p);
1360                 *curpos += 20;
1361         } else
1362                 die("I am totally screwed");
1363         return base_offset;
1364 }
1365
1366 /* forward declaration for a mutually recursive function */
1367 static int packed_object_info(struct packed_git *p, off_t offset,
1368                               unsigned long *sizep);
1369
1370 static int packed_delta_info(struct packed_git *p,
1371                              struct pack_window **w_curs,
1372                              off_t curpos,
1373                              enum object_type type,
1374                              off_t obj_offset,
1375                              unsigned long *sizep)
1376 {
1377         off_t base_offset;
1378
1379         base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1380         type = packed_object_info(p, base_offset, NULL);
1381
1382         /* We choose to only get the type of the base object and
1383          * ignore potentially corrupt pack file that expects the delta
1384          * based on a base with a wrong size.  This saves tons of
1385          * inflate() calls.
1386          */
1387         if (sizep)
1388                 *sizep = get_size_from_delta(p, w_curs, curpos);
1389
1390         return type;
1391 }
1392
1393 static int unpack_object_header(struct packed_git *p,
1394                                 struct pack_window **w_curs,
1395                                 off_t *curpos,
1396                                 unsigned long *sizep)
1397 {
1398         unsigned char *base;
1399         unsigned int left;
1400         unsigned long used;
1401         enum object_type type;
1402
1403         /* use_pack() assures us we have [base, base + 20) available
1404          * as a range that we can look at at.  (Its actually the hash
1405          * size that is assured.)  With our object header encoding
1406          * the maximum deflated object size is 2^137, which is just
1407          * insane, so we know won't exceed what we have been given.
1408          */
1409         base = use_pack(p, w_curs, *curpos, &left);
1410         used = unpack_object_header_gently(base, left, &type, sizep);
1411         if (!used)
1412                 die("object offset outside of pack file");
1413         *curpos += used;
1414
1415         return type;
1416 }
1417
1418 const char *packed_object_info_detail(struct packed_git *p,
1419                                       off_t obj_offset,
1420                                       unsigned long *size,
1421                                       unsigned long *store_size,
1422                                       unsigned int *delta_chain_length,
1423                                       unsigned char *base_sha1)
1424 {
1425         struct pack_window *w_curs = NULL;
1426         off_t curpos;
1427         unsigned long dummy;
1428         unsigned char *next_sha1;
1429         enum object_type type;
1430         struct revindex_entry *revidx;
1431
1432         *delta_chain_length = 0;
1433         curpos = obj_offset;
1434         type = unpack_object_header(p, &w_curs, &curpos, size);
1435
1436         revidx = find_pack_revindex(p, obj_offset);
1437         *store_size = revidx[1].offset - obj_offset;
1438
1439         for (;;) {
1440                 switch (type) {
1441                 default:
1442                         die("pack %s contains unknown object type %d",
1443                             p->pack_name, type);
1444                 case OBJ_COMMIT:
1445                 case OBJ_TREE:
1446                 case OBJ_BLOB:
1447                 case OBJ_TAG:
1448                         unuse_pack(&w_curs);
1449                         return typename(type);
1450                 case OBJ_OFS_DELTA:
1451                         obj_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1452                         if (!obj_offset)
1453                                 die("pack %s contains bad delta base reference of type %s",
1454                                     p->pack_name, typename(type));
1455                         if (*delta_chain_length == 0) {
1456                                 revidx = find_pack_revindex(p, obj_offset);
1457                                 hashcpy(base_sha1, nth_packed_object_sha1(p, revidx->nr));
1458                         }
1459                         break;
1460                 case OBJ_REF_DELTA:
1461                         next_sha1 = use_pack(p, &w_curs, curpos, NULL);
1462                         if (*delta_chain_length == 0)
1463                                 hashcpy(base_sha1, next_sha1);
1464                         obj_offset = find_pack_entry_one(next_sha1, p);
1465                         break;
1466                 }
1467                 (*delta_chain_length)++;
1468                 curpos = obj_offset;
1469                 type = unpack_object_header(p, &w_curs, &curpos, &dummy);
1470         }
1471 }
1472
1473 static int packed_object_info(struct packed_git *p, off_t obj_offset,
1474                               unsigned long *sizep)
1475 {
1476         struct pack_window *w_curs = NULL;
1477         unsigned long size;
1478         off_t curpos = obj_offset;
1479         enum object_type type;
1480
1481         type = unpack_object_header(p, &w_curs, &curpos, &size);
1482
1483         switch (type) {
1484         case OBJ_OFS_DELTA:
1485         case OBJ_REF_DELTA:
1486                 type = packed_delta_info(p, &w_curs, curpos,
1487                                          type, obj_offset, sizep);
1488                 break;
1489         case OBJ_COMMIT:
1490         case OBJ_TREE:
1491         case OBJ_BLOB:
1492         case OBJ_TAG:
1493                 if (sizep)
1494                         *sizep = size;
1495                 break;
1496         default:
1497                 die("pack %s contains unknown object type %d",
1498                     p->pack_name, type);
1499         }
1500         unuse_pack(&w_curs);
1501         return type;
1502 }
1503
1504 static void *unpack_compressed_entry(struct packed_git *p,
1505                                     struct pack_window **w_curs,
1506                                     off_t curpos,
1507                                     unsigned long size)
1508 {
1509         int st;
1510         z_stream stream;
1511         unsigned char *buffer, *in;
1512
1513         buffer = xmalloc(size + 1);
1514         buffer[size] = 0;
1515         memset(&stream, 0, sizeof(stream));
1516         stream.next_out = buffer;
1517         stream.avail_out = size;
1518
1519         inflateInit(&stream);
1520         do {
1521                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1522                 stream.next_in = in;
1523                 st = inflate(&stream, Z_FINISH);
1524                 curpos += stream.next_in - in;
1525         } while (st == Z_OK || st == Z_BUF_ERROR);
1526         inflateEnd(&stream);
1527         if ((st != Z_STREAM_END) || stream.total_out != size) {
1528                 free(buffer);
1529                 return NULL;
1530         }
1531
1532         return buffer;
1533 }
1534
1535 #define MAX_DELTA_CACHE (256)
1536
1537 static size_t delta_base_cached;
1538
1539 static struct delta_base_cache_lru_list {
1540         struct delta_base_cache_lru_list *prev;
1541         struct delta_base_cache_lru_list *next;
1542 } delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
1543
1544 static struct delta_base_cache_entry {
1545         struct delta_base_cache_lru_list lru;
1546         void *data;
1547         struct packed_git *p;
1548         off_t base_offset;
1549         unsigned long size;
1550         enum object_type type;
1551 } delta_base_cache[MAX_DELTA_CACHE];
1552
1553 static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
1554 {
1555         unsigned long hash;
1556
1557         hash = (unsigned long)p + (unsigned long)base_offset;
1558         hash += (hash >> 8) + (hash >> 16);
1559         return hash % MAX_DELTA_CACHE;
1560 }
1561
1562 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
1563         unsigned long *base_size, enum object_type *type, int keep_cache)
1564 {
1565         void *ret;
1566         unsigned long hash = pack_entry_hash(p, base_offset);
1567         struct delta_base_cache_entry *ent = delta_base_cache + hash;
1568
1569         ret = ent->data;
1570         if (ret && ent->p == p && ent->base_offset == base_offset)
1571                 goto found_cache_entry;
1572         return unpack_entry(p, base_offset, type, base_size);
1573
1574 found_cache_entry:
1575         if (!keep_cache) {
1576                 ent->data = NULL;
1577                 ent->lru.next->prev = ent->lru.prev;
1578                 ent->lru.prev->next = ent->lru.next;
1579                 delta_base_cached -= ent->size;
1580         } else {
1581                 ret = xmemdupz(ent->data, ent->size);
1582         }
1583         *type = ent->type;
1584         *base_size = ent->size;
1585         return ret;
1586 }
1587
1588 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1589 {
1590         if (ent->data) {
1591                 free(ent->data);
1592                 ent->data = NULL;
1593                 ent->lru.next->prev = ent->lru.prev;
1594                 ent->lru.prev->next = ent->lru.next;
1595                 delta_base_cached -= ent->size;
1596         }
1597 }
1598
1599 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1600         void *base, unsigned long base_size, enum object_type type)
1601 {
1602         unsigned long hash = pack_entry_hash(p, base_offset);
1603         struct delta_base_cache_entry *ent = delta_base_cache + hash;
1604         struct delta_base_cache_lru_list *lru;
1605
1606         release_delta_base_cache(ent);
1607         delta_base_cached += base_size;
1608
1609         for (lru = delta_base_cache_lru.next;
1610              delta_base_cached > delta_base_cache_limit
1611              && lru != &delta_base_cache_lru;
1612              lru = lru->next) {
1613                 struct delta_base_cache_entry *f = (void *)lru;
1614                 if (f->type == OBJ_BLOB)
1615                         release_delta_base_cache(f);
1616         }
1617         for (lru = delta_base_cache_lru.next;
1618              delta_base_cached > delta_base_cache_limit
1619              && lru != &delta_base_cache_lru;
1620              lru = lru->next) {
1621                 struct delta_base_cache_entry *f = (void *)lru;
1622                 release_delta_base_cache(f);
1623         }
1624
1625         ent->p = p;
1626         ent->base_offset = base_offset;
1627         ent->type = type;
1628         ent->data = base;
1629         ent->size = base_size;
1630         ent->lru.next = &delta_base_cache_lru;
1631         ent->lru.prev = delta_base_cache_lru.prev;
1632         delta_base_cache_lru.prev->next = &ent->lru;
1633         delta_base_cache_lru.prev = &ent->lru;
1634 }
1635
1636 static void *unpack_delta_entry(struct packed_git *p,
1637                                 struct pack_window **w_curs,
1638                                 off_t curpos,
1639                                 unsigned long delta_size,
1640                                 off_t obj_offset,
1641                                 enum object_type *type,
1642                                 unsigned long *sizep)
1643 {
1644         void *delta_data, *result, *base;
1645         unsigned long base_size;
1646         off_t base_offset;
1647
1648         base_offset = get_delta_base(p, w_curs, &curpos, *type, obj_offset);
1649         if (!base_offset) {
1650                 error("failed to validate delta base reference "
1651                       "at offset %"PRIuMAX" from %s",
1652                       (uintmax_t)curpos, p->pack_name);
1653                 return NULL;
1654         }
1655         unuse_pack(w_curs);
1656         base = cache_or_unpack_entry(p, base_offset, &base_size, type, 0);
1657         if (!base) {
1658                 /*
1659                  * We're probably in deep shit, but let's try to fetch
1660                  * the required base anyway from another pack or loose.
1661                  * This is costly but should happen only in the presence
1662                  * of a corrupted pack, and is better than failing outright.
1663                  */
1664                 struct revindex_entry *revidx = find_pack_revindex(p, base_offset);
1665                 const unsigned char *base_sha1 =
1666                                         nth_packed_object_sha1(p, revidx->nr);
1667                 error("failed to read delta base object %s"
1668                       " at offset %"PRIuMAX" from %s",
1669                       sha1_to_hex(base_sha1), (uintmax_t)base_offset,
1670                       p->pack_name);
1671                 mark_bad_packed_object(p, base_sha1);
1672                 base = read_object(base_sha1, type, &base_size);
1673                 if (!base)
1674                         return NULL;
1675         }
1676
1677         delta_data = unpack_compressed_entry(p, w_curs, curpos, delta_size);
1678         if (!delta_data) {
1679                 error("failed to unpack compressed delta "
1680                       "at offset %"PRIuMAX" from %s",
1681                       (uintmax_t)curpos, p->pack_name);
1682                 free(base);
1683                 return NULL;
1684         }
1685         result = patch_delta(base, base_size,
1686                              delta_data, delta_size,
1687                              sizep);
1688         if (!result)
1689                 die("failed to apply delta");
1690         free(delta_data);
1691         add_delta_base_cache(p, base_offset, base, base_size, *type);
1692         return result;
1693 }
1694
1695 void *unpack_entry(struct packed_git *p, off_t obj_offset,
1696                    enum object_type *type, unsigned long *sizep)
1697 {
1698         struct pack_window *w_curs = NULL;
1699         off_t curpos = obj_offset;
1700         void *data;
1701
1702         *type = unpack_object_header(p, &w_curs, &curpos, sizep);
1703         switch (*type) {
1704         case OBJ_OFS_DELTA:
1705         case OBJ_REF_DELTA:
1706                 data = unpack_delta_entry(p, &w_curs, curpos, *sizep,
1707                                           obj_offset, type, sizep);
1708                 break;
1709         case OBJ_COMMIT:
1710         case OBJ_TREE:
1711         case OBJ_BLOB:
1712         case OBJ_TAG:
1713                 data = unpack_compressed_entry(p, &w_curs, curpos, *sizep);
1714                 break;
1715         default:
1716                 data = NULL;
1717                 error("unknown object type %i at offset %"PRIuMAX" in %s",
1718                       *type, (uintmax_t)obj_offset, p->pack_name);
1719         }
1720         unuse_pack(&w_curs);
1721         return data;
1722 }
1723
1724 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1725                                             uint32_t n)
1726 {
1727         const unsigned char *index = p->index_data;
1728         if (!index) {
1729                 if (open_pack_index(p))
1730                         return NULL;
1731                 index = p->index_data;
1732         }
1733         if (n >= p->num_objects)
1734                 return NULL;
1735         index += 4 * 256;
1736         if (p->index_version == 1) {
1737                 return index + 24 * n + 4;
1738         } else {
1739                 index += 8;
1740                 return index + 20 * n;
1741         }
1742 }
1743
1744 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1745 {
1746         const unsigned char *index = p->index_data;
1747         index += 4 * 256;
1748         if (p->index_version == 1) {
1749                 return ntohl(*((uint32_t *)(index + 24 * n)));
1750         } else {
1751                 uint32_t off;
1752                 index += 8 + p->num_objects * (20 + 4);
1753                 off = ntohl(*((uint32_t *)(index + 4 * n)));
1754                 if (!(off & 0x80000000))
1755                         return off;
1756                 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1757                 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
1758                                    ntohl(*((uint32_t *)(index + 4)));
1759         }
1760 }
1761
1762 off_t find_pack_entry_one(const unsigned char *sha1,
1763                                   struct packed_git *p)
1764 {
1765         const uint32_t *level1_ofs = p->index_data;
1766         const unsigned char *index = p->index_data;
1767         unsigned hi, lo, stride;
1768         static int use_lookup = -1;
1769         static int debug_lookup = -1;
1770
1771         if (debug_lookup < 0)
1772                 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
1773
1774         if (!index) {
1775                 if (open_pack_index(p))
1776                         return 0;
1777                 level1_ofs = p->index_data;
1778                 index = p->index_data;
1779         }
1780         if (p->index_version > 1) {
1781                 level1_ofs += 2;
1782                 index += 8;
1783         }
1784         index += 4 * 256;
1785         hi = ntohl(level1_ofs[*sha1]);
1786         lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1787         if (p->index_version > 1) {
1788                 stride = 20;
1789         } else {
1790                 stride = 24;
1791                 index += 4;
1792         }
1793
1794         if (debug_lookup)
1795                 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
1796                        sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
1797
1798         if (use_lookup < 0)
1799                 use_lookup = !!getenv("GIT_USE_LOOKUP");
1800         if (use_lookup) {
1801                 int pos = sha1_entry_pos(index, stride, 0,
1802                                          lo, hi, p->num_objects, sha1);
1803                 if (pos < 0)
1804                         return 0;
1805                 return nth_packed_object_offset(p, pos);
1806         }
1807
1808         do {
1809                 unsigned mi = (lo + hi) / 2;
1810                 int cmp = hashcmp(index + mi * stride, sha1);
1811
1812                 if (debug_lookup)
1813                         printf("lo %u hi %u rg %u mi %u\n",
1814                                lo, hi, hi - lo, mi);
1815                 if (!cmp)
1816                         return nth_packed_object_offset(p, mi);
1817                 if (cmp > 0)
1818                         hi = mi;
1819                 else
1820                         lo = mi+1;
1821         } while (lo < hi);
1822         return 0;
1823 }
1824
1825 int matches_pack_name(struct packed_git *p, const char *name)
1826 {
1827         const char *last_c, *c;
1828
1829         if (!strcmp(p->pack_name, name))
1830                 return 1;
1831
1832         for (c = p->pack_name, last_c = c; *c;)
1833                 if (*c == '/')
1834                         last_c = ++c;
1835                 else
1836                         ++c;
1837         if (!strcmp(last_c, name))
1838                 return 1;
1839
1840         return 0;
1841 }
1842
1843 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e, const char **ignore_packed)
1844 {
1845         static struct packed_git *last_found = (void *)1;
1846         struct packed_git *p;
1847         off_t offset;
1848
1849         prepare_packed_git();
1850         if (!packed_git)
1851                 return 0;
1852         p = (last_found == (void *)1) ? packed_git : last_found;
1853
1854         do {
1855                 if (ignore_packed) {
1856                         const char **ig;
1857                         for (ig = ignore_packed; *ig; ig++)
1858                                 if (matches_pack_name(p, *ig))
1859                                         break;
1860                         if (*ig)
1861                                 goto next;
1862                 }
1863
1864                 if (p->num_bad_objects) {
1865                         unsigned i;
1866                         for (i = 0; i < p->num_bad_objects; i++)
1867                                 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1868                                         goto next;
1869                 }
1870
1871                 offset = find_pack_entry_one(sha1, p);
1872                 if (offset) {
1873                         /*
1874                          * We are about to tell the caller where they can
1875                          * locate the requested object.  We better make
1876                          * sure the packfile is still here and can be
1877                          * accessed before supplying that answer, as
1878                          * it may have been deleted since the index
1879                          * was loaded!
1880                          */
1881                         if (p->pack_fd == -1 && open_packed_git(p)) {
1882                                 error("packfile %s cannot be accessed", p->pack_name);
1883                                 goto next;
1884                         }
1885                         e->offset = offset;
1886                         e->p = p;
1887                         hashcpy(e->sha1, sha1);
1888                         last_found = p;
1889                         return 1;
1890                 }
1891
1892                 next:
1893                 if (p == last_found)
1894                         p = packed_git;
1895                 else
1896                         p = p->next;
1897                 if (p == last_found)
1898                         p = p->next;
1899         } while (p);
1900         return 0;
1901 }
1902
1903 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1904                                   struct packed_git *packs)
1905 {
1906         struct packed_git *p;
1907
1908         for (p = packs; p; p = p->next) {
1909                 if (find_pack_entry_one(sha1, p))
1910                         return p;
1911         }
1912         return NULL;
1913
1914 }
1915
1916 static int sha1_loose_object_info(const unsigned char *sha1, unsigned long *sizep)
1917 {
1918         int status;
1919         unsigned long mapsize, size;
1920         void *map;
1921         z_stream stream;
1922         char hdr[32];
1923
1924         map = map_sha1_file(sha1, &mapsize);
1925         if (!map)
1926                 return error("unable to find %s", sha1_to_hex(sha1));
1927         if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1928                 status = error("unable to unpack %s header",
1929                                sha1_to_hex(sha1));
1930         else if ((status = parse_sha1_header(hdr, &size)) < 0)
1931                 status = error("unable to parse %s header", sha1_to_hex(sha1));
1932         else if (sizep)
1933                 *sizep = size;
1934         inflateEnd(&stream);
1935         munmap(map, mapsize);
1936         return status;
1937 }
1938
1939 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
1940 {
1941         struct pack_entry e;
1942         int status;
1943
1944         if (!find_pack_entry(sha1, &e, NULL)) {
1945                 /* Most likely it's a loose object. */
1946                 status = sha1_loose_object_info(sha1, sizep);
1947                 if (status >= 0)
1948                         return status;
1949
1950                 /* Not a loose object; someone else may have just packed it. */
1951                 reprepare_packed_git();
1952                 if (!find_pack_entry(sha1, &e, NULL))
1953                         return status;
1954         }
1955         return packed_object_info(e.p, e.offset, sizep);
1956 }
1957
1958 static void *read_packed_sha1(const unsigned char *sha1,
1959                               enum object_type *type, unsigned long *size)
1960 {
1961         struct pack_entry e;
1962         void *data;
1963
1964         if (!find_pack_entry(sha1, &e, NULL))
1965                 return NULL;
1966         data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
1967         if (!data) {
1968                 /*
1969                  * We're probably in deep shit, but let's try to fetch
1970                  * the required object anyway from another pack or loose.
1971                  * This should happen only in the presence of a corrupted
1972                  * pack, and is better than failing outright.
1973                  */
1974                 error("failed to read object %s at offset %"PRIuMAX" from %s",
1975                       sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
1976                 mark_bad_packed_object(e.p, sha1);
1977                 data = read_object(sha1, type, size);
1978         }
1979         return data;
1980 }
1981
1982 /*
1983  * This is meant to hold a *small* number of objects that you would
1984  * want read_sha1_file() to be able to return, but yet you do not want
1985  * to write them into the object store (e.g. a browse-only
1986  * application).
1987  */
1988 static struct cached_object {
1989         unsigned char sha1[20];
1990         enum object_type type;
1991         void *buf;
1992         unsigned long size;
1993 } *cached_objects;
1994 static int cached_object_nr, cached_object_alloc;
1995
1996 static struct cached_object empty_tree = {
1997         /* empty tree sha1: 4b825dc642cb6eb9a060e54bf8d69288fbee4904 */
1998         "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60"
1999         "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04",
2000         OBJ_TREE,
2001         "",
2002         0
2003 };
2004
2005 static struct cached_object *find_cached_object(const unsigned char *sha1)
2006 {
2007         int i;
2008         struct cached_object *co = cached_objects;
2009
2010         for (i = 0; i < cached_object_nr; i++, co++) {
2011                 if (!hashcmp(co->sha1, sha1))
2012                         return co;
2013         }
2014         if (!hashcmp(sha1, empty_tree.sha1))
2015                 return &empty_tree;
2016         return NULL;
2017 }
2018
2019 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2020                       unsigned char *sha1)
2021 {
2022         struct cached_object *co;
2023
2024         hash_sha1_file(buf, len, typename(type), sha1);
2025         if (has_sha1_file(sha1) || find_cached_object(sha1))
2026                 return 0;
2027         if (cached_object_alloc <= cached_object_nr) {
2028                 cached_object_alloc = alloc_nr(cached_object_alloc);
2029                 cached_objects = xrealloc(cached_objects,
2030                                           sizeof(*cached_objects) *
2031                                           cached_object_alloc);
2032         }
2033         co = &cached_objects[cached_object_nr++];
2034         co->size = len;
2035         co->type = type;
2036         co->buf = xmalloc(len);
2037         memcpy(co->buf, buf, len);
2038         hashcpy(co->sha1, sha1);
2039         return 0;
2040 }
2041
2042 void *read_object(const unsigned char *sha1, enum object_type *type,
2043                   unsigned long *size)
2044 {
2045         unsigned long mapsize;
2046         void *map, *buf;
2047         struct cached_object *co;
2048
2049         co = find_cached_object(sha1);
2050         if (co) {
2051                 *type = co->type;
2052                 *size = co->size;
2053                 return xmemdupz(co->buf, co->size);
2054         }
2055
2056         buf = read_packed_sha1(sha1, type, size);
2057         if (buf)
2058                 return buf;
2059         map = map_sha1_file(sha1, &mapsize);
2060         if (map) {
2061                 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
2062                 munmap(map, mapsize);
2063                 return buf;
2064         }
2065         reprepare_packed_git();
2066         return read_packed_sha1(sha1, type, size);
2067 }
2068
2069 void *read_sha1_file(const unsigned char *sha1, enum object_type *type,
2070                      unsigned long *size)
2071 {
2072         void *data = read_object(sha1, type, size);
2073         /* legacy behavior is to die on corrupted objects */
2074         if (!data && (has_loose_object(sha1) || has_packed_and_bad(sha1)))
2075                 die("object %s is corrupted", sha1_to_hex(sha1));
2076         return data;
2077 }
2078
2079 void *read_object_with_reference(const unsigned char *sha1,
2080                                  const char *required_type_name,
2081                                  unsigned long *size,
2082                                  unsigned char *actual_sha1_return)
2083 {
2084         enum object_type type, required_type;
2085         void *buffer;
2086         unsigned long isize;
2087         unsigned char actual_sha1[20];
2088
2089         required_type = type_from_string(required_type_name);
2090         hashcpy(actual_sha1, sha1);
2091         while (1) {
2092                 int ref_length = -1;
2093                 const char *ref_type = NULL;
2094
2095                 buffer = read_sha1_file(actual_sha1, &type, &isize);
2096                 if (!buffer)
2097                         return NULL;
2098                 if (type == required_type) {
2099                         *size = isize;
2100                         if (actual_sha1_return)
2101                                 hashcpy(actual_sha1_return, actual_sha1);
2102                         return buffer;
2103                 }
2104                 /* Handle references */
2105                 else if (type == OBJ_COMMIT)
2106                         ref_type = "tree ";
2107                 else if (type == OBJ_TAG)
2108                         ref_type = "object ";
2109                 else {
2110                         free(buffer);
2111                         return NULL;
2112                 }
2113                 ref_length = strlen(ref_type);
2114
2115                 if (ref_length + 40 > isize ||
2116                     memcmp(buffer, ref_type, ref_length) ||
2117                     get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2118                         free(buffer);
2119                         return NULL;
2120                 }
2121                 free(buffer);
2122                 /* Now we have the ID of the referred-to object in
2123                  * actual_sha1.  Check again. */
2124         }
2125 }
2126
2127 static void write_sha1_file_prepare(const void *buf, unsigned long len,
2128                                     const char *type, unsigned char *sha1,
2129                                     char *hdr, int *hdrlen)
2130 {
2131         SHA_CTX c;
2132
2133         /* Generate the header */
2134         *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
2135
2136         /* Sha1.. */
2137         SHA1_Init(&c);
2138         SHA1_Update(&c, hdr, *hdrlen);
2139         SHA1_Update(&c, buf, len);
2140         SHA1_Final(sha1, &c);
2141 }
2142
2143 /*
2144  * Move the just written object into its final resting place
2145  */
2146 int move_temp_to_file(const char *tmpfile, const char *filename)
2147 {
2148         int ret = link(tmpfile, filename);
2149
2150         /*
2151          * Coda hack - coda doesn't like cross-directory links,
2152          * so we fall back to a rename, which will mean that it
2153          * won't be able to check collisions, but that's not a
2154          * big deal.
2155          *
2156          * The same holds for FAT formatted media.
2157          *
2158          * When this succeeds, we just return 0. We have nothing
2159          * left to unlink.
2160          */
2161         if (ret && ret != EEXIST) {
2162                 if (!rename(tmpfile, filename))
2163                         return 0;
2164                 ret = errno;
2165         }
2166         unlink(tmpfile);
2167         if (ret) {
2168                 if (ret != EEXIST) {
2169                         return error("unable to write sha1 filename %s: %s\n", filename, strerror(ret));
2170                 }
2171                 /* FIXME!!! Collision check here ? */
2172         }
2173
2174         return 0;
2175 }
2176
2177 static int write_buffer(int fd, const void *buf, size_t len)
2178 {
2179         if (write_in_full(fd, buf, len) < 0)
2180                 return error("file write error (%s)", strerror(errno));
2181         return 0;
2182 }
2183
2184 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2185                    unsigned char *sha1)
2186 {
2187         char hdr[32];
2188         int hdrlen;
2189         write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2190         return 0;
2191 }
2192
2193 /* Finalize a file on disk, and close it. */
2194 static void close_sha1_file(int fd)
2195 {
2196         if (fsync_object_files)
2197                 fsync_or_die(fd, "sha1 file");
2198         fchmod(fd, 0444);
2199         if (close(fd) != 0)
2200                 die("unable to write sha1 file");
2201 }
2202
2203 /* Size of directory component, including the ending '/' */
2204 static inline int directory_size(const char *filename)
2205 {
2206         const char *s = strrchr(filename, '/');
2207         if (!s)
2208                 return 0;
2209         return s - filename + 1;
2210 }
2211
2212 /*
2213  * This creates a temporary file in the same directory as the final
2214  * 'filename'
2215  *
2216  * We want to avoid cross-directory filename renames, because those
2217  * can have problems on various filesystems (FAT, NFS, Coda).
2218  */
2219 static int create_tmpfile(char *buffer, size_t bufsiz, const char *filename)
2220 {
2221         int fd, dirlen = directory_size(filename);
2222
2223         if (dirlen + 20 > bufsiz) {
2224                 errno = ENAMETOOLONG;
2225                 return -1;
2226         }
2227         memcpy(buffer, filename, dirlen);
2228         strcpy(buffer + dirlen, "tmp_obj_XXXXXX");
2229         fd = mkstemp(buffer);
2230         if (fd < 0 && dirlen) {
2231                 /* Make sure the directory exists */
2232                 memcpy(buffer, filename, dirlen);
2233                 buffer[dirlen-1] = 0;
2234                 if (mkdir(buffer, 0777) || adjust_shared_perm(buffer))
2235                         return -1;
2236
2237                 /* Try again */
2238                 strcpy(buffer + dirlen - 1, "/tmp_obj_XXXXXX");
2239                 fd = mkstemp(buffer);
2240         }
2241         return fd;
2242 }
2243
2244 static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2245                               void *buf, unsigned long len, time_t mtime)
2246 {
2247         int fd, size, ret;
2248         unsigned char *compressed;
2249         z_stream stream;
2250         char *filename;
2251         static char tmpfile[PATH_MAX];
2252
2253         filename = sha1_file_name(sha1);
2254         fd = create_tmpfile(tmpfile, sizeof(tmpfile), filename);
2255         if (fd < 0) {
2256                 if (errno == EPERM)
2257                         return error("insufficient permission for adding an object to repository database %s\n", get_object_directory());
2258                 else
2259                         return error("unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
2260         }
2261
2262         /* Set it up */
2263         memset(&stream, 0, sizeof(stream));
2264         deflateInit(&stream, zlib_compression_level);
2265         size = 8 + deflateBound(&stream, len+hdrlen);
2266         compressed = xmalloc(size);
2267
2268         /* Compress it */
2269         stream.next_out = compressed;
2270         stream.avail_out = size;
2271
2272         /* First header.. */
2273         stream.next_in = (unsigned char *)hdr;
2274         stream.avail_in = hdrlen;
2275         while (deflate(&stream, 0) == Z_OK)
2276                 /* nothing */;
2277
2278         /* Then the data itself.. */
2279         stream.next_in = buf;
2280         stream.avail_in = len;
2281         ret = deflate(&stream, Z_FINISH);
2282         if (ret != Z_STREAM_END)
2283                 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2284
2285         ret = deflateEnd(&stream);
2286         if (ret != Z_OK)
2287                 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2288
2289         size = stream.total_out;
2290
2291         if (write_buffer(fd, compressed, size) < 0)
2292                 die("unable to write sha1 file");
2293         close_sha1_file(fd);
2294         free(compressed);
2295
2296         if (mtime) {
2297                 struct utimbuf utb;
2298                 utb.actime = mtime;
2299                 utb.modtime = mtime;
2300                 if (utime(tmpfile, &utb) < 0)
2301                         warning("failed utime() on %s: %s",
2302                                 tmpfile, strerror(errno));
2303         }
2304
2305         return move_temp_to_file(tmpfile, filename);
2306 }
2307
2308 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
2309 {
2310         unsigned char sha1[20];
2311         char hdr[32];
2312         int hdrlen;
2313
2314         /* Normally if we have it in the pack then we do not bother writing
2315          * it out into .git/objects/??/?{38} file.
2316          */
2317         write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2318         if (returnsha1)
2319                 hashcpy(returnsha1, sha1);
2320         if (has_sha1_file(sha1))
2321                 return 0;
2322         return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
2323 }
2324
2325 int force_object_loose(const unsigned char *sha1, time_t mtime)
2326 {
2327         void *buf;
2328         unsigned long len;
2329         enum object_type type;
2330         char hdr[32];
2331         int hdrlen;
2332
2333         if (has_loose_object(sha1))
2334                 return 0;
2335         buf = read_packed_sha1(sha1, &type, &len);
2336         if (!buf)
2337                 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
2338         hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
2339         return write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
2340 }
2341
2342 int has_pack_index(const unsigned char *sha1)
2343 {
2344         struct stat st;
2345         if (stat(sha1_pack_index_name(sha1), &st))
2346                 return 0;
2347         return 1;
2348 }
2349
2350 int has_pack_file(const unsigned char *sha1)
2351 {
2352         struct stat st;
2353         if (stat(sha1_pack_name(sha1), &st))
2354                 return 0;
2355         return 1;
2356 }
2357
2358 int has_sha1_pack(const unsigned char *sha1, const char **ignore_packed)
2359 {
2360         struct pack_entry e;
2361         return find_pack_entry(sha1, &e, ignore_packed);
2362 }
2363
2364 int has_sha1_file(const unsigned char *sha1)
2365 {
2366         struct pack_entry e;
2367
2368         if (find_pack_entry(sha1, &e, NULL))
2369                 return 1;
2370         return has_loose_object(sha1);
2371 }
2372
2373 static int index_mem(unsigned char *sha1, void *buf, size_t size,
2374                      int write_object, enum object_type type, const char *path)
2375 {
2376         int ret, re_allocated = 0;
2377
2378         if (!type)
2379                 type = OBJ_BLOB;
2380
2381         /*
2382          * Convert blobs to git internal format
2383          */
2384         if ((type == OBJ_BLOB) && path) {
2385                 struct strbuf nbuf;
2386                 strbuf_init(&nbuf, 0);
2387                 if (convert_to_git(path, buf, size, &nbuf,
2388                                    write_object ? safe_crlf : 0)) {
2389                         buf = strbuf_detach(&nbuf, &size);
2390                         re_allocated = 1;
2391                 }
2392         }
2393
2394         if (write_object)
2395                 ret = write_sha1_file(buf, size, typename(type), sha1);
2396         else
2397                 ret = hash_sha1_file(buf, size, typename(type), sha1);
2398         if (re_allocated)
2399                 free(buf);
2400         return ret;
2401 }
2402
2403 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object,
2404              enum object_type type, const char *path)
2405 {
2406         int ret;
2407         size_t size = xsize_t(st->st_size);
2408
2409         if (!S_ISREG(st->st_mode)) {
2410                 struct strbuf sbuf;
2411                 strbuf_init(&sbuf, 0);
2412                 if (strbuf_read(&sbuf, fd, 4096) >= 0)
2413                         ret = index_mem(sha1, sbuf.buf, sbuf.len, write_object,
2414                                         type, path);
2415                 else
2416                         ret = -1;
2417                 strbuf_release(&sbuf);
2418         } else if (size) {
2419                 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
2420                 ret = index_mem(sha1, buf, size, write_object, type, path);
2421                 munmap(buf, size);
2422         } else
2423                 ret = index_mem(sha1, NULL, size, write_object, type, path);
2424         close(fd);
2425         return ret;
2426 }
2427
2428 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
2429 {
2430         int fd;
2431         char *target;
2432         size_t len;
2433
2434         switch (st->st_mode & S_IFMT) {
2435         case S_IFREG:
2436                 fd = open(path, O_RDONLY);
2437                 if (fd < 0)
2438                         return error("open(\"%s\"): %s", path,
2439                                      strerror(errno));
2440                 if (index_fd(sha1, fd, st, write_object, OBJ_BLOB, path) < 0)
2441                         return error("%s: failed to insert into database",
2442                                      path);
2443                 break;
2444         case S_IFLNK:
2445                 len = xsize_t(st->st_size);
2446                 target = xmalloc(len + 1);
2447                 if (readlink(path, target, len + 1) != st->st_size) {
2448                         char *errstr = strerror(errno);
2449                         free(target);
2450                         return error("readlink(\"%s\"): %s", path,
2451                                      errstr);
2452                 }
2453                 if (!write_object)
2454                         hash_sha1_file(target, len, blob_type, sha1);
2455                 else if (write_sha1_file(target, len, blob_type, sha1))
2456                         return error("%s: failed to insert into database",
2457                                      path);
2458                 free(target);
2459                 break;
2460         case S_IFDIR:
2461                 return resolve_gitlink_ref(path, "HEAD", sha1);
2462         default:
2463                 return error("%s: unsupported file type", path);
2464         }
2465         return 0;
2466 }
2467
2468 int read_pack_header(int fd, struct pack_header *header)
2469 {
2470         if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
2471                 /* "eof before pack header was fully read" */
2472                 return PH_ERROR_EOF;
2473
2474         if (header->hdr_signature != htonl(PACK_SIGNATURE))
2475                 /* "protocol error (pack signature mismatch detected)" */
2476                 return PH_ERROR_PACK_SIGNATURE;
2477         if (!pack_version_ok(header->hdr_version))
2478                 /* "protocol error (pack version unsupported)" */
2479                 return PH_ERROR_PROTOCOL;
2480         return 0;
2481 }