write_sha1_file: freshen existing objects
[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 "string-list.h"
11 #include "delta.h"
12 #include "pack.h"
13 #include "blob.h"
14 #include "commit.h"
15 #include "run-command.h"
16 #include "tag.h"
17 #include "tree.h"
18 #include "tree-walk.h"
19 #include "refs.h"
20 #include "pack-revindex.h"
21 #include "sha1-lookup.h"
22 #include "bulk-checkin.h"
23 #include "streaming.h"
24 #include "dir.h"
25
26 #ifndef O_NOATIME
27 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
28 #define O_NOATIME 01000000
29 #else
30 #define O_NOATIME 0
31 #endif
32 #endif
33
34 #define SZ_FMT PRIuMAX
35 static inline uintmax_t sz_fmt(size_t s) { return s; }
36
37 const unsigned char null_sha1[20];
38
39 /*
40  * This is meant to hold a *small* number of objects that you would
41  * want read_sha1_file() to be able to return, but yet you do not want
42  * to write them into the object store (e.g. a browse-only
43  * application).
44  */
45 static struct cached_object {
46         unsigned char sha1[20];
47         enum object_type type;
48         void *buf;
49         unsigned long size;
50 } *cached_objects;
51 static int cached_object_nr, cached_object_alloc;
52
53 static struct cached_object empty_tree = {
54         EMPTY_TREE_SHA1_BIN_LITERAL,
55         OBJ_TREE,
56         "",
57         0
58 };
59
60 /*
61  * A pointer to the last packed_git in which an object was found.
62  * When an object is sought, we look in this packfile first, because
63  * objects that are looked up at similar times are often in the same
64  * packfile as one another.
65  */
66 static struct packed_git *last_found_pack;
67
68 static struct cached_object *find_cached_object(const unsigned char *sha1)
69 {
70         int i;
71         struct cached_object *co = cached_objects;
72
73         for (i = 0; i < cached_object_nr; i++, co++) {
74                 if (!hashcmp(co->sha1, sha1))
75                         return co;
76         }
77         if (!hashcmp(sha1, empty_tree.sha1))
78                 return &empty_tree;
79         return NULL;
80 }
81
82 int mkdir_in_gitdir(const char *path)
83 {
84         if (mkdir(path, 0777)) {
85                 int saved_errno = errno;
86                 struct stat st;
87                 struct strbuf sb = STRBUF_INIT;
88
89                 if (errno != EEXIST)
90                         return -1;
91                 /*
92                  * Are we looking at a path in a symlinked worktree
93                  * whose original repository does not yet have it?
94                  * e.g. .git/rr-cache pointing at its original
95                  * repository in which the user hasn't performed any
96                  * conflict resolution yet?
97                  */
98                 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
99                     strbuf_readlink(&sb, path, st.st_size) ||
100                     !is_absolute_path(sb.buf) ||
101                     mkdir(sb.buf, 0777)) {
102                         strbuf_release(&sb);
103                         errno = saved_errno;
104                         return -1;
105                 }
106                 strbuf_release(&sb);
107         }
108         return adjust_shared_perm(path);
109 }
110
111 enum scld_error safe_create_leading_directories(char *path)
112 {
113         char *next_component = path + offset_1st_component(path);
114         enum scld_error ret = SCLD_OK;
115
116         while (ret == SCLD_OK && next_component) {
117                 struct stat st;
118                 char *slash = next_component, slash_character;
119
120                 while (*slash && !is_dir_sep(*slash))
121                         slash++;
122
123                 if (!*slash)
124                         break;
125
126                 next_component = slash + 1;
127                 while (is_dir_sep(*next_component))
128                         next_component++;
129                 if (!*next_component)
130                         break;
131
132                 slash_character = *slash;
133                 *slash = '\0';
134                 if (!stat(path, &st)) {
135                         /* path exists */
136                         if (!S_ISDIR(st.st_mode))
137                                 ret = SCLD_EXISTS;
138                 } else if (mkdir(path, 0777)) {
139                         if (errno == EEXIST &&
140                             !stat(path, &st) && S_ISDIR(st.st_mode))
141                                 ; /* somebody created it since we checked */
142                         else if (errno == ENOENT)
143                                 /*
144                                  * Either mkdir() failed because
145                                  * somebody just pruned the containing
146                                  * directory, or stat() failed because
147                                  * the file that was in our way was
148                                  * just removed.  Either way, inform
149                                  * the caller that it might be worth
150                                  * trying again:
151                                  */
152                                 ret = SCLD_VANISHED;
153                         else
154                                 ret = SCLD_FAILED;
155                 } else if (adjust_shared_perm(path)) {
156                         ret = SCLD_PERMS;
157                 }
158                 *slash = slash_character;
159         }
160         return ret;
161 }
162
163 enum scld_error safe_create_leading_directories_const(const char *path)
164 {
165         /* path points to cache entries, so xstrdup before messing with it */
166         char *buf = xstrdup(path);
167         enum scld_error result = safe_create_leading_directories(buf);
168         free(buf);
169         return result;
170 }
171
172 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
173 {
174         int i;
175         for (i = 0; i < 20; i++) {
176                 static char hex[] = "0123456789abcdef";
177                 unsigned int val = sha1[i];
178                 char *pos = pathbuf + i*2 + (i > 0);
179                 *pos++ = hex[val >> 4];
180                 *pos = hex[val & 0xf];
181         }
182 }
183
184 const char *sha1_file_name(const unsigned char *sha1)
185 {
186         static char buf[PATH_MAX];
187         const char *objdir;
188         int len;
189
190         objdir = get_object_directory();
191         len = strlen(objdir);
192
193         /* '/' + sha1(2) + '/' + sha1(38) + '\0' */
194         if (len + 43 > PATH_MAX)
195                 die("insanely long object directory %s", objdir);
196         memcpy(buf, objdir, len);
197         buf[len] = '/';
198         buf[len+3] = '/';
199         buf[len+42] = '\0';
200         fill_sha1_path(buf + len + 1, sha1);
201         return buf;
202 }
203
204 /*
205  * Return the name of the pack or index file with the specified sha1
206  * in its filename.  *base and *name are scratch space that must be
207  * provided by the caller.  which should be "pack" or "idx".
208  */
209 static char *sha1_get_pack_name(const unsigned char *sha1,
210                                 char **name, char **base, const char *which)
211 {
212         static const char hex[] = "0123456789abcdef";
213         char *buf;
214         int i;
215
216         if (!*base) {
217                 const char *sha1_file_directory = get_object_directory();
218                 int len = strlen(sha1_file_directory);
219                 *base = xmalloc(len + 60);
220                 sprintf(*base, "%s/pack/pack-1234567890123456789012345678901234567890.%s",
221                         sha1_file_directory, which);
222                 *name = *base + len + 11;
223         }
224
225         buf = *name;
226
227         for (i = 0; i < 20; i++) {
228                 unsigned int val = *sha1++;
229                 *buf++ = hex[val >> 4];
230                 *buf++ = hex[val & 0xf];
231         }
232
233         return *base;
234 }
235
236 char *sha1_pack_name(const unsigned char *sha1)
237 {
238         static char *name, *base;
239
240         return sha1_get_pack_name(sha1, &name, &base, "pack");
241 }
242
243 char *sha1_pack_index_name(const unsigned char *sha1)
244 {
245         static char *name, *base;
246
247         return sha1_get_pack_name(sha1, &name, &base, "idx");
248 }
249
250 struct alternate_object_database *alt_odb_list;
251 static struct alternate_object_database **alt_odb_tail;
252
253 /*
254  * Prepare alternate object database registry.
255  *
256  * The variable alt_odb_list points at the list of struct
257  * alternate_object_database.  The elements on this list come from
258  * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
259  * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
260  * whose contents is similar to that environment variable but can be
261  * LF separated.  Its base points at a statically allocated buffer that
262  * contains "/the/directory/corresponding/to/.git/objects/...", while
263  * its name points just after the slash at the end of ".git/objects/"
264  * in the example above, and has enough space to hold 40-byte hex
265  * SHA1, an extra slash for the first level indirection, and the
266  * terminating NUL.
267  */
268 static int link_alt_odb_entry(const char *entry, const char *relative_base,
269         int depth, const char *normalized_objdir)
270 {
271         struct alternate_object_database *ent;
272         struct alternate_object_database *alt;
273         int pfxlen, entlen;
274         struct strbuf pathbuf = STRBUF_INIT;
275
276         if (!is_absolute_path(entry) && relative_base) {
277                 strbuf_addstr(&pathbuf, real_path(relative_base));
278                 strbuf_addch(&pathbuf, '/');
279         }
280         strbuf_addstr(&pathbuf, entry);
281
282         normalize_path_copy(pathbuf.buf, pathbuf.buf);
283
284         pfxlen = strlen(pathbuf.buf);
285
286         /*
287          * The trailing slash after the directory name is given by
288          * this function at the end. Remove duplicates.
289          */
290         while (pfxlen && pathbuf.buf[pfxlen-1] == '/')
291                 pfxlen -= 1;
292
293         entlen = pfxlen + 43; /* '/' + 2 hex + '/' + 38 hex + NUL */
294         ent = xmalloc(sizeof(*ent) + entlen);
295         memcpy(ent->base, pathbuf.buf, pfxlen);
296         strbuf_release(&pathbuf);
297
298         ent->name = ent->base + pfxlen + 1;
299         ent->base[pfxlen + 3] = '/';
300         ent->base[pfxlen] = ent->base[entlen-1] = 0;
301
302         /* Detect cases where alternate disappeared */
303         if (!is_directory(ent->base)) {
304                 error("object directory %s does not exist; "
305                       "check .git/objects/info/alternates.",
306                       ent->base);
307                 free(ent);
308                 return -1;
309         }
310
311         /* Prevent the common mistake of listing the same
312          * thing twice, or object directory itself.
313          */
314         for (alt = alt_odb_list; alt; alt = alt->next) {
315                 if (pfxlen == alt->name - alt->base - 1 &&
316                     !memcmp(ent->base, alt->base, pfxlen)) {
317                         free(ent);
318                         return -1;
319                 }
320         }
321         if (!strcmp_icase(ent->base, normalized_objdir)) {
322                 free(ent);
323                 return -1;
324         }
325
326         /* add the alternate entry */
327         *alt_odb_tail = ent;
328         alt_odb_tail = &(ent->next);
329         ent->next = NULL;
330
331         /* recursively add alternates */
332         read_info_alternates(ent->base, depth + 1);
333
334         ent->base[pfxlen] = '/';
335
336         return 0;
337 }
338
339 static void link_alt_odb_entries(const char *alt, int len, int sep,
340                                  const char *relative_base, int depth)
341 {
342         struct string_list entries = STRING_LIST_INIT_NODUP;
343         char *alt_copy;
344         int i;
345         struct strbuf objdirbuf = STRBUF_INIT;
346
347         if (depth > 5) {
348                 error("%s: ignoring alternate object stores, nesting too deep.",
349                                 relative_base);
350                 return;
351         }
352
353         strbuf_add_absolute_path(&objdirbuf, get_object_directory());
354         normalize_path_copy(objdirbuf.buf, objdirbuf.buf);
355
356         alt_copy = xmemdupz(alt, len);
357         string_list_split_in_place(&entries, alt_copy, sep, -1);
358         for (i = 0; i < entries.nr; i++) {
359                 const char *entry = entries.items[i].string;
360                 if (entry[0] == '\0' || entry[0] == '#')
361                         continue;
362                 if (!is_absolute_path(entry) && depth) {
363                         error("%s: ignoring relative alternate object store %s",
364                                         relative_base, entry);
365                 } else {
366                         link_alt_odb_entry(entry, relative_base, depth, objdirbuf.buf);
367                 }
368         }
369         string_list_clear(&entries, 0);
370         free(alt_copy);
371         strbuf_release(&objdirbuf);
372 }
373
374 void read_info_alternates(const char * relative_base, int depth)
375 {
376         char *map;
377         size_t mapsz;
378         struct stat st;
379         const char alt_file_name[] = "info/alternates";
380         /* Given that relative_base is no longer than PATH_MAX,
381            ensure that "path" has enough space to append "/", the
382            file name, "info/alternates", and a trailing NUL.  */
383         char path[PATH_MAX + 1 + sizeof alt_file_name];
384         int fd;
385
386         sprintf(path, "%s/%s", relative_base, alt_file_name);
387         fd = git_open_noatime(path);
388         if (fd < 0)
389                 return;
390         if (fstat(fd, &st) || (st.st_size == 0)) {
391                 close(fd);
392                 return;
393         }
394         mapsz = xsize_t(st.st_size);
395         map = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, fd, 0);
396         close(fd);
397
398         link_alt_odb_entries(map, mapsz, '\n', relative_base, depth);
399
400         munmap(map, mapsz);
401 }
402
403 void add_to_alternates_file(const char *reference)
404 {
405         struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
406         int fd = hold_lock_file_for_append(lock, git_path("objects/info/alternates"), LOCK_DIE_ON_ERROR);
407         char *alt = mkpath("%s\n", reference);
408         write_or_die(fd, alt, strlen(alt));
409         if (commit_lock_file(lock))
410                 die("could not close alternates file");
411         if (alt_odb_tail)
412                 link_alt_odb_entries(alt, strlen(alt), '\n', NULL, 0);
413 }
414
415 int foreach_alt_odb(alt_odb_fn fn, void *cb)
416 {
417         struct alternate_object_database *ent;
418         int r = 0;
419
420         prepare_alt_odb();
421         for (ent = alt_odb_list; ent; ent = ent->next) {
422                 r = fn(ent, cb);
423                 if (r)
424                         break;
425         }
426         return r;
427 }
428
429 void prepare_alt_odb(void)
430 {
431         const char *alt;
432
433         if (alt_odb_tail)
434                 return;
435
436         alt = getenv(ALTERNATE_DB_ENVIRONMENT);
437         if (!alt) alt = "";
438
439         alt_odb_tail = &alt_odb_list;
440         link_alt_odb_entries(alt, strlen(alt), PATH_SEP, NULL, 0);
441
442         read_info_alternates(get_object_directory(), 0);
443 }
444
445 static int freshen_file(const char *fn)
446 {
447         struct utimbuf t;
448         t.actime = t.modtime = time(NULL);
449         return !utime(fn, &t);
450 }
451
452 static int check_and_freshen_file(const char *fn, int freshen)
453 {
454         if (access(fn, F_OK))
455                 return 0;
456         if (freshen && freshen_file(fn))
457                 return 0;
458         return 1;
459 }
460
461 static int check_and_freshen_local(const unsigned char *sha1, int freshen)
462 {
463         return check_and_freshen_file(sha1_file_name(sha1), freshen);
464 }
465
466 static int check_and_freshen_nonlocal(const unsigned char *sha1, int freshen)
467 {
468         struct alternate_object_database *alt;
469         prepare_alt_odb();
470         for (alt = alt_odb_list; alt; alt = alt->next) {
471                 fill_sha1_path(alt->name, sha1);
472                 if (check_and_freshen_file(alt->base, freshen))
473                         return 1;
474         }
475         return 0;
476 }
477
478 static int check_and_freshen(const unsigned char *sha1, int freshen)
479 {
480         return check_and_freshen_local(sha1, freshen) ||
481                check_and_freshen_nonlocal(sha1, freshen);
482 }
483
484 int has_loose_object_nonlocal(const unsigned char *sha1)
485 {
486         return check_and_freshen_nonlocal(sha1, 0);
487 }
488
489 static int has_loose_object(const unsigned char *sha1)
490 {
491         return check_and_freshen(sha1, 0);
492 }
493
494 static unsigned int pack_used_ctr;
495 static unsigned int pack_mmap_calls;
496 static unsigned int peak_pack_open_windows;
497 static unsigned int pack_open_windows;
498 static unsigned int pack_open_fds;
499 static unsigned int pack_max_fds;
500 static size_t peak_pack_mapped;
501 static size_t pack_mapped;
502 struct packed_git *packed_git;
503
504 void pack_report(void)
505 {
506         fprintf(stderr,
507                 "pack_report: getpagesize()            = %10" SZ_FMT "\n"
508                 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
509                 "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n",
510                 sz_fmt(getpagesize()),
511                 sz_fmt(packed_git_window_size),
512                 sz_fmt(packed_git_limit));
513         fprintf(stderr,
514                 "pack_report: pack_used_ctr            = %10u\n"
515                 "pack_report: pack_mmap_calls          = %10u\n"
516                 "pack_report: pack_open_windows        = %10u / %10u\n"
517                 "pack_report: pack_mapped              = "
518                         "%10" SZ_FMT " / %10" SZ_FMT "\n",
519                 pack_used_ctr,
520                 pack_mmap_calls,
521                 pack_open_windows, peak_pack_open_windows,
522                 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
523 }
524
525 /*
526  * Open and mmap the index file at path, perform a couple of
527  * consistency checks, then record its information to p.  Return 0 on
528  * success.
529  */
530 static int check_packed_git_idx(const char *path, struct packed_git *p)
531 {
532         void *idx_map;
533         struct pack_idx_header *hdr;
534         size_t idx_size;
535         uint32_t version, nr, i, *index;
536         int fd = git_open_noatime(path);
537         struct stat st;
538
539         if (fd < 0)
540                 return -1;
541         if (fstat(fd, &st)) {
542                 close(fd);
543                 return -1;
544         }
545         idx_size = xsize_t(st.st_size);
546         if (idx_size < 4 * 256 + 20 + 20) {
547                 close(fd);
548                 return error("index file %s is too small", path);
549         }
550         idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
551         close(fd);
552
553         hdr = idx_map;
554         if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
555                 version = ntohl(hdr->idx_version);
556                 if (version < 2 || version > 2) {
557                         munmap(idx_map, idx_size);
558                         return error("index file %s is version %"PRIu32
559                                      " and is not supported by this binary"
560                                      " (try upgrading GIT to a newer version)",
561                                      path, version);
562                 }
563         } else
564                 version = 1;
565
566         nr = 0;
567         index = idx_map;
568         if (version > 1)
569                 index += 2;  /* skip index header */
570         for (i = 0; i < 256; i++) {
571                 uint32_t n = ntohl(index[i]);
572                 if (n < nr) {
573                         munmap(idx_map, idx_size);
574                         return error("non-monotonic index %s", path);
575                 }
576                 nr = n;
577         }
578
579         if (version == 1) {
580                 /*
581                  * Total size:
582                  *  - 256 index entries 4 bytes each
583                  *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
584                  *  - 20-byte SHA1 of the packfile
585                  *  - 20-byte SHA1 file checksum
586                  */
587                 if (idx_size != 4*256 + nr * 24 + 20 + 20) {
588                         munmap(idx_map, idx_size);
589                         return error("wrong index v1 file size in %s", path);
590                 }
591         } else if (version == 2) {
592                 /*
593                  * Minimum size:
594                  *  - 8 bytes of header
595                  *  - 256 index entries 4 bytes each
596                  *  - 20-byte sha1 entry * nr
597                  *  - 4-byte crc entry * nr
598                  *  - 4-byte offset entry * nr
599                  *  - 20-byte SHA1 of the packfile
600                  *  - 20-byte SHA1 file checksum
601                  * And after the 4-byte offset table might be a
602                  * variable sized table containing 8-byte entries
603                  * for offsets larger than 2^31.
604                  */
605                 unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
606                 unsigned long max_size = min_size;
607                 if (nr)
608                         max_size += (nr - 1)*8;
609                 if (idx_size < min_size || idx_size > max_size) {
610                         munmap(idx_map, idx_size);
611                         return error("wrong index v2 file size in %s", path);
612                 }
613                 if (idx_size != min_size &&
614                     /*
615                      * make sure we can deal with large pack offsets.
616                      * 31-bit signed offset won't be enough, neither
617                      * 32-bit unsigned one will be.
618                      */
619                     (sizeof(off_t) <= 4)) {
620                         munmap(idx_map, idx_size);
621                         return error("pack too large for current definition of off_t in %s", path);
622                 }
623         }
624
625         p->index_version = version;
626         p->index_data = idx_map;
627         p->index_size = idx_size;
628         p->num_objects = nr;
629         return 0;
630 }
631
632 int open_pack_index(struct packed_git *p)
633 {
634         char *idx_name;
635         int ret;
636
637         if (p->index_data)
638                 return 0;
639
640         idx_name = xstrdup(p->pack_name);
641         strcpy(idx_name + strlen(idx_name) - strlen(".pack"), ".idx");
642         ret = check_packed_git_idx(idx_name, p);
643         free(idx_name);
644         return ret;
645 }
646
647 static void scan_windows(struct packed_git *p,
648         struct packed_git **lru_p,
649         struct pack_window **lru_w,
650         struct pack_window **lru_l)
651 {
652         struct pack_window *w, *w_l;
653
654         for (w_l = NULL, w = p->windows; w; w = w->next) {
655                 if (!w->inuse_cnt) {
656                         if (!*lru_w || w->last_used < (*lru_w)->last_used) {
657                                 *lru_p = p;
658                                 *lru_w = w;
659                                 *lru_l = w_l;
660                         }
661                 }
662                 w_l = w;
663         }
664 }
665
666 static int unuse_one_window(struct packed_git *current)
667 {
668         struct packed_git *p, *lru_p = NULL;
669         struct pack_window *lru_w = NULL, *lru_l = NULL;
670
671         if (current)
672                 scan_windows(current, &lru_p, &lru_w, &lru_l);
673         for (p = packed_git; p; p = p->next)
674                 scan_windows(p, &lru_p, &lru_w, &lru_l);
675         if (lru_p) {
676                 munmap(lru_w->base, lru_w->len);
677                 pack_mapped -= lru_w->len;
678                 if (lru_l)
679                         lru_l->next = lru_w->next;
680                 else
681                         lru_p->windows = lru_w->next;
682                 free(lru_w);
683                 pack_open_windows--;
684                 return 1;
685         }
686         return 0;
687 }
688
689 void release_pack_memory(size_t need)
690 {
691         size_t cur = pack_mapped;
692         while (need >= (cur - pack_mapped) && unuse_one_window(NULL))
693                 ; /* nothing */
694 }
695
696 static void mmap_limit_check(size_t length)
697 {
698         static size_t limit = 0;
699         if (!limit) {
700                 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
701                 if (!limit)
702                         limit = SIZE_MAX;
703         }
704         if (length > limit)
705                 die("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX,
706                     (uintmax_t)length, (uintmax_t)limit);
707 }
708
709 void *xmmap(void *start, size_t length,
710         int prot, int flags, int fd, off_t offset)
711 {
712         void *ret;
713
714         mmap_limit_check(length);
715         ret = mmap(start, length, prot, flags, fd, offset);
716         if (ret == MAP_FAILED) {
717                 if (!length)
718                         return NULL;
719                 release_pack_memory(length);
720                 ret = mmap(start, length, prot, flags, fd, offset);
721                 if (ret == MAP_FAILED)
722                         die_errno("Out of memory? mmap failed");
723         }
724         return ret;
725 }
726
727 void close_pack_windows(struct packed_git *p)
728 {
729         while (p->windows) {
730                 struct pack_window *w = p->windows;
731
732                 if (w->inuse_cnt)
733                         die("pack '%s' still has open windows to it",
734                             p->pack_name);
735                 munmap(w->base, w->len);
736                 pack_mapped -= w->len;
737                 pack_open_windows--;
738                 p->windows = w->next;
739                 free(w);
740         }
741 }
742
743 /*
744  * The LRU pack is the one with the oldest MRU window, preferring packs
745  * with no used windows, or the oldest mtime if it has no windows allocated.
746  */
747 static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
748 {
749         struct pack_window *w, *this_mru_w;
750         int has_windows_inuse = 0;
751
752         /*
753          * Reject this pack if it has windows and the previously selected
754          * one does not.  If this pack does not have windows, reject
755          * it if the pack file is newer than the previously selected one.
756          */
757         if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
758                 return;
759
760         for (w = this_mru_w = p->windows; w; w = w->next) {
761                 /*
762                  * Reject this pack if any of its windows are in use,
763                  * but the previously selected pack did not have any
764                  * inuse windows.  Otherwise, record that this pack
765                  * has windows in use.
766                  */
767                 if (w->inuse_cnt) {
768                         if (*accept_windows_inuse)
769                                 has_windows_inuse = 1;
770                         else
771                                 return;
772                 }
773
774                 if (w->last_used > this_mru_w->last_used)
775                         this_mru_w = w;
776
777                 /*
778                  * Reject this pack if it has windows that have been
779                  * used more recently than the previously selected pack.
780                  * If the previously selected pack had windows inuse and
781                  * we have not encountered a window in this pack that is
782                  * inuse, skip this check since we prefer a pack with no
783                  * inuse windows to one that has inuse windows.
784                  */
785                 if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
786                     this_mru_w->last_used > (*mru_w)->last_used)
787                         return;
788         }
789
790         /*
791          * Select this pack.
792          */
793         *mru_w = this_mru_w;
794         *lru_p = p;
795         *accept_windows_inuse = has_windows_inuse;
796 }
797
798 static int close_one_pack(void)
799 {
800         struct packed_git *p, *lru_p = NULL;
801         struct pack_window *mru_w = NULL;
802         int accept_windows_inuse = 1;
803
804         for (p = packed_git; p; p = p->next) {
805                 if (p->pack_fd == -1)
806                         continue;
807                 find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
808         }
809
810         if (lru_p) {
811                 close(lru_p->pack_fd);
812                 pack_open_fds--;
813                 lru_p->pack_fd = -1;
814                 return 1;
815         }
816
817         return 0;
818 }
819
820 void unuse_pack(struct pack_window **w_cursor)
821 {
822         struct pack_window *w = *w_cursor;
823         if (w) {
824                 w->inuse_cnt--;
825                 *w_cursor = NULL;
826         }
827 }
828
829 void close_pack_index(struct packed_git *p)
830 {
831         if (p->index_data) {
832                 munmap((void *)p->index_data, p->index_size);
833                 p->index_data = NULL;
834         }
835 }
836
837 /*
838  * This is used by git-repack in case a newly created pack happens to
839  * contain the same set of objects as an existing one.  In that case
840  * the resulting file might be different even if its name would be the
841  * same.  It is best to close any reference to the old pack before it is
842  * replaced on disk.  Of course no index pointers or windows for given pack
843  * must subsist at this point.  If ever objects from this pack are requested
844  * again, the new version of the pack will be reinitialized through
845  * reprepare_packed_git().
846  */
847 void free_pack_by_name(const char *pack_name)
848 {
849         struct packed_git *p, **pp = &packed_git;
850
851         while (*pp) {
852                 p = *pp;
853                 if (strcmp(pack_name, p->pack_name) == 0) {
854                         clear_delta_base_cache();
855                         close_pack_windows(p);
856                         if (p->pack_fd != -1) {
857                                 close(p->pack_fd);
858                                 pack_open_fds--;
859                         }
860                         close_pack_index(p);
861                         free(p->bad_object_sha1);
862                         *pp = p->next;
863                         if (last_found_pack == p)
864                                 last_found_pack = NULL;
865                         free(p);
866                         return;
867                 }
868                 pp = &p->next;
869         }
870 }
871
872 static unsigned int get_max_fd_limit(void)
873 {
874 #ifdef RLIMIT_NOFILE
875         {
876                 struct rlimit lim;
877
878                 if (!getrlimit(RLIMIT_NOFILE, &lim))
879                         return lim.rlim_cur;
880         }
881 #endif
882
883 #ifdef _SC_OPEN_MAX
884         {
885                 long open_max = sysconf(_SC_OPEN_MAX);
886                 if (0 < open_max)
887                         return open_max;
888                 /*
889                  * Otherwise, we got -1 for one of the two
890                  * reasons:
891                  *
892                  * (1) sysconf() did not understand _SC_OPEN_MAX
893                  *     and signaled an error with -1; or
894                  * (2) sysconf() said there is no limit.
895                  *
896                  * We _could_ clear errno before calling sysconf() to
897                  * tell these two cases apart and return a huge number
898                  * in the latter case to let the caller cap it to a
899                  * value that is not so selfish, but letting the
900                  * fallback OPEN_MAX codepath take care of these cases
901                  * is a lot simpler.
902                  */
903         }
904 #endif
905
906 #ifdef OPEN_MAX
907         return OPEN_MAX;
908 #else
909         return 1; /* see the caller ;-) */
910 #endif
911 }
912
913 /*
914  * Do not call this directly as this leaks p->pack_fd on error return;
915  * call open_packed_git() instead.
916  */
917 static int open_packed_git_1(struct packed_git *p)
918 {
919         struct stat st;
920         struct pack_header hdr;
921         unsigned char sha1[20];
922         unsigned char *idx_sha1;
923         long fd_flag;
924
925         if (!p->index_data && open_pack_index(p))
926                 return error("packfile %s index unavailable", p->pack_name);
927
928         if (!pack_max_fds) {
929                 unsigned int max_fds = get_max_fd_limit();
930
931                 /* Save 3 for stdin/stdout/stderr, 22 for work */
932                 if (25 < max_fds)
933                         pack_max_fds = max_fds - 25;
934                 else
935                         pack_max_fds = 1;
936         }
937
938         while (pack_max_fds <= pack_open_fds && close_one_pack())
939                 ; /* nothing */
940
941         p->pack_fd = git_open_noatime(p->pack_name);
942         if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
943                 return -1;
944         pack_open_fds++;
945
946         /* If we created the struct before we had the pack we lack size. */
947         if (!p->pack_size) {
948                 if (!S_ISREG(st.st_mode))
949                         return error("packfile %s not a regular file", p->pack_name);
950                 p->pack_size = st.st_size;
951         } else if (p->pack_size != st.st_size)
952                 return error("packfile %s size changed", p->pack_name);
953
954         /* We leave these file descriptors open with sliding mmap;
955          * there is no point keeping them open across exec(), though.
956          */
957         fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
958         if (fd_flag < 0)
959                 return error("cannot determine file descriptor flags");
960         fd_flag |= FD_CLOEXEC;
961         if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
962                 return error("cannot set FD_CLOEXEC");
963
964         /* Verify we recognize this pack file format. */
965         if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
966                 return error("file %s is far too short to be a packfile", p->pack_name);
967         if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
968                 return error("file %s is not a GIT packfile", p->pack_name);
969         if (!pack_version_ok(hdr.hdr_version))
970                 return error("packfile %s is version %"PRIu32" and not"
971                         " supported (try upgrading GIT to a newer version)",
972                         p->pack_name, ntohl(hdr.hdr_version));
973
974         /* Verify the pack matches its index. */
975         if (p->num_objects != ntohl(hdr.hdr_entries))
976                 return error("packfile %s claims to have %"PRIu32" objects"
977                              " while index indicates %"PRIu32" objects",
978                              p->pack_name, ntohl(hdr.hdr_entries),
979                              p->num_objects);
980         if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
981                 return error("end of packfile %s is unavailable", p->pack_name);
982         if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
983                 return error("packfile %s signature is unavailable", p->pack_name);
984         idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
985         if (hashcmp(sha1, idx_sha1))
986                 return error("packfile %s does not match index", p->pack_name);
987         return 0;
988 }
989
990 static int open_packed_git(struct packed_git *p)
991 {
992         if (!open_packed_git_1(p))
993                 return 0;
994         if (p->pack_fd != -1) {
995                 close(p->pack_fd);
996                 pack_open_fds--;
997                 p->pack_fd = -1;
998         }
999         return -1;
1000 }
1001
1002 static int in_window(struct pack_window *win, off_t offset)
1003 {
1004         /* We must promise at least 20 bytes (one hash) after the
1005          * offset is available from this window, otherwise the offset
1006          * is not actually in this window and a different window (which
1007          * has that one hash excess) must be used.  This is to support
1008          * the object header and delta base parsing routines below.
1009          */
1010         off_t win_off = win->offset;
1011         return win_off <= offset
1012                 && (offset + 20) <= (win_off + win->len);
1013 }
1014
1015 unsigned char *use_pack(struct packed_git *p,
1016                 struct pack_window **w_cursor,
1017                 off_t offset,
1018                 unsigned long *left)
1019 {
1020         struct pack_window *win = *w_cursor;
1021
1022         /* Since packfiles end in a hash of their content and it's
1023          * pointless to ask for an offset into the middle of that
1024          * hash, and the in_window function above wouldn't match
1025          * don't allow an offset too close to the end of the file.
1026          */
1027         if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
1028                 die("packfile %s cannot be accessed", p->pack_name);
1029         if (offset > (p->pack_size - 20))
1030                 die("offset beyond end of packfile (truncated pack?)");
1031
1032         if (!win || !in_window(win, offset)) {
1033                 if (win)
1034                         win->inuse_cnt--;
1035                 for (win = p->windows; win; win = win->next) {
1036                         if (in_window(win, offset))
1037                                 break;
1038                 }
1039                 if (!win) {
1040                         size_t window_align = packed_git_window_size / 2;
1041                         off_t len;
1042
1043                         if (p->pack_fd == -1 && open_packed_git(p))
1044                                 die("packfile %s cannot be accessed", p->pack_name);
1045
1046                         win = xcalloc(1, sizeof(*win));
1047                         win->offset = (offset / window_align) * window_align;
1048                         len = p->pack_size - win->offset;
1049                         if (len > packed_git_window_size)
1050                                 len = packed_git_window_size;
1051                         win->len = (size_t)len;
1052                         pack_mapped += win->len;
1053                         while (packed_git_limit < pack_mapped
1054                                 && unuse_one_window(p))
1055                                 ; /* nothing */
1056                         win->base = xmmap(NULL, win->len,
1057                                 PROT_READ, MAP_PRIVATE,
1058                                 p->pack_fd, win->offset);
1059                         if (win->base == MAP_FAILED)
1060                                 die("packfile %s cannot be mapped: %s",
1061                                         p->pack_name,
1062                                         strerror(errno));
1063                         if (!win->offset && win->len == p->pack_size
1064                                 && !p->do_not_close) {
1065                                 close(p->pack_fd);
1066                                 pack_open_fds--;
1067                                 p->pack_fd = -1;
1068                         }
1069                         pack_mmap_calls++;
1070                         pack_open_windows++;
1071                         if (pack_mapped > peak_pack_mapped)
1072                                 peak_pack_mapped = pack_mapped;
1073                         if (pack_open_windows > peak_pack_open_windows)
1074                                 peak_pack_open_windows = pack_open_windows;
1075                         win->next = p->windows;
1076                         p->windows = win;
1077                 }
1078         }
1079         if (win != *w_cursor) {
1080                 win->last_used = pack_used_ctr++;
1081                 win->inuse_cnt++;
1082                 *w_cursor = win;
1083         }
1084         offset -= win->offset;
1085         if (left)
1086                 *left = win->len - xsize_t(offset);
1087         return win->base + offset;
1088 }
1089
1090 static struct packed_git *alloc_packed_git(int extra)
1091 {
1092         struct packed_git *p = xmalloc(sizeof(*p) + extra);
1093         memset(p, 0, sizeof(*p));
1094         p->pack_fd = -1;
1095         return p;
1096 }
1097
1098 static void try_to_free_pack_memory(size_t size)
1099 {
1100         release_pack_memory(size);
1101 }
1102
1103 struct packed_git *add_packed_git(const char *path, int path_len, int local)
1104 {
1105         static int have_set_try_to_free_routine;
1106         struct stat st;
1107         struct packed_git *p = alloc_packed_git(path_len + 2);
1108
1109         if (!have_set_try_to_free_routine) {
1110                 have_set_try_to_free_routine = 1;
1111                 set_try_to_free_routine(try_to_free_pack_memory);
1112         }
1113
1114         /*
1115          * Make sure a corresponding .pack file exists and that
1116          * the index looks sane.
1117          */
1118         path_len -= strlen(".idx");
1119         if (path_len < 1) {
1120                 free(p);
1121                 return NULL;
1122         }
1123         memcpy(p->pack_name, path, path_len);
1124
1125         strcpy(p->pack_name + path_len, ".keep");
1126         if (!access(p->pack_name, F_OK))
1127                 p->pack_keep = 1;
1128
1129         strcpy(p->pack_name + path_len, ".pack");
1130         if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
1131                 free(p);
1132                 return NULL;
1133         }
1134
1135         /* ok, it looks sane as far as we can check without
1136          * actually mapping the pack file.
1137          */
1138         p->pack_size = st.st_size;
1139         p->pack_local = local;
1140         p->mtime = st.st_mtime;
1141         if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
1142                 hashclr(p->sha1);
1143         return p;
1144 }
1145
1146 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
1147 {
1148         const char *path = sha1_pack_name(sha1);
1149         struct packed_git *p = alloc_packed_git(strlen(path) + 1);
1150
1151         strcpy(p->pack_name, path);
1152         hashcpy(p->sha1, sha1);
1153         if (check_packed_git_idx(idx_path, p)) {
1154                 free(p);
1155                 return NULL;
1156         }
1157
1158         return p;
1159 }
1160
1161 void install_packed_git(struct packed_git *pack)
1162 {
1163         if (pack->pack_fd != -1)
1164                 pack_open_fds++;
1165
1166         pack->next = packed_git;
1167         packed_git = pack;
1168 }
1169
1170 void (*report_garbage)(const char *desc, const char *path);
1171
1172 static void report_helper(const struct string_list *list,
1173                           int seen_bits, int first, int last)
1174 {
1175         const char *msg;
1176         switch (seen_bits) {
1177         case 0:
1178                 msg = "no corresponding .idx or .pack";
1179                 break;
1180         case 1:
1181                 msg = "no corresponding .idx";
1182                 break;
1183         case 2:
1184                 msg = "no corresponding .pack";
1185                 break;
1186         default:
1187                 return;
1188         }
1189         for (; first < last; first++)
1190                 report_garbage(msg, list->items[first].string);
1191 }
1192
1193 static void report_pack_garbage(struct string_list *list)
1194 {
1195         int i, baselen = -1, first = 0, seen_bits = 0;
1196
1197         if (!report_garbage)
1198                 return;
1199
1200         sort_string_list(list);
1201
1202         for (i = 0; i < list->nr; i++) {
1203                 const char *path = list->items[i].string;
1204                 if (baselen != -1 &&
1205                     strncmp(path, list->items[first].string, baselen)) {
1206                         report_helper(list, seen_bits, first, i);
1207                         baselen = -1;
1208                         seen_bits = 0;
1209                 }
1210                 if (baselen == -1) {
1211                         const char *dot = strrchr(path, '.');
1212                         if (!dot) {
1213                                 report_garbage("garbage found", path);
1214                                 continue;
1215                         }
1216                         baselen = dot - path + 1;
1217                         first = i;
1218                 }
1219                 if (!strcmp(path + baselen, "pack"))
1220                         seen_bits |= 1;
1221                 else if (!strcmp(path + baselen, "idx"))
1222                         seen_bits |= 2;
1223         }
1224         report_helper(list, seen_bits, first, list->nr);
1225 }
1226
1227 static void prepare_packed_git_one(char *objdir, int local)
1228 {
1229         struct strbuf path = STRBUF_INIT;
1230         size_t dirnamelen;
1231         DIR *dir;
1232         struct dirent *de;
1233         struct string_list garbage = STRING_LIST_INIT_DUP;
1234
1235         strbuf_addstr(&path, objdir);
1236         strbuf_addstr(&path, "/pack");
1237         dir = opendir(path.buf);
1238         if (!dir) {
1239                 if (errno != ENOENT)
1240                         error("unable to open object pack directory: %s: %s",
1241                               path.buf, strerror(errno));
1242                 strbuf_release(&path);
1243                 return;
1244         }
1245         strbuf_addch(&path, '/');
1246         dirnamelen = path.len;
1247         while ((de = readdir(dir)) != NULL) {
1248                 struct packed_git *p;
1249                 size_t base_len;
1250
1251                 if (is_dot_or_dotdot(de->d_name))
1252                         continue;
1253
1254                 strbuf_setlen(&path, dirnamelen);
1255                 strbuf_addstr(&path, de->d_name);
1256
1257                 base_len = path.len;
1258                 if (strip_suffix_mem(path.buf, &base_len, ".idx")) {
1259                         /* Don't reopen a pack we already have. */
1260                         for (p = packed_git; p; p = p->next) {
1261                                 size_t len;
1262                                 if (strip_suffix(p->pack_name, ".pack", &len) &&
1263                                     len == base_len &&
1264                                     !memcmp(p->pack_name, path.buf, len))
1265                                         break;
1266                         }
1267                         if (p == NULL &&
1268                             /*
1269                              * See if it really is a valid .idx file with
1270                              * corresponding .pack file that we can map.
1271                              */
1272                             (p = add_packed_git(path.buf, path.len, local)) != NULL)
1273                                 install_packed_git(p);
1274                 }
1275
1276                 if (!report_garbage)
1277                         continue;
1278
1279                 if (ends_with(de->d_name, ".idx") ||
1280                     ends_with(de->d_name, ".pack") ||
1281                     ends_with(de->d_name, ".bitmap") ||
1282                     ends_with(de->d_name, ".keep"))
1283                         string_list_append(&garbage, path.buf);
1284                 else
1285                         report_garbage("garbage found", path.buf);
1286         }
1287         closedir(dir);
1288         report_pack_garbage(&garbage);
1289         string_list_clear(&garbage, 0);
1290         strbuf_release(&path);
1291 }
1292
1293 static int sort_pack(const void *a_, const void *b_)
1294 {
1295         struct packed_git *a = *((struct packed_git **)a_);
1296         struct packed_git *b = *((struct packed_git **)b_);
1297         int st;
1298
1299         /*
1300          * Local packs tend to contain objects specific to our
1301          * variant of the project than remote ones.  In addition,
1302          * remote ones could be on a network mounted filesystem.
1303          * Favor local ones for these reasons.
1304          */
1305         st = a->pack_local - b->pack_local;
1306         if (st)
1307                 return -st;
1308
1309         /*
1310          * Younger packs tend to contain more recent objects,
1311          * and more recent objects tend to get accessed more
1312          * often.
1313          */
1314         if (a->mtime < b->mtime)
1315                 return 1;
1316         else if (a->mtime == b->mtime)
1317                 return 0;
1318         return -1;
1319 }
1320
1321 static void rearrange_packed_git(void)
1322 {
1323         struct packed_git **ary, *p;
1324         int i, n;
1325
1326         for (n = 0, p = packed_git; p; p = p->next)
1327                 n++;
1328         if (n < 2)
1329                 return;
1330
1331         /* prepare an array of packed_git for easier sorting */
1332         ary = xcalloc(n, sizeof(struct packed_git *));
1333         for (n = 0, p = packed_git; p; p = p->next)
1334                 ary[n++] = p;
1335
1336         qsort(ary, n, sizeof(struct packed_git *), sort_pack);
1337
1338         /* link them back again */
1339         for (i = 0; i < n - 1; i++)
1340                 ary[i]->next = ary[i + 1];
1341         ary[n - 1]->next = NULL;
1342         packed_git = ary[0];
1343
1344         free(ary);
1345 }
1346
1347 static int prepare_packed_git_run_once = 0;
1348 void prepare_packed_git(void)
1349 {
1350         struct alternate_object_database *alt;
1351
1352         if (prepare_packed_git_run_once)
1353                 return;
1354         prepare_packed_git_one(get_object_directory(), 1);
1355         prepare_alt_odb();
1356         for (alt = alt_odb_list; alt; alt = alt->next) {
1357                 alt->name[-1] = 0;
1358                 prepare_packed_git_one(alt->base, 0);
1359                 alt->name[-1] = '/';
1360         }
1361         rearrange_packed_git();
1362         prepare_packed_git_run_once = 1;
1363 }
1364
1365 void reprepare_packed_git(void)
1366 {
1367         prepare_packed_git_run_once = 0;
1368         prepare_packed_git();
1369 }
1370
1371 static void mark_bad_packed_object(struct packed_git *p,
1372                                    const unsigned char *sha1)
1373 {
1374         unsigned i;
1375         for (i = 0; i < p->num_bad_objects; i++)
1376                 if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1377                         return;
1378         p->bad_object_sha1 = xrealloc(p->bad_object_sha1, 20 * (p->num_bad_objects + 1));
1379         hashcpy(p->bad_object_sha1 + 20 * p->num_bad_objects, sha1);
1380         p->num_bad_objects++;
1381 }
1382
1383 static const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
1384 {
1385         struct packed_git *p;
1386         unsigned i;
1387
1388         for (p = packed_git; p; p = p->next)
1389                 for (i = 0; i < p->num_bad_objects; i++)
1390                         if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
1391                                 return p;
1392         return NULL;
1393 }
1394
1395 /*
1396  * With an in-core object data in "map", rehash it to make sure the
1397  * object name actually matches "sha1" to detect object corruption.
1398  * With "map" == NULL, try reading the object named with "sha1" using
1399  * the streaming interface and rehash it to do the same.
1400  */
1401 int check_sha1_signature(const unsigned char *sha1, void *map,
1402                          unsigned long size, const char *type)
1403 {
1404         unsigned char real_sha1[20];
1405         enum object_type obj_type;
1406         struct git_istream *st;
1407         git_SHA_CTX c;
1408         char hdr[32];
1409         int hdrlen;
1410
1411         if (map) {
1412                 hash_sha1_file(map, size, type, real_sha1);
1413                 return hashcmp(sha1, real_sha1) ? -1 : 0;
1414         }
1415
1416         st = open_istream(sha1, &obj_type, &size, NULL);
1417         if (!st)
1418                 return -1;
1419
1420         /* Generate the header */
1421         hdrlen = sprintf(hdr, "%s %lu", typename(obj_type), size) + 1;
1422
1423         /* Sha1.. */
1424         git_SHA1_Init(&c);
1425         git_SHA1_Update(&c, hdr, hdrlen);
1426         for (;;) {
1427                 char buf[1024 * 16];
1428                 ssize_t readlen = read_istream(st, buf, sizeof(buf));
1429
1430                 if (readlen < 0) {
1431                         close_istream(st);
1432                         return -1;
1433                 }
1434                 if (!readlen)
1435                         break;
1436                 git_SHA1_Update(&c, buf, readlen);
1437         }
1438         git_SHA1_Final(real_sha1, &c);
1439         close_istream(st);
1440         return hashcmp(sha1, real_sha1) ? -1 : 0;
1441 }
1442
1443 int git_open_noatime(const char *name)
1444 {
1445         static int sha1_file_open_flag = O_NOATIME;
1446
1447         for (;;) {
1448                 int fd = open(name, O_RDONLY | sha1_file_open_flag);
1449                 if (fd >= 0)
1450                         return fd;
1451
1452                 /* Might the failure be due to O_NOATIME? */
1453                 if (errno != ENOENT && sha1_file_open_flag) {
1454                         sha1_file_open_flag = 0;
1455                         continue;
1456                 }
1457
1458                 return -1;
1459         }
1460 }
1461
1462 static int stat_sha1_file(const unsigned char *sha1, struct stat *st)
1463 {
1464         struct alternate_object_database *alt;
1465
1466         if (!lstat(sha1_file_name(sha1), st))
1467                 return 0;
1468
1469         prepare_alt_odb();
1470         errno = ENOENT;
1471         for (alt = alt_odb_list; alt; alt = alt->next) {
1472                 fill_sha1_path(alt->name, sha1);
1473                 if (!lstat(alt->base, st))
1474                         return 0;
1475         }
1476
1477         return -1;
1478 }
1479
1480 static int open_sha1_file(const unsigned char *sha1)
1481 {
1482         int fd;
1483         struct alternate_object_database *alt;
1484         int most_interesting_errno;
1485
1486         fd = git_open_noatime(sha1_file_name(sha1));
1487         if (fd >= 0)
1488                 return fd;
1489         most_interesting_errno = errno;
1490
1491         prepare_alt_odb();
1492         for (alt = alt_odb_list; alt; alt = alt->next) {
1493                 fill_sha1_path(alt->name, sha1);
1494                 fd = git_open_noatime(alt->base);
1495                 if (fd >= 0)
1496                         return fd;
1497                 if (most_interesting_errno == ENOENT)
1498                         most_interesting_errno = errno;
1499         }
1500         errno = most_interesting_errno;
1501         return -1;
1502 }
1503
1504 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
1505 {
1506         void *map;
1507         int fd;
1508
1509         fd = open_sha1_file(sha1);
1510         map = NULL;
1511         if (fd >= 0) {
1512                 struct stat st;
1513
1514                 if (!fstat(fd, &st)) {
1515                         *size = xsize_t(st.st_size);
1516                         if (!*size) {
1517                                 /* mmap() is forbidden on empty files */
1518                                 error("object file %s is empty", sha1_file_name(sha1));
1519                                 return NULL;
1520                         }
1521                         map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1522                 }
1523                 close(fd);
1524         }
1525         return map;
1526 }
1527
1528 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1529                 unsigned long len, enum object_type *type, unsigned long *sizep)
1530 {
1531         unsigned shift;
1532         unsigned long size, c;
1533         unsigned long used = 0;
1534
1535         c = buf[used++];
1536         *type = (c >> 4) & 7;
1537         size = c & 15;
1538         shift = 4;
1539         while (c & 0x80) {
1540                 if (len <= used || bitsizeof(long) <= shift) {
1541                         error("bad object header");
1542                         size = used = 0;
1543                         break;
1544                 }
1545                 c = buf[used++];
1546                 size += (c & 0x7f) << shift;
1547                 shift += 7;
1548         }
1549         *sizep = size;
1550         return used;
1551 }
1552
1553 int unpack_sha1_header(git_zstream *stream, unsigned char *map, unsigned long mapsize, void *buffer, unsigned long bufsiz)
1554 {
1555         /* Get the data stream */
1556         memset(stream, 0, sizeof(*stream));
1557         stream->next_in = map;
1558         stream->avail_in = mapsize;
1559         stream->next_out = buffer;
1560         stream->avail_out = bufsiz;
1561
1562         git_inflate_init(stream);
1563         return git_inflate(stream, 0);
1564 }
1565
1566 static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1567 {
1568         int bytes = strlen(buffer) + 1;
1569         unsigned char *buf = xmallocz(size);
1570         unsigned long n;
1571         int status = Z_OK;
1572
1573         n = stream->total_out - bytes;
1574         if (n > size)
1575                 n = size;
1576         memcpy(buf, (char *) buffer + bytes, n);
1577         bytes = n;
1578         if (bytes <= size) {
1579                 /*
1580                  * The above condition must be (bytes <= size), not
1581                  * (bytes < size).  In other words, even though we
1582                  * expect no more output and set avail_out to zero,
1583                  * the input zlib stream may have bytes that express
1584                  * "this concludes the stream", and we *do* want to
1585                  * eat that input.
1586                  *
1587                  * Otherwise we would not be able to test that we
1588                  * consumed all the input to reach the expected size;
1589                  * we also want to check that zlib tells us that all
1590                  * went well with status == Z_STREAM_END at the end.
1591                  */
1592                 stream->next_out = buf + bytes;
1593                 stream->avail_out = size - bytes;
1594                 while (status == Z_OK)
1595                         status = git_inflate(stream, Z_FINISH);
1596         }
1597         if (status == Z_STREAM_END && !stream->avail_in) {
1598                 git_inflate_end(stream);
1599                 return buf;
1600         }
1601
1602         if (status < 0)
1603                 error("corrupt loose object '%s'", sha1_to_hex(sha1));
1604         else if (stream->avail_in)
1605                 error("garbage at end of loose object '%s'",
1606                       sha1_to_hex(sha1));
1607         free(buf);
1608         return NULL;
1609 }
1610
1611 /*
1612  * We used to just use "sscanf()", but that's actually way
1613  * too permissive for what we want to check. So do an anal
1614  * object header parse by hand.
1615  */
1616 int parse_sha1_header(const char *hdr, unsigned long *sizep)
1617 {
1618         char type[10];
1619         int i;
1620         unsigned long size;
1621
1622         /*
1623          * The type can be at most ten bytes (including the
1624          * terminating '\0' that we add), and is followed by
1625          * a space.
1626          */
1627         i = 0;
1628         for (;;) {
1629                 char c = *hdr++;
1630                 if (c == ' ')
1631                         break;
1632                 type[i++] = c;
1633                 if (i >= sizeof(type))
1634                         return -1;
1635         }
1636         type[i] = 0;
1637
1638         /*
1639          * The length must follow immediately, and be in canonical
1640          * decimal format (ie "010" is not valid).
1641          */
1642         size = *hdr++ - '0';
1643         if (size > 9)
1644                 return -1;
1645         if (size) {
1646                 for (;;) {
1647                         unsigned long c = *hdr - '0';
1648                         if (c > 9)
1649                                 break;
1650                         hdr++;
1651                         size = size * 10 + c;
1652                 }
1653         }
1654         *sizep = size;
1655
1656         /*
1657          * The length must be followed by a zero byte
1658          */
1659         return *hdr ? -1 : type_from_string(type);
1660 }
1661
1662 static void *unpack_sha1_file(void *map, unsigned long mapsize, enum object_type *type, unsigned long *size, const unsigned char *sha1)
1663 {
1664         int ret;
1665         git_zstream stream;
1666         char hdr[8192];
1667
1668         ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
1669         if (ret < Z_OK || (*type = parse_sha1_header(hdr, size)) < 0)
1670                 return NULL;
1671
1672         return unpack_sha1_rest(&stream, hdr, *size, sha1);
1673 }
1674
1675 unsigned long get_size_from_delta(struct packed_git *p,
1676                                   struct pack_window **w_curs,
1677                                   off_t curpos)
1678 {
1679         const unsigned char *data;
1680         unsigned char delta_head[20], *in;
1681         git_zstream stream;
1682         int st;
1683
1684         memset(&stream, 0, sizeof(stream));
1685         stream.next_out = delta_head;
1686         stream.avail_out = sizeof(delta_head);
1687
1688         git_inflate_init(&stream);
1689         do {
1690                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1691                 stream.next_in = in;
1692                 st = git_inflate(&stream, Z_FINISH);
1693                 curpos += stream.next_in - in;
1694         } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1695                  stream.total_out < sizeof(delta_head));
1696         git_inflate_end(&stream);
1697         if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1698                 error("delta data unpack-initial failed");
1699                 return 0;
1700         }
1701
1702         /* Examine the initial part of the delta to figure out
1703          * the result size.
1704          */
1705         data = delta_head;
1706
1707         /* ignore base size */
1708         get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1709
1710         /* Read the result size */
1711         return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1712 }
1713
1714 static off_t get_delta_base(struct packed_git *p,
1715                                     struct pack_window **w_curs,
1716                                     off_t *curpos,
1717                                     enum object_type type,
1718                                     off_t delta_obj_offset)
1719 {
1720         unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1721         off_t base_offset;
1722
1723         /* use_pack() assured us we have [base_info, base_info + 20)
1724          * as a range that we can look at without walking off the
1725          * end of the mapped window.  Its actually the hash size
1726          * that is assured.  An OFS_DELTA longer than the hash size
1727          * is stupid, as then a REF_DELTA would be smaller to store.
1728          */
1729         if (type == OBJ_OFS_DELTA) {
1730                 unsigned used = 0;
1731                 unsigned char c = base_info[used++];
1732                 base_offset = c & 127;
1733                 while (c & 128) {
1734                         base_offset += 1;
1735                         if (!base_offset || MSB(base_offset, 7))
1736                                 return 0;  /* overflow */
1737                         c = base_info[used++];
1738                         base_offset = (base_offset << 7) + (c & 127);
1739                 }
1740                 base_offset = delta_obj_offset - base_offset;
1741                 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1742                         return 0;  /* out of bound */
1743                 *curpos += used;
1744         } else if (type == OBJ_REF_DELTA) {
1745                 /* The base entry _must_ be in the same pack */
1746                 base_offset = find_pack_entry_one(base_info, p);
1747                 *curpos += 20;
1748         } else
1749                 die("I am totally screwed");
1750         return base_offset;
1751 }
1752
1753 /*
1754  * Like get_delta_base above, but we return the sha1 instead of the pack
1755  * offset. This means it is cheaper for REF deltas (we do not have to do
1756  * the final object lookup), but more expensive for OFS deltas (we
1757  * have to load the revidx to convert the offset back into a sha1).
1758  */
1759 static const unsigned char *get_delta_base_sha1(struct packed_git *p,
1760                                                 struct pack_window **w_curs,
1761                                                 off_t curpos,
1762                                                 enum object_type type,
1763                                                 off_t delta_obj_offset)
1764 {
1765         if (type == OBJ_REF_DELTA) {
1766                 unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1767                 return base;
1768         } else if (type == OBJ_OFS_DELTA) {
1769                 struct revindex_entry *revidx;
1770                 off_t base_offset = get_delta_base(p, w_curs, &curpos,
1771                                                    type, delta_obj_offset);
1772
1773                 if (!base_offset)
1774                         return NULL;
1775
1776                 revidx = find_pack_revindex(p, base_offset);
1777                 if (!revidx)
1778                         return NULL;
1779
1780                 return nth_packed_object_sha1(p, revidx->nr);
1781         } else
1782                 return NULL;
1783 }
1784
1785 int unpack_object_header(struct packed_git *p,
1786                          struct pack_window **w_curs,
1787                          off_t *curpos,
1788                          unsigned long *sizep)
1789 {
1790         unsigned char *base;
1791         unsigned long left;
1792         unsigned long used;
1793         enum object_type type;
1794
1795         /* use_pack() assures us we have [base, base + 20) available
1796          * as a range that we can look at.  (Its actually the hash
1797          * size that is assured.)  With our object header encoding
1798          * the maximum deflated object size is 2^137, which is just
1799          * insane, so we know won't exceed what we have been given.
1800          */
1801         base = use_pack(p, w_curs, *curpos, &left);
1802         used = unpack_object_header_buffer(base, left, &type, sizep);
1803         if (!used) {
1804                 type = OBJ_BAD;
1805         } else
1806                 *curpos += used;
1807
1808         return type;
1809 }
1810
1811 static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
1812 {
1813         int type;
1814         struct revindex_entry *revidx;
1815         const unsigned char *sha1;
1816         revidx = find_pack_revindex(p, obj_offset);
1817         if (!revidx)
1818                 return OBJ_BAD;
1819         sha1 = nth_packed_object_sha1(p, revidx->nr);
1820         mark_bad_packed_object(p, sha1);
1821         type = sha1_object_info(sha1, NULL);
1822         if (type <= OBJ_NONE)
1823                 return OBJ_BAD;
1824         return type;
1825 }
1826
1827 #define POI_STACK_PREALLOC 64
1828
1829 static enum object_type packed_to_object_type(struct packed_git *p,
1830                                               off_t obj_offset,
1831                                               enum object_type type,
1832                                               struct pack_window **w_curs,
1833                                               off_t curpos)
1834 {
1835         off_t small_poi_stack[POI_STACK_PREALLOC];
1836         off_t *poi_stack = small_poi_stack;
1837         int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1838
1839         while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1840                 off_t base_offset;
1841                 unsigned long size;
1842                 /* Push the object we're going to leave behind */
1843                 if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1844                         poi_stack_alloc = alloc_nr(poi_stack_nr);
1845                         poi_stack = xmalloc(sizeof(off_t)*poi_stack_alloc);
1846                         memcpy(poi_stack, small_poi_stack, sizeof(off_t)*poi_stack_nr);
1847                 } else {
1848                         ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1849                 }
1850                 poi_stack[poi_stack_nr++] = obj_offset;
1851                 /* If parsing the base offset fails, just unwind */
1852                 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1853                 if (!base_offset)
1854                         goto unwind;
1855                 curpos = obj_offset = base_offset;
1856                 type = unpack_object_header(p, w_curs, &curpos, &size);
1857                 if (type <= OBJ_NONE) {
1858                         /* If getting the base itself fails, we first
1859                          * retry the base, otherwise unwind */
1860                         type = retry_bad_packed_offset(p, base_offset);
1861                         if (type > OBJ_NONE)
1862                                 goto out;
1863                         goto unwind;
1864                 }
1865         }
1866
1867         switch (type) {
1868         case OBJ_BAD:
1869         case OBJ_COMMIT:
1870         case OBJ_TREE:
1871         case OBJ_BLOB:
1872         case OBJ_TAG:
1873                 break;
1874         default:
1875                 error("unknown object type %i at offset %"PRIuMAX" in %s",
1876                       type, (uintmax_t)obj_offset, p->pack_name);
1877                 type = OBJ_BAD;
1878         }
1879
1880 out:
1881         if (poi_stack != small_poi_stack)
1882                 free(poi_stack);
1883         return type;
1884
1885 unwind:
1886         while (poi_stack_nr) {
1887                 obj_offset = poi_stack[--poi_stack_nr];
1888                 type = retry_bad_packed_offset(p, obj_offset);
1889                 if (type > OBJ_NONE)
1890                         goto out;
1891         }
1892         type = OBJ_BAD;
1893         goto out;
1894 }
1895
1896 static int packed_object_info(struct packed_git *p, off_t obj_offset,
1897                               struct object_info *oi)
1898 {
1899         struct pack_window *w_curs = NULL;
1900         unsigned long size;
1901         off_t curpos = obj_offset;
1902         enum object_type type;
1903
1904         /*
1905          * We always get the representation type, but only convert it to
1906          * a "real" type later if the caller is interested.
1907          */
1908         type = unpack_object_header(p, &w_curs, &curpos, &size);
1909
1910         if (oi->sizep) {
1911                 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1912                         off_t tmp_pos = curpos;
1913                         off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1914                                                            type, obj_offset);
1915                         if (!base_offset) {
1916                                 type = OBJ_BAD;
1917                                 goto out;
1918                         }
1919                         *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
1920                         if (*oi->sizep == 0) {
1921                                 type = OBJ_BAD;
1922                                 goto out;
1923                         }
1924                 } else {
1925                         *oi->sizep = size;
1926                 }
1927         }
1928
1929         if (oi->disk_sizep) {
1930                 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1931                 *oi->disk_sizep = revidx[1].offset - obj_offset;
1932         }
1933
1934         if (oi->typep) {
1935                 *oi->typep = packed_to_object_type(p, obj_offset, type, &w_curs, curpos);
1936                 if (*oi->typep < 0) {
1937                         type = OBJ_BAD;
1938                         goto out;
1939                 }
1940         }
1941
1942         if (oi->delta_base_sha1) {
1943                 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1944                         const unsigned char *base;
1945
1946                         base = get_delta_base_sha1(p, &w_curs, curpos,
1947                                                    type, obj_offset);
1948                         if (!base) {
1949                                 type = OBJ_BAD;
1950                                 goto out;
1951                         }
1952
1953                         hashcpy(oi->delta_base_sha1, base);
1954                 } else
1955                         hashclr(oi->delta_base_sha1);
1956         }
1957
1958 out:
1959         unuse_pack(&w_curs);
1960         return type;
1961 }
1962
1963 static void *unpack_compressed_entry(struct packed_git *p,
1964                                     struct pack_window **w_curs,
1965                                     off_t curpos,
1966                                     unsigned long size)
1967 {
1968         int st;
1969         git_zstream stream;
1970         unsigned char *buffer, *in;
1971
1972         buffer = xmallocz_gently(size);
1973         if (!buffer)
1974                 return NULL;
1975         memset(&stream, 0, sizeof(stream));
1976         stream.next_out = buffer;
1977         stream.avail_out = size + 1;
1978
1979         git_inflate_init(&stream);
1980         do {
1981                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1982                 stream.next_in = in;
1983                 st = git_inflate(&stream, Z_FINISH);
1984                 if (!stream.avail_out)
1985                         break; /* the payload is larger than it should be */
1986                 curpos += stream.next_in - in;
1987         } while (st == Z_OK || st == Z_BUF_ERROR);
1988         git_inflate_end(&stream);
1989         if ((st != Z_STREAM_END) || stream.total_out != size) {
1990                 free(buffer);
1991                 return NULL;
1992         }
1993
1994         return buffer;
1995 }
1996
1997 #define MAX_DELTA_CACHE (256)
1998
1999 static size_t delta_base_cached;
2000
2001 static struct delta_base_cache_lru_list {
2002         struct delta_base_cache_lru_list *prev;
2003         struct delta_base_cache_lru_list *next;
2004 } delta_base_cache_lru = { &delta_base_cache_lru, &delta_base_cache_lru };
2005
2006 static struct delta_base_cache_entry {
2007         struct delta_base_cache_lru_list lru;
2008         void *data;
2009         struct packed_git *p;
2010         off_t base_offset;
2011         unsigned long size;
2012         enum object_type type;
2013 } delta_base_cache[MAX_DELTA_CACHE];
2014
2015 static unsigned long pack_entry_hash(struct packed_git *p, off_t base_offset)
2016 {
2017         unsigned long hash;
2018
2019         hash = (unsigned long)p + (unsigned long)base_offset;
2020         hash += (hash >> 8) + (hash >> 16);
2021         return hash % MAX_DELTA_CACHE;
2022 }
2023
2024 static struct delta_base_cache_entry *
2025 get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
2026 {
2027         unsigned long hash = pack_entry_hash(p, base_offset);
2028         return delta_base_cache + hash;
2029 }
2030
2031 static int eq_delta_base_cache_entry(struct delta_base_cache_entry *ent,
2032                                      struct packed_git *p, off_t base_offset)
2033 {
2034         return (ent->data && ent->p == p && ent->base_offset == base_offset);
2035 }
2036
2037 static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
2038 {
2039         struct delta_base_cache_entry *ent;
2040         ent = get_delta_base_cache_entry(p, base_offset);
2041         return eq_delta_base_cache_entry(ent, p, base_offset);
2042 }
2043
2044 static void clear_delta_base_cache_entry(struct delta_base_cache_entry *ent)
2045 {
2046         ent->data = NULL;
2047         ent->lru.next->prev = ent->lru.prev;
2048         ent->lru.prev->next = ent->lru.next;
2049         delta_base_cached -= ent->size;
2050 }
2051
2052 static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
2053         unsigned long *base_size, enum object_type *type, int keep_cache)
2054 {
2055         struct delta_base_cache_entry *ent;
2056         void *ret;
2057
2058         ent = get_delta_base_cache_entry(p, base_offset);
2059
2060         if (!eq_delta_base_cache_entry(ent, p, base_offset))
2061                 return unpack_entry(p, base_offset, type, base_size);
2062
2063         ret = ent->data;
2064
2065         if (!keep_cache)
2066                 clear_delta_base_cache_entry(ent);
2067         else
2068                 ret = xmemdupz(ent->data, ent->size);
2069         *type = ent->type;
2070         *base_size = ent->size;
2071         return ret;
2072 }
2073
2074 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
2075 {
2076         if (ent->data) {
2077                 free(ent->data);
2078                 ent->data = NULL;
2079                 ent->lru.next->prev = ent->lru.prev;
2080                 ent->lru.prev->next = ent->lru.next;
2081                 delta_base_cached -= ent->size;
2082         }
2083 }
2084
2085 void clear_delta_base_cache(void)
2086 {
2087         unsigned long p;
2088         for (p = 0; p < MAX_DELTA_CACHE; p++)
2089                 release_delta_base_cache(&delta_base_cache[p]);
2090 }
2091
2092 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
2093         void *base, unsigned long base_size, enum object_type type)
2094 {
2095         unsigned long hash = pack_entry_hash(p, base_offset);
2096         struct delta_base_cache_entry *ent = delta_base_cache + hash;
2097         struct delta_base_cache_lru_list *lru;
2098
2099         release_delta_base_cache(ent);
2100         delta_base_cached += base_size;
2101
2102         for (lru = delta_base_cache_lru.next;
2103              delta_base_cached > delta_base_cache_limit
2104              && lru != &delta_base_cache_lru;
2105              lru = lru->next) {
2106                 struct delta_base_cache_entry *f = (void *)lru;
2107                 if (f->type == OBJ_BLOB)
2108                         release_delta_base_cache(f);
2109         }
2110         for (lru = delta_base_cache_lru.next;
2111              delta_base_cached > delta_base_cache_limit
2112              && lru != &delta_base_cache_lru;
2113              lru = lru->next) {
2114                 struct delta_base_cache_entry *f = (void *)lru;
2115                 release_delta_base_cache(f);
2116         }
2117
2118         ent->p = p;
2119         ent->base_offset = base_offset;
2120         ent->type = type;
2121         ent->data = base;
2122         ent->size = base_size;
2123         ent->lru.next = &delta_base_cache_lru;
2124         ent->lru.prev = delta_base_cache_lru.prev;
2125         delta_base_cache_lru.prev->next = &ent->lru;
2126         delta_base_cache_lru.prev = &ent->lru;
2127 }
2128
2129 static void *read_object(const unsigned char *sha1, enum object_type *type,
2130                          unsigned long *size);
2131
2132 static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
2133 {
2134         static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
2135         trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
2136                          p->pack_name, (uintmax_t)obj_offset);
2137 }
2138
2139 int do_check_packed_object_crc;
2140
2141 #define UNPACK_ENTRY_STACK_PREALLOC 64
2142 struct unpack_entry_stack_ent {
2143         off_t obj_offset;
2144         off_t curpos;
2145         unsigned long size;
2146 };
2147
2148 void *unpack_entry(struct packed_git *p, off_t obj_offset,
2149                    enum object_type *final_type, unsigned long *final_size)
2150 {
2151         struct pack_window *w_curs = NULL;
2152         off_t curpos = obj_offset;
2153         void *data = NULL;
2154         unsigned long size;
2155         enum object_type type;
2156         struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
2157         struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
2158         int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
2159         int base_from_cache = 0;
2160
2161         write_pack_access_log(p, obj_offset);
2162
2163         /* PHASE 1: drill down to the innermost base object */
2164         for (;;) {
2165                 off_t base_offset;
2166                 int i;
2167                 struct delta_base_cache_entry *ent;
2168
2169                 ent = get_delta_base_cache_entry(p, curpos);
2170                 if (eq_delta_base_cache_entry(ent, p, curpos)) {
2171                         type = ent->type;
2172                         data = ent->data;
2173                         size = ent->size;
2174                         clear_delta_base_cache_entry(ent);
2175                         base_from_cache = 1;
2176                         break;
2177                 }
2178
2179                 if (do_check_packed_object_crc && p->index_version > 1) {
2180                         struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
2181                         unsigned long len = revidx[1].offset - obj_offset;
2182                         if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
2183                                 const unsigned char *sha1 =
2184                                         nth_packed_object_sha1(p, revidx->nr);
2185                                 error("bad packed object CRC for %s",
2186                                       sha1_to_hex(sha1));
2187                                 mark_bad_packed_object(p, sha1);
2188                                 unuse_pack(&w_curs);
2189                                 return NULL;
2190                         }
2191                 }
2192
2193                 type = unpack_object_header(p, &w_curs, &curpos, &size);
2194                 if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
2195                         break;
2196
2197                 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
2198                 if (!base_offset) {
2199                         error("failed to validate delta base reference "
2200                               "at offset %"PRIuMAX" from %s",
2201                               (uintmax_t)curpos, p->pack_name);
2202                         /* bail to phase 2, in hopes of recovery */
2203                         data = NULL;
2204                         break;
2205                 }
2206
2207                 /* push object, proceed to base */
2208                 if (delta_stack_nr >= delta_stack_alloc
2209                     && delta_stack == small_delta_stack) {
2210                         delta_stack_alloc = alloc_nr(delta_stack_nr);
2211                         delta_stack = xmalloc(sizeof(*delta_stack)*delta_stack_alloc);
2212                         memcpy(delta_stack, small_delta_stack,
2213                                sizeof(*delta_stack)*delta_stack_nr);
2214                 } else {
2215                         ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
2216                 }
2217                 i = delta_stack_nr++;
2218                 delta_stack[i].obj_offset = obj_offset;
2219                 delta_stack[i].curpos = curpos;
2220                 delta_stack[i].size = size;
2221
2222                 curpos = obj_offset = base_offset;
2223         }
2224
2225         /* PHASE 2: handle the base */
2226         switch (type) {
2227         case OBJ_OFS_DELTA:
2228         case OBJ_REF_DELTA:
2229                 if (data)
2230                         die("BUG in unpack_entry: left loop at a valid delta");
2231                 break;
2232         case OBJ_COMMIT:
2233         case OBJ_TREE:
2234         case OBJ_BLOB:
2235         case OBJ_TAG:
2236                 if (!base_from_cache)
2237                         data = unpack_compressed_entry(p, &w_curs, curpos, size);
2238                 break;
2239         default:
2240                 data = NULL;
2241                 error("unknown object type %i at offset %"PRIuMAX" in %s",
2242                       type, (uintmax_t)obj_offset, p->pack_name);
2243         }
2244
2245         /* PHASE 3: apply deltas in order */
2246
2247         /* invariants:
2248          *   'data' holds the base data, or NULL if there was corruption
2249          */
2250         while (delta_stack_nr) {
2251                 void *delta_data;
2252                 void *base = data;
2253                 unsigned long delta_size, base_size = size;
2254                 int i;
2255
2256                 data = NULL;
2257
2258                 if (base)
2259                         add_delta_base_cache(p, obj_offset, base, base_size, type);
2260
2261                 if (!base) {
2262                         /*
2263                          * We're probably in deep shit, but let's try to fetch
2264                          * the required base anyway from another pack or loose.
2265                          * This is costly but should happen only in the presence
2266                          * of a corrupted pack, and is better than failing outright.
2267                          */
2268                         struct revindex_entry *revidx;
2269                         const unsigned char *base_sha1;
2270                         revidx = find_pack_revindex(p, obj_offset);
2271                         if (revidx) {
2272                                 base_sha1 = nth_packed_object_sha1(p, revidx->nr);
2273                                 error("failed to read delta base object %s"
2274                                       " at offset %"PRIuMAX" from %s",
2275                                       sha1_to_hex(base_sha1), (uintmax_t)obj_offset,
2276                                       p->pack_name);
2277                                 mark_bad_packed_object(p, base_sha1);
2278                                 base = read_object(base_sha1, &type, &base_size);
2279                         }
2280                 }
2281
2282                 i = --delta_stack_nr;
2283                 obj_offset = delta_stack[i].obj_offset;
2284                 curpos = delta_stack[i].curpos;
2285                 delta_size = delta_stack[i].size;
2286
2287                 if (!base)
2288                         continue;
2289
2290                 delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
2291
2292                 if (!delta_data) {
2293                         error("failed to unpack compressed delta "
2294                               "at offset %"PRIuMAX" from %s",
2295                               (uintmax_t)curpos, p->pack_name);
2296                         data = NULL;
2297                         continue;
2298                 }
2299
2300                 data = patch_delta(base, base_size,
2301                                    delta_data, delta_size,
2302                                    &size);
2303
2304                 /*
2305                  * We could not apply the delta; warn the user, but keep going.
2306                  * Our failure will be noticed either in the next iteration of
2307                  * the loop, or if this is the final delta, in the caller when
2308                  * we return NULL. Those code paths will take care of making
2309                  * a more explicit warning and retrying with another copy of
2310                  * the object.
2311                  */
2312                 if (!data)
2313                         error("failed to apply delta");
2314
2315                 free(delta_data);
2316         }
2317
2318         *final_type = type;
2319         *final_size = size;
2320
2321         unuse_pack(&w_curs);
2322
2323         if (delta_stack != small_delta_stack)
2324                 free(delta_stack);
2325
2326         return data;
2327 }
2328
2329 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
2330                                             uint32_t n)
2331 {
2332         const unsigned char *index = p->index_data;
2333         if (!index) {
2334                 if (open_pack_index(p))
2335                         return NULL;
2336                 index = p->index_data;
2337         }
2338         if (n >= p->num_objects)
2339                 return NULL;
2340         index += 4 * 256;
2341         if (p->index_version == 1) {
2342                 return index + 24 * n + 4;
2343         } else {
2344                 index += 8;
2345                 return index + 20 * n;
2346         }
2347 }
2348
2349 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
2350 {
2351         const unsigned char *index = p->index_data;
2352         index += 4 * 256;
2353         if (p->index_version == 1) {
2354                 return ntohl(*((uint32_t *)(index + 24 * n)));
2355         } else {
2356                 uint32_t off;
2357                 index += 8 + p->num_objects * (20 + 4);
2358                 off = ntohl(*((uint32_t *)(index + 4 * n)));
2359                 if (!(off & 0x80000000))
2360                         return off;
2361                 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
2362                 return (((uint64_t)ntohl(*((uint32_t *)(index + 0)))) << 32) |
2363                                    ntohl(*((uint32_t *)(index + 4)));
2364         }
2365 }
2366
2367 off_t find_pack_entry_one(const unsigned char *sha1,
2368                                   struct packed_git *p)
2369 {
2370         const uint32_t *level1_ofs = p->index_data;
2371         const unsigned char *index = p->index_data;
2372         unsigned hi, lo, stride;
2373         static int use_lookup = -1;
2374         static int debug_lookup = -1;
2375
2376         if (debug_lookup < 0)
2377                 debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
2378
2379         if (!index) {
2380                 if (open_pack_index(p))
2381                         return 0;
2382                 level1_ofs = p->index_data;
2383                 index = p->index_data;
2384         }
2385         if (p->index_version > 1) {
2386                 level1_ofs += 2;
2387                 index += 8;
2388         }
2389         index += 4 * 256;
2390         hi = ntohl(level1_ofs[*sha1]);
2391         lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
2392         if (p->index_version > 1) {
2393                 stride = 20;
2394         } else {
2395                 stride = 24;
2396                 index += 4;
2397         }
2398
2399         if (debug_lookup)
2400                 printf("%02x%02x%02x... lo %u hi %u nr %"PRIu32"\n",
2401                        sha1[0], sha1[1], sha1[2], lo, hi, p->num_objects);
2402
2403         if (use_lookup < 0)
2404                 use_lookup = !!getenv("GIT_USE_LOOKUP");
2405         if (use_lookup) {
2406                 int pos = sha1_entry_pos(index, stride, 0,
2407                                          lo, hi, p->num_objects, sha1);
2408                 if (pos < 0)
2409                         return 0;
2410                 return nth_packed_object_offset(p, pos);
2411         }
2412
2413         do {
2414                 unsigned mi = (lo + hi) / 2;
2415                 int cmp = hashcmp(index + mi * stride, sha1);
2416
2417                 if (debug_lookup)
2418                         printf("lo %u hi %u rg %u mi %u\n",
2419                                lo, hi, hi - lo, mi);
2420                 if (!cmp)
2421                         return nth_packed_object_offset(p, mi);
2422                 if (cmp > 0)
2423                         hi = mi;
2424                 else
2425                         lo = mi+1;
2426         } while (lo < hi);
2427         return 0;
2428 }
2429
2430 int is_pack_valid(struct packed_git *p)
2431 {
2432         /* An already open pack is known to be valid. */
2433         if (p->pack_fd != -1)
2434                 return 1;
2435
2436         /* If the pack has one window completely covering the
2437          * file size, the pack is known to be valid even if
2438          * the descriptor is not currently open.
2439          */
2440         if (p->windows) {
2441                 struct pack_window *w = p->windows;
2442
2443                 if (!w->offset && w->len == p->pack_size)
2444                         return 1;
2445         }
2446
2447         /* Force the pack to open to prove its valid. */
2448         return !open_packed_git(p);
2449 }
2450
2451 static int fill_pack_entry(const unsigned char *sha1,
2452                            struct pack_entry *e,
2453                            struct packed_git *p)
2454 {
2455         off_t offset;
2456
2457         if (p->num_bad_objects) {
2458                 unsigned i;
2459                 for (i = 0; i < p->num_bad_objects; i++)
2460                         if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
2461                                 return 0;
2462         }
2463
2464         offset = find_pack_entry_one(sha1, p);
2465         if (!offset)
2466                 return 0;
2467
2468         /*
2469          * We are about to tell the caller where they can locate the
2470          * requested object.  We better make sure the packfile is
2471          * still here and can be accessed before supplying that
2472          * answer, as it may have been deleted since the index was
2473          * loaded!
2474          */
2475         if (!is_pack_valid(p)) {
2476                 warning("packfile %s cannot be accessed", p->pack_name);
2477                 return 0;
2478         }
2479         e->offset = offset;
2480         e->p = p;
2481         hashcpy(e->sha1, sha1);
2482         return 1;
2483 }
2484
2485 /*
2486  * Iff a pack file contains the object named by sha1, return true and
2487  * store its location to e.
2488  */
2489 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
2490 {
2491         struct packed_git *p;
2492
2493         prepare_packed_git();
2494         if (!packed_git)
2495                 return 0;
2496
2497         if (last_found_pack && fill_pack_entry(sha1, e, last_found_pack))
2498                 return 1;
2499
2500         for (p = packed_git; p; p = p->next) {
2501                 if (p == last_found_pack)
2502                         continue; /* we already checked this one */
2503
2504                 if (fill_pack_entry(sha1, e, p)) {
2505                         last_found_pack = p;
2506                         return 1;
2507                 }
2508         }
2509         return 0;
2510 }
2511
2512 struct packed_git *find_sha1_pack(const unsigned char *sha1,
2513                                   struct packed_git *packs)
2514 {
2515         struct packed_git *p;
2516
2517         for (p = packs; p; p = p->next) {
2518                 if (find_pack_entry_one(sha1, p))
2519                         return p;
2520         }
2521         return NULL;
2522
2523 }
2524
2525 static int sha1_loose_object_info(const unsigned char *sha1,
2526                                   struct object_info *oi)
2527 {
2528         int status;
2529         unsigned long mapsize, size;
2530         void *map;
2531         git_zstream stream;
2532         char hdr[32];
2533
2534         if (oi->delta_base_sha1)
2535                 hashclr(oi->delta_base_sha1);
2536
2537         /*
2538          * If we don't care about type or size, then we don't
2539          * need to look inside the object at all. Note that we
2540          * do not optimize out the stat call, even if the
2541          * caller doesn't care about the disk-size, since our
2542          * return value implicitly indicates whether the
2543          * object even exists.
2544          */
2545         if (!oi->typep && !oi->sizep) {
2546                 struct stat st;
2547                 if (stat_sha1_file(sha1, &st) < 0)
2548                         return -1;
2549                 if (oi->disk_sizep)
2550                         *oi->disk_sizep = st.st_size;
2551                 return 0;
2552         }
2553
2554         map = map_sha1_file(sha1, &mapsize);
2555         if (!map)
2556                 return -1;
2557         if (oi->disk_sizep)
2558                 *oi->disk_sizep = mapsize;
2559         if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
2560                 status = error("unable to unpack %s header",
2561                                sha1_to_hex(sha1));
2562         else if ((status = parse_sha1_header(hdr, &size)) < 0)
2563                 status = error("unable to parse %s header", sha1_to_hex(sha1));
2564         else if (oi->sizep)
2565                 *oi->sizep = size;
2566         git_inflate_end(&stream);
2567         munmap(map, mapsize);
2568         if (oi->typep)
2569                 *oi->typep = status;
2570         return 0;
2571 }
2572
2573 int sha1_object_info_extended(const unsigned char *sha1, struct object_info *oi, unsigned flags)
2574 {
2575         struct cached_object *co;
2576         struct pack_entry e;
2577         int rtype;
2578         const unsigned char *real = lookup_replace_object_extended(sha1, flags);
2579
2580         co = find_cached_object(real);
2581         if (co) {
2582                 if (oi->typep)
2583                         *(oi->typep) = co->type;
2584                 if (oi->sizep)
2585                         *(oi->sizep) = co->size;
2586                 if (oi->disk_sizep)
2587                         *(oi->disk_sizep) = 0;
2588                 if (oi->delta_base_sha1)
2589                         hashclr(oi->delta_base_sha1);
2590                 oi->whence = OI_CACHED;
2591                 return 0;
2592         }
2593
2594         if (!find_pack_entry(real, &e)) {
2595                 /* Most likely it's a loose object. */
2596                 if (!sha1_loose_object_info(real, oi)) {
2597                         oi->whence = OI_LOOSE;
2598                         return 0;
2599                 }
2600
2601                 /* Not a loose object; someone else may have just packed it. */
2602                 reprepare_packed_git();
2603                 if (!find_pack_entry(real, &e))
2604                         return -1;
2605         }
2606
2607         rtype = packed_object_info(e.p, e.offset, oi);
2608         if (rtype < 0) {
2609                 mark_bad_packed_object(e.p, real);
2610                 return sha1_object_info_extended(real, oi, 0);
2611         } else if (in_delta_base_cache(e.p, e.offset)) {
2612                 oi->whence = OI_DBCACHED;
2613         } else {
2614                 oi->whence = OI_PACKED;
2615                 oi->u.packed.offset = e.offset;
2616                 oi->u.packed.pack = e.p;
2617                 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
2618                                          rtype == OBJ_OFS_DELTA);
2619         }
2620
2621         return 0;
2622 }
2623
2624 /* returns enum object_type or negative */
2625 int sha1_object_info(const unsigned char *sha1, unsigned long *sizep)
2626 {
2627         enum object_type type;
2628         struct object_info oi = {NULL};
2629
2630         oi.typep = &type;
2631         oi.sizep = sizep;
2632         if (sha1_object_info_extended(sha1, &oi, LOOKUP_REPLACE_OBJECT) < 0)
2633                 return -1;
2634         return type;
2635 }
2636
2637 static void *read_packed_sha1(const unsigned char *sha1,
2638                               enum object_type *type, unsigned long *size)
2639 {
2640         struct pack_entry e;
2641         void *data;
2642
2643         if (!find_pack_entry(sha1, &e))
2644                 return NULL;
2645         data = cache_or_unpack_entry(e.p, e.offset, size, type, 1);
2646         if (!data) {
2647                 /*
2648                  * We're probably in deep shit, but let's try to fetch
2649                  * the required object anyway from another pack or loose.
2650                  * This should happen only in the presence of a corrupted
2651                  * pack, and is better than failing outright.
2652                  */
2653                 error("failed to read object %s at offset %"PRIuMAX" from %s",
2654                       sha1_to_hex(sha1), (uintmax_t)e.offset, e.p->pack_name);
2655                 mark_bad_packed_object(e.p, sha1);
2656                 data = read_object(sha1, type, size);
2657         }
2658         return data;
2659 }
2660
2661 int pretend_sha1_file(void *buf, unsigned long len, enum object_type type,
2662                       unsigned char *sha1)
2663 {
2664         struct cached_object *co;
2665
2666         hash_sha1_file(buf, len, typename(type), sha1);
2667         if (has_sha1_file(sha1) || find_cached_object(sha1))
2668                 return 0;
2669         ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
2670         co = &cached_objects[cached_object_nr++];
2671         co->size = len;
2672         co->type = type;
2673         co->buf = xmalloc(len);
2674         memcpy(co->buf, buf, len);
2675         hashcpy(co->sha1, sha1);
2676         return 0;
2677 }
2678
2679 static void *read_object(const unsigned char *sha1, enum object_type *type,
2680                          unsigned long *size)
2681 {
2682         unsigned long mapsize;
2683         void *map, *buf;
2684         struct cached_object *co;
2685
2686         co = find_cached_object(sha1);
2687         if (co) {
2688                 *type = co->type;
2689                 *size = co->size;
2690                 return xmemdupz(co->buf, co->size);
2691         }
2692
2693         buf = read_packed_sha1(sha1, type, size);
2694         if (buf)
2695                 return buf;
2696         map = map_sha1_file(sha1, &mapsize);
2697         if (map) {
2698                 buf = unpack_sha1_file(map, mapsize, type, size, sha1);
2699                 munmap(map, mapsize);
2700                 return buf;
2701         }
2702         reprepare_packed_git();
2703         return read_packed_sha1(sha1, type, size);
2704 }
2705
2706 /*
2707  * This function dies on corrupt objects; the callers who want to
2708  * deal with them should arrange to call read_object() and give error
2709  * messages themselves.
2710  */
2711 void *read_sha1_file_extended(const unsigned char *sha1,
2712                               enum object_type *type,
2713                               unsigned long *size,
2714                               unsigned flag)
2715 {
2716         void *data;
2717         const struct packed_git *p;
2718         const unsigned char *repl = lookup_replace_object_extended(sha1, flag);
2719
2720         errno = 0;
2721         data = read_object(repl, type, size);
2722         if (data)
2723                 return data;
2724
2725         if (errno && errno != ENOENT)
2726                 die_errno("failed to read object %s", sha1_to_hex(sha1));
2727
2728         /* die if we replaced an object with one that does not exist */
2729         if (repl != sha1)
2730                 die("replacement %s not found for %s",
2731                     sha1_to_hex(repl), sha1_to_hex(sha1));
2732
2733         if (has_loose_object(repl)) {
2734                 const char *path = sha1_file_name(sha1);
2735
2736                 die("loose object %s (stored in %s) is corrupt",
2737                     sha1_to_hex(repl), path);
2738         }
2739
2740         if ((p = has_packed_and_bad(repl)) != NULL)
2741                 die("packed object %s (stored in %s) is corrupt",
2742                     sha1_to_hex(repl), p->pack_name);
2743
2744         return NULL;
2745 }
2746
2747 void *read_object_with_reference(const unsigned char *sha1,
2748                                  const char *required_type_name,
2749                                  unsigned long *size,
2750                                  unsigned char *actual_sha1_return)
2751 {
2752         enum object_type type, required_type;
2753         void *buffer;
2754         unsigned long isize;
2755         unsigned char actual_sha1[20];
2756
2757         required_type = type_from_string(required_type_name);
2758         hashcpy(actual_sha1, sha1);
2759         while (1) {
2760                 int ref_length = -1;
2761                 const char *ref_type = NULL;
2762
2763                 buffer = read_sha1_file(actual_sha1, &type, &isize);
2764                 if (!buffer)
2765                         return NULL;
2766                 if (type == required_type) {
2767                         *size = isize;
2768                         if (actual_sha1_return)
2769                                 hashcpy(actual_sha1_return, actual_sha1);
2770                         return buffer;
2771                 }
2772                 /* Handle references */
2773                 else if (type == OBJ_COMMIT)
2774                         ref_type = "tree ";
2775                 else if (type == OBJ_TAG)
2776                         ref_type = "object ";
2777                 else {
2778                         free(buffer);
2779                         return NULL;
2780                 }
2781                 ref_length = strlen(ref_type);
2782
2783                 if (ref_length + 40 > isize ||
2784                     memcmp(buffer, ref_type, ref_length) ||
2785                     get_sha1_hex((char *) buffer + ref_length, actual_sha1)) {
2786                         free(buffer);
2787                         return NULL;
2788                 }
2789                 free(buffer);
2790                 /* Now we have the ID of the referred-to object in
2791                  * actual_sha1.  Check again. */
2792         }
2793 }
2794
2795 static void write_sha1_file_prepare(const void *buf, unsigned long len,
2796                                     const char *type, unsigned char *sha1,
2797                                     char *hdr, int *hdrlen)
2798 {
2799         git_SHA_CTX c;
2800
2801         /* Generate the header */
2802         *hdrlen = sprintf(hdr, "%s %lu", type, len)+1;
2803
2804         /* Sha1.. */
2805         git_SHA1_Init(&c);
2806         git_SHA1_Update(&c, hdr, *hdrlen);
2807         git_SHA1_Update(&c, buf, len);
2808         git_SHA1_Final(sha1, &c);
2809 }
2810
2811 /*
2812  * Move the just written object into its final resting place.
2813  * NEEDSWORK: this should be renamed to finalize_temp_file() as
2814  * "moving" is only a part of what it does, when no patch between
2815  * master to pu changes the call sites of this function.
2816  */
2817 int move_temp_to_file(const char *tmpfile, const char *filename)
2818 {
2819         int ret = 0;
2820
2821         if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
2822                 goto try_rename;
2823         else if (link(tmpfile, filename))
2824                 ret = errno;
2825
2826         /*
2827          * Coda hack - coda doesn't like cross-directory links,
2828          * so we fall back to a rename, which will mean that it
2829          * won't be able to check collisions, but that's not a
2830          * big deal.
2831          *
2832          * The same holds for FAT formatted media.
2833          *
2834          * When this succeeds, we just return.  We have nothing
2835          * left to unlink.
2836          */
2837         if (ret && ret != EEXIST) {
2838         try_rename:
2839                 if (!rename(tmpfile, filename))
2840                         goto out;
2841                 ret = errno;
2842         }
2843         unlink_or_warn(tmpfile);
2844         if (ret) {
2845                 if (ret != EEXIST) {
2846                         return error("unable to write sha1 filename %s: %s", filename, strerror(ret));
2847                 }
2848                 /* FIXME!!! Collision check here ? */
2849         }
2850
2851 out:
2852         if (adjust_shared_perm(filename))
2853                 return error("unable to set permission to '%s'", filename);
2854         return 0;
2855 }
2856
2857 static int write_buffer(int fd, const void *buf, size_t len)
2858 {
2859         if (write_in_full(fd, buf, len) < 0)
2860                 return error("file write error (%s)", strerror(errno));
2861         return 0;
2862 }
2863
2864 int hash_sha1_file(const void *buf, unsigned long len, const char *type,
2865                    unsigned char *sha1)
2866 {
2867         char hdr[32];
2868         int hdrlen;
2869         write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
2870         return 0;
2871 }
2872
2873 /* Finalize a file on disk, and close it. */
2874 static void close_sha1_file(int fd)
2875 {
2876         if (fsync_object_files)
2877                 fsync_or_die(fd, "sha1 file");
2878         if (close(fd) != 0)
2879                 die_errno("error when closing sha1 file");
2880 }
2881
2882 /* Size of directory component, including the ending '/' */
2883 static inline int directory_size(const char *filename)
2884 {
2885         const char *s = strrchr(filename, '/');
2886         if (!s)
2887                 return 0;
2888         return s - filename + 1;
2889 }
2890
2891 /*
2892  * This creates a temporary file in the same directory as the final
2893  * 'filename'
2894  *
2895  * We want to avoid cross-directory filename renames, because those
2896  * can have problems on various filesystems (FAT, NFS, Coda).
2897  */
2898 static int create_tmpfile(char *buffer, size_t bufsiz, const char *filename)
2899 {
2900         int fd, dirlen = directory_size(filename);
2901
2902         if (dirlen + 20 > bufsiz) {
2903                 errno = ENAMETOOLONG;
2904                 return -1;
2905         }
2906         memcpy(buffer, filename, dirlen);
2907         strcpy(buffer + dirlen, "tmp_obj_XXXXXX");
2908         fd = git_mkstemp_mode(buffer, 0444);
2909         if (fd < 0 && dirlen && errno == ENOENT) {
2910                 /* Make sure the directory exists */
2911                 memcpy(buffer, filename, dirlen);
2912                 buffer[dirlen-1] = 0;
2913                 if (mkdir(buffer, 0777) && errno != EEXIST)
2914                         return -1;
2915                 if (adjust_shared_perm(buffer))
2916                         return -1;
2917
2918                 /* Try again */
2919                 strcpy(buffer + dirlen - 1, "/tmp_obj_XXXXXX");
2920                 fd = git_mkstemp_mode(buffer, 0444);
2921         }
2922         return fd;
2923 }
2924
2925 static int write_loose_object(const unsigned char *sha1, char *hdr, int hdrlen,
2926                               const void *buf, unsigned long len, time_t mtime)
2927 {
2928         int fd, ret;
2929         unsigned char compressed[4096];
2930         git_zstream stream;
2931         git_SHA_CTX c;
2932         unsigned char parano_sha1[20];
2933         static char tmp_file[PATH_MAX];
2934         const char *filename = sha1_file_name(sha1);
2935
2936         fd = create_tmpfile(tmp_file, sizeof(tmp_file), filename);
2937         if (fd < 0) {
2938                 if (errno == EACCES)
2939                         return error("insufficient permission for adding an object to repository database %s", get_object_directory());
2940                 else
2941                         return error("unable to create temporary file: %s", strerror(errno));
2942         }
2943
2944         /* Set it up */
2945         memset(&stream, 0, sizeof(stream));
2946         git_deflate_init(&stream, zlib_compression_level);
2947         stream.next_out = compressed;
2948         stream.avail_out = sizeof(compressed);
2949         git_SHA1_Init(&c);
2950
2951         /* First header.. */
2952         stream.next_in = (unsigned char *)hdr;
2953         stream.avail_in = hdrlen;
2954         while (git_deflate(&stream, 0) == Z_OK)
2955                 ; /* nothing */
2956         git_SHA1_Update(&c, hdr, hdrlen);
2957
2958         /* Then the data itself.. */
2959         stream.next_in = (void *)buf;
2960         stream.avail_in = len;
2961         do {
2962                 unsigned char *in0 = stream.next_in;
2963                 ret = git_deflate(&stream, Z_FINISH);
2964                 git_SHA1_Update(&c, in0, stream.next_in - in0);
2965                 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
2966                         die("unable to write sha1 file");
2967                 stream.next_out = compressed;
2968                 stream.avail_out = sizeof(compressed);
2969         } while (ret == Z_OK);
2970
2971         if (ret != Z_STREAM_END)
2972                 die("unable to deflate new object %s (%d)", sha1_to_hex(sha1), ret);
2973         ret = git_deflate_end_gently(&stream);
2974         if (ret != Z_OK)
2975                 die("deflateEnd on object %s failed (%d)", sha1_to_hex(sha1), ret);
2976         git_SHA1_Final(parano_sha1, &c);
2977         if (hashcmp(sha1, parano_sha1) != 0)
2978                 die("confused by unstable object source data for %s", sha1_to_hex(sha1));
2979
2980         close_sha1_file(fd);
2981
2982         if (mtime) {
2983                 struct utimbuf utb;
2984                 utb.actime = mtime;
2985                 utb.modtime = mtime;
2986                 if (utime(tmp_file, &utb) < 0)
2987                         warning("failed utime() on %s: %s",
2988                                 tmp_file, strerror(errno));
2989         }
2990
2991         return move_temp_to_file(tmp_file, filename);
2992 }
2993
2994 static int freshen_loose_object(const unsigned char *sha1)
2995 {
2996         return check_and_freshen(sha1, 1);
2997 }
2998
2999 static int freshen_packed_object(const unsigned char *sha1)
3000 {
3001         struct pack_entry e;
3002         return find_pack_entry(sha1, &e) && freshen_file(e.p->pack_name);
3003 }
3004
3005 int write_sha1_file(const void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
3006 {
3007         unsigned char sha1[20];
3008         char hdr[32];
3009         int hdrlen;
3010
3011         /* Normally if we have it in the pack then we do not bother writing
3012          * it out into .git/objects/??/?{38} file.
3013          */
3014         write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
3015         if (returnsha1)
3016                 hashcpy(returnsha1, sha1);
3017         if (freshen_loose_object(sha1) || freshen_packed_object(sha1))
3018                 return 0;
3019         return write_loose_object(sha1, hdr, hdrlen, buf, len, 0);
3020 }
3021
3022 int force_object_loose(const unsigned char *sha1, time_t mtime)
3023 {
3024         void *buf;
3025         unsigned long len;
3026         enum object_type type;
3027         char hdr[32];
3028         int hdrlen;
3029         int ret;
3030
3031         if (has_loose_object(sha1))
3032                 return 0;
3033         buf = read_packed_sha1(sha1, &type, &len);
3034         if (!buf)
3035                 return error("cannot read sha1_file for %s", sha1_to_hex(sha1));
3036         hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1;
3037         ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime);
3038         free(buf);
3039
3040         return ret;
3041 }
3042
3043 int has_pack_index(const unsigned char *sha1)
3044 {
3045         struct stat st;
3046         if (stat(sha1_pack_index_name(sha1), &st))
3047                 return 0;
3048         return 1;
3049 }
3050
3051 int has_sha1_pack(const unsigned char *sha1)
3052 {
3053         struct pack_entry e;
3054         return find_pack_entry(sha1, &e);
3055 }
3056
3057 int has_sha1_file(const unsigned char *sha1)
3058 {
3059         struct pack_entry e;
3060
3061         if (find_pack_entry(sha1, &e))
3062                 return 1;
3063         if (has_loose_object(sha1))
3064                 return 1;
3065         reprepare_packed_git();
3066         return find_pack_entry(sha1, &e);
3067 }
3068
3069 static void check_tree(const void *buf, size_t size)
3070 {
3071         struct tree_desc desc;
3072         struct name_entry entry;
3073
3074         init_tree_desc(&desc, buf, size);
3075         while (tree_entry(&desc, &entry))
3076                 /* do nothing
3077                  * tree_entry() will die() on malformed entries */
3078                 ;
3079 }
3080
3081 static void check_commit(const void *buf, size_t size)
3082 {
3083         struct commit c;
3084         memset(&c, 0, sizeof(c));
3085         if (parse_commit_buffer(&c, buf, size))
3086                 die("corrupt commit");
3087 }
3088
3089 static void check_tag(const void *buf, size_t size)
3090 {
3091         struct tag t;
3092         memset(&t, 0, sizeof(t));
3093         if (parse_tag_buffer(&t, buf, size))
3094                 die("corrupt tag");
3095 }
3096
3097 static int index_mem(unsigned char *sha1, void *buf, size_t size,
3098                      enum object_type type,
3099                      const char *path, unsigned flags)
3100 {
3101         int ret, re_allocated = 0;
3102         int write_object = flags & HASH_WRITE_OBJECT;
3103
3104         if (!type)
3105                 type = OBJ_BLOB;
3106
3107         /*
3108          * Convert blobs to git internal format
3109          */
3110         if ((type == OBJ_BLOB) && path) {
3111                 struct strbuf nbuf = STRBUF_INIT;
3112                 if (convert_to_git(path, buf, size, &nbuf,
3113                                    write_object ? safe_crlf : SAFE_CRLF_FALSE)) {
3114                         buf = strbuf_detach(&nbuf, &size);
3115                         re_allocated = 1;
3116                 }
3117         }
3118         if (flags & HASH_FORMAT_CHECK) {
3119                 if (type == OBJ_TREE)
3120                         check_tree(buf, size);
3121                 if (type == OBJ_COMMIT)
3122                         check_commit(buf, size);
3123                 if (type == OBJ_TAG)
3124                         check_tag(buf, size);
3125         }
3126
3127         if (write_object)
3128                 ret = write_sha1_file(buf, size, typename(type), sha1);
3129         else
3130                 ret = hash_sha1_file(buf, size, typename(type), sha1);
3131         if (re_allocated)
3132                 free(buf);
3133         return ret;
3134 }
3135
3136 static int index_stream_convert_blob(unsigned char *sha1, int fd,
3137                                      const char *path, unsigned flags)
3138 {
3139         int ret;
3140         const int write_object = flags & HASH_WRITE_OBJECT;
3141         struct strbuf sbuf = STRBUF_INIT;
3142
3143         assert(path);
3144         assert(would_convert_to_git_filter_fd(path));
3145
3146         convert_to_git_filter_fd(path, fd, &sbuf,
3147                                  write_object ? safe_crlf : SAFE_CRLF_FALSE);
3148
3149         if (write_object)
3150                 ret = write_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
3151                                       sha1);
3152         else
3153                 ret = hash_sha1_file(sbuf.buf, sbuf.len, typename(OBJ_BLOB),
3154                                      sha1);
3155         strbuf_release(&sbuf);
3156         return ret;
3157 }
3158
3159 static int index_pipe(unsigned char *sha1, int fd, enum object_type type,
3160                       const char *path, unsigned flags)
3161 {
3162         struct strbuf sbuf = STRBUF_INIT;
3163         int ret;
3164
3165         if (strbuf_read(&sbuf, fd, 4096) >= 0)
3166                 ret = index_mem(sha1, sbuf.buf, sbuf.len, type, path, flags);
3167         else
3168                 ret = -1;
3169         strbuf_release(&sbuf);
3170         return ret;
3171 }
3172
3173 #define SMALL_FILE_SIZE (32*1024)
3174
3175 static int index_core(unsigned char *sha1, int fd, size_t size,
3176                       enum object_type type, const char *path,
3177                       unsigned flags)
3178 {
3179         int ret;
3180
3181         if (!size) {
3182                 ret = index_mem(sha1, NULL, size, type, path, flags);
3183         } else if (size <= SMALL_FILE_SIZE) {
3184                 char *buf = xmalloc(size);
3185                 if (size == read_in_full(fd, buf, size))
3186                         ret = index_mem(sha1, buf, size, type, path, flags);
3187                 else
3188                         ret = error("short read %s", strerror(errno));
3189                 free(buf);
3190         } else {
3191                 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
3192                 ret = index_mem(sha1, buf, size, type, path, flags);
3193                 munmap(buf, size);
3194         }
3195         return ret;
3196 }
3197
3198 /*
3199  * This creates one packfile per large blob unless bulk-checkin
3200  * machinery is "plugged".
3201  *
3202  * This also bypasses the usual "convert-to-git" dance, and that is on
3203  * purpose. We could write a streaming version of the converting
3204  * functions and insert that before feeding the data to fast-import
3205  * (or equivalent in-core API described above). However, that is
3206  * somewhat complicated, as we do not know the size of the filter
3207  * result, which we need to know beforehand when writing a git object.
3208  * Since the primary motivation for trying to stream from the working
3209  * tree file and to avoid mmaping it in core is to deal with large
3210  * binary blobs, they generally do not want to get any conversion, and
3211  * callers should avoid this code path when filters are requested.
3212  */
3213 static int index_stream(unsigned char *sha1, int fd, size_t size,
3214                         enum object_type type, const char *path,
3215                         unsigned flags)
3216 {
3217         return index_bulk_checkin(sha1, fd, size, type, path, flags);
3218 }
3219
3220 int index_fd(unsigned char *sha1, int fd, struct stat *st,
3221              enum object_type type, const char *path, unsigned flags)
3222 {
3223         int ret;
3224
3225         /*
3226          * Call xsize_t() only when needed to avoid potentially unnecessary
3227          * die() for large files.
3228          */
3229         if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(path))
3230                 ret = index_stream_convert_blob(sha1, fd, path, flags);
3231         else if (!S_ISREG(st->st_mode))
3232                 ret = index_pipe(sha1, fd, type, path, flags);
3233         else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
3234                  (path && would_convert_to_git(path)))
3235                 ret = index_core(sha1, fd, xsize_t(st->st_size), type, path,
3236                                  flags);
3237         else
3238                 ret = index_stream(sha1, fd, xsize_t(st->st_size), type, path,
3239                                    flags);
3240         close(fd);
3241         return ret;
3242 }
3243
3244 int index_path(unsigned char *sha1, const char *path, struct stat *st, unsigned flags)
3245 {
3246         int fd;
3247         struct strbuf sb = STRBUF_INIT;
3248
3249         switch (st->st_mode & S_IFMT) {
3250         case S_IFREG:
3251                 fd = open(path, O_RDONLY);
3252                 if (fd < 0)
3253                         return error("open(\"%s\"): %s", path,
3254                                      strerror(errno));
3255                 if (index_fd(sha1, fd, st, OBJ_BLOB, path, flags) < 0)
3256                         return error("%s: failed to insert into database",
3257                                      path);
3258                 break;
3259         case S_IFLNK:
3260                 if (strbuf_readlink(&sb, path, st->st_size)) {
3261                         char *errstr = strerror(errno);
3262                         return error("readlink(\"%s\"): %s", path,
3263                                      errstr);
3264                 }
3265                 if (!(flags & HASH_WRITE_OBJECT))
3266                         hash_sha1_file(sb.buf, sb.len, blob_type, sha1);
3267                 else if (write_sha1_file(sb.buf, sb.len, blob_type, sha1))
3268                         return error("%s: failed to insert into database",
3269                                      path);
3270                 strbuf_release(&sb);
3271                 break;
3272         case S_IFDIR:
3273                 return resolve_gitlink_ref(path, "HEAD", sha1);
3274         default:
3275                 return error("%s: unsupported file type", path);
3276         }
3277         return 0;
3278 }
3279
3280 int read_pack_header(int fd, struct pack_header *header)
3281 {
3282         if (read_in_full(fd, header, sizeof(*header)) < sizeof(*header))
3283                 /* "eof before pack header was fully read" */
3284                 return PH_ERROR_EOF;
3285
3286         if (header->hdr_signature != htonl(PACK_SIGNATURE))
3287                 /* "protocol error (pack signature mismatch detected)" */
3288                 return PH_ERROR_PACK_SIGNATURE;
3289         if (!pack_version_ok(header->hdr_version))
3290                 /* "protocol error (pack version unsupported)" */
3291                 return PH_ERROR_PROTOCOL;
3292         return 0;
3293 }
3294
3295 void assert_sha1_type(const unsigned char *sha1, enum object_type expect)
3296 {
3297         enum object_type type = sha1_object_info(sha1, NULL);
3298         if (type < 0)
3299                 die("%s is not a valid object", sha1_to_hex(sha1));
3300         if (type != expect)
3301                 die("%s is not a valid '%s' object", sha1_to_hex(sha1),
3302                     typename(expect));
3303 }
3304
3305 static int for_each_file_in_obj_subdir(int subdir_nr,
3306                                        struct strbuf *path,
3307                                        each_loose_object_fn obj_cb,
3308                                        each_loose_cruft_fn cruft_cb,
3309                                        each_loose_subdir_fn subdir_cb,
3310                                        void *data)
3311 {
3312         size_t baselen = path->len;
3313         DIR *dir = opendir(path->buf);
3314         struct dirent *de;
3315         int r = 0;
3316
3317         if (!dir) {
3318                 if (errno == ENOENT)
3319                         return 0;
3320                 return error("unable to open %s: %s", path->buf, strerror(errno));
3321         }
3322
3323         while ((de = readdir(dir))) {
3324                 if (is_dot_or_dotdot(de->d_name))
3325                         continue;
3326
3327                 strbuf_setlen(path, baselen);
3328                 strbuf_addf(path, "/%s", de->d_name);
3329
3330                 if (strlen(de->d_name) == 38)  {
3331                         char hex[41];
3332                         unsigned char sha1[20];
3333
3334                         snprintf(hex, sizeof(hex), "%02x%s",
3335                                  subdir_nr, de->d_name);
3336                         if (!get_sha1_hex(hex, sha1)) {
3337                                 if (obj_cb) {
3338                                         r = obj_cb(sha1, path->buf, data);
3339                                         if (r)
3340                                                 break;
3341                                 }
3342                                 continue;
3343                         }
3344                 }
3345
3346                 if (cruft_cb) {
3347                         r = cruft_cb(de->d_name, path->buf, data);
3348                         if (r)
3349                                 break;
3350                 }
3351         }
3352         strbuf_setlen(path, baselen);
3353
3354         if (!r && subdir_cb)
3355                 r = subdir_cb(subdir_nr, path->buf, data);
3356
3357         closedir(dir);
3358         return r;
3359 }
3360
3361 int for_each_loose_file_in_objdir(const char *path,
3362                             each_loose_object_fn obj_cb,
3363                             each_loose_cruft_fn cruft_cb,
3364                             each_loose_subdir_fn subdir_cb,
3365                             void *data)
3366 {
3367         struct strbuf buf = STRBUF_INIT;
3368         size_t baselen;
3369         int r = 0;
3370         int i;
3371
3372         strbuf_addstr(&buf, path);
3373         strbuf_addch(&buf, '/');
3374         baselen = buf.len;
3375
3376         for (i = 0; i < 256; i++) {
3377                 strbuf_addf(&buf, "%02x", i);
3378                 r = for_each_file_in_obj_subdir(i, &buf, obj_cb, cruft_cb,
3379                                                 subdir_cb, data);
3380                 strbuf_setlen(&buf, baselen);
3381                 if (r)
3382                         break;
3383         }
3384
3385         strbuf_release(&buf);
3386         return r;
3387 }
3388
3389 struct loose_alt_odb_data {
3390         each_loose_object_fn *cb;
3391         void *data;
3392 };
3393
3394 static int loose_from_alt_odb(struct alternate_object_database *alt,
3395                               void *vdata)
3396 {
3397         struct loose_alt_odb_data *data = vdata;
3398         return for_each_loose_file_in_objdir(alt->base,
3399                                              data->cb, NULL, NULL,
3400                                              data->data);
3401 }
3402
3403 int for_each_loose_object(each_loose_object_fn cb, void *data)
3404 {
3405         struct loose_alt_odb_data alt;
3406         int r;
3407
3408         r = for_each_loose_file_in_objdir(get_object_directory(),
3409                                           cb, NULL, NULL, data);
3410         if (r)
3411                 return r;
3412
3413         alt.cb = cb;
3414         alt.data = data;
3415         return foreach_alt_odb(loose_from_alt_odb, &alt);
3416 }
3417
3418 static int for_each_object_in_pack(struct packed_git *p, each_packed_object_fn cb, void *data)
3419 {
3420         uint32_t i;
3421         int r = 0;
3422
3423         for (i = 0; i < p->num_objects; i++) {
3424                 const unsigned char *sha1 = nth_packed_object_sha1(p, i);
3425
3426                 if (!sha1)
3427                         return error("unable to get sha1 of object %u in %s",
3428                                      i, p->pack_name);
3429
3430                 r = cb(sha1, p, i, data);
3431                 if (r)
3432                         break;
3433         }
3434         return r;
3435 }
3436
3437 int for_each_packed_object(each_packed_object_fn cb, void *data)
3438 {
3439         struct packed_git *p;
3440         int r = 0;
3441
3442         prepare_packed_git();
3443         for (p = packed_git; p; p = p->next) {
3444                 r = for_each_object_in_pack(p, cb, data);
3445                 if (r)
3446                         break;
3447         }
3448         return r;
3449 }