Add a base implementation of SHA-256 support
[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 "config.h"
11 #include "string-list.h"
12 #include "lockfile.h"
13 #include "delta.h"
14 #include "pack.h"
15 #include "blob.h"
16 #include "commit.h"
17 #include "run-command.h"
18 #include "tag.h"
19 #include "tree.h"
20 #include "tree-walk.h"
21 #include "refs.h"
22 #include "pack-revindex.h"
23 #include "sha1-lookup.h"
24 #include "bulk-checkin.h"
25 #include "repository.h"
26 #include "replace-object.h"
27 #include "streaming.h"
28 #include "dir.h"
29 #include "list.h"
30 #include "mergesort.h"
31 #include "quote.h"
32 #include "packfile.h"
33 #include "fetch-object.h"
34 #include "object-store.h"
35
36 /* The maximum size for an object header. */
37 #define MAX_HEADER_LEN 32
38
39
40 #define EMPTY_TREE_SHA1_BIN_LITERAL \
41          "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60" \
42          "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04"
43 #define EMPTY_TREE_SHA256_BIN_LITERAL \
44         "\x6e\xf1\x9b\x41\x22\x5c\x53\x69\xf1\xc1" \
45         "\x04\xd4\x5d\x8d\x85\xef\xa9\xb0\x57\xb5" \
46         "\x3b\x14\xb4\xb9\xb9\x39\xdd\x74\xde\xcc" \
47         "\x53\x21"
48
49 #define EMPTY_BLOB_SHA1_BIN_LITERAL \
50         "\xe6\x9d\xe2\x9b\xb2\xd1\xd6\x43\x4b\x8b" \
51         "\x29\xae\x77\x5a\xd8\xc2\xe4\x8c\x53\x91"
52 #define EMPTY_BLOB_SHA256_BIN_LITERAL \
53         "\x47\x3a\x0f\x4c\x3b\xe8\xa9\x36\x81\xa2" \
54         "\x67\xe3\xb1\xe9\xa7\xdc\xda\x11\x85\x43" \
55         "\x6f\xe1\x41\xf7\x74\x91\x20\xa3\x03\x72" \
56         "\x18\x13"
57
58 const unsigned char null_sha1[GIT_MAX_RAWSZ];
59 const struct object_id null_oid;
60 static const struct object_id empty_tree_oid = {
61         EMPTY_TREE_SHA1_BIN_LITERAL
62 };
63 static const struct object_id empty_blob_oid = {
64         EMPTY_BLOB_SHA1_BIN_LITERAL
65 };
66 static const struct object_id empty_tree_oid_sha256 = {
67         EMPTY_TREE_SHA256_BIN_LITERAL
68 };
69 static const struct object_id empty_blob_oid_sha256 = {
70         EMPTY_BLOB_SHA256_BIN_LITERAL
71 };
72
73 static void git_hash_sha1_init(git_hash_ctx *ctx)
74 {
75         git_SHA1_Init(&ctx->sha1);
76 }
77
78 static void git_hash_sha1_update(git_hash_ctx *ctx, const void *data, size_t len)
79 {
80         git_SHA1_Update(&ctx->sha1, data, len);
81 }
82
83 static void git_hash_sha1_final(unsigned char *hash, git_hash_ctx *ctx)
84 {
85         git_SHA1_Final(hash, &ctx->sha1);
86 }
87
88
89 static void git_hash_sha256_init(git_hash_ctx *ctx)
90 {
91         git_SHA256_Init(&ctx->sha256);
92 }
93
94 static void git_hash_sha256_update(git_hash_ctx *ctx, const void *data, size_t len)
95 {
96         git_SHA256_Update(&ctx->sha256, data, len);
97 }
98
99 static void git_hash_sha256_final(unsigned char *hash, git_hash_ctx *ctx)
100 {
101         git_SHA256_Final(hash, &ctx->sha256);
102 }
103
104 static void git_hash_unknown_init(git_hash_ctx *ctx)
105 {
106         BUG("trying to init unknown hash");
107 }
108
109 static void git_hash_unknown_update(git_hash_ctx *ctx, const void *data, size_t len)
110 {
111         BUG("trying to update unknown hash");
112 }
113
114 static void git_hash_unknown_final(unsigned char *hash, git_hash_ctx *ctx)
115 {
116         BUG("trying to finalize unknown hash");
117 }
118
119 const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
120         {
121                 NULL,
122                 0x00000000,
123                 0,
124                 0,
125                 0,
126                 git_hash_unknown_init,
127                 git_hash_unknown_update,
128                 git_hash_unknown_final,
129                 NULL,
130                 NULL,
131         },
132         {
133                 "sha1",
134                 /* "sha1", big-endian */
135                 0x73686131,
136                 GIT_SHA1_RAWSZ,
137                 GIT_SHA1_HEXSZ,
138                 GIT_SHA1_BLKSZ,
139                 git_hash_sha1_init,
140                 git_hash_sha1_update,
141                 git_hash_sha1_final,
142                 &empty_tree_oid,
143                 &empty_blob_oid,
144         },
145         {
146                 "sha256",
147                 /* "s256", big-endian */
148                 0x73323536,
149                 GIT_SHA256_RAWSZ,
150                 GIT_SHA256_HEXSZ,
151                 GIT_SHA256_BLKSZ,
152                 git_hash_sha256_init,
153                 git_hash_sha256_update,
154                 git_hash_sha256_final,
155                 &empty_tree_oid_sha256,
156                 &empty_blob_oid_sha256,
157         }
158 };
159
160 const char *empty_tree_oid_hex(void)
161 {
162         static char buf[GIT_MAX_HEXSZ + 1];
163         return oid_to_hex_r(buf, the_hash_algo->empty_tree);
164 }
165
166 const char *empty_blob_oid_hex(void)
167 {
168         static char buf[GIT_MAX_HEXSZ + 1];
169         return oid_to_hex_r(buf, the_hash_algo->empty_blob);
170 }
171
172 int hash_algo_by_name(const char *name)
173 {
174         int i;
175         if (!name)
176                 return GIT_HASH_UNKNOWN;
177         for (i = 1; i < GIT_HASH_NALGOS; i++)
178                 if (!strcmp(name, hash_algos[i].name))
179                         return i;
180         return GIT_HASH_UNKNOWN;
181 }
182
183 int hash_algo_by_id(uint32_t format_id)
184 {
185         int i;
186         for (i = 1; i < GIT_HASH_NALGOS; i++)
187                 if (format_id == hash_algos[i].format_id)
188                         return i;
189         return GIT_HASH_UNKNOWN;
190 }
191
192
193 /*
194  * This is meant to hold a *small* number of objects that you would
195  * want read_sha1_file() to be able to return, but yet you do not want
196  * to write them into the object store (e.g. a browse-only
197  * application).
198  */
199 static struct cached_object {
200         struct object_id oid;
201         enum object_type type;
202         void *buf;
203         unsigned long size;
204 } *cached_objects;
205 static int cached_object_nr, cached_object_alloc;
206
207 static struct cached_object empty_tree = {
208         { EMPTY_TREE_SHA1_BIN_LITERAL },
209         OBJ_TREE,
210         "",
211         0
212 };
213
214 static struct cached_object *find_cached_object(const struct object_id *oid)
215 {
216         int i;
217         struct cached_object *co = cached_objects;
218
219         for (i = 0; i < cached_object_nr; i++, co++) {
220                 if (oideq(&co->oid, oid))
221                         return co;
222         }
223         if (oideq(oid, the_hash_algo->empty_tree))
224                 return &empty_tree;
225         return NULL;
226 }
227
228
229 static int get_conv_flags(unsigned flags)
230 {
231         if (flags & HASH_RENORMALIZE)
232                 return CONV_EOL_RENORMALIZE;
233         else if (flags & HASH_WRITE_OBJECT)
234                 return global_conv_flags_eol | CONV_WRITE_OBJECT;
235         else
236                 return 0;
237 }
238
239
240 int mkdir_in_gitdir(const char *path)
241 {
242         if (mkdir(path, 0777)) {
243                 int saved_errno = errno;
244                 struct stat st;
245                 struct strbuf sb = STRBUF_INIT;
246
247                 if (errno != EEXIST)
248                         return -1;
249                 /*
250                  * Are we looking at a path in a symlinked worktree
251                  * whose original repository does not yet have it?
252                  * e.g. .git/rr-cache pointing at its original
253                  * repository in which the user hasn't performed any
254                  * conflict resolution yet?
255                  */
256                 if (lstat(path, &st) || !S_ISLNK(st.st_mode) ||
257                     strbuf_readlink(&sb, path, st.st_size) ||
258                     !is_absolute_path(sb.buf) ||
259                     mkdir(sb.buf, 0777)) {
260                         strbuf_release(&sb);
261                         errno = saved_errno;
262                         return -1;
263                 }
264                 strbuf_release(&sb);
265         }
266         return adjust_shared_perm(path);
267 }
268
269 enum scld_error safe_create_leading_directories(char *path)
270 {
271         char *next_component = path + offset_1st_component(path);
272         enum scld_error ret = SCLD_OK;
273
274         while (ret == SCLD_OK && next_component) {
275                 struct stat st;
276                 char *slash = next_component, slash_character;
277
278                 while (*slash && !is_dir_sep(*slash))
279                         slash++;
280
281                 if (!*slash)
282                         break;
283
284                 next_component = slash + 1;
285                 while (is_dir_sep(*next_component))
286                         next_component++;
287                 if (!*next_component)
288                         break;
289
290                 slash_character = *slash;
291                 *slash = '\0';
292                 if (!stat(path, &st)) {
293                         /* path exists */
294                         if (!S_ISDIR(st.st_mode)) {
295                                 errno = ENOTDIR;
296                                 ret = SCLD_EXISTS;
297                         }
298                 } else if (mkdir(path, 0777)) {
299                         if (errno == EEXIST &&
300                             !stat(path, &st) && S_ISDIR(st.st_mode))
301                                 ; /* somebody created it since we checked */
302                         else if (errno == ENOENT)
303                                 /*
304                                  * Either mkdir() failed because
305                                  * somebody just pruned the containing
306                                  * directory, or stat() failed because
307                                  * the file that was in our way was
308                                  * just removed.  Either way, inform
309                                  * the caller that it might be worth
310                                  * trying again:
311                                  */
312                                 ret = SCLD_VANISHED;
313                         else
314                                 ret = SCLD_FAILED;
315                 } else if (adjust_shared_perm(path)) {
316                         ret = SCLD_PERMS;
317                 }
318                 *slash = slash_character;
319         }
320         return ret;
321 }
322
323 enum scld_error safe_create_leading_directories_const(const char *path)
324 {
325         int save_errno;
326         /* path points to cache entries, so xstrdup before messing with it */
327         char *buf = xstrdup(path);
328         enum scld_error result = safe_create_leading_directories(buf);
329
330         save_errno = errno;
331         free(buf);
332         errno = save_errno;
333         return result;
334 }
335
336 int raceproof_create_file(const char *path, create_file_fn fn, void *cb)
337 {
338         /*
339          * The number of times we will try to remove empty directories
340          * in the way of path. This is only 1 because if another
341          * process is racily creating directories that conflict with
342          * us, we don't want to fight against them.
343          */
344         int remove_directories_remaining = 1;
345
346         /*
347          * The number of times that we will try to create the
348          * directories containing path. We are willing to attempt this
349          * more than once, because another process could be trying to
350          * clean up empty directories at the same time as we are
351          * trying to create them.
352          */
353         int create_directories_remaining = 3;
354
355         /* A scratch copy of path, filled lazily if we need it: */
356         struct strbuf path_copy = STRBUF_INIT;
357
358         int ret, save_errno;
359
360         /* Sanity check: */
361         assert(*path);
362
363 retry_fn:
364         ret = fn(path, cb);
365         save_errno = errno;
366         if (!ret)
367                 goto out;
368
369         if (errno == EISDIR && remove_directories_remaining-- > 0) {
370                 /*
371                  * A directory is in the way. Maybe it is empty; try
372                  * to remove it:
373                  */
374                 if (!path_copy.len)
375                         strbuf_addstr(&path_copy, path);
376
377                 if (!remove_dir_recursively(&path_copy, REMOVE_DIR_EMPTY_ONLY))
378                         goto retry_fn;
379         } else if (errno == ENOENT && create_directories_remaining-- > 0) {
380                 /*
381                  * Maybe the containing directory didn't exist, or
382                  * maybe it was just deleted by a process that is
383                  * racing with us to clean up empty directories. Try
384                  * to create it:
385                  */
386                 enum scld_error scld_result;
387
388                 if (!path_copy.len)
389                         strbuf_addstr(&path_copy, path);
390
391                 do {
392                         scld_result = safe_create_leading_directories(path_copy.buf);
393                         if (scld_result == SCLD_OK)
394                                 goto retry_fn;
395                 } while (scld_result == SCLD_VANISHED && create_directories_remaining-- > 0);
396         }
397
398 out:
399         strbuf_release(&path_copy);
400         errno = save_errno;
401         return ret;
402 }
403
404 static void fill_sha1_path(struct strbuf *buf, const unsigned char *sha1)
405 {
406         int i;
407         for (i = 0; i < the_hash_algo->rawsz; i++) {
408                 static char hex[] = "0123456789abcdef";
409                 unsigned int val = sha1[i];
410                 strbuf_addch(buf, hex[val >> 4]);
411                 strbuf_addch(buf, hex[val & 0xf]);
412                 if (!i)
413                         strbuf_addch(buf, '/');
414         }
415 }
416
417 void sha1_file_name(struct repository *r, struct strbuf *buf, const unsigned char *sha1)
418 {
419         strbuf_addstr(buf, r->objects->objectdir);
420         strbuf_addch(buf, '/');
421         fill_sha1_path(buf, sha1);
422 }
423
424 struct strbuf *alt_scratch_buf(struct alternate_object_database *alt)
425 {
426         strbuf_setlen(&alt->scratch, alt->base_len);
427         return &alt->scratch;
428 }
429
430 static const char *alt_sha1_path(struct alternate_object_database *alt,
431                                  const unsigned char *sha1)
432 {
433         struct strbuf *buf = alt_scratch_buf(alt);
434         fill_sha1_path(buf, sha1);
435         return buf->buf;
436 }
437
438 /*
439  * Return non-zero iff the path is usable as an alternate object database.
440  */
441 static int alt_odb_usable(struct raw_object_store *o,
442                           struct strbuf *path,
443                           const char *normalized_objdir)
444 {
445         struct alternate_object_database *alt;
446
447         /* Detect cases where alternate disappeared */
448         if (!is_directory(path->buf)) {
449                 error(_("object directory %s does not exist; "
450                         "check .git/objects/info/alternates"),
451                       path->buf);
452                 return 0;
453         }
454
455         /*
456          * Prevent the common mistake of listing the same
457          * thing twice, or object directory itself.
458          */
459         for (alt = o->alt_odb_list; alt; alt = alt->next) {
460                 if (!fspathcmp(path->buf, alt->path))
461                         return 0;
462         }
463         if (!fspathcmp(path->buf, normalized_objdir))
464                 return 0;
465
466         return 1;
467 }
468
469 /*
470  * Prepare alternate object database registry.
471  *
472  * The variable alt_odb_list points at the list of struct
473  * alternate_object_database.  The elements on this list come from
474  * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
475  * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
476  * whose contents is similar to that environment variable but can be
477  * LF separated.  Its base points at a statically allocated buffer that
478  * contains "/the/directory/corresponding/to/.git/objects/...", while
479  * its name points just after the slash at the end of ".git/objects/"
480  * in the example above, and has enough space to hold 40-byte hex
481  * SHA1, an extra slash for the first level indirection, and the
482  * terminating NUL.
483  */
484 static void read_info_alternates(struct repository *r,
485                                  const char *relative_base,
486                                  int depth);
487 static int link_alt_odb_entry(struct repository *r, const char *entry,
488         const char *relative_base, int depth, const char *normalized_objdir)
489 {
490         struct alternate_object_database *ent;
491         struct strbuf pathbuf = STRBUF_INIT;
492
493         if (!is_absolute_path(entry) && relative_base) {
494                 strbuf_realpath(&pathbuf, relative_base, 1);
495                 strbuf_addch(&pathbuf, '/');
496         }
497         strbuf_addstr(&pathbuf, entry);
498
499         if (strbuf_normalize_path(&pathbuf) < 0 && relative_base) {
500                 error(_("unable to normalize alternate object path: %s"),
501                       pathbuf.buf);
502                 strbuf_release(&pathbuf);
503                 return -1;
504         }
505
506         /*
507          * The trailing slash after the directory name is given by
508          * this function at the end. Remove duplicates.
509          */
510         while (pathbuf.len && pathbuf.buf[pathbuf.len - 1] == '/')
511                 strbuf_setlen(&pathbuf, pathbuf.len - 1);
512
513         if (!alt_odb_usable(r->objects, &pathbuf, normalized_objdir)) {
514                 strbuf_release(&pathbuf);
515                 return -1;
516         }
517
518         ent = alloc_alt_odb(pathbuf.buf);
519
520         /* add the alternate entry */
521         *r->objects->alt_odb_tail = ent;
522         r->objects->alt_odb_tail = &(ent->next);
523         ent->next = NULL;
524
525         /* recursively add alternates */
526         read_info_alternates(r, pathbuf.buf, depth + 1);
527
528         strbuf_release(&pathbuf);
529         return 0;
530 }
531
532 static const char *parse_alt_odb_entry(const char *string,
533                                        int sep,
534                                        struct strbuf *out)
535 {
536         const char *end;
537
538         strbuf_reset(out);
539
540         if (*string == '#') {
541                 /* comment; consume up to next separator */
542                 end = strchrnul(string, sep);
543         } else if (*string == '"' && !unquote_c_style(out, string, &end)) {
544                 /*
545                  * quoted path; unquote_c_style has copied the
546                  * data for us and set "end". Broken quoting (e.g.,
547                  * an entry that doesn't end with a quote) falls
548                  * back to the unquoted case below.
549                  */
550         } else {
551                 /* normal, unquoted path */
552                 end = strchrnul(string, sep);
553                 strbuf_add(out, string, end - string);
554         }
555
556         if (*end)
557                 end++;
558         return end;
559 }
560
561 static void link_alt_odb_entries(struct repository *r, const char *alt,
562                                  int sep, const char *relative_base, int depth)
563 {
564         struct strbuf objdirbuf = STRBUF_INIT;
565         struct strbuf entry = STRBUF_INIT;
566
567         if (!alt || !*alt)
568                 return;
569
570         if (depth > 5) {
571                 error(_("%s: ignoring alternate object stores, nesting too deep"),
572                                 relative_base);
573                 return;
574         }
575
576         strbuf_add_absolute_path(&objdirbuf, r->objects->objectdir);
577         if (strbuf_normalize_path(&objdirbuf) < 0)
578                 die(_("unable to normalize object directory: %s"),
579                     objdirbuf.buf);
580
581         while (*alt) {
582                 alt = parse_alt_odb_entry(alt, sep, &entry);
583                 if (!entry.len)
584                         continue;
585                 link_alt_odb_entry(r, entry.buf,
586                                    relative_base, depth, objdirbuf.buf);
587         }
588         strbuf_release(&entry);
589         strbuf_release(&objdirbuf);
590 }
591
592 static void read_info_alternates(struct repository *r,
593                                  const char *relative_base,
594                                  int depth)
595 {
596         char *path;
597         struct strbuf buf = STRBUF_INIT;
598
599         path = xstrfmt("%s/info/alternates", relative_base);
600         if (strbuf_read_file(&buf, path, 1024) < 0) {
601                 warn_on_fopen_errors(path);
602                 free(path);
603                 return;
604         }
605
606         link_alt_odb_entries(r, buf.buf, '\n', relative_base, depth);
607         strbuf_release(&buf);
608         free(path);
609 }
610
611 struct alternate_object_database *alloc_alt_odb(const char *dir)
612 {
613         struct alternate_object_database *ent;
614
615         FLEX_ALLOC_STR(ent, path, dir);
616         strbuf_init(&ent->scratch, 0);
617         strbuf_addf(&ent->scratch, "%s/", dir);
618         ent->base_len = ent->scratch.len;
619
620         return ent;
621 }
622
623 void add_to_alternates_file(const char *reference)
624 {
625         struct lock_file lock = LOCK_INIT;
626         char *alts = git_pathdup("objects/info/alternates");
627         FILE *in, *out;
628         int found = 0;
629
630         hold_lock_file_for_update(&lock, alts, LOCK_DIE_ON_ERROR);
631         out = fdopen_lock_file(&lock, "w");
632         if (!out)
633                 die_errno(_("unable to fdopen alternates lockfile"));
634
635         in = fopen(alts, "r");
636         if (in) {
637                 struct strbuf line = STRBUF_INIT;
638
639                 while (strbuf_getline(&line, in) != EOF) {
640                         if (!strcmp(reference, line.buf)) {
641                                 found = 1;
642                                 break;
643                         }
644                         fprintf_or_die(out, "%s\n", line.buf);
645                 }
646
647                 strbuf_release(&line);
648                 fclose(in);
649         }
650         else if (errno != ENOENT)
651                 die_errno(_("unable to read alternates file"));
652
653         if (found) {
654                 rollback_lock_file(&lock);
655         } else {
656                 fprintf_or_die(out, "%s\n", reference);
657                 if (commit_lock_file(&lock))
658                         die_errno(_("unable to move new alternates file into place"));
659                 if (the_repository->objects->alt_odb_tail)
660                         link_alt_odb_entries(the_repository, reference,
661                                              '\n', NULL, 0);
662         }
663         free(alts);
664 }
665
666 void add_to_alternates_memory(const char *reference)
667 {
668         /*
669          * Make sure alternates are initialized, or else our entry may be
670          * overwritten when they are.
671          */
672         prepare_alt_odb(the_repository);
673
674         link_alt_odb_entries(the_repository, reference,
675                              '\n', NULL, 0);
676 }
677
678 /*
679  * Compute the exact path an alternate is at and returns it. In case of
680  * error NULL is returned and the human readable error is added to `err`
681  * `path` may be relative and should point to $GIT_DIR.
682  * `err` must not be null.
683  */
684 char *compute_alternate_path(const char *path, struct strbuf *err)
685 {
686         char *ref_git = NULL;
687         const char *repo, *ref_git_s;
688         int seen_error = 0;
689
690         ref_git_s = real_path_if_valid(path);
691         if (!ref_git_s) {
692                 seen_error = 1;
693                 strbuf_addf(err, _("path '%s' does not exist"), path);
694                 goto out;
695         } else
696                 /*
697                  * Beware: read_gitfile(), real_path() and mkpath()
698                  * return static buffer
699                  */
700                 ref_git = xstrdup(ref_git_s);
701
702         repo = read_gitfile(ref_git);
703         if (!repo)
704                 repo = read_gitfile(mkpath("%s/.git", ref_git));
705         if (repo) {
706                 free(ref_git);
707                 ref_git = xstrdup(repo);
708         }
709
710         if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
711                 char *ref_git_git = mkpathdup("%s/.git", ref_git);
712                 free(ref_git);
713                 ref_git = ref_git_git;
714         } else if (!is_directory(mkpath("%s/objects", ref_git))) {
715                 struct strbuf sb = STRBUF_INIT;
716                 seen_error = 1;
717                 if (get_common_dir(&sb, ref_git)) {
718                         strbuf_addf(err,
719                                     _("reference repository '%s' as a linked "
720                                       "checkout is not supported yet."),
721                                     path);
722                         goto out;
723                 }
724
725                 strbuf_addf(err, _("reference repository '%s' is not a "
726                                         "local repository."), path);
727                 goto out;
728         }
729
730         if (!access(mkpath("%s/shallow", ref_git), F_OK)) {
731                 strbuf_addf(err, _("reference repository '%s' is shallow"),
732                             path);
733                 seen_error = 1;
734                 goto out;
735         }
736
737         if (!access(mkpath("%s/info/grafts", ref_git), F_OK)) {
738                 strbuf_addf(err,
739                             _("reference repository '%s' is grafted"),
740                             path);
741                 seen_error = 1;
742                 goto out;
743         }
744
745 out:
746         if (seen_error) {
747                 FREE_AND_NULL(ref_git);
748         }
749
750         return ref_git;
751 }
752
753 int foreach_alt_odb(alt_odb_fn fn, void *cb)
754 {
755         struct alternate_object_database *ent;
756         int r = 0;
757
758         prepare_alt_odb(the_repository);
759         for (ent = the_repository->objects->alt_odb_list; ent; ent = ent->next) {
760                 r = fn(ent, cb);
761                 if (r)
762                         break;
763         }
764         return r;
765 }
766
767 void prepare_alt_odb(struct repository *r)
768 {
769         if (r->objects->alt_odb_tail)
770                 return;
771
772         r->objects->alt_odb_tail = &r->objects->alt_odb_list;
773         link_alt_odb_entries(r, r->objects->alternate_db, PATH_SEP, NULL, 0);
774
775         read_info_alternates(r, r->objects->objectdir, 0);
776 }
777
778 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
779 static int freshen_file(const char *fn)
780 {
781         struct utimbuf t;
782         t.actime = t.modtime = time(NULL);
783         return !utime(fn, &t);
784 }
785
786 /*
787  * All of the check_and_freshen functions return 1 if the file exists and was
788  * freshened (if freshening was requested), 0 otherwise. If they return
789  * 0, you should not assume that it is safe to skip a write of the object (it
790  * either does not exist on disk, or has a stale mtime and may be subject to
791  * pruning).
792  */
793 int check_and_freshen_file(const char *fn, int freshen)
794 {
795         if (access(fn, F_OK))
796                 return 0;
797         if (freshen && !freshen_file(fn))
798                 return 0;
799         return 1;
800 }
801
802 static int check_and_freshen_local(const struct object_id *oid, int freshen)
803 {
804         static struct strbuf buf = STRBUF_INIT;
805
806         strbuf_reset(&buf);
807         sha1_file_name(the_repository, &buf, oid->hash);
808
809         return check_and_freshen_file(buf.buf, freshen);
810 }
811
812 static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
813 {
814         struct alternate_object_database *alt;
815         prepare_alt_odb(the_repository);
816         for (alt = the_repository->objects->alt_odb_list; alt; alt = alt->next) {
817                 const char *path = alt_sha1_path(alt, oid->hash);
818                 if (check_and_freshen_file(path, freshen))
819                         return 1;
820         }
821         return 0;
822 }
823
824 static int check_and_freshen(const struct object_id *oid, int freshen)
825 {
826         return check_and_freshen_local(oid, freshen) ||
827                check_and_freshen_nonlocal(oid, freshen);
828 }
829
830 int has_loose_object_nonlocal(const struct object_id *oid)
831 {
832         return check_and_freshen_nonlocal(oid, 0);
833 }
834
835 static int has_loose_object(const struct object_id *oid)
836 {
837         return check_and_freshen(oid, 0);
838 }
839
840 static void mmap_limit_check(size_t length)
841 {
842         static size_t limit = 0;
843         if (!limit) {
844                 limit = git_env_ulong("GIT_MMAP_LIMIT", 0);
845                 if (!limit)
846                         limit = SIZE_MAX;
847         }
848         if (length > limit)
849                 die(_("attempting to mmap %"PRIuMAX" over limit %"PRIuMAX),
850                     (uintmax_t)length, (uintmax_t)limit);
851 }
852
853 void *xmmap_gently(void *start, size_t length,
854                   int prot, int flags, int fd, off_t offset)
855 {
856         void *ret;
857
858         mmap_limit_check(length);
859         ret = mmap(start, length, prot, flags, fd, offset);
860         if (ret == MAP_FAILED) {
861                 if (!length)
862                         return NULL;
863                 release_pack_memory(length);
864                 ret = mmap(start, length, prot, flags, fd, offset);
865         }
866         return ret;
867 }
868
869 void *xmmap(void *start, size_t length,
870         int prot, int flags, int fd, off_t offset)
871 {
872         void *ret = xmmap_gently(start, length, prot, flags, fd, offset);
873         if (ret == MAP_FAILED)
874                 die_errno(_("mmap failed"));
875         return ret;
876 }
877
878 /*
879  * With an in-core object data in "map", rehash it to make sure the
880  * object name actually matches "sha1" to detect object corruption.
881  * With "map" == NULL, try reading the object named with "sha1" using
882  * the streaming interface and rehash it to do the same.
883  */
884 int check_object_signature(const struct object_id *oid, void *map,
885                            unsigned long size, const char *type)
886 {
887         struct object_id real_oid;
888         enum object_type obj_type;
889         struct git_istream *st;
890         git_hash_ctx c;
891         char hdr[MAX_HEADER_LEN];
892         int hdrlen;
893
894         if (map) {
895                 hash_object_file(map, size, type, &real_oid);
896                 return !oideq(oid, &real_oid) ? -1 : 0;
897         }
898
899         st = open_istream(oid, &obj_type, &size, NULL);
900         if (!st)
901                 return -1;
902
903         /* Generate the header */
904         hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", type_name(obj_type), size) + 1;
905
906         /* Sha1.. */
907         the_hash_algo->init_fn(&c);
908         the_hash_algo->update_fn(&c, hdr, hdrlen);
909         for (;;) {
910                 char buf[1024 * 16];
911                 ssize_t readlen = read_istream(st, buf, sizeof(buf));
912
913                 if (readlen < 0) {
914                         close_istream(st);
915                         return -1;
916                 }
917                 if (!readlen)
918                         break;
919                 the_hash_algo->update_fn(&c, buf, readlen);
920         }
921         the_hash_algo->final_fn(real_oid.hash, &c);
922         close_istream(st);
923         return !oideq(oid, &real_oid) ? -1 : 0;
924 }
925
926 int git_open_cloexec(const char *name, int flags)
927 {
928         int fd;
929         static int o_cloexec = O_CLOEXEC;
930
931         fd = open(name, flags | o_cloexec);
932         if ((o_cloexec & O_CLOEXEC) && fd < 0 && errno == EINVAL) {
933                 /* Try again w/o O_CLOEXEC: the kernel might not support it */
934                 o_cloexec &= ~O_CLOEXEC;
935                 fd = open(name, flags | o_cloexec);
936         }
937
938 #if defined(F_GETFD) && defined(F_SETFD) && defined(FD_CLOEXEC)
939         {
940                 static int fd_cloexec = FD_CLOEXEC;
941
942                 if (!o_cloexec && 0 <= fd && fd_cloexec) {
943                         /* Opened w/o O_CLOEXEC?  try with fcntl(2) to add it */
944                         int flags = fcntl(fd, F_GETFD);
945                         if (fcntl(fd, F_SETFD, flags | fd_cloexec))
946                                 fd_cloexec = 0;
947                 }
948         }
949 #endif
950         return fd;
951 }
952
953 /*
954  * Find "sha1" as a loose object in the local repository or in an alternate.
955  * Returns 0 on success, negative on failure.
956  *
957  * The "path" out-parameter will give the path of the object we found (if any).
958  * Note that it may point to static storage and is only valid until another
959  * call to sha1_file_name(), etc.
960  */
961 static int stat_sha1_file(struct repository *r, const unsigned char *sha1,
962                           struct stat *st, const char **path)
963 {
964         struct alternate_object_database *alt;
965         static struct strbuf buf = STRBUF_INIT;
966
967         strbuf_reset(&buf);
968         sha1_file_name(r, &buf, sha1);
969         *path = buf.buf;
970
971         if (!lstat(*path, st))
972                 return 0;
973
974         prepare_alt_odb(r);
975         errno = ENOENT;
976         for (alt = r->objects->alt_odb_list; alt; alt = alt->next) {
977                 *path = alt_sha1_path(alt, sha1);
978                 if (!lstat(*path, st))
979                         return 0;
980         }
981
982         return -1;
983 }
984
985 /*
986  * Like stat_sha1_file(), but actually open the object and return the
987  * descriptor. See the caveats on the "path" parameter above.
988  */
989 static int open_sha1_file(struct repository *r,
990                           const unsigned char *sha1, const char **path)
991 {
992         int fd;
993         struct alternate_object_database *alt;
994         int most_interesting_errno;
995         static struct strbuf buf = STRBUF_INIT;
996
997         strbuf_reset(&buf);
998         sha1_file_name(r, &buf, sha1);
999         *path = buf.buf;
1000
1001         fd = git_open(*path);
1002         if (fd >= 0)
1003                 return fd;
1004         most_interesting_errno = errno;
1005
1006         prepare_alt_odb(r);
1007         for (alt = r->objects->alt_odb_list; alt; alt = alt->next) {
1008                 *path = alt_sha1_path(alt, sha1);
1009                 fd = git_open(*path);
1010                 if (fd >= 0)
1011                         return fd;
1012                 if (most_interesting_errno == ENOENT)
1013                         most_interesting_errno = errno;
1014         }
1015         errno = most_interesting_errno;
1016         return -1;
1017 }
1018
1019 /*
1020  * Map the loose object at "path" if it is not NULL, or the path found by
1021  * searching for a loose object named "sha1".
1022  */
1023 static void *map_sha1_file_1(struct repository *r, const char *path,
1024                              const unsigned char *sha1, unsigned long *size)
1025 {
1026         void *map;
1027         int fd;
1028
1029         if (path)
1030                 fd = git_open(path);
1031         else
1032                 fd = open_sha1_file(r, sha1, &path);
1033         map = NULL;
1034         if (fd >= 0) {
1035                 struct stat st;
1036
1037                 if (!fstat(fd, &st)) {
1038                         *size = xsize_t(st.st_size);
1039                         if (!*size) {
1040                                 /* mmap() is forbidden on empty files */
1041                                 error(_("object file %s is empty"), path);
1042                                 return NULL;
1043                         }
1044                         map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
1045                 }
1046                 close(fd);
1047         }
1048         return map;
1049 }
1050
1051 void *map_sha1_file(struct repository *r,
1052                     const unsigned char *sha1, unsigned long *size)
1053 {
1054         return map_sha1_file_1(r, NULL, sha1, size);
1055 }
1056
1057 static int unpack_sha1_short_header(git_zstream *stream,
1058                                     unsigned char *map, unsigned long mapsize,
1059                                     void *buffer, unsigned long bufsiz)
1060 {
1061         /* Get the data stream */
1062         memset(stream, 0, sizeof(*stream));
1063         stream->next_in = map;
1064         stream->avail_in = mapsize;
1065         stream->next_out = buffer;
1066         stream->avail_out = bufsiz;
1067
1068         git_inflate_init(stream);
1069         return git_inflate(stream, 0);
1070 }
1071
1072 int unpack_sha1_header(git_zstream *stream,
1073                        unsigned char *map, unsigned long mapsize,
1074                        void *buffer, unsigned long bufsiz)
1075 {
1076         int status = unpack_sha1_short_header(stream, map, mapsize,
1077                                               buffer, bufsiz);
1078
1079         if (status < Z_OK)
1080                 return status;
1081
1082         /* Make sure we have the terminating NUL */
1083         if (!memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1084                 return -1;
1085         return 0;
1086 }
1087
1088 static int unpack_sha1_header_to_strbuf(git_zstream *stream, unsigned char *map,
1089                                         unsigned long mapsize, void *buffer,
1090                                         unsigned long bufsiz, struct strbuf *header)
1091 {
1092         int status;
1093
1094         status = unpack_sha1_short_header(stream, map, mapsize, buffer, bufsiz);
1095         if (status < Z_OK)
1096                 return -1;
1097
1098         /*
1099          * Check if entire header is unpacked in the first iteration.
1100          */
1101         if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1102                 return 0;
1103
1104         /*
1105          * buffer[0..bufsiz] was not large enough.  Copy the partial
1106          * result out to header, and then append the result of further
1107          * reading the stream.
1108          */
1109         strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1110         stream->next_out = buffer;
1111         stream->avail_out = bufsiz;
1112
1113         do {
1114                 status = git_inflate(stream, 0);
1115                 strbuf_add(header, buffer, stream->next_out - (unsigned char *)buffer);
1116                 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
1117                         return 0;
1118                 stream->next_out = buffer;
1119                 stream->avail_out = bufsiz;
1120         } while (status != Z_STREAM_END);
1121         return -1;
1122 }
1123
1124 static void *unpack_sha1_rest(git_zstream *stream, void *buffer, unsigned long size, const unsigned char *sha1)
1125 {
1126         int bytes = strlen(buffer) + 1;
1127         unsigned char *buf = xmallocz(size);
1128         unsigned long n;
1129         int status = Z_OK;
1130
1131         n = stream->total_out - bytes;
1132         if (n > size)
1133                 n = size;
1134         memcpy(buf, (char *) buffer + bytes, n);
1135         bytes = n;
1136         if (bytes <= size) {
1137                 /*
1138                  * The above condition must be (bytes <= size), not
1139                  * (bytes < size).  In other words, even though we
1140                  * expect no more output and set avail_out to zero,
1141                  * the input zlib stream may have bytes that express
1142                  * "this concludes the stream", and we *do* want to
1143                  * eat that input.
1144                  *
1145                  * Otherwise we would not be able to test that we
1146                  * consumed all the input to reach the expected size;
1147                  * we also want to check that zlib tells us that all
1148                  * went well with status == Z_STREAM_END at the end.
1149                  */
1150                 stream->next_out = buf + bytes;
1151                 stream->avail_out = size - bytes;
1152                 while (status == Z_OK)
1153                         status = git_inflate(stream, Z_FINISH);
1154         }
1155         if (status == Z_STREAM_END && !stream->avail_in) {
1156                 git_inflate_end(stream);
1157                 return buf;
1158         }
1159
1160         if (status < 0)
1161                 error(_("corrupt loose object '%s'"), sha1_to_hex(sha1));
1162         else if (stream->avail_in)
1163                 error(_("garbage at end of loose object '%s'"),
1164                       sha1_to_hex(sha1));
1165         free(buf);
1166         return NULL;
1167 }
1168
1169 /*
1170  * We used to just use "sscanf()", but that's actually way
1171  * too permissive for what we want to check. So do an anal
1172  * object header parse by hand.
1173  */
1174 static int parse_sha1_header_extended(const char *hdr, struct object_info *oi,
1175                                unsigned int flags)
1176 {
1177         const char *type_buf = hdr;
1178         unsigned long size;
1179         int type, type_len = 0;
1180
1181         /*
1182          * The type can be of any size but is followed by
1183          * a space.
1184          */
1185         for (;;) {
1186                 char c = *hdr++;
1187                 if (!c)
1188                         return -1;
1189                 if (c == ' ')
1190                         break;
1191                 type_len++;
1192         }
1193
1194         type = type_from_string_gently(type_buf, type_len, 1);
1195         if (oi->type_name)
1196                 strbuf_add(oi->type_name, type_buf, type_len);
1197         /*
1198          * Set type to 0 if its an unknown object and
1199          * we're obtaining the type using '--allow-unknown-type'
1200          * option.
1201          */
1202         if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE) && (type < 0))
1203                 type = 0;
1204         else if (type < 0)
1205                 die(_("invalid object type"));
1206         if (oi->typep)
1207                 *oi->typep = type;
1208
1209         /*
1210          * The length must follow immediately, and be in canonical
1211          * decimal format (ie "010" is not valid).
1212          */
1213         size = *hdr++ - '0';
1214         if (size > 9)
1215                 return -1;
1216         if (size) {
1217                 for (;;) {
1218                         unsigned long c = *hdr - '0';
1219                         if (c > 9)
1220                                 break;
1221                         hdr++;
1222                         size = size * 10 + c;
1223                 }
1224         }
1225
1226         if (oi->sizep)
1227                 *oi->sizep = size;
1228
1229         /*
1230          * The length must be followed by a zero byte
1231          */
1232         return *hdr ? -1 : type;
1233 }
1234
1235 int parse_sha1_header(const char *hdr, unsigned long *sizep)
1236 {
1237         struct object_info oi = OBJECT_INFO_INIT;
1238
1239         oi.sizep = sizep;
1240         return parse_sha1_header_extended(hdr, &oi, 0);
1241 }
1242
1243 static int sha1_loose_object_info(struct repository *r,
1244                                   const unsigned char *sha1,
1245                                   struct object_info *oi, int flags)
1246 {
1247         int status = 0;
1248         unsigned long mapsize;
1249         void *map;
1250         git_zstream stream;
1251         char hdr[MAX_HEADER_LEN];
1252         struct strbuf hdrbuf = STRBUF_INIT;
1253         unsigned long size_scratch;
1254
1255         if (oi->delta_base_sha1)
1256                 hashclr(oi->delta_base_sha1);
1257
1258         /*
1259          * If we don't care about type or size, then we don't
1260          * need to look inside the object at all. Note that we
1261          * do not optimize out the stat call, even if the
1262          * caller doesn't care about the disk-size, since our
1263          * return value implicitly indicates whether the
1264          * object even exists.
1265          */
1266         if (!oi->typep && !oi->type_name && !oi->sizep && !oi->contentp) {
1267                 const char *path;
1268                 struct stat st;
1269                 if (stat_sha1_file(r, sha1, &st, &path) < 0)
1270                         return -1;
1271                 if (oi->disk_sizep)
1272                         *oi->disk_sizep = st.st_size;
1273                 return 0;
1274         }
1275
1276         map = map_sha1_file(r, sha1, &mapsize);
1277         if (!map)
1278                 return -1;
1279
1280         if (!oi->sizep)
1281                 oi->sizep = &size_scratch;
1282
1283         if (oi->disk_sizep)
1284                 *oi->disk_sizep = mapsize;
1285         if ((flags & OBJECT_INFO_ALLOW_UNKNOWN_TYPE)) {
1286                 if (unpack_sha1_header_to_strbuf(&stream, map, mapsize, hdr, sizeof(hdr), &hdrbuf) < 0)
1287                         status = error(_("unable to unpack %s header with --allow-unknown-type"),
1288                                        sha1_to_hex(sha1));
1289         } else if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1290                 status = error(_("unable to unpack %s header"),
1291                                sha1_to_hex(sha1));
1292         if (status < 0)
1293                 ; /* Do nothing */
1294         else if (hdrbuf.len) {
1295                 if ((status = parse_sha1_header_extended(hdrbuf.buf, oi, flags)) < 0)
1296                         status = error(_("unable to parse %s header with --allow-unknown-type"),
1297                                        sha1_to_hex(sha1));
1298         } else if ((status = parse_sha1_header_extended(hdr, oi, flags)) < 0)
1299                 status = error(_("unable to parse %s header"), sha1_to_hex(sha1));
1300
1301         if (status >= 0 && oi->contentp) {
1302                 *oi->contentp = unpack_sha1_rest(&stream, hdr,
1303                                                  *oi->sizep, sha1);
1304                 if (!*oi->contentp) {
1305                         git_inflate_end(&stream);
1306                         status = -1;
1307                 }
1308         } else
1309                 git_inflate_end(&stream);
1310
1311         munmap(map, mapsize);
1312         if (status && oi->typep)
1313                 *oi->typep = status;
1314         if (oi->sizep == &size_scratch)
1315                 oi->sizep = NULL;
1316         strbuf_release(&hdrbuf);
1317         oi->whence = OI_LOOSE;
1318         return (status < 0) ? status : 0;
1319 }
1320
1321 int fetch_if_missing = 1;
1322
1323 int oid_object_info_extended(struct repository *r, const struct object_id *oid,
1324                              struct object_info *oi, unsigned flags)
1325 {
1326         static struct object_info blank_oi = OBJECT_INFO_INIT;
1327         struct pack_entry e;
1328         int rtype;
1329         const struct object_id *real = oid;
1330         int already_retried = 0;
1331
1332         if (flags & OBJECT_INFO_LOOKUP_REPLACE)
1333                 real = lookup_replace_object(r, oid);
1334
1335         if (is_null_oid(real))
1336                 return -1;
1337
1338         if (!oi)
1339                 oi = &blank_oi;
1340
1341         if (!(flags & OBJECT_INFO_SKIP_CACHED)) {
1342                 struct cached_object *co = find_cached_object(real);
1343                 if (co) {
1344                         if (oi->typep)
1345                                 *(oi->typep) = co->type;
1346                         if (oi->sizep)
1347                                 *(oi->sizep) = co->size;
1348                         if (oi->disk_sizep)
1349                                 *(oi->disk_sizep) = 0;
1350                         if (oi->delta_base_sha1)
1351                                 hashclr(oi->delta_base_sha1);
1352                         if (oi->type_name)
1353                                 strbuf_addstr(oi->type_name, type_name(co->type));
1354                         if (oi->contentp)
1355                                 *oi->contentp = xmemdupz(co->buf, co->size);
1356                         oi->whence = OI_CACHED;
1357                         return 0;
1358                 }
1359         }
1360
1361         while (1) {
1362                 if (find_pack_entry(r, real, &e))
1363                         break;
1364
1365                 if (flags & OBJECT_INFO_IGNORE_LOOSE)
1366                         return -1;
1367
1368                 /* Most likely it's a loose object. */
1369                 if (!sha1_loose_object_info(r, real->hash, oi, flags))
1370                         return 0;
1371
1372                 /* Not a loose object; someone else may have just packed it. */
1373                 if (!(flags & OBJECT_INFO_QUICK)) {
1374                         reprepare_packed_git(r);
1375                         if (find_pack_entry(r, real, &e))
1376                                 break;
1377                 }
1378
1379                 /* Check if it is a missing object */
1380                 if (fetch_if_missing && repository_format_partial_clone &&
1381                     !already_retried && r == the_repository) {
1382                         /*
1383                          * TODO Investigate having fetch_object() return
1384                          * TODO error/success and stopping the music here.
1385                          * TODO Pass a repository struct through fetch_object,
1386                          * such that arbitrary repositories work.
1387                          */
1388                         fetch_objects(repository_format_partial_clone, real, 1);
1389                         already_retried = 1;
1390                         continue;
1391                 }
1392
1393                 return -1;
1394         }
1395
1396         if (oi == &blank_oi)
1397                 /*
1398                  * We know that the caller doesn't actually need the
1399                  * information below, so return early.
1400                  */
1401                 return 0;
1402         rtype = packed_object_info(r, e.p, e.offset, oi);
1403         if (rtype < 0) {
1404                 mark_bad_packed_object(e.p, real->hash);
1405                 return oid_object_info_extended(r, real, oi, 0);
1406         } else if (oi->whence == OI_PACKED) {
1407                 oi->u.packed.offset = e.offset;
1408                 oi->u.packed.pack = e.p;
1409                 oi->u.packed.is_delta = (rtype == OBJ_REF_DELTA ||
1410                                          rtype == OBJ_OFS_DELTA);
1411         }
1412
1413         return 0;
1414 }
1415
1416 /* returns enum object_type or negative */
1417 int oid_object_info(struct repository *r,
1418                     const struct object_id *oid,
1419                     unsigned long *sizep)
1420 {
1421         enum object_type type;
1422         struct object_info oi = OBJECT_INFO_INIT;
1423
1424         oi.typep = &type;
1425         oi.sizep = sizep;
1426         if (oid_object_info_extended(r, oid, &oi,
1427                                       OBJECT_INFO_LOOKUP_REPLACE) < 0)
1428                 return -1;
1429         return type;
1430 }
1431
1432 static void *read_object(const unsigned char *sha1, enum object_type *type,
1433                          unsigned long *size)
1434 {
1435         struct object_id oid;
1436         struct object_info oi = OBJECT_INFO_INIT;
1437         void *content;
1438         oi.typep = type;
1439         oi.sizep = size;
1440         oi.contentp = &content;
1441
1442         hashcpy(oid.hash, sha1);
1443
1444         if (oid_object_info_extended(the_repository, &oid, &oi, 0) < 0)
1445                 return NULL;
1446         return content;
1447 }
1448
1449 int pretend_object_file(void *buf, unsigned long len, enum object_type type,
1450                         struct object_id *oid)
1451 {
1452         struct cached_object *co;
1453
1454         hash_object_file(buf, len, type_name(type), oid);
1455         if (has_sha1_file(oid->hash) || find_cached_object(oid))
1456                 return 0;
1457         ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
1458         co = &cached_objects[cached_object_nr++];
1459         co->size = len;
1460         co->type = type;
1461         co->buf = xmalloc(len);
1462         memcpy(co->buf, buf, len);
1463         oidcpy(&co->oid, oid);
1464         return 0;
1465 }
1466
1467 /*
1468  * This function dies on corrupt objects; the callers who want to
1469  * deal with them should arrange to call read_object() and give error
1470  * messages themselves.
1471  */
1472 void *read_object_file_extended(const struct object_id *oid,
1473                                 enum object_type *type,
1474                                 unsigned long *size,
1475                                 int lookup_replace)
1476 {
1477         void *data;
1478         const struct packed_git *p;
1479         const char *path;
1480         struct stat st;
1481         const struct object_id *repl = lookup_replace ?
1482                 lookup_replace_object(the_repository, oid) : oid;
1483
1484         errno = 0;
1485         data = read_object(repl->hash, type, size);
1486         if (data)
1487                 return data;
1488
1489         if (errno && errno != ENOENT)
1490                 die_errno(_("failed to read object %s"), oid_to_hex(oid));
1491
1492         /* die if we replaced an object with one that does not exist */
1493         if (repl != oid)
1494                 die(_("replacement %s not found for %s"),
1495                     oid_to_hex(repl), oid_to_hex(oid));
1496
1497         if (!stat_sha1_file(the_repository, repl->hash, &st, &path))
1498                 die(_("loose object %s (stored in %s) is corrupt"),
1499                     oid_to_hex(repl), path);
1500
1501         if ((p = has_packed_and_bad(repl->hash)) != NULL)
1502                 die(_("packed object %s (stored in %s) is corrupt"),
1503                     oid_to_hex(repl), p->pack_name);
1504
1505         return NULL;
1506 }
1507
1508 void *read_object_with_reference(const struct object_id *oid,
1509                                  const char *required_type_name,
1510                                  unsigned long *size,
1511                                  struct object_id *actual_oid_return)
1512 {
1513         enum object_type type, required_type;
1514         void *buffer;
1515         unsigned long isize;
1516         struct object_id actual_oid;
1517
1518         required_type = type_from_string(required_type_name);
1519         oidcpy(&actual_oid, oid);
1520         while (1) {
1521                 int ref_length = -1;
1522                 const char *ref_type = NULL;
1523
1524                 buffer = read_object_file(&actual_oid, &type, &isize);
1525                 if (!buffer)
1526                         return NULL;
1527                 if (type == required_type) {
1528                         *size = isize;
1529                         if (actual_oid_return)
1530                                 oidcpy(actual_oid_return, &actual_oid);
1531                         return buffer;
1532                 }
1533                 /* Handle references */
1534                 else if (type == OBJ_COMMIT)
1535                         ref_type = "tree ";
1536                 else if (type == OBJ_TAG)
1537                         ref_type = "object ";
1538                 else {
1539                         free(buffer);
1540                         return NULL;
1541                 }
1542                 ref_length = strlen(ref_type);
1543
1544                 if (ref_length + the_hash_algo->hexsz > isize ||
1545                     memcmp(buffer, ref_type, ref_length) ||
1546                     get_oid_hex((char *) buffer + ref_length, &actual_oid)) {
1547                         free(buffer);
1548                         return NULL;
1549                 }
1550                 free(buffer);
1551                 /* Now we have the ID of the referred-to object in
1552                  * actual_oid.  Check again. */
1553         }
1554 }
1555
1556 static void write_object_file_prepare(const void *buf, unsigned long len,
1557                                       const char *type, struct object_id *oid,
1558                                       char *hdr, int *hdrlen)
1559 {
1560         git_hash_ctx c;
1561
1562         /* Generate the header */
1563         *hdrlen = xsnprintf(hdr, *hdrlen, "%s %lu", type, len)+1;
1564
1565         /* Sha1.. */
1566         the_hash_algo->init_fn(&c);
1567         the_hash_algo->update_fn(&c, hdr, *hdrlen);
1568         the_hash_algo->update_fn(&c, buf, len);
1569         the_hash_algo->final_fn(oid->hash, &c);
1570 }
1571
1572 /*
1573  * Move the just written object into its final resting place.
1574  */
1575 int finalize_object_file(const char *tmpfile, const char *filename)
1576 {
1577         int ret = 0;
1578
1579         if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
1580                 goto try_rename;
1581         else if (link(tmpfile, filename))
1582                 ret = errno;
1583
1584         /*
1585          * Coda hack - coda doesn't like cross-directory links,
1586          * so we fall back to a rename, which will mean that it
1587          * won't be able to check collisions, but that's not a
1588          * big deal.
1589          *
1590          * The same holds for FAT formatted media.
1591          *
1592          * When this succeeds, we just return.  We have nothing
1593          * left to unlink.
1594          */
1595         if (ret && ret != EEXIST) {
1596         try_rename:
1597                 if (!rename(tmpfile, filename))
1598                         goto out;
1599                 ret = errno;
1600         }
1601         unlink_or_warn(tmpfile);
1602         if (ret) {
1603                 if (ret != EEXIST) {
1604                         return error_errno(_("unable to write sha1 filename %s"), filename);
1605                 }
1606                 /* FIXME!!! Collision check here ? */
1607         }
1608
1609 out:
1610         if (adjust_shared_perm(filename))
1611                 return error(_("unable to set permission to '%s'"), filename);
1612         return 0;
1613 }
1614
1615 static int write_buffer(int fd, const void *buf, size_t len)
1616 {
1617         if (write_in_full(fd, buf, len) < 0)
1618                 return error_errno(_("file write error"));
1619         return 0;
1620 }
1621
1622 int hash_object_file(const void *buf, unsigned long len, const char *type,
1623                      struct object_id *oid)
1624 {
1625         char hdr[MAX_HEADER_LEN];
1626         int hdrlen = sizeof(hdr);
1627         write_object_file_prepare(buf, len, type, oid, hdr, &hdrlen);
1628         return 0;
1629 }
1630
1631 /* Finalize a file on disk, and close it. */
1632 static void close_sha1_file(int fd)
1633 {
1634         if (fsync_object_files)
1635                 fsync_or_die(fd, "sha1 file");
1636         if (close(fd) != 0)
1637                 die_errno(_("error when closing sha1 file"));
1638 }
1639
1640 /* Size of directory component, including the ending '/' */
1641 static inline int directory_size(const char *filename)
1642 {
1643         const char *s = strrchr(filename, '/');
1644         if (!s)
1645                 return 0;
1646         return s - filename + 1;
1647 }
1648
1649 /*
1650  * This creates a temporary file in the same directory as the final
1651  * 'filename'
1652  *
1653  * We want to avoid cross-directory filename renames, because those
1654  * can have problems on various filesystems (FAT, NFS, Coda).
1655  */
1656 static int create_tmpfile(struct strbuf *tmp, const char *filename)
1657 {
1658         int fd, dirlen = directory_size(filename);
1659
1660         strbuf_reset(tmp);
1661         strbuf_add(tmp, filename, dirlen);
1662         strbuf_addstr(tmp, "tmp_obj_XXXXXX");
1663         fd = git_mkstemp_mode(tmp->buf, 0444);
1664         if (fd < 0 && dirlen && errno == ENOENT) {
1665                 /*
1666                  * Make sure the directory exists; note that the contents
1667                  * of the buffer are undefined after mkstemp returns an
1668                  * error, so we have to rewrite the whole buffer from
1669                  * scratch.
1670                  */
1671                 strbuf_reset(tmp);
1672                 strbuf_add(tmp, filename, dirlen - 1);
1673                 if (mkdir(tmp->buf, 0777) && errno != EEXIST)
1674                         return -1;
1675                 if (adjust_shared_perm(tmp->buf))
1676                         return -1;
1677
1678                 /* Try again */
1679                 strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
1680                 fd = git_mkstemp_mode(tmp->buf, 0444);
1681         }
1682         return fd;
1683 }
1684
1685 static int write_loose_object(const struct object_id *oid, char *hdr,
1686                               int hdrlen, const void *buf, unsigned long len,
1687                               time_t mtime)
1688 {
1689         int fd, ret;
1690         unsigned char compressed[4096];
1691         git_zstream stream;
1692         git_hash_ctx c;
1693         struct object_id parano_oid;
1694         static struct strbuf tmp_file = STRBUF_INIT;
1695         static struct strbuf filename = STRBUF_INIT;
1696
1697         strbuf_reset(&filename);
1698         sha1_file_name(the_repository, &filename, oid->hash);
1699
1700         fd = create_tmpfile(&tmp_file, filename.buf);
1701         if (fd < 0) {
1702                 if (errno == EACCES)
1703                         return error(_("insufficient permission for adding an object to repository database %s"), get_object_directory());
1704                 else
1705                         return error_errno(_("unable to create temporary file"));
1706         }
1707
1708         /* Set it up */
1709         git_deflate_init(&stream, zlib_compression_level);
1710         stream.next_out = compressed;
1711         stream.avail_out = sizeof(compressed);
1712         the_hash_algo->init_fn(&c);
1713
1714         /* First header.. */
1715         stream.next_in = (unsigned char *)hdr;
1716         stream.avail_in = hdrlen;
1717         while (git_deflate(&stream, 0) == Z_OK)
1718                 ; /* nothing */
1719         the_hash_algo->update_fn(&c, hdr, hdrlen);
1720
1721         /* Then the data itself.. */
1722         stream.next_in = (void *)buf;
1723         stream.avail_in = len;
1724         do {
1725                 unsigned char *in0 = stream.next_in;
1726                 ret = git_deflate(&stream, Z_FINISH);
1727                 the_hash_algo->update_fn(&c, in0, stream.next_in - in0);
1728                 if (write_buffer(fd, compressed, stream.next_out - compressed) < 0)
1729                         die(_("unable to write sha1 file"));
1730                 stream.next_out = compressed;
1731                 stream.avail_out = sizeof(compressed);
1732         } while (ret == Z_OK);
1733
1734         if (ret != Z_STREAM_END)
1735                 die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
1736                     ret);
1737         ret = git_deflate_end_gently(&stream);
1738         if (ret != Z_OK)
1739                 die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
1740                     ret);
1741         the_hash_algo->final_fn(parano_oid.hash, &c);
1742         if (!oideq(oid, &parano_oid))
1743                 die(_("confused by unstable object source data for %s"),
1744                     oid_to_hex(oid));
1745
1746         close_sha1_file(fd);
1747
1748         if (mtime) {
1749                 struct utimbuf utb;
1750                 utb.actime = mtime;
1751                 utb.modtime = mtime;
1752                 if (utime(tmp_file.buf, &utb) < 0)
1753                         warning_errno(_("failed utime() on %s"), tmp_file.buf);
1754         }
1755
1756         return finalize_object_file(tmp_file.buf, filename.buf);
1757 }
1758
1759 static int freshen_loose_object(const struct object_id *oid)
1760 {
1761         return check_and_freshen(oid, 1);
1762 }
1763
1764 static int freshen_packed_object(const struct object_id *oid)
1765 {
1766         struct pack_entry e;
1767         if (!find_pack_entry(the_repository, oid, &e))
1768                 return 0;
1769         if (e.p->freshened)
1770                 return 1;
1771         if (!freshen_file(e.p->pack_name))
1772                 return 0;
1773         e.p->freshened = 1;
1774         return 1;
1775 }
1776
1777 int write_object_file(const void *buf, unsigned long len, const char *type,
1778                       struct object_id *oid)
1779 {
1780         char hdr[MAX_HEADER_LEN];
1781         int hdrlen = sizeof(hdr);
1782
1783         /* Normally if we have it in the pack then we do not bother writing
1784          * it out into .git/objects/??/?{38} file.
1785          */
1786         write_object_file_prepare(buf, len, type, oid, hdr, &hdrlen);
1787         if (freshen_packed_object(oid) || freshen_loose_object(oid))
1788                 return 0;
1789         return write_loose_object(oid, hdr, hdrlen, buf, len, 0);
1790 }
1791
1792 int hash_object_file_literally(const void *buf, unsigned long len,
1793                                const char *type, struct object_id *oid,
1794                                unsigned flags)
1795 {
1796         char *header;
1797         int hdrlen, status = 0;
1798
1799         /* type string, SP, %lu of the length plus NUL must fit this */
1800         hdrlen = strlen(type) + MAX_HEADER_LEN;
1801         header = xmalloc(hdrlen);
1802         write_object_file_prepare(buf, len, type, oid, header, &hdrlen);
1803
1804         if (!(flags & HASH_WRITE_OBJECT))
1805                 goto cleanup;
1806         if (freshen_packed_object(oid) || freshen_loose_object(oid))
1807                 goto cleanup;
1808         status = write_loose_object(oid, header, hdrlen, buf, len, 0);
1809
1810 cleanup:
1811         free(header);
1812         return status;
1813 }
1814
1815 int force_object_loose(const struct object_id *oid, time_t mtime)
1816 {
1817         void *buf;
1818         unsigned long len;
1819         enum object_type type;
1820         char hdr[MAX_HEADER_LEN];
1821         int hdrlen;
1822         int ret;
1823
1824         if (has_loose_object(oid))
1825                 return 0;
1826         buf = read_object(oid->hash, &type, &len);
1827         if (!buf)
1828                 return error(_("cannot read sha1_file for %s"), oid_to_hex(oid));
1829         hdrlen = xsnprintf(hdr, sizeof(hdr), "%s %lu", type_name(type), len) + 1;
1830         ret = write_loose_object(oid, hdr, hdrlen, buf, len, mtime);
1831         free(buf);
1832
1833         return ret;
1834 }
1835
1836 int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
1837 {
1838         struct object_id oid;
1839         if (!startup_info->have_repository)
1840                 return 0;
1841         hashcpy(oid.hash, sha1);
1842         return oid_object_info_extended(the_repository, &oid, NULL,
1843                                         flags | OBJECT_INFO_SKIP_CACHED) >= 0;
1844 }
1845
1846 int has_object_file(const struct object_id *oid)
1847 {
1848         return has_sha1_file(oid->hash);
1849 }
1850
1851 int has_object_file_with_flags(const struct object_id *oid, int flags)
1852 {
1853         return has_sha1_file_with_flags(oid->hash, flags);
1854 }
1855
1856 static void check_tree(const void *buf, size_t size)
1857 {
1858         struct tree_desc desc;
1859         struct name_entry entry;
1860
1861         init_tree_desc(&desc, buf, size);
1862         while (tree_entry(&desc, &entry))
1863                 /* do nothing
1864                  * tree_entry() will die() on malformed entries */
1865                 ;
1866 }
1867
1868 static void check_commit(const void *buf, size_t size)
1869 {
1870         struct commit c;
1871         memset(&c, 0, sizeof(c));
1872         if (parse_commit_buffer(the_repository, &c, buf, size, 0))
1873                 die(_("corrupt commit"));
1874 }
1875
1876 static void check_tag(const void *buf, size_t size)
1877 {
1878         struct tag t;
1879         memset(&t, 0, sizeof(t));
1880         if (parse_tag_buffer(the_repository, &t, buf, size))
1881                 die(_("corrupt tag"));
1882 }
1883
1884 static int index_mem(struct object_id *oid, void *buf, size_t size,
1885                      enum object_type type,
1886                      const char *path, unsigned flags)
1887 {
1888         int ret, re_allocated = 0;
1889         int write_object = flags & HASH_WRITE_OBJECT;
1890
1891         if (!type)
1892                 type = OBJ_BLOB;
1893
1894         /*
1895          * Convert blobs to git internal format
1896          */
1897         if ((type == OBJ_BLOB) && path) {
1898                 struct strbuf nbuf = STRBUF_INIT;
1899                 if (convert_to_git(&the_index, path, buf, size, &nbuf,
1900                                    get_conv_flags(flags))) {
1901                         buf = strbuf_detach(&nbuf, &size);
1902                         re_allocated = 1;
1903                 }
1904         }
1905         if (flags & HASH_FORMAT_CHECK) {
1906                 if (type == OBJ_TREE)
1907                         check_tree(buf, size);
1908                 if (type == OBJ_COMMIT)
1909                         check_commit(buf, size);
1910                 if (type == OBJ_TAG)
1911                         check_tag(buf, size);
1912         }
1913
1914         if (write_object)
1915                 ret = write_object_file(buf, size, type_name(type), oid);
1916         else
1917                 ret = hash_object_file(buf, size, type_name(type), oid);
1918         if (re_allocated)
1919                 free(buf);
1920         return ret;
1921 }
1922
1923 static int index_stream_convert_blob(struct object_id *oid, int fd,
1924                                      const char *path, unsigned flags)
1925 {
1926         int ret;
1927         const int write_object = flags & HASH_WRITE_OBJECT;
1928         struct strbuf sbuf = STRBUF_INIT;
1929
1930         assert(path);
1931         assert(would_convert_to_git_filter_fd(&the_index, path));
1932
1933         convert_to_git_filter_fd(&the_index, path, fd, &sbuf,
1934                                  get_conv_flags(flags));
1935
1936         if (write_object)
1937                 ret = write_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
1938                                         oid);
1939         else
1940                 ret = hash_object_file(sbuf.buf, sbuf.len, type_name(OBJ_BLOB),
1941                                        oid);
1942         strbuf_release(&sbuf);
1943         return ret;
1944 }
1945
1946 static int index_pipe(struct object_id *oid, int fd, enum object_type type,
1947                       const char *path, unsigned flags)
1948 {
1949         struct strbuf sbuf = STRBUF_INIT;
1950         int ret;
1951
1952         if (strbuf_read(&sbuf, fd, 4096) >= 0)
1953                 ret = index_mem(oid, sbuf.buf, sbuf.len, type, path, flags);
1954         else
1955                 ret = -1;
1956         strbuf_release(&sbuf);
1957         return ret;
1958 }
1959
1960 #define SMALL_FILE_SIZE (32*1024)
1961
1962 static int index_core(struct object_id *oid, int fd, size_t size,
1963                       enum object_type type, const char *path,
1964                       unsigned flags)
1965 {
1966         int ret;
1967
1968         if (!size) {
1969                 ret = index_mem(oid, "", size, type, path, flags);
1970         } else if (size <= SMALL_FILE_SIZE) {
1971                 char *buf = xmalloc(size);
1972                 ssize_t read_result = read_in_full(fd, buf, size);
1973                 if (read_result < 0)
1974                         ret = error_errno(_("read error while indexing %s"),
1975                                           path ? path : "<unknown>");
1976                 else if (read_result != size)
1977                         ret = error(_("short read while indexing %s"),
1978                                     path ? path : "<unknown>");
1979                 else
1980                         ret = index_mem(oid, buf, size, type, path, flags);
1981                 free(buf);
1982         } else {
1983                 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1984                 ret = index_mem(oid, buf, size, type, path, flags);
1985                 munmap(buf, size);
1986         }
1987         return ret;
1988 }
1989
1990 /*
1991  * This creates one packfile per large blob unless bulk-checkin
1992  * machinery is "plugged".
1993  *
1994  * This also bypasses the usual "convert-to-git" dance, and that is on
1995  * purpose. We could write a streaming version of the converting
1996  * functions and insert that before feeding the data to fast-import
1997  * (or equivalent in-core API described above). However, that is
1998  * somewhat complicated, as we do not know the size of the filter
1999  * result, which we need to know beforehand when writing a git object.
2000  * Since the primary motivation for trying to stream from the working
2001  * tree file and to avoid mmaping it in core is to deal with large
2002  * binary blobs, they generally do not want to get any conversion, and
2003  * callers should avoid this code path when filters are requested.
2004  */
2005 static int index_stream(struct object_id *oid, int fd, size_t size,
2006                         enum object_type type, const char *path,
2007                         unsigned flags)
2008 {
2009         return index_bulk_checkin(oid, fd, size, type, path, flags);
2010 }
2011
2012 int index_fd(struct object_id *oid, int fd, struct stat *st,
2013              enum object_type type, const char *path, unsigned flags)
2014 {
2015         int ret;
2016
2017         /*
2018          * Call xsize_t() only when needed to avoid potentially unnecessary
2019          * die() for large files.
2020          */
2021         if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(&the_index, path))
2022                 ret = index_stream_convert_blob(oid, fd, path, flags);
2023         else if (!S_ISREG(st->st_mode))
2024                 ret = index_pipe(oid, fd, type, path, flags);
2025         else if (st->st_size <= big_file_threshold || type != OBJ_BLOB ||
2026                  (path && would_convert_to_git(&the_index, path)))
2027                 ret = index_core(oid, fd, xsize_t(st->st_size), type, path,
2028                                  flags);
2029         else
2030                 ret = index_stream(oid, fd, xsize_t(st->st_size), type, path,
2031                                    flags);
2032         close(fd);
2033         return ret;
2034 }
2035
2036 int index_path(struct object_id *oid, const char *path, struct stat *st, unsigned flags)
2037 {
2038         int fd;
2039         struct strbuf sb = STRBUF_INIT;
2040         int rc = 0;
2041
2042         switch (st->st_mode & S_IFMT) {
2043         case S_IFREG:
2044                 fd = open(path, O_RDONLY);
2045                 if (fd < 0)
2046                         return error_errno("open(\"%s\")", path);
2047                 if (index_fd(oid, fd, st, OBJ_BLOB, path, flags) < 0)
2048                         return error(_("%s: failed to insert into database"),
2049                                      path);
2050                 break;
2051         case S_IFLNK:
2052                 if (strbuf_readlink(&sb, path, st->st_size))
2053                         return error_errno("readlink(\"%s\")", path);
2054                 if (!(flags & HASH_WRITE_OBJECT))
2055                         hash_object_file(sb.buf, sb.len, blob_type, oid);
2056                 else if (write_object_file(sb.buf, sb.len, blob_type, oid))
2057                         rc = error(_("%s: failed to insert into database"), path);
2058                 strbuf_release(&sb);
2059                 break;
2060         case S_IFDIR:
2061                 return resolve_gitlink_ref(path, "HEAD", oid);
2062         default:
2063                 return error(_("%s: unsupported file type"), path);
2064         }
2065         return rc;
2066 }
2067
2068 int read_pack_header(int fd, struct pack_header *header)
2069 {
2070         if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
2071                 /* "eof before pack header was fully read" */
2072                 return PH_ERROR_EOF;
2073
2074         if (header->hdr_signature != htonl(PACK_SIGNATURE))
2075                 /* "protocol error (pack signature mismatch detected)" */
2076                 return PH_ERROR_PACK_SIGNATURE;
2077         if (!pack_version_ok(header->hdr_version))
2078                 /* "protocol error (pack version unsupported)" */
2079                 return PH_ERROR_PROTOCOL;
2080         return 0;
2081 }
2082
2083 void assert_oid_type(const struct object_id *oid, enum object_type expect)
2084 {
2085         enum object_type type = oid_object_info(the_repository, oid, NULL);
2086         if (type < 0)
2087                 die(_("%s is not a valid object"), oid_to_hex(oid));
2088         if (type != expect)
2089                 die(_("%s is not a valid '%s' object"), oid_to_hex(oid),
2090                     type_name(expect));
2091 }
2092
2093 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
2094                                 struct strbuf *path,
2095                                 each_loose_object_fn obj_cb,
2096                                 each_loose_cruft_fn cruft_cb,
2097                                 each_loose_subdir_fn subdir_cb,
2098                                 void *data)
2099 {
2100         size_t origlen, baselen;
2101         DIR *dir;
2102         struct dirent *de;
2103         int r = 0;
2104         struct object_id oid;
2105
2106         if (subdir_nr > 0xff)
2107                 BUG("invalid loose object subdirectory: %x", subdir_nr);
2108
2109         origlen = path->len;
2110         strbuf_complete(path, '/');
2111         strbuf_addf(path, "%02x", subdir_nr);
2112
2113         dir = opendir(path->buf);
2114         if (!dir) {
2115                 if (errno != ENOENT)
2116                         r = error_errno(_("unable to open %s"), path->buf);
2117                 strbuf_setlen(path, origlen);
2118                 return r;
2119         }
2120
2121         oid.hash[0] = subdir_nr;
2122         strbuf_addch(path, '/');
2123         baselen = path->len;
2124
2125         while ((de = readdir(dir))) {
2126                 size_t namelen;
2127                 if (is_dot_or_dotdot(de->d_name))
2128                         continue;
2129
2130                 namelen = strlen(de->d_name);
2131                 strbuf_setlen(path, baselen);
2132                 strbuf_add(path, de->d_name, namelen);
2133                 if (namelen == the_hash_algo->hexsz - 2 &&
2134                     !hex_to_bytes(oid.hash + 1, de->d_name,
2135                                   the_hash_algo->rawsz - 1)) {
2136                         if (obj_cb) {
2137                                 r = obj_cb(&oid, path->buf, data);
2138                                 if (r)
2139                                         break;
2140                         }
2141                         continue;
2142                 }
2143
2144                 if (cruft_cb) {
2145                         r = cruft_cb(de->d_name, path->buf, data);
2146                         if (r)
2147                                 break;
2148                 }
2149         }
2150         closedir(dir);
2151
2152         strbuf_setlen(path, baselen - 1);
2153         if (!r && subdir_cb)
2154                 r = subdir_cb(subdir_nr, path->buf, data);
2155
2156         strbuf_setlen(path, origlen);
2157
2158         return r;
2159 }
2160
2161 int for_each_loose_file_in_objdir_buf(struct strbuf *path,
2162                             each_loose_object_fn obj_cb,
2163                             each_loose_cruft_fn cruft_cb,
2164                             each_loose_subdir_fn subdir_cb,
2165                             void *data)
2166 {
2167         int r = 0;
2168         int i;
2169
2170         for (i = 0; i < 256; i++) {
2171                 r = for_each_file_in_obj_subdir(i, path, obj_cb, cruft_cb,
2172                                                 subdir_cb, data);
2173                 if (r)
2174                         break;
2175         }
2176
2177         return r;
2178 }
2179
2180 int for_each_loose_file_in_objdir(const char *path,
2181                                   each_loose_object_fn obj_cb,
2182                                   each_loose_cruft_fn cruft_cb,
2183                                   each_loose_subdir_fn subdir_cb,
2184                                   void *data)
2185 {
2186         struct strbuf buf = STRBUF_INIT;
2187         int r;
2188
2189         strbuf_addstr(&buf, path);
2190         r = for_each_loose_file_in_objdir_buf(&buf, obj_cb, cruft_cb,
2191                                               subdir_cb, data);
2192         strbuf_release(&buf);
2193
2194         return r;
2195 }
2196
2197 struct loose_alt_odb_data {
2198         each_loose_object_fn *cb;
2199         void *data;
2200 };
2201
2202 static int loose_from_alt_odb(struct alternate_object_database *alt,
2203                               void *vdata)
2204 {
2205         struct loose_alt_odb_data *data = vdata;
2206         struct strbuf buf = STRBUF_INIT;
2207         int r;
2208
2209         strbuf_addstr(&buf, alt->path);
2210         r = for_each_loose_file_in_objdir_buf(&buf,
2211                                               data->cb, NULL, NULL,
2212                                               data->data);
2213         strbuf_release(&buf);
2214         return r;
2215 }
2216
2217 int for_each_loose_object(each_loose_object_fn cb, void *data,
2218                           enum for_each_object_flags flags)
2219 {
2220         struct loose_alt_odb_data alt;
2221         int r;
2222
2223         r = for_each_loose_file_in_objdir(get_object_directory(),
2224                                           cb, NULL, NULL, data);
2225         if (r)
2226                 return r;
2227
2228         if (flags & FOR_EACH_OBJECT_LOCAL_ONLY)
2229                 return 0;
2230
2231         alt.cb = cb;
2232         alt.data = data;
2233         return foreach_alt_odb(loose_from_alt_odb, &alt);
2234 }
2235
2236 static int check_stream_sha1(git_zstream *stream,
2237                              const char *hdr,
2238                              unsigned long size,
2239                              const char *path,
2240                              const unsigned char *expected_sha1)
2241 {
2242         git_hash_ctx c;
2243         unsigned char real_sha1[GIT_MAX_RAWSZ];
2244         unsigned char buf[4096];
2245         unsigned long total_read;
2246         int status = Z_OK;
2247
2248         the_hash_algo->init_fn(&c);
2249         the_hash_algo->update_fn(&c, hdr, stream->total_out);
2250
2251         /*
2252          * We already read some bytes into hdr, but the ones up to the NUL
2253          * do not count against the object's content size.
2254          */
2255         total_read = stream->total_out - strlen(hdr) - 1;
2256
2257         /*
2258          * This size comparison must be "<=" to read the final zlib packets;
2259          * see the comment in unpack_sha1_rest for details.
2260          */
2261         while (total_read <= size &&
2262                (status == Z_OK || status == Z_BUF_ERROR)) {
2263                 stream->next_out = buf;
2264                 stream->avail_out = sizeof(buf);
2265                 if (size - total_read < stream->avail_out)
2266                         stream->avail_out = size - total_read;
2267                 status = git_inflate(stream, Z_FINISH);
2268                 the_hash_algo->update_fn(&c, buf, stream->next_out - buf);
2269                 total_read += stream->next_out - buf;
2270         }
2271         git_inflate_end(stream);
2272
2273         if (status != Z_STREAM_END) {
2274                 error(_("corrupt loose object '%s'"), sha1_to_hex(expected_sha1));
2275                 return -1;
2276         }
2277         if (stream->avail_in) {
2278                 error(_("garbage at end of loose object '%s'"),
2279                       sha1_to_hex(expected_sha1));
2280                 return -1;
2281         }
2282
2283         the_hash_algo->final_fn(real_sha1, &c);
2284         if (!hasheq(expected_sha1, real_sha1)) {
2285                 error(_("sha1 mismatch for %s (expected %s)"), path,
2286                       sha1_to_hex(expected_sha1));
2287                 return -1;
2288         }
2289
2290         return 0;
2291 }
2292
2293 int read_loose_object(const char *path,
2294                       const struct object_id *expected_oid,
2295                       enum object_type *type,
2296                       unsigned long *size,
2297                       void **contents)
2298 {
2299         int ret = -1;
2300         void *map = NULL;
2301         unsigned long mapsize;
2302         git_zstream stream;
2303         char hdr[MAX_HEADER_LEN];
2304
2305         *contents = NULL;
2306
2307         map = map_sha1_file_1(the_repository, path, NULL, &mapsize);
2308         if (!map) {
2309                 error_errno(_("unable to mmap %s"), path);
2310                 goto out;
2311         }
2312
2313         if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0) {
2314                 error(_("unable to unpack header of %s"), path);
2315                 goto out;
2316         }
2317
2318         *type = parse_sha1_header(hdr, size);
2319         if (*type < 0) {
2320                 error(_("unable to parse header of %s"), path);
2321                 git_inflate_end(&stream);
2322                 goto out;
2323         }
2324
2325         if (*type == OBJ_BLOB && *size > big_file_threshold) {
2326                 if (check_stream_sha1(&stream, hdr, *size, path, expected_oid->hash) < 0)
2327                         goto out;
2328         } else {
2329                 *contents = unpack_sha1_rest(&stream, hdr, *size, expected_oid->hash);
2330                 if (!*contents) {
2331                         error(_("unable to unpack contents of %s"), path);
2332                         git_inflate_end(&stream);
2333                         goto out;
2334                 }
2335                 if (check_object_signature(expected_oid, *contents,
2336                                          *size, type_name(*type))) {
2337                         error(_("sha1 mismatch for %s (expected %s)"), path,
2338                               oid_to_hex(expected_oid));
2339                         free(*contents);
2340                         goto out;
2341                 }
2342         }
2343
2344         ret = 0; /* everything checks out */
2345
2346 out:
2347         if (map)
2348                 munmap(map, mapsize);
2349         return ret;
2350 }