add_packed_ref(): teach function to overwrite existing refs
[git] / refs / files-backend.c
1 #include "../cache.h"
2 #include "../refs.h"
3 #include "refs-internal.h"
4 #include "ref-cache.h"
5 #include "../iterator.h"
6 #include "../dir-iterator.h"
7 #include "../lockfile.h"
8 #include "../object.h"
9 #include "../dir.h"
10
11 struct ref_lock {
12         char *ref_name;
13         struct lock_file *lk;
14         struct object_id old_oid;
15 };
16
17 /*
18  * Return true if refname, which has the specified oid and flags, can
19  * be resolved to an object in the database. If the referred-to object
20  * does not exist, emit a warning and return false.
21  */
22 static int ref_resolves_to_object(const char *refname,
23                                   const struct object_id *oid,
24                                   unsigned int flags)
25 {
26         if (flags & REF_ISBROKEN)
27                 return 0;
28         if (!has_sha1_file(oid->hash)) {
29                 error("%s does not point to a valid object!", refname);
30                 return 0;
31         }
32         return 1;
33 }
34
35 struct packed_ref_cache {
36         struct ref_cache *cache;
37
38         /*
39          * Count of references to the data structure in this instance,
40          * including the pointer from files_ref_store::packed if any.
41          * The data will not be freed as long as the reference count
42          * is nonzero.
43          */
44         unsigned int referrers;
45
46         /* The metadata from when this packed-refs cache was read */
47         struct stat_validity validity;
48 };
49
50 /*
51  * Future: need to be in "struct repository"
52  * when doing a full libification.
53  */
54 struct files_ref_store {
55         struct ref_store base;
56         unsigned int store_flags;
57
58         char *gitdir;
59         char *gitcommondir;
60         char *packed_refs_path;
61
62         struct ref_cache *loose;
63         struct packed_ref_cache *packed;
64
65         /*
66          * Lock used for the "packed-refs" file. Note that this (and
67          * thus the enclosing `files_ref_store`) must not be freed.
68          */
69         struct lock_file packed_refs_lock;
70 };
71
72 /*
73  * Increment the reference count of *packed_refs.
74  */
75 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
76 {
77         packed_refs->referrers++;
78 }
79
80 /*
81  * Decrease the reference count of *packed_refs.  If it goes to zero,
82  * free *packed_refs and return true; otherwise return false.
83  */
84 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
85 {
86         if (!--packed_refs->referrers) {
87                 free_ref_cache(packed_refs->cache);
88                 stat_validity_clear(&packed_refs->validity);
89                 free(packed_refs);
90                 return 1;
91         } else {
92                 return 0;
93         }
94 }
95
96 static void clear_packed_ref_cache(struct files_ref_store *refs)
97 {
98         if (refs->packed) {
99                 struct packed_ref_cache *packed_refs = refs->packed;
100
101                 if (is_lock_file_locked(&refs->packed_refs_lock))
102                         die("BUG: packed-ref cache cleared while locked");
103                 refs->packed = NULL;
104                 release_packed_ref_cache(packed_refs);
105         }
106 }
107
108 static void clear_loose_ref_cache(struct files_ref_store *refs)
109 {
110         if (refs->loose) {
111                 free_ref_cache(refs->loose);
112                 refs->loose = NULL;
113         }
114 }
115
116 /*
117  * Create a new submodule ref cache and add it to the internal
118  * set of caches.
119  */
120 static struct ref_store *files_ref_store_create(const char *gitdir,
121                                                 unsigned int flags)
122 {
123         struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
124         struct ref_store *ref_store = (struct ref_store *)refs;
125         struct strbuf sb = STRBUF_INIT;
126
127         base_ref_store_init(ref_store, &refs_be_files);
128         refs->store_flags = flags;
129
130         refs->gitdir = xstrdup(gitdir);
131         get_common_dir_noenv(&sb, gitdir);
132         refs->gitcommondir = strbuf_detach(&sb, NULL);
133         strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
134         refs->packed_refs_path = strbuf_detach(&sb, NULL);
135
136         return ref_store;
137 }
138
139 /*
140  * Die if refs is not the main ref store. caller is used in any
141  * necessary error messages.
142  */
143 static void files_assert_main_repository(struct files_ref_store *refs,
144                                          const char *caller)
145 {
146         if (refs->store_flags & REF_STORE_MAIN)
147                 return;
148
149         die("BUG: operation %s only allowed for main ref store", caller);
150 }
151
152 /*
153  * Downcast ref_store to files_ref_store. Die if ref_store is not a
154  * files_ref_store. required_flags is compared with ref_store's
155  * store_flags to ensure the ref_store has all required capabilities.
156  * "caller" is used in any necessary error messages.
157  */
158 static struct files_ref_store *files_downcast(struct ref_store *ref_store,
159                                               unsigned int required_flags,
160                                               const char *caller)
161 {
162         struct files_ref_store *refs;
163
164         if (ref_store->be != &refs_be_files)
165                 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
166                     ref_store->be->name, caller);
167
168         refs = (struct files_ref_store *)ref_store;
169
170         if ((refs->store_flags & required_flags) != required_flags)
171                 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
172                     caller, required_flags, refs->store_flags);
173
174         return refs;
175 }
176
177 /* The length of a peeled reference line in packed-refs, including EOL: */
178 #define PEELED_LINE_LENGTH 42
179
180 /*
181  * The packed-refs header line that we write out.  Perhaps other
182  * traits will be added later.  The trailing space is required.
183  */
184 static const char PACKED_REFS_HEADER[] =
185         "# pack-refs with: peeled fully-peeled \n";
186
187 /*
188  * Parse one line from a packed-refs file.  Write the SHA1 to sha1.
189  * Return a pointer to the refname within the line (null-terminated),
190  * or NULL if there was a problem.
191  */
192 static const char *parse_ref_line(struct strbuf *line, struct object_id *oid)
193 {
194         const char *ref;
195
196         if (parse_oid_hex(line->buf, oid, &ref) < 0)
197                 return NULL;
198         if (!isspace(*ref++))
199                 return NULL;
200
201         if (isspace(*ref))
202                 return NULL;
203
204         if (line->buf[line->len - 1] != '\n')
205                 return NULL;
206         line->buf[--line->len] = 0;
207
208         return ref;
209 }
210
211 /*
212  * Read from `packed_refs_file` into a newly-allocated
213  * `packed_ref_cache` and return it. The return value will already
214  * have its reference count incremented.
215  *
216  * A comment line of the form "# pack-refs with: " may contain zero or
217  * more traits. We interpret the traits as follows:
218  *
219  *   No traits:
220  *
221  *      Probably no references are peeled. But if the file contains a
222  *      peeled value for a reference, we will use it.
223  *
224  *   peeled:
225  *
226  *      References under "refs/tags/", if they *can* be peeled, *are*
227  *      peeled in this file. References outside of "refs/tags/" are
228  *      probably not peeled even if they could have been, but if we find
229  *      a peeled value for such a reference we will use it.
230  *
231  *   fully-peeled:
232  *
233  *      All references in the file that can be peeled are peeled.
234  *      Inversely (and this is more important), any references in the
235  *      file for which no peeled value is recorded is not peelable. This
236  *      trait should typically be written alongside "peeled" for
237  *      compatibility with older clients, but we do not require it
238  *      (i.e., "peeled" is a no-op if "fully-peeled" is set).
239  */
240 static struct packed_ref_cache *read_packed_refs(const char *packed_refs_file)
241 {
242         FILE *f;
243         struct packed_ref_cache *packed_refs = xcalloc(1, sizeof(*packed_refs));
244         struct ref_entry *last = NULL;
245         struct strbuf line = STRBUF_INIT;
246         enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
247         struct ref_dir *dir;
248
249         acquire_packed_ref_cache(packed_refs);
250         packed_refs->cache = create_ref_cache(NULL, NULL);
251         packed_refs->cache->root->flag &= ~REF_INCOMPLETE;
252
253         f = fopen(packed_refs_file, "r");
254         if (!f) {
255                 if (errno == ENOENT) {
256                         /*
257                          * This is OK; it just means that no
258                          * "packed-refs" file has been written yet,
259                          * which is equivalent to it being empty.
260                          */
261                         return packed_refs;
262                 } else {
263                         die_errno("couldn't read %s", packed_refs_file);
264                 }
265         }
266
267         stat_validity_update(&packed_refs->validity, fileno(f));
268
269         dir = get_ref_dir(packed_refs->cache->root);
270         while (strbuf_getwholeline(&line, f, '\n') != EOF) {
271                 struct object_id oid;
272                 const char *refname;
273                 const char *traits;
274
275                 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
276                         if (strstr(traits, " fully-peeled "))
277                                 peeled = PEELED_FULLY;
278                         else if (strstr(traits, " peeled "))
279                                 peeled = PEELED_TAGS;
280                         /* perhaps other traits later as well */
281                         continue;
282                 }
283
284                 refname = parse_ref_line(&line, &oid);
285                 if (refname) {
286                         int flag = REF_ISPACKED;
287
288                         if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
289                                 if (!refname_is_safe(refname))
290                                         die("packed refname is dangerous: %s", refname);
291                                 oidclr(&oid);
292                                 flag |= REF_BAD_NAME | REF_ISBROKEN;
293                         }
294                         last = create_ref_entry(refname, &oid, flag);
295                         if (peeled == PEELED_FULLY ||
296                             (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
297                                 last->flag |= REF_KNOWS_PEELED;
298                         add_ref_entry(dir, last);
299                         continue;
300                 }
301                 if (last &&
302                     line.buf[0] == '^' &&
303                     line.len == PEELED_LINE_LENGTH &&
304                     line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
305                     !get_oid_hex(line.buf + 1, &oid)) {
306                         oidcpy(&last->u.value.peeled, &oid);
307                         /*
308                          * Regardless of what the file header said,
309                          * we definitely know the value of *this*
310                          * reference:
311                          */
312                         last->flag |= REF_KNOWS_PEELED;
313                 }
314         }
315
316         fclose(f);
317         strbuf_release(&line);
318
319         return packed_refs;
320 }
321
322 static const char *files_packed_refs_path(struct files_ref_store *refs)
323 {
324         return refs->packed_refs_path;
325 }
326
327 static void files_reflog_path(struct files_ref_store *refs,
328                               struct strbuf *sb,
329                               const char *refname)
330 {
331         if (!refname) {
332                 /*
333                  * FIXME: of course this is wrong in multi worktree
334                  * setting. To be fixed real soon.
335                  */
336                 strbuf_addf(sb, "%s/logs", refs->gitcommondir);
337                 return;
338         }
339
340         switch (ref_type(refname)) {
341         case REF_TYPE_PER_WORKTREE:
342         case REF_TYPE_PSEUDOREF:
343                 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
344                 break;
345         case REF_TYPE_NORMAL:
346                 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
347                 break;
348         default:
349                 die("BUG: unknown ref type %d of ref %s",
350                     ref_type(refname), refname);
351         }
352 }
353
354 static void files_ref_path(struct files_ref_store *refs,
355                            struct strbuf *sb,
356                            const char *refname)
357 {
358         switch (ref_type(refname)) {
359         case REF_TYPE_PER_WORKTREE:
360         case REF_TYPE_PSEUDOREF:
361                 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
362                 break;
363         case REF_TYPE_NORMAL:
364                 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
365                 break;
366         default:
367                 die("BUG: unknown ref type %d of ref %s",
368                     ref_type(refname), refname);
369         }
370 }
371
372 /*
373  * Check that the packed refs cache (if any) still reflects the
374  * contents of the file. If not, clear the cache.
375  */
376 static void validate_packed_ref_cache(struct files_ref_store *refs)
377 {
378         if (refs->packed &&
379             !stat_validity_check(&refs->packed->validity,
380                                  files_packed_refs_path(refs)))
381                 clear_packed_ref_cache(refs);
382 }
383
384 /*
385  * Get the packed_ref_cache for the specified files_ref_store,
386  * creating and populating it if it hasn't been read before or if the
387  * file has been changed (according to its `validity` field) since it
388  * was last read. On the other hand, if we hold the lock, then assume
389  * that the file hasn't been changed out from under us, so skip the
390  * extra `stat()` call in `stat_validity_check()`.
391  */
392 static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs)
393 {
394         const char *packed_refs_file = files_packed_refs_path(refs);
395
396         if (!is_lock_file_locked(&refs->packed_refs_lock))
397                 validate_packed_ref_cache(refs);
398
399         if (!refs->packed)
400                 refs->packed = read_packed_refs(packed_refs_file);
401
402         return refs->packed;
403 }
404
405 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
406 {
407         return get_ref_dir(packed_ref_cache->cache->root);
408 }
409
410 static struct ref_dir *get_packed_refs(struct files_ref_store *refs)
411 {
412         return get_packed_ref_dir(get_packed_ref_cache(refs));
413 }
414
415 /*
416  * Add or overwrite a reference in the in-memory packed reference
417  * cache. This may only be called while the packed-refs file is locked
418  * (see lock_packed_refs()). To actually write the packed-refs file,
419  * call commit_packed_refs().
420  */
421 static void add_packed_ref(struct files_ref_store *refs,
422                            const char *refname, const struct object_id *oid)
423 {
424         struct ref_dir *packed_refs;
425         struct ref_entry *packed_entry;
426
427         if (!is_lock_file_locked(&refs->packed_refs_lock))
428                 die("BUG: packed refs not locked");
429
430         if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
431                 die("Reference has invalid format: '%s'", refname);
432
433         packed_refs = get_packed_refs(refs);
434         packed_entry = find_ref_entry(packed_refs, refname);
435         if (packed_entry) {
436                 /* Overwrite the existing entry: */
437                 oidcpy(&packed_entry->u.value.oid, oid);
438                 packed_entry->flag = REF_ISPACKED;
439                 oidclr(&packed_entry->u.value.peeled);
440         } else {
441                 packed_entry = create_ref_entry(refname, oid, REF_ISPACKED);
442                 add_ref_entry(packed_refs, packed_entry);
443         }
444 }
445
446 /*
447  * Read the loose references from the namespace dirname into dir
448  * (without recursing).  dirname must end with '/'.  dir must be the
449  * directory entry corresponding to dirname.
450  */
451 static void loose_fill_ref_dir(struct ref_store *ref_store,
452                                struct ref_dir *dir, const char *dirname)
453 {
454         struct files_ref_store *refs =
455                 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
456         DIR *d;
457         struct dirent *de;
458         int dirnamelen = strlen(dirname);
459         struct strbuf refname;
460         struct strbuf path = STRBUF_INIT;
461         size_t path_baselen;
462
463         files_ref_path(refs, &path, dirname);
464         path_baselen = path.len;
465
466         d = opendir(path.buf);
467         if (!d) {
468                 strbuf_release(&path);
469                 return;
470         }
471
472         strbuf_init(&refname, dirnamelen + 257);
473         strbuf_add(&refname, dirname, dirnamelen);
474
475         while ((de = readdir(d)) != NULL) {
476                 struct object_id oid;
477                 struct stat st;
478                 int flag;
479
480                 if (de->d_name[0] == '.')
481                         continue;
482                 if (ends_with(de->d_name, ".lock"))
483                         continue;
484                 strbuf_addstr(&refname, de->d_name);
485                 strbuf_addstr(&path, de->d_name);
486                 if (stat(path.buf, &st) < 0) {
487                         ; /* silently ignore */
488                 } else if (S_ISDIR(st.st_mode)) {
489                         strbuf_addch(&refname, '/');
490                         add_entry_to_dir(dir,
491                                          create_dir_entry(dir->cache, refname.buf,
492                                                           refname.len, 1));
493                 } else {
494                         if (!refs_resolve_ref_unsafe(&refs->base,
495                                                      refname.buf,
496                                                      RESOLVE_REF_READING,
497                                                      oid.hash, &flag)) {
498                                 oidclr(&oid);
499                                 flag |= REF_ISBROKEN;
500                         } else if (is_null_oid(&oid)) {
501                                 /*
502                                  * It is so astronomically unlikely
503                                  * that NULL_SHA1 is the SHA-1 of an
504                                  * actual object that we consider its
505                                  * appearance in a loose reference
506                                  * file to be repo corruption
507                                  * (probably due to a software bug).
508                                  */
509                                 flag |= REF_ISBROKEN;
510                         }
511
512                         if (check_refname_format(refname.buf,
513                                                  REFNAME_ALLOW_ONELEVEL)) {
514                                 if (!refname_is_safe(refname.buf))
515                                         die("loose refname is dangerous: %s", refname.buf);
516                                 oidclr(&oid);
517                                 flag |= REF_BAD_NAME | REF_ISBROKEN;
518                         }
519                         add_entry_to_dir(dir,
520                                          create_ref_entry(refname.buf, &oid, flag));
521                 }
522                 strbuf_setlen(&refname, dirnamelen);
523                 strbuf_setlen(&path, path_baselen);
524         }
525         strbuf_release(&refname);
526         strbuf_release(&path);
527         closedir(d);
528
529         /*
530          * Manually add refs/bisect, which, being per-worktree, might
531          * not appear in the directory listing for refs/ in the main
532          * repo.
533          */
534         if (!strcmp(dirname, "refs/")) {
535                 int pos = search_ref_dir(dir, "refs/bisect/", 12);
536
537                 if (pos < 0) {
538                         struct ref_entry *child_entry = create_dir_entry(
539                                         dir->cache, "refs/bisect/", 12, 1);
540                         add_entry_to_dir(dir, child_entry);
541                 }
542         }
543 }
544
545 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
546 {
547         if (!refs->loose) {
548                 /*
549                  * Mark the top-level directory complete because we
550                  * are about to read the only subdirectory that can
551                  * hold references:
552                  */
553                 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
554
555                 /* We're going to fill the top level ourselves: */
556                 refs->loose->root->flag &= ~REF_INCOMPLETE;
557
558                 /*
559                  * Add an incomplete entry for "refs/" (to be filled
560                  * lazily):
561                  */
562                 add_entry_to_dir(get_ref_dir(refs->loose->root),
563                                  create_dir_entry(refs->loose, "refs/", 5, 1));
564         }
565         return refs->loose;
566 }
567
568 /*
569  * Return the ref_entry for the given refname from the packed
570  * references.  If it does not exist, return NULL.
571  */
572 static struct ref_entry *get_packed_ref(struct files_ref_store *refs,
573                                         const char *refname)
574 {
575         return find_ref_entry(get_packed_refs(refs), refname);
576 }
577
578 /*
579  * A loose ref file doesn't exist; check for a packed ref.
580  */
581 static int resolve_packed_ref(struct files_ref_store *refs,
582                               const char *refname,
583                               unsigned char *sha1, unsigned int *flags)
584 {
585         struct ref_entry *entry;
586
587         /*
588          * The loose reference file does not exist; check for a packed
589          * reference.
590          */
591         entry = get_packed_ref(refs, refname);
592         if (entry) {
593                 hashcpy(sha1, entry->u.value.oid.hash);
594                 *flags |= REF_ISPACKED;
595                 return 0;
596         }
597         /* refname is not a packed reference. */
598         return -1;
599 }
600
601 static int files_read_raw_ref(struct ref_store *ref_store,
602                               const char *refname, unsigned char *sha1,
603                               struct strbuf *referent, unsigned int *type)
604 {
605         struct files_ref_store *refs =
606                 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
607         struct strbuf sb_contents = STRBUF_INIT;
608         struct strbuf sb_path = STRBUF_INIT;
609         const char *path;
610         const char *buf;
611         struct stat st;
612         int fd;
613         int ret = -1;
614         int save_errno;
615         int remaining_retries = 3;
616
617         *type = 0;
618         strbuf_reset(&sb_path);
619
620         files_ref_path(refs, &sb_path, refname);
621
622         path = sb_path.buf;
623
624 stat_ref:
625         /*
626          * We might have to loop back here to avoid a race
627          * condition: first we lstat() the file, then we try
628          * to read it as a link or as a file.  But if somebody
629          * changes the type of the file (file <-> directory
630          * <-> symlink) between the lstat() and reading, then
631          * we don't want to report that as an error but rather
632          * try again starting with the lstat().
633          *
634          * We'll keep a count of the retries, though, just to avoid
635          * any confusing situation sending us into an infinite loop.
636          */
637
638         if (remaining_retries-- <= 0)
639                 goto out;
640
641         if (lstat(path, &st) < 0) {
642                 if (errno != ENOENT)
643                         goto out;
644                 if (resolve_packed_ref(refs, refname, sha1, type)) {
645                         errno = ENOENT;
646                         goto out;
647                 }
648                 ret = 0;
649                 goto out;
650         }
651
652         /* Follow "normalized" - ie "refs/.." symlinks by hand */
653         if (S_ISLNK(st.st_mode)) {
654                 strbuf_reset(&sb_contents);
655                 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
656                         if (errno == ENOENT || errno == EINVAL)
657                                 /* inconsistent with lstat; retry */
658                                 goto stat_ref;
659                         else
660                                 goto out;
661                 }
662                 if (starts_with(sb_contents.buf, "refs/") &&
663                     !check_refname_format(sb_contents.buf, 0)) {
664                         strbuf_swap(&sb_contents, referent);
665                         *type |= REF_ISSYMREF;
666                         ret = 0;
667                         goto out;
668                 }
669                 /*
670                  * It doesn't look like a refname; fall through to just
671                  * treating it like a non-symlink, and reading whatever it
672                  * points to.
673                  */
674         }
675
676         /* Is it a directory? */
677         if (S_ISDIR(st.st_mode)) {
678                 /*
679                  * Even though there is a directory where the loose
680                  * ref is supposed to be, there could still be a
681                  * packed ref:
682                  */
683                 if (resolve_packed_ref(refs, refname, sha1, type)) {
684                         errno = EISDIR;
685                         goto out;
686                 }
687                 ret = 0;
688                 goto out;
689         }
690
691         /*
692          * Anything else, just open it and try to use it as
693          * a ref
694          */
695         fd = open(path, O_RDONLY);
696         if (fd < 0) {
697                 if (errno == ENOENT && !S_ISLNK(st.st_mode))
698                         /* inconsistent with lstat; retry */
699                         goto stat_ref;
700                 else
701                         goto out;
702         }
703         strbuf_reset(&sb_contents);
704         if (strbuf_read(&sb_contents, fd, 256) < 0) {
705                 int save_errno = errno;
706                 close(fd);
707                 errno = save_errno;
708                 goto out;
709         }
710         close(fd);
711         strbuf_rtrim(&sb_contents);
712         buf = sb_contents.buf;
713         if (starts_with(buf, "ref:")) {
714                 buf += 4;
715                 while (isspace(*buf))
716                         buf++;
717
718                 strbuf_reset(referent);
719                 strbuf_addstr(referent, buf);
720                 *type |= REF_ISSYMREF;
721                 ret = 0;
722                 goto out;
723         }
724
725         /*
726          * Please note that FETCH_HEAD has additional
727          * data after the sha.
728          */
729         if (get_sha1_hex(buf, sha1) ||
730             (buf[40] != '\0' && !isspace(buf[40]))) {
731                 *type |= REF_ISBROKEN;
732                 errno = EINVAL;
733                 goto out;
734         }
735
736         ret = 0;
737
738 out:
739         save_errno = errno;
740         strbuf_release(&sb_path);
741         strbuf_release(&sb_contents);
742         errno = save_errno;
743         return ret;
744 }
745
746 static void unlock_ref(struct ref_lock *lock)
747 {
748         /* Do not free lock->lk -- atexit() still looks at them */
749         if (lock->lk)
750                 rollback_lock_file(lock->lk);
751         free(lock->ref_name);
752         free(lock);
753 }
754
755 /*
756  * Lock refname, without following symrefs, and set *lock_p to point
757  * at a newly-allocated lock object. Fill in lock->old_oid, referent,
758  * and type similarly to read_raw_ref().
759  *
760  * The caller must verify that refname is a "safe" reference name (in
761  * the sense of refname_is_safe()) before calling this function.
762  *
763  * If the reference doesn't already exist, verify that refname doesn't
764  * have a D/F conflict with any existing references. extras and skip
765  * are passed to refs_verify_refname_available() for this check.
766  *
767  * If mustexist is not set and the reference is not found or is
768  * broken, lock the reference anyway but clear sha1.
769  *
770  * Return 0 on success. On failure, write an error message to err and
771  * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
772  *
773  * Implementation note: This function is basically
774  *
775  *     lock reference
776  *     read_raw_ref()
777  *
778  * but it includes a lot more code to
779  * - Deal with possible races with other processes
780  * - Avoid calling refs_verify_refname_available() when it can be
781  *   avoided, namely if we were successfully able to read the ref
782  * - Generate informative error messages in the case of failure
783  */
784 static int lock_raw_ref(struct files_ref_store *refs,
785                         const char *refname, int mustexist,
786                         const struct string_list *extras,
787                         const struct string_list *skip,
788                         struct ref_lock **lock_p,
789                         struct strbuf *referent,
790                         unsigned int *type,
791                         struct strbuf *err)
792 {
793         struct ref_lock *lock;
794         struct strbuf ref_file = STRBUF_INIT;
795         int attempts_remaining = 3;
796         int ret = TRANSACTION_GENERIC_ERROR;
797
798         assert(err);
799         files_assert_main_repository(refs, "lock_raw_ref");
800
801         *type = 0;
802
803         /* First lock the file so it can't change out from under us. */
804
805         *lock_p = lock = xcalloc(1, sizeof(*lock));
806
807         lock->ref_name = xstrdup(refname);
808         files_ref_path(refs, &ref_file, refname);
809
810 retry:
811         switch (safe_create_leading_directories(ref_file.buf)) {
812         case SCLD_OK:
813                 break; /* success */
814         case SCLD_EXISTS:
815                 /*
816                  * Suppose refname is "refs/foo/bar". We just failed
817                  * to create the containing directory, "refs/foo",
818                  * because there was a non-directory in the way. This
819                  * indicates a D/F conflict, probably because of
820                  * another reference such as "refs/foo". There is no
821                  * reason to expect this error to be transitory.
822                  */
823                 if (refs_verify_refname_available(&refs->base, refname,
824                                                   extras, skip, err)) {
825                         if (mustexist) {
826                                 /*
827                                  * To the user the relevant error is
828                                  * that the "mustexist" reference is
829                                  * missing:
830                                  */
831                                 strbuf_reset(err);
832                                 strbuf_addf(err, "unable to resolve reference '%s'",
833                                             refname);
834                         } else {
835                                 /*
836                                  * The error message set by
837                                  * refs_verify_refname_available() is
838                                  * OK.
839                                  */
840                                 ret = TRANSACTION_NAME_CONFLICT;
841                         }
842                 } else {
843                         /*
844                          * The file that is in the way isn't a loose
845                          * reference. Report it as a low-level
846                          * failure.
847                          */
848                         strbuf_addf(err, "unable to create lock file %s.lock; "
849                                     "non-directory in the way",
850                                     ref_file.buf);
851                 }
852                 goto error_return;
853         case SCLD_VANISHED:
854                 /* Maybe another process was tidying up. Try again. */
855                 if (--attempts_remaining > 0)
856                         goto retry;
857                 /* fall through */
858         default:
859                 strbuf_addf(err, "unable to create directory for %s",
860                             ref_file.buf);
861                 goto error_return;
862         }
863
864         if (!lock->lk)
865                 lock->lk = xcalloc(1, sizeof(struct lock_file));
866
867         if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
868                 if (errno == ENOENT && --attempts_remaining > 0) {
869                         /*
870                          * Maybe somebody just deleted one of the
871                          * directories leading to ref_file.  Try
872                          * again:
873                          */
874                         goto retry;
875                 } else {
876                         unable_to_lock_message(ref_file.buf, errno, err);
877                         goto error_return;
878                 }
879         }
880
881         /*
882          * Now we hold the lock and can read the reference without
883          * fear that its value will change.
884          */
885
886         if (files_read_raw_ref(&refs->base, refname,
887                                lock->old_oid.hash, referent, type)) {
888                 if (errno == ENOENT) {
889                         if (mustexist) {
890                                 /* Garden variety missing reference. */
891                                 strbuf_addf(err, "unable to resolve reference '%s'",
892                                             refname);
893                                 goto error_return;
894                         } else {
895                                 /*
896                                  * Reference is missing, but that's OK. We
897                                  * know that there is not a conflict with
898                                  * another loose reference because
899                                  * (supposing that we are trying to lock
900                                  * reference "refs/foo/bar"):
901                                  *
902                                  * - We were successfully able to create
903                                  *   the lockfile refs/foo/bar.lock, so we
904                                  *   know there cannot be a loose reference
905                                  *   named "refs/foo".
906                                  *
907                                  * - We got ENOENT and not EISDIR, so we
908                                  *   know that there cannot be a loose
909                                  *   reference named "refs/foo/bar/baz".
910                                  */
911                         }
912                 } else if (errno == EISDIR) {
913                         /*
914                          * There is a directory in the way. It might have
915                          * contained references that have been deleted. If
916                          * we don't require that the reference already
917                          * exists, try to remove the directory so that it
918                          * doesn't cause trouble when we want to rename the
919                          * lockfile into place later.
920                          */
921                         if (mustexist) {
922                                 /* Garden variety missing reference. */
923                                 strbuf_addf(err, "unable to resolve reference '%s'",
924                                             refname);
925                                 goto error_return;
926                         } else if (remove_dir_recursively(&ref_file,
927                                                           REMOVE_DIR_EMPTY_ONLY)) {
928                                 if (refs_verify_refname_available(
929                                                     &refs->base, refname,
930                                                     extras, skip, err)) {
931                                         /*
932                                          * The error message set by
933                                          * verify_refname_available() is OK.
934                                          */
935                                         ret = TRANSACTION_NAME_CONFLICT;
936                                         goto error_return;
937                                 } else {
938                                         /*
939                                          * We can't delete the directory,
940                                          * but we also don't know of any
941                                          * references that it should
942                                          * contain.
943                                          */
944                                         strbuf_addf(err, "there is a non-empty directory '%s' "
945                                                     "blocking reference '%s'",
946                                                     ref_file.buf, refname);
947                                         goto error_return;
948                                 }
949                         }
950                 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
951                         strbuf_addf(err, "unable to resolve reference '%s': "
952                                     "reference broken", refname);
953                         goto error_return;
954                 } else {
955                         strbuf_addf(err, "unable to resolve reference '%s': %s",
956                                     refname, strerror(errno));
957                         goto error_return;
958                 }
959
960                 /*
961                  * If the ref did not exist and we are creating it,
962                  * make sure there is no existing ref that conflicts
963                  * with refname:
964                  */
965                 if (refs_verify_refname_available(
966                                     &refs->base, refname,
967                                     extras, skip, err))
968                         goto error_return;
969         }
970
971         ret = 0;
972         goto out;
973
974 error_return:
975         unlock_ref(lock);
976         *lock_p = NULL;
977
978 out:
979         strbuf_release(&ref_file);
980         return ret;
981 }
982
983 static int files_peel_ref(struct ref_store *ref_store,
984                           const char *refname, unsigned char *sha1)
985 {
986         struct files_ref_store *refs =
987                 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
988                                "peel_ref");
989         int flag;
990         unsigned char base[20];
991
992         if (current_ref_iter && current_ref_iter->refname == refname) {
993                 struct object_id peeled;
994
995                 if (ref_iterator_peel(current_ref_iter, &peeled))
996                         return -1;
997                 hashcpy(sha1, peeled.hash);
998                 return 0;
999         }
1000
1001         if (refs_read_ref_full(ref_store, refname,
1002                                RESOLVE_REF_READING, base, &flag))
1003                 return -1;
1004
1005         /*
1006          * If the reference is packed, read its ref_entry from the
1007          * cache in the hope that we already know its peeled value.
1008          * We only try this optimization on packed references because
1009          * (a) forcing the filling of the loose reference cache could
1010          * be expensive and (b) loose references anyway usually do not
1011          * have REF_KNOWS_PEELED.
1012          */
1013         if (flag & REF_ISPACKED) {
1014                 struct ref_entry *r = get_packed_ref(refs, refname);
1015                 if (r) {
1016                         if (peel_entry(r, 0))
1017                                 return -1;
1018                         hashcpy(sha1, r->u.value.peeled.hash);
1019                         return 0;
1020                 }
1021         }
1022
1023         return peel_object(base, sha1);
1024 }
1025
1026 struct files_ref_iterator {
1027         struct ref_iterator base;
1028
1029         struct packed_ref_cache *packed_ref_cache;
1030         struct ref_iterator *iter0;
1031         unsigned int flags;
1032 };
1033
1034 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
1035 {
1036         struct files_ref_iterator *iter =
1037                 (struct files_ref_iterator *)ref_iterator;
1038         int ok;
1039
1040         while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1041                 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1042                     ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1043                         continue;
1044
1045                 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1046                     !ref_resolves_to_object(iter->iter0->refname,
1047                                             iter->iter0->oid,
1048                                             iter->iter0->flags))
1049                         continue;
1050
1051                 iter->base.refname = iter->iter0->refname;
1052                 iter->base.oid = iter->iter0->oid;
1053                 iter->base.flags = iter->iter0->flags;
1054                 return ITER_OK;
1055         }
1056
1057         iter->iter0 = NULL;
1058         if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1059                 ok = ITER_ERROR;
1060
1061         return ok;
1062 }
1063
1064 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1065                                    struct object_id *peeled)
1066 {
1067         struct files_ref_iterator *iter =
1068                 (struct files_ref_iterator *)ref_iterator;
1069
1070         return ref_iterator_peel(iter->iter0, peeled);
1071 }
1072
1073 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1074 {
1075         struct files_ref_iterator *iter =
1076                 (struct files_ref_iterator *)ref_iterator;
1077         int ok = ITER_DONE;
1078
1079         if (iter->iter0)
1080                 ok = ref_iterator_abort(iter->iter0);
1081
1082         release_packed_ref_cache(iter->packed_ref_cache);
1083         base_ref_iterator_free(ref_iterator);
1084         return ok;
1085 }
1086
1087 static struct ref_iterator_vtable files_ref_iterator_vtable = {
1088         files_ref_iterator_advance,
1089         files_ref_iterator_peel,
1090         files_ref_iterator_abort
1091 };
1092
1093 static struct ref_iterator *files_ref_iterator_begin(
1094                 struct ref_store *ref_store,
1095                 const char *prefix, unsigned int flags)
1096 {
1097         struct files_ref_store *refs;
1098         struct ref_iterator *loose_iter, *packed_iter;
1099         struct files_ref_iterator *iter;
1100         struct ref_iterator *ref_iterator;
1101         unsigned int required_flags = REF_STORE_READ;
1102
1103         if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
1104                 required_flags |= REF_STORE_ODB;
1105
1106         refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
1107
1108         iter = xcalloc(1, sizeof(*iter));
1109         ref_iterator = &iter->base;
1110         base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1111
1112         /*
1113          * We must make sure that all loose refs are read before
1114          * accessing the packed-refs file; this avoids a race
1115          * condition if loose refs are migrated to the packed-refs
1116          * file by a simultaneous process, but our in-memory view is
1117          * from before the migration. We ensure this as follows:
1118          * First, we call start the loose refs iteration with its
1119          * `prime_ref` argument set to true. This causes the loose
1120          * references in the subtree to be pre-read into the cache.
1121          * (If they've already been read, that's OK; we only need to
1122          * guarantee that they're read before the packed refs, not
1123          * *how much* before.) After that, we call
1124          * get_packed_ref_cache(), which internally checks whether the
1125          * packed-ref cache is up to date with what is on disk, and
1126          * re-reads it if not.
1127          */
1128
1129         loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
1130                                               prefix, 1);
1131
1132         iter->packed_ref_cache = get_packed_ref_cache(refs);
1133         acquire_packed_ref_cache(iter->packed_ref_cache);
1134         packed_iter = cache_ref_iterator_begin(iter->packed_ref_cache->cache,
1135                                                prefix, 0);
1136
1137         iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1138         iter->flags = flags;
1139
1140         return ref_iterator;
1141 }
1142
1143 /*
1144  * Verify that the reference locked by lock has the value old_sha1.
1145  * Fail if the reference doesn't exist and mustexist is set. Return 0
1146  * on success. On error, write an error message to err, set errno, and
1147  * return a negative value.
1148  */
1149 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
1150                        const unsigned char *old_sha1, int mustexist,
1151                        struct strbuf *err)
1152 {
1153         assert(err);
1154
1155         if (refs_read_ref_full(ref_store, lock->ref_name,
1156                                mustexist ? RESOLVE_REF_READING : 0,
1157                                lock->old_oid.hash, NULL)) {
1158                 if (old_sha1) {
1159                         int save_errno = errno;
1160                         strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
1161                         errno = save_errno;
1162                         return -1;
1163                 } else {
1164                         oidclr(&lock->old_oid);
1165                         return 0;
1166                 }
1167         }
1168         if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1169                 strbuf_addf(err, "ref '%s' is at %s but expected %s",
1170                             lock->ref_name,
1171                             oid_to_hex(&lock->old_oid),
1172                             sha1_to_hex(old_sha1));
1173                 errno = EBUSY;
1174                 return -1;
1175         }
1176         return 0;
1177 }
1178
1179 static int remove_empty_directories(struct strbuf *path)
1180 {
1181         /*
1182          * we want to create a file but there is a directory there;
1183          * if that is an empty directory (or a directory that contains
1184          * only empty directories), remove them.
1185          */
1186         return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1187 }
1188
1189 static int create_reflock(const char *path, void *cb)
1190 {
1191         struct lock_file *lk = cb;
1192
1193         return hold_lock_file_for_update(lk, path, LOCK_NO_DEREF) < 0 ? -1 : 0;
1194 }
1195
1196 /*
1197  * Locks a ref returning the lock on success and NULL on failure.
1198  * On failure errno is set to something meaningful.
1199  */
1200 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1201                                             const char *refname,
1202                                             const unsigned char *old_sha1,
1203                                             const struct string_list *extras,
1204                                             const struct string_list *skip,
1205                                             unsigned int flags, int *type,
1206                                             struct strbuf *err)
1207 {
1208         struct strbuf ref_file = STRBUF_INIT;
1209         struct ref_lock *lock;
1210         int last_errno = 0;
1211         int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1212         int resolve_flags = RESOLVE_REF_NO_RECURSE;
1213         int resolved;
1214
1215         files_assert_main_repository(refs, "lock_ref_sha1_basic");
1216         assert(err);
1217
1218         lock = xcalloc(1, sizeof(struct ref_lock));
1219
1220         if (mustexist)
1221                 resolve_flags |= RESOLVE_REF_READING;
1222         if (flags & REF_DELETING)
1223                 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1224
1225         files_ref_path(refs, &ref_file, refname);
1226         resolved = !!refs_resolve_ref_unsafe(&refs->base,
1227                                              refname, resolve_flags,
1228                                              lock->old_oid.hash, type);
1229         if (!resolved && errno == EISDIR) {
1230                 /*
1231                  * we are trying to lock foo but we used to
1232                  * have foo/bar which now does not exist;
1233                  * it is normal for the empty directory 'foo'
1234                  * to remain.
1235                  */
1236                 if (remove_empty_directories(&ref_file)) {
1237                         last_errno = errno;
1238                         if (!refs_verify_refname_available(
1239                                             &refs->base,
1240                                             refname, extras, skip, err))
1241                                 strbuf_addf(err, "there are still refs under '%s'",
1242                                             refname);
1243                         goto error_return;
1244                 }
1245                 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1246                                                      refname, resolve_flags,
1247                                                      lock->old_oid.hash, type);
1248         }
1249         if (!resolved) {
1250                 last_errno = errno;
1251                 if (last_errno != ENOTDIR ||
1252                     !refs_verify_refname_available(&refs->base, refname,
1253                                                    extras, skip, err))
1254                         strbuf_addf(err, "unable to resolve reference '%s': %s",
1255                                     refname, strerror(last_errno));
1256
1257                 goto error_return;
1258         }
1259
1260         /*
1261          * If the ref did not exist and we are creating it, make sure
1262          * there is no existing packed ref whose name begins with our
1263          * refname, nor a packed ref whose name is a proper prefix of
1264          * our refname.
1265          */
1266         if (is_null_oid(&lock->old_oid) &&
1267             refs_verify_refname_available(&refs->base, refname,
1268                                           extras, skip, err)) {
1269                 last_errno = ENOTDIR;
1270                 goto error_return;
1271         }
1272
1273         lock->lk = xcalloc(1, sizeof(struct lock_file));
1274
1275         lock->ref_name = xstrdup(refname);
1276
1277         if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
1278                 last_errno = errno;
1279                 unable_to_lock_message(ref_file.buf, errno, err);
1280                 goto error_return;
1281         }
1282
1283         if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
1284                 last_errno = errno;
1285                 goto error_return;
1286         }
1287         goto out;
1288
1289  error_return:
1290         unlock_ref(lock);
1291         lock = NULL;
1292
1293  out:
1294         strbuf_release(&ref_file);
1295         errno = last_errno;
1296         return lock;
1297 }
1298
1299 /*
1300  * Write an entry to the packed-refs file for the specified refname.
1301  * If peeled is non-NULL, write it as the entry's peeled value.
1302  */
1303 static void write_packed_entry(FILE *fh, const char *refname,
1304                                const unsigned char *sha1,
1305                                const unsigned char *peeled)
1306 {
1307         fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1308         if (peeled)
1309                 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1310 }
1311
1312 /*
1313  * Lock the packed-refs file for writing. Flags is passed to
1314  * hold_lock_file_for_update(). Return 0 on success. On errors, set
1315  * errno appropriately and return a nonzero value.
1316  */
1317 static int lock_packed_refs(struct files_ref_store *refs, int flags)
1318 {
1319         static int timeout_configured = 0;
1320         static int timeout_value = 1000;
1321         struct packed_ref_cache *packed_ref_cache;
1322
1323         files_assert_main_repository(refs, "lock_packed_refs");
1324
1325         if (!timeout_configured) {
1326                 git_config_get_int("core.packedrefstimeout", &timeout_value);
1327                 timeout_configured = 1;
1328         }
1329
1330         if (hold_lock_file_for_update_timeout(
1331                             &refs->packed_refs_lock, files_packed_refs_path(refs),
1332                             flags, timeout_value) < 0)
1333                 return -1;
1334
1335         /*
1336          * Now that we hold the `packed-refs` lock, make sure that our
1337          * cache matches the current version of the file. Normally
1338          * `get_packed_ref_cache()` does that for us, but that
1339          * function assumes that when the file is locked, any existing
1340          * cache is still valid. We've just locked the file, but it
1341          * might have changed the moment *before* we locked it.
1342          */
1343         validate_packed_ref_cache(refs);
1344
1345         packed_ref_cache = get_packed_ref_cache(refs);
1346         /* Increment the reference count to prevent it from being freed: */
1347         acquire_packed_ref_cache(packed_ref_cache);
1348         return 0;
1349 }
1350
1351 /*
1352  * Write the current version of the packed refs cache from memory to
1353  * disk. The packed-refs file must already be locked for writing (see
1354  * lock_packed_refs()). Return zero on success. On errors, set errno
1355  * and return a nonzero value
1356  */
1357 static int commit_packed_refs(struct files_ref_store *refs)
1358 {
1359         struct packed_ref_cache *packed_ref_cache =
1360                 get_packed_ref_cache(refs);
1361         int ok, error = 0;
1362         int save_errno = 0;
1363         FILE *out;
1364         struct ref_iterator *iter;
1365
1366         files_assert_main_repository(refs, "commit_packed_refs");
1367
1368         if (!is_lock_file_locked(&refs->packed_refs_lock))
1369                 die("BUG: packed-refs not locked");
1370
1371         out = fdopen_lock_file(&refs->packed_refs_lock, "w");
1372         if (!out)
1373                 die_errno("unable to fdopen packed-refs descriptor");
1374
1375         fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1376
1377         iter = cache_ref_iterator_begin(packed_ref_cache->cache, NULL, 0);
1378         while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1379                 struct object_id peeled;
1380                 int peel_error = ref_iterator_peel(iter, &peeled);
1381
1382                 write_packed_entry(out, iter->refname, iter->oid->hash,
1383                                    peel_error ? NULL : peeled.hash);
1384         }
1385
1386         if (ok != ITER_DONE)
1387                 die("error while iterating over references");
1388
1389         if (commit_lock_file(&refs->packed_refs_lock)) {
1390                 save_errno = errno;
1391                 error = -1;
1392         }
1393         release_packed_ref_cache(packed_ref_cache);
1394         errno = save_errno;
1395         return error;
1396 }
1397
1398 /*
1399  * Rollback the lockfile for the packed-refs file, and discard the
1400  * in-memory packed reference cache.  (The packed-refs file will be
1401  * read anew if it is needed again after this function is called.)
1402  */
1403 static void rollback_packed_refs(struct files_ref_store *refs)
1404 {
1405         struct packed_ref_cache *packed_ref_cache =
1406                 get_packed_ref_cache(refs);
1407
1408         files_assert_main_repository(refs, "rollback_packed_refs");
1409
1410         if (!is_lock_file_locked(&refs->packed_refs_lock))
1411                 die("BUG: packed-refs not locked");
1412         rollback_lock_file(&refs->packed_refs_lock);
1413         release_packed_ref_cache(packed_ref_cache);
1414         clear_packed_ref_cache(refs);
1415 }
1416
1417 struct ref_to_prune {
1418         struct ref_to_prune *next;
1419         unsigned char sha1[20];
1420         char name[FLEX_ARRAY];
1421 };
1422
1423 enum {
1424         REMOVE_EMPTY_PARENTS_REF = 0x01,
1425         REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1426 };
1427
1428 /*
1429  * Remove empty parent directories associated with the specified
1430  * reference and/or its reflog, but spare [logs/]refs/ and immediate
1431  * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1432  * REMOVE_EMPTY_PARENTS_REFLOG.
1433  */
1434 static void try_remove_empty_parents(struct files_ref_store *refs,
1435                                      const char *refname,
1436                                      unsigned int flags)
1437 {
1438         struct strbuf buf = STRBUF_INIT;
1439         struct strbuf sb = STRBUF_INIT;
1440         char *p, *q;
1441         int i;
1442
1443         strbuf_addstr(&buf, refname);
1444         p = buf.buf;
1445         for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1446                 while (*p && *p != '/')
1447                         p++;
1448                 /* tolerate duplicate slashes; see check_refname_format() */
1449                 while (*p == '/')
1450                         p++;
1451         }
1452         q = buf.buf + buf.len;
1453         while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1454                 while (q > p && *q != '/')
1455                         q--;
1456                 while (q > p && *(q-1) == '/')
1457                         q--;
1458                 if (q == p)
1459                         break;
1460                 strbuf_setlen(&buf, q - buf.buf);
1461
1462                 strbuf_reset(&sb);
1463                 files_ref_path(refs, &sb, buf.buf);
1464                 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1465                         flags &= ~REMOVE_EMPTY_PARENTS_REF;
1466
1467                 strbuf_reset(&sb);
1468                 files_reflog_path(refs, &sb, buf.buf);
1469                 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1470                         flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1471         }
1472         strbuf_release(&buf);
1473         strbuf_release(&sb);
1474 }
1475
1476 /* make sure nobody touched the ref, and unlink */
1477 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1478 {
1479         struct ref_transaction *transaction;
1480         struct strbuf err = STRBUF_INIT;
1481
1482         if (check_refname_format(r->name, 0))
1483                 return;
1484
1485         transaction = ref_store_transaction_begin(&refs->base, &err);
1486         if (!transaction ||
1487             ref_transaction_delete(transaction, r->name, r->sha1,
1488                                    REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1489             ref_transaction_commit(transaction, &err)) {
1490                 ref_transaction_free(transaction);
1491                 error("%s", err.buf);
1492                 strbuf_release(&err);
1493                 return;
1494         }
1495         ref_transaction_free(transaction);
1496         strbuf_release(&err);
1497 }
1498
1499 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1500 {
1501         while (r) {
1502                 prune_ref(refs, r);
1503                 r = r->next;
1504         }
1505 }
1506
1507 /*
1508  * Return true if the specified reference should be packed.
1509  */
1510 static int should_pack_ref(const char *refname,
1511                            const struct object_id *oid, unsigned int ref_flags,
1512                            unsigned int pack_flags)
1513 {
1514         /* Do not pack per-worktree refs: */
1515         if (ref_type(refname) != REF_TYPE_NORMAL)
1516                 return 0;
1517
1518         /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1519         if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1520                 return 0;
1521
1522         /* Do not pack symbolic refs: */
1523         if (ref_flags & REF_ISSYMREF)
1524                 return 0;
1525
1526         /* Do not pack broken refs: */
1527         if (!ref_resolves_to_object(refname, oid, ref_flags))
1528                 return 0;
1529
1530         return 1;
1531 }
1532
1533 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1534 {
1535         struct files_ref_store *refs =
1536                 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1537                                "pack_refs");
1538         struct ref_iterator *iter;
1539         int ok;
1540         struct ref_to_prune *refs_to_prune = NULL;
1541
1542         lock_packed_refs(refs, LOCK_DIE_ON_ERROR);
1543
1544         iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1545         while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1546                 /*
1547                  * If the loose reference can be packed, add an entry
1548                  * in the packed ref cache. If the reference should be
1549                  * pruned, also add it to refs_to_prune.
1550                  */
1551                 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1552                                      flags))
1553                         continue;
1554
1555                 /*
1556                  * Create an entry in the packed-refs cache equivalent
1557                  * to the one from the loose ref cache, except that
1558                  * we don't copy the peeled status, because we want it
1559                  * to be re-peeled.
1560                  */
1561                 add_packed_ref(refs, iter->refname, iter->oid);
1562
1563                 /* Schedule the loose reference for pruning if requested. */
1564                 if ((flags & PACK_REFS_PRUNE)) {
1565                         struct ref_to_prune *n;
1566                         FLEX_ALLOC_STR(n, name, iter->refname);
1567                         hashcpy(n->sha1, iter->oid->hash);
1568                         n->next = refs_to_prune;
1569                         refs_to_prune = n;
1570                 }
1571         }
1572         if (ok != ITER_DONE)
1573                 die("error while iterating over references");
1574
1575         if (commit_packed_refs(refs))
1576                 die_errno("unable to overwrite old ref-pack file");
1577
1578         prune_refs(refs, refs_to_prune);
1579         return 0;
1580 }
1581
1582 /*
1583  * Rewrite the packed-refs file, omitting any refs listed in
1584  * 'refnames'. On error, leave packed-refs unchanged, write an error
1585  * message to 'err', and return a nonzero value.
1586  *
1587  * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
1588  */
1589 static int repack_without_refs(struct files_ref_store *refs,
1590                                struct string_list *refnames, struct strbuf *err)
1591 {
1592         struct ref_dir *packed;
1593         struct string_list_item *refname;
1594         int ret, needs_repacking = 0, removed = 0;
1595
1596         files_assert_main_repository(refs, "repack_without_refs");
1597         assert(err);
1598
1599         /* Look for a packed ref */
1600         for_each_string_list_item(refname, refnames) {
1601                 if (get_packed_ref(refs, refname->string)) {
1602                         needs_repacking = 1;
1603                         break;
1604                 }
1605         }
1606
1607         /* Avoid locking if we have nothing to do */
1608         if (!needs_repacking)
1609                 return 0; /* no refname exists in packed refs */
1610
1611         if (lock_packed_refs(refs, 0)) {
1612                 unable_to_lock_message(files_packed_refs_path(refs), errno, err);
1613                 return -1;
1614         }
1615         packed = get_packed_refs(refs);
1616
1617         /* Remove refnames from the cache */
1618         for_each_string_list_item(refname, refnames)
1619                 if (remove_entry_from_dir(packed, refname->string) != -1)
1620                         removed = 1;
1621         if (!removed) {
1622                 /*
1623                  * All packed entries disappeared while we were
1624                  * acquiring the lock.
1625                  */
1626                 rollback_packed_refs(refs);
1627                 return 0;
1628         }
1629
1630         /* Write what remains */
1631         ret = commit_packed_refs(refs);
1632         if (ret)
1633                 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
1634                             strerror(errno));
1635         return ret;
1636 }
1637
1638 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1639                              struct string_list *refnames, unsigned int flags)
1640 {
1641         struct files_ref_store *refs =
1642                 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1643         struct strbuf err = STRBUF_INIT;
1644         int i, result = 0;
1645
1646         if (!refnames->nr)
1647                 return 0;
1648
1649         result = repack_without_refs(refs, refnames, &err);
1650         if (result) {
1651                 /*
1652                  * If we failed to rewrite the packed-refs file, then
1653                  * it is unsafe to try to remove loose refs, because
1654                  * doing so might expose an obsolete packed value for
1655                  * a reference that might even point at an object that
1656                  * has been garbage collected.
1657                  */
1658                 if (refnames->nr == 1)
1659                         error(_("could not delete reference %s: %s"),
1660                               refnames->items[0].string, err.buf);
1661                 else
1662                         error(_("could not delete references: %s"), err.buf);
1663
1664                 goto out;
1665         }
1666
1667         for (i = 0; i < refnames->nr; i++) {
1668                 const char *refname = refnames->items[i].string;
1669
1670                 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1671                         result |= error(_("could not remove reference %s"), refname);
1672         }
1673
1674 out:
1675         strbuf_release(&err);
1676         return result;
1677 }
1678
1679 /*
1680  * People using contrib's git-new-workdir have .git/logs/refs ->
1681  * /some/other/path/.git/logs/refs, and that may live on another device.
1682  *
1683  * IOW, to avoid cross device rename errors, the temporary renamed log must
1684  * live into logs/refs.
1685  */
1686 #define TMP_RENAMED_LOG  "refs/.tmp-renamed-log"
1687
1688 struct rename_cb {
1689         const char *tmp_renamed_log;
1690         int true_errno;
1691 };
1692
1693 static int rename_tmp_log_callback(const char *path, void *cb_data)
1694 {
1695         struct rename_cb *cb = cb_data;
1696
1697         if (rename(cb->tmp_renamed_log, path)) {
1698                 /*
1699                  * rename(a, b) when b is an existing directory ought
1700                  * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1701                  * Sheesh. Record the true errno for error reporting,
1702                  * but report EISDIR to raceproof_create_file() so
1703                  * that it knows to retry.
1704                  */
1705                 cb->true_errno = errno;
1706                 if (errno == ENOTDIR)
1707                         errno = EISDIR;
1708                 return -1;
1709         } else {
1710                 return 0;
1711         }
1712 }
1713
1714 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1715 {
1716         struct strbuf path = STRBUF_INIT;
1717         struct strbuf tmp = STRBUF_INIT;
1718         struct rename_cb cb;
1719         int ret;
1720
1721         files_reflog_path(refs, &path, newrefname);
1722         files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1723         cb.tmp_renamed_log = tmp.buf;
1724         ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1725         if (ret) {
1726                 if (errno == EISDIR)
1727                         error("directory not empty: %s", path.buf);
1728                 else
1729                         error("unable to move logfile %s to %s: %s",
1730                               tmp.buf, path.buf,
1731                               strerror(cb.true_errno));
1732         }
1733
1734         strbuf_release(&path);
1735         strbuf_release(&tmp);
1736         return ret;
1737 }
1738
1739 static int write_ref_to_lockfile(struct ref_lock *lock,
1740                                  const struct object_id *oid, struct strbuf *err);
1741 static int commit_ref_update(struct files_ref_store *refs,
1742                              struct ref_lock *lock,
1743                              const struct object_id *oid, const char *logmsg,
1744                              struct strbuf *err);
1745
1746 static int files_rename_ref(struct ref_store *ref_store,
1747                             const char *oldrefname, const char *newrefname,
1748                             const char *logmsg)
1749 {
1750         struct files_ref_store *refs =
1751                 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1752         struct object_id oid, orig_oid;
1753         int flag = 0, logmoved = 0;
1754         struct ref_lock *lock;
1755         struct stat loginfo;
1756         struct strbuf sb_oldref = STRBUF_INIT;
1757         struct strbuf sb_newref = STRBUF_INIT;
1758         struct strbuf tmp_renamed_log = STRBUF_INIT;
1759         int log, ret;
1760         struct strbuf err = STRBUF_INIT;
1761
1762         files_reflog_path(refs, &sb_oldref, oldrefname);
1763         files_reflog_path(refs, &sb_newref, newrefname);
1764         files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1765
1766         log = !lstat(sb_oldref.buf, &loginfo);
1767         if (log && S_ISLNK(loginfo.st_mode)) {
1768                 ret = error("reflog for %s is a symlink", oldrefname);
1769                 goto out;
1770         }
1771
1772         if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1773                                      RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1774                                 orig_oid.hash, &flag)) {
1775                 ret = error("refname %s not found", oldrefname);
1776                 goto out;
1777         }
1778
1779         if (flag & REF_ISSYMREF) {
1780                 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1781                             oldrefname);
1782                 goto out;
1783         }
1784         if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1785                 ret = 1;
1786                 goto out;
1787         }
1788
1789         if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1790                 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1791                             oldrefname, strerror(errno));
1792                 goto out;
1793         }
1794
1795         if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1796                             orig_oid.hash, REF_NODEREF)) {
1797                 error("unable to delete old %s", oldrefname);
1798                 goto rollback;
1799         }
1800
1801         /*
1802          * Since we are doing a shallow lookup, oid is not the
1803          * correct value to pass to delete_ref as old_oid. But that
1804          * doesn't matter, because an old_oid check wouldn't add to
1805          * the safety anyway; we want to delete the reference whatever
1806          * its current value.
1807          */
1808         if (!refs_read_ref_full(&refs->base, newrefname,
1809                                 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1810                                 oid.hash, NULL) &&
1811             refs_delete_ref(&refs->base, NULL, newrefname,
1812                             NULL, REF_NODEREF)) {
1813                 if (errno == EISDIR) {
1814                         struct strbuf path = STRBUF_INIT;
1815                         int result;
1816
1817                         files_ref_path(refs, &path, newrefname);
1818                         result = remove_empty_directories(&path);
1819                         strbuf_release(&path);
1820
1821                         if (result) {
1822                                 error("Directory not empty: %s", newrefname);
1823                                 goto rollback;
1824                         }
1825                 } else {
1826                         error("unable to delete existing %s", newrefname);
1827                         goto rollback;
1828                 }
1829         }
1830
1831         if (log && rename_tmp_log(refs, newrefname))
1832                 goto rollback;
1833
1834         logmoved = log;
1835
1836         lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1837                                    REF_NODEREF, NULL, &err);
1838         if (!lock) {
1839                 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1840                 strbuf_release(&err);
1841                 goto rollback;
1842         }
1843         oidcpy(&lock->old_oid, &orig_oid);
1844
1845         if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1846             commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1847                 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1848                 strbuf_release(&err);
1849                 goto rollback;
1850         }
1851
1852         ret = 0;
1853         goto out;
1854
1855  rollback:
1856         lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1857                                    REF_NODEREF, NULL, &err);
1858         if (!lock) {
1859                 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1860                 strbuf_release(&err);
1861                 goto rollbacklog;
1862         }
1863
1864         flag = log_all_ref_updates;
1865         log_all_ref_updates = LOG_REFS_NONE;
1866         if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1867             commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1868                 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1869                 strbuf_release(&err);
1870         }
1871         log_all_ref_updates = flag;
1872
1873  rollbacklog:
1874         if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1875                 error("unable to restore logfile %s from %s: %s",
1876                         oldrefname, newrefname, strerror(errno));
1877         if (!logmoved && log &&
1878             rename(tmp_renamed_log.buf, sb_oldref.buf))
1879                 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1880                         oldrefname, strerror(errno));
1881         ret = 1;
1882  out:
1883         strbuf_release(&sb_newref);
1884         strbuf_release(&sb_oldref);
1885         strbuf_release(&tmp_renamed_log);
1886
1887         return ret;
1888 }
1889
1890 static int close_ref(struct ref_lock *lock)
1891 {
1892         if (close_lock_file(lock->lk))
1893                 return -1;
1894         return 0;
1895 }
1896
1897 static int commit_ref(struct ref_lock *lock)
1898 {
1899         char *path = get_locked_file_path(lock->lk);
1900         struct stat st;
1901
1902         if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1903                 /*
1904                  * There is a directory at the path we want to rename
1905                  * the lockfile to. Hopefully it is empty; try to
1906                  * delete it.
1907                  */
1908                 size_t len = strlen(path);
1909                 struct strbuf sb_path = STRBUF_INIT;
1910
1911                 strbuf_attach(&sb_path, path, len, len);
1912
1913                 /*
1914                  * If this fails, commit_lock_file() will also fail
1915                  * and will report the problem.
1916                  */
1917                 remove_empty_directories(&sb_path);
1918                 strbuf_release(&sb_path);
1919         } else {
1920                 free(path);
1921         }
1922
1923         if (commit_lock_file(lock->lk))
1924                 return -1;
1925         return 0;
1926 }
1927
1928 static int open_or_create_logfile(const char *path, void *cb)
1929 {
1930         int *fd = cb;
1931
1932         *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1933         return (*fd < 0) ? -1 : 0;
1934 }
1935
1936 /*
1937  * Create a reflog for a ref. If force_create = 0, only create the
1938  * reflog for certain refs (those for which should_autocreate_reflog
1939  * returns non-zero). Otherwise, create it regardless of the reference
1940  * name. If the logfile already existed or was created, return 0 and
1941  * set *logfd to the file descriptor opened for appending to the file.
1942  * If no logfile exists and we decided not to create one, return 0 and
1943  * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1944  * return -1.
1945  */
1946 static int log_ref_setup(struct files_ref_store *refs,
1947                          const char *refname, int force_create,
1948                          int *logfd, struct strbuf *err)
1949 {
1950         struct strbuf logfile_sb = STRBUF_INIT;
1951         char *logfile;
1952
1953         files_reflog_path(refs, &logfile_sb, refname);
1954         logfile = strbuf_detach(&logfile_sb, NULL);
1955
1956         if (force_create || should_autocreate_reflog(refname)) {
1957                 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1958                         if (errno == ENOENT)
1959                                 strbuf_addf(err, "unable to create directory for '%s': "
1960                                             "%s", logfile, strerror(errno));
1961                         else if (errno == EISDIR)
1962                                 strbuf_addf(err, "there are still logs under '%s'",
1963                                             logfile);
1964                         else
1965                                 strbuf_addf(err, "unable to append to '%s': %s",
1966                                             logfile, strerror(errno));
1967
1968                         goto error;
1969                 }
1970         } else {
1971                 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1972                 if (*logfd < 0) {
1973                         if (errno == ENOENT || errno == EISDIR) {
1974                                 /*
1975                                  * The logfile doesn't already exist,
1976                                  * but that is not an error; it only
1977                                  * means that we won't write log
1978                                  * entries to it.
1979                                  */
1980                                 ;
1981                         } else {
1982                                 strbuf_addf(err, "unable to append to '%s': %s",
1983                                             logfile, strerror(errno));
1984                                 goto error;
1985                         }
1986                 }
1987         }
1988
1989         if (*logfd >= 0)
1990                 adjust_shared_perm(logfile);
1991
1992         free(logfile);
1993         return 0;
1994
1995 error:
1996         free(logfile);
1997         return -1;
1998 }
1999
2000 static int files_create_reflog(struct ref_store *ref_store,
2001                                const char *refname, int force_create,
2002                                struct strbuf *err)
2003 {
2004         struct files_ref_store *refs =
2005                 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
2006         int fd;
2007
2008         if (log_ref_setup(refs, refname, force_create, &fd, err))
2009                 return -1;
2010
2011         if (fd >= 0)
2012                 close(fd);
2013
2014         return 0;
2015 }
2016
2017 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
2018                             const struct object_id *new_oid,
2019                             const char *committer, const char *msg)
2020 {
2021         int msglen, written;
2022         unsigned maxlen, len;
2023         char *logrec;
2024
2025         msglen = msg ? strlen(msg) : 0;
2026         maxlen = strlen(committer) + msglen + 100;
2027         logrec = xmalloc(maxlen);
2028         len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2029                         oid_to_hex(old_oid),
2030                         oid_to_hex(new_oid),
2031                         committer);
2032         if (msglen)
2033                 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2034
2035         written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2036         free(logrec);
2037         if (written != len)
2038                 return -1;
2039
2040         return 0;
2041 }
2042
2043 static int files_log_ref_write(struct files_ref_store *refs,
2044                                const char *refname, const struct object_id *old_oid,
2045                                const struct object_id *new_oid, const char *msg,
2046                                int flags, struct strbuf *err)
2047 {
2048         int logfd, result;
2049
2050         if (log_all_ref_updates == LOG_REFS_UNSET)
2051                 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
2052
2053         result = log_ref_setup(refs, refname,
2054                                flags & REF_FORCE_CREATE_REFLOG,
2055                                &logfd, err);
2056
2057         if (result)
2058                 return result;
2059
2060         if (logfd < 0)
2061                 return 0;
2062         result = log_ref_write_fd(logfd, old_oid, new_oid,
2063                                   git_committer_info(0), msg);
2064         if (result) {
2065                 struct strbuf sb = STRBUF_INIT;
2066                 int save_errno = errno;
2067
2068                 files_reflog_path(refs, &sb, refname);
2069                 strbuf_addf(err, "unable to append to '%s': %s",
2070                             sb.buf, strerror(save_errno));
2071                 strbuf_release(&sb);
2072                 close(logfd);
2073                 return -1;
2074         }
2075         if (close(logfd)) {
2076                 struct strbuf sb = STRBUF_INIT;
2077                 int save_errno = errno;
2078
2079                 files_reflog_path(refs, &sb, refname);
2080                 strbuf_addf(err, "unable to append to '%s': %s",
2081                             sb.buf, strerror(save_errno));
2082                 strbuf_release(&sb);
2083                 return -1;
2084         }
2085         return 0;
2086 }
2087
2088 /*
2089  * Write sha1 into the open lockfile, then close the lockfile. On
2090  * errors, rollback the lockfile, fill in *err and
2091  * return -1.
2092  */
2093 static int write_ref_to_lockfile(struct ref_lock *lock,
2094                                  const struct object_id *oid, struct strbuf *err)
2095 {
2096         static char term = '\n';
2097         struct object *o;
2098         int fd;
2099
2100         o = parse_object(oid);
2101         if (!o) {
2102                 strbuf_addf(err,
2103                             "trying to write ref '%s' with nonexistent object %s",
2104                             lock->ref_name, oid_to_hex(oid));
2105                 unlock_ref(lock);
2106                 return -1;
2107         }
2108         if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2109                 strbuf_addf(err,
2110                             "trying to write non-commit object %s to branch '%s'",
2111                             oid_to_hex(oid), lock->ref_name);
2112                 unlock_ref(lock);
2113                 return -1;
2114         }
2115         fd = get_lock_file_fd(lock->lk);
2116         if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2117             write_in_full(fd, &term, 1) != 1 ||
2118             close_ref(lock) < 0) {
2119                 strbuf_addf(err,
2120                             "couldn't write '%s'", get_lock_file_path(lock->lk));
2121                 unlock_ref(lock);
2122                 return -1;
2123         }
2124         return 0;
2125 }
2126
2127 /*
2128  * Commit a change to a loose reference that has already been written
2129  * to the loose reference lockfile. Also update the reflogs if
2130  * necessary, using the specified lockmsg (which can be NULL).
2131  */
2132 static int commit_ref_update(struct files_ref_store *refs,
2133                              struct ref_lock *lock,
2134                              const struct object_id *oid, const char *logmsg,
2135                              struct strbuf *err)
2136 {
2137         files_assert_main_repository(refs, "commit_ref_update");
2138
2139         clear_loose_ref_cache(refs);
2140         if (files_log_ref_write(refs, lock->ref_name,
2141                                 &lock->old_oid, oid,
2142                                 logmsg, 0, err)) {
2143                 char *old_msg = strbuf_detach(err, NULL);
2144                 strbuf_addf(err, "cannot update the ref '%s': %s",
2145                             lock->ref_name, old_msg);
2146                 free(old_msg);
2147                 unlock_ref(lock);
2148                 return -1;
2149         }
2150
2151         if (strcmp(lock->ref_name, "HEAD") != 0) {
2152                 /*
2153                  * Special hack: If a branch is updated directly and HEAD
2154                  * points to it (may happen on the remote side of a push
2155                  * for example) then logically the HEAD reflog should be
2156                  * updated too.
2157                  * A generic solution implies reverse symref information,
2158                  * but finding all symrefs pointing to the given branch
2159                  * would be rather costly for this rare event (the direct
2160                  * update of a branch) to be worth it.  So let's cheat and
2161                  * check with HEAD only which should cover 99% of all usage
2162                  * scenarios (even 100% of the default ones).
2163                  */
2164                 struct object_id head_oid;
2165                 int head_flag;
2166                 const char *head_ref;
2167
2168                 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2169                                                    RESOLVE_REF_READING,
2170                                                    head_oid.hash, &head_flag);
2171                 if (head_ref && (head_flag & REF_ISSYMREF) &&
2172                     !strcmp(head_ref, lock->ref_name)) {
2173                         struct strbuf log_err = STRBUF_INIT;
2174                         if (files_log_ref_write(refs, "HEAD",
2175                                                 &lock->old_oid, oid,
2176                                                 logmsg, 0, &log_err)) {
2177                                 error("%s", log_err.buf);
2178                                 strbuf_release(&log_err);
2179                         }
2180                 }
2181         }
2182
2183         if (commit_ref(lock)) {
2184                 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2185                 unlock_ref(lock);
2186                 return -1;
2187         }
2188
2189         unlock_ref(lock);
2190         return 0;
2191 }
2192
2193 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2194 {
2195         int ret = -1;
2196 #ifndef NO_SYMLINK_HEAD
2197         char *ref_path = get_locked_file_path(lock->lk);
2198         unlink(ref_path);
2199         ret = symlink(target, ref_path);
2200         free(ref_path);
2201
2202         if (ret)
2203                 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2204 #endif
2205         return ret;
2206 }
2207
2208 static void update_symref_reflog(struct files_ref_store *refs,
2209                                  struct ref_lock *lock, const char *refname,
2210                                  const char *target, const char *logmsg)
2211 {
2212         struct strbuf err = STRBUF_INIT;
2213         struct object_id new_oid;
2214         if (logmsg &&
2215             !refs_read_ref_full(&refs->base, target,
2216                                 RESOLVE_REF_READING, new_oid.hash, NULL) &&
2217             files_log_ref_write(refs, refname, &lock->old_oid,
2218                                 &new_oid, logmsg, 0, &err)) {
2219                 error("%s", err.buf);
2220                 strbuf_release(&err);
2221         }
2222 }
2223
2224 static int create_symref_locked(struct files_ref_store *refs,
2225                                 struct ref_lock *lock, const char *refname,
2226                                 const char *target, const char *logmsg)
2227 {
2228         if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2229                 update_symref_reflog(refs, lock, refname, target, logmsg);
2230                 return 0;
2231         }
2232
2233         if (!fdopen_lock_file(lock->lk, "w"))
2234                 return error("unable to fdopen %s: %s",
2235                              lock->lk->tempfile.filename.buf, strerror(errno));
2236
2237         update_symref_reflog(refs, lock, refname, target, logmsg);
2238
2239         /* no error check; commit_ref will check ferror */
2240         fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2241         if (commit_ref(lock) < 0)
2242                 return error("unable to write symref for %s: %s", refname,
2243                              strerror(errno));
2244         return 0;
2245 }
2246
2247 static int files_create_symref(struct ref_store *ref_store,
2248                                const char *refname, const char *target,
2249                                const char *logmsg)
2250 {
2251         struct files_ref_store *refs =
2252                 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
2253         struct strbuf err = STRBUF_INIT;
2254         struct ref_lock *lock;
2255         int ret;
2256
2257         lock = lock_ref_sha1_basic(refs, refname, NULL,
2258                                    NULL, NULL, REF_NODEREF, NULL,
2259                                    &err);
2260         if (!lock) {
2261                 error("%s", err.buf);
2262                 strbuf_release(&err);
2263                 return -1;
2264         }
2265
2266         ret = create_symref_locked(refs, lock, refname, target, logmsg);
2267         unlock_ref(lock);
2268         return ret;
2269 }
2270
2271 static int files_reflog_exists(struct ref_store *ref_store,
2272                                const char *refname)
2273 {
2274         struct files_ref_store *refs =
2275                 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
2276         struct strbuf sb = STRBUF_INIT;
2277         struct stat st;
2278         int ret;
2279
2280         files_reflog_path(refs, &sb, refname);
2281         ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2282         strbuf_release(&sb);
2283         return ret;
2284 }
2285
2286 static int files_delete_reflog(struct ref_store *ref_store,
2287                                const char *refname)
2288 {
2289         struct files_ref_store *refs =
2290                 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
2291         struct strbuf sb = STRBUF_INIT;
2292         int ret;
2293
2294         files_reflog_path(refs, &sb, refname);
2295         ret = remove_path(sb.buf);
2296         strbuf_release(&sb);
2297         return ret;
2298 }
2299
2300 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2301 {
2302         struct object_id ooid, noid;
2303         char *email_end, *message;
2304         timestamp_t timestamp;
2305         int tz;
2306         const char *p = sb->buf;
2307
2308         /* old SP new SP name <email> SP time TAB msg LF */
2309         if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2310             parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
2311             parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
2312             !(email_end = strchr(p, '>')) ||
2313             email_end[1] != ' ' ||
2314             !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
2315             !message || message[0] != ' ' ||
2316             (message[1] != '+' && message[1] != '-') ||
2317             !isdigit(message[2]) || !isdigit(message[3]) ||
2318             !isdigit(message[4]) || !isdigit(message[5]))
2319                 return 0; /* corrupt? */
2320         email_end[1] = '\0';
2321         tz = strtol(message + 1, NULL, 10);
2322         if (message[6] != '\t')
2323                 message += 6;
2324         else
2325                 message += 7;
2326         return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
2327 }
2328
2329 static char *find_beginning_of_line(char *bob, char *scan)
2330 {
2331         while (bob < scan && *(--scan) != '\n')
2332                 ; /* keep scanning backwards */
2333         /*
2334          * Return either beginning of the buffer, or LF at the end of
2335          * the previous line.
2336          */
2337         return scan;
2338 }
2339
2340 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2341                                              const char *refname,
2342                                              each_reflog_ent_fn fn,
2343                                              void *cb_data)
2344 {
2345         struct files_ref_store *refs =
2346                 files_downcast(ref_store, REF_STORE_READ,
2347                                "for_each_reflog_ent_reverse");
2348         struct strbuf sb = STRBUF_INIT;
2349         FILE *logfp;
2350         long pos;
2351         int ret = 0, at_tail = 1;
2352
2353         files_reflog_path(refs, &sb, refname);
2354         logfp = fopen(sb.buf, "r");
2355         strbuf_release(&sb);
2356         if (!logfp)
2357                 return -1;
2358
2359         /* Jump to the end */
2360         if (fseek(logfp, 0, SEEK_END) < 0)
2361                 ret = error("cannot seek back reflog for %s: %s",
2362                             refname, strerror(errno));
2363         pos = ftell(logfp);
2364         while (!ret && 0 < pos) {
2365                 int cnt;
2366                 size_t nread;
2367                 char buf[BUFSIZ];
2368                 char *endp, *scanp;
2369
2370                 /* Fill next block from the end */
2371                 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2372                 if (fseek(logfp, pos - cnt, SEEK_SET)) {
2373                         ret = error("cannot seek back reflog for %s: %s",
2374                                     refname, strerror(errno));
2375                         break;
2376                 }
2377                 nread = fread(buf, cnt, 1, logfp);
2378                 if (nread != 1) {
2379                         ret = error("cannot read %d bytes from reflog for %s: %s",
2380                                     cnt, refname, strerror(errno));
2381                         break;
2382                 }
2383                 pos -= cnt;
2384
2385                 scanp = endp = buf + cnt;
2386                 if (at_tail && scanp[-1] == '\n')
2387                         /* Looking at the final LF at the end of the file */
2388                         scanp--;
2389                 at_tail = 0;
2390
2391                 while (buf < scanp) {
2392                         /*
2393                          * terminating LF of the previous line, or the beginning
2394                          * of the buffer.
2395                          */
2396                         char *bp;
2397
2398                         bp = find_beginning_of_line(buf, scanp);
2399
2400                         if (*bp == '\n') {
2401                                 /*
2402                                  * The newline is the end of the previous line,
2403                                  * so we know we have complete line starting
2404                                  * at (bp + 1). Prefix it onto any prior data
2405                                  * we collected for the line and process it.
2406                                  */
2407                                 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2408                                 scanp = bp;
2409                                 endp = bp + 1;
2410                                 ret = show_one_reflog_ent(&sb, fn, cb_data);
2411                                 strbuf_reset(&sb);
2412                                 if (ret)
2413                                         break;
2414                         } else if (!pos) {
2415                                 /*
2416                                  * We are at the start of the buffer, and the
2417                                  * start of the file; there is no previous
2418                                  * line, and we have everything for this one.
2419                                  * Process it, and we can end the loop.
2420                                  */
2421                                 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2422                                 ret = show_one_reflog_ent(&sb, fn, cb_data);
2423                                 strbuf_reset(&sb);
2424                                 break;
2425                         }
2426
2427                         if (bp == buf) {
2428                                 /*
2429                                  * We are at the start of the buffer, and there
2430                                  * is more file to read backwards. Which means
2431                                  * we are in the middle of a line. Note that we
2432                                  * may get here even if *bp was a newline; that
2433                                  * just means we are at the exact end of the
2434                                  * previous line, rather than some spot in the
2435                                  * middle.
2436                                  *
2437                                  * Save away what we have to be combined with
2438                                  * the data from the next read.
2439                                  */
2440                                 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2441                                 break;
2442                         }
2443                 }
2444
2445         }
2446         if (!ret && sb.len)
2447                 die("BUG: reverse reflog parser had leftover data");
2448
2449         fclose(logfp);
2450         strbuf_release(&sb);
2451         return ret;
2452 }
2453
2454 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2455                                      const char *refname,
2456                                      each_reflog_ent_fn fn, void *cb_data)
2457 {
2458         struct files_ref_store *refs =
2459                 files_downcast(ref_store, REF_STORE_READ,
2460                                "for_each_reflog_ent");
2461         FILE *logfp;
2462         struct strbuf sb = STRBUF_INIT;
2463         int ret = 0;
2464
2465         files_reflog_path(refs, &sb, refname);
2466         logfp = fopen(sb.buf, "r");
2467         strbuf_release(&sb);
2468         if (!logfp)
2469                 return -1;
2470
2471         while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2472                 ret = show_one_reflog_ent(&sb, fn, cb_data);
2473         fclose(logfp);
2474         strbuf_release(&sb);
2475         return ret;
2476 }
2477
2478 struct files_reflog_iterator {
2479         struct ref_iterator base;
2480
2481         struct ref_store *ref_store;
2482         struct dir_iterator *dir_iterator;
2483         struct object_id oid;
2484 };
2485
2486 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2487 {
2488         struct files_reflog_iterator *iter =
2489                 (struct files_reflog_iterator *)ref_iterator;
2490         struct dir_iterator *diter = iter->dir_iterator;
2491         int ok;
2492
2493         while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2494                 int flags;
2495
2496                 if (!S_ISREG(diter->st.st_mode))
2497                         continue;
2498                 if (diter->basename[0] == '.')
2499                         continue;
2500                 if (ends_with(diter->basename, ".lock"))
2501                         continue;
2502
2503                 if (refs_read_ref_full(iter->ref_store,
2504                                        diter->relative_path, 0,
2505                                        iter->oid.hash, &flags)) {
2506                         error("bad ref for %s", diter->path.buf);
2507                         continue;
2508                 }
2509
2510                 iter->base.refname = diter->relative_path;
2511                 iter->base.oid = &iter->oid;
2512                 iter->base.flags = flags;
2513                 return ITER_OK;
2514         }
2515
2516         iter->dir_iterator = NULL;
2517         if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2518                 ok = ITER_ERROR;
2519         return ok;
2520 }
2521
2522 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2523                                    struct object_id *peeled)
2524 {
2525         die("BUG: ref_iterator_peel() called for reflog_iterator");
2526 }
2527
2528 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2529 {
2530         struct files_reflog_iterator *iter =
2531                 (struct files_reflog_iterator *)ref_iterator;
2532         int ok = ITER_DONE;
2533
2534         if (iter->dir_iterator)
2535                 ok = dir_iterator_abort(iter->dir_iterator);
2536
2537         base_ref_iterator_free(ref_iterator);
2538         return ok;
2539 }
2540
2541 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2542         files_reflog_iterator_advance,
2543         files_reflog_iterator_peel,
2544         files_reflog_iterator_abort
2545 };
2546
2547 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2548 {
2549         struct files_ref_store *refs =
2550                 files_downcast(ref_store, REF_STORE_READ,
2551                                "reflog_iterator_begin");
2552         struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2553         struct ref_iterator *ref_iterator = &iter->base;
2554         struct strbuf sb = STRBUF_INIT;
2555
2556         base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2557         files_reflog_path(refs, &sb, NULL);
2558         iter->dir_iterator = dir_iterator_begin(sb.buf);
2559         iter->ref_store = ref_store;
2560         strbuf_release(&sb);
2561         return ref_iterator;
2562 }
2563
2564 /*
2565  * If update is a direct update of head_ref (the reference pointed to
2566  * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2567  */
2568 static int split_head_update(struct ref_update *update,
2569                              struct ref_transaction *transaction,
2570                              const char *head_ref,
2571                              struct string_list *affected_refnames,
2572                              struct strbuf *err)
2573 {
2574         struct string_list_item *item;
2575         struct ref_update *new_update;
2576
2577         if ((update->flags & REF_LOG_ONLY) ||
2578             (update->flags & REF_ISPRUNING) ||
2579             (update->flags & REF_UPDATE_VIA_HEAD))
2580                 return 0;
2581
2582         if (strcmp(update->refname, head_ref))
2583                 return 0;
2584
2585         /*
2586          * First make sure that HEAD is not already in the
2587          * transaction. This insertion is O(N) in the transaction
2588          * size, but it happens at most once per transaction.
2589          */
2590         item = string_list_insert(affected_refnames, "HEAD");
2591         if (item->util) {
2592                 /* An entry already existed */
2593                 strbuf_addf(err,
2594                             "multiple updates for 'HEAD' (including one "
2595                             "via its referent '%s') are not allowed",
2596                             update->refname);
2597                 return TRANSACTION_NAME_CONFLICT;
2598         }
2599
2600         new_update = ref_transaction_add_update(
2601                         transaction, "HEAD",
2602                         update->flags | REF_LOG_ONLY | REF_NODEREF,
2603                         update->new_oid.hash, update->old_oid.hash,
2604                         update->msg);
2605
2606         item->util = new_update;
2607
2608         return 0;
2609 }
2610
2611 /*
2612  * update is for a symref that points at referent and doesn't have
2613  * REF_NODEREF set. Split it into two updates:
2614  * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2615  * - A new, separate update for the referent reference
2616  * Note that the new update will itself be subject to splitting when
2617  * the iteration gets to it.
2618  */
2619 static int split_symref_update(struct files_ref_store *refs,
2620                                struct ref_update *update,
2621                                const char *referent,
2622                                struct ref_transaction *transaction,
2623                                struct string_list *affected_refnames,
2624                                struct strbuf *err)
2625 {
2626         struct string_list_item *item;
2627         struct ref_update *new_update;
2628         unsigned int new_flags;
2629
2630         /*
2631          * First make sure that referent is not already in the
2632          * transaction. This insertion is O(N) in the transaction
2633          * size, but it happens at most once per symref in a
2634          * transaction.
2635          */
2636         item = string_list_insert(affected_refnames, referent);
2637         if (item->util) {
2638                 /* An entry already existed */
2639                 strbuf_addf(err,
2640                             "multiple updates for '%s' (including one "
2641                             "via symref '%s') are not allowed",
2642                             referent, update->refname);
2643                 return TRANSACTION_NAME_CONFLICT;
2644         }
2645
2646         new_flags = update->flags;
2647         if (!strcmp(update->refname, "HEAD")) {
2648                 /*
2649                  * Record that the new update came via HEAD, so that
2650                  * when we process it, split_head_update() doesn't try
2651                  * to add another reflog update for HEAD. Note that
2652                  * this bit will be propagated if the new_update
2653                  * itself needs to be split.
2654                  */
2655                 new_flags |= REF_UPDATE_VIA_HEAD;
2656         }
2657
2658         new_update = ref_transaction_add_update(
2659                         transaction, referent, new_flags,
2660                         update->new_oid.hash, update->old_oid.hash,
2661                         update->msg);
2662
2663         new_update->parent_update = update;
2664
2665         /*
2666          * Change the symbolic ref update to log only. Also, it
2667          * doesn't need to check its old SHA-1 value, as that will be
2668          * done when new_update is processed.
2669          */
2670         update->flags |= REF_LOG_ONLY | REF_NODEREF;
2671         update->flags &= ~REF_HAVE_OLD;
2672
2673         item->util = new_update;
2674
2675         return 0;
2676 }
2677
2678 /*
2679  * Return the refname under which update was originally requested.
2680  */
2681 static const char *original_update_refname(struct ref_update *update)
2682 {
2683         while (update->parent_update)
2684                 update = update->parent_update;
2685
2686         return update->refname;
2687 }
2688
2689 /*
2690  * Check whether the REF_HAVE_OLD and old_oid values stored in update
2691  * are consistent with oid, which is the reference's current value. If
2692  * everything is OK, return 0; otherwise, write an error message to
2693  * err and return -1.
2694  */
2695 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2696                          struct strbuf *err)
2697 {
2698         if (!(update->flags & REF_HAVE_OLD) ||
2699                    !oidcmp(oid, &update->old_oid))
2700                 return 0;
2701
2702         if (is_null_oid(&update->old_oid))
2703                 strbuf_addf(err, "cannot lock ref '%s': "
2704                             "reference already exists",
2705                             original_update_refname(update));
2706         else if (is_null_oid(oid))
2707                 strbuf_addf(err, "cannot lock ref '%s': "
2708                             "reference is missing but expected %s",
2709                             original_update_refname(update),
2710                             oid_to_hex(&update->old_oid));
2711         else
2712                 strbuf_addf(err, "cannot lock ref '%s': "
2713                             "is at %s but expected %s",
2714                             original_update_refname(update),
2715                             oid_to_hex(oid),
2716                             oid_to_hex(&update->old_oid));
2717
2718         return -1;
2719 }
2720
2721 /*
2722  * Prepare for carrying out update:
2723  * - Lock the reference referred to by update.
2724  * - Read the reference under lock.
2725  * - Check that its old SHA-1 value (if specified) is correct, and in
2726  *   any case record it in update->lock->old_oid for later use when
2727  *   writing the reflog.
2728  * - If it is a symref update without REF_NODEREF, split it up into a
2729  *   REF_LOG_ONLY update of the symref and add a separate update for
2730  *   the referent to transaction.
2731  * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2732  *   update of HEAD.
2733  */
2734 static int lock_ref_for_update(struct files_ref_store *refs,
2735                                struct ref_update *update,
2736                                struct ref_transaction *transaction,
2737                                const char *head_ref,
2738                                struct string_list *affected_refnames,
2739                                struct strbuf *err)
2740 {
2741         struct strbuf referent = STRBUF_INIT;
2742         int mustexist = (update->flags & REF_HAVE_OLD) &&
2743                 !is_null_oid(&update->old_oid);
2744         int ret;
2745         struct ref_lock *lock;
2746
2747         files_assert_main_repository(refs, "lock_ref_for_update");
2748
2749         if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2750                 update->flags |= REF_DELETING;
2751
2752         if (head_ref) {
2753                 ret = split_head_update(update, transaction, head_ref,
2754                                         affected_refnames, err);
2755                 if (ret)
2756                         return ret;
2757         }
2758
2759         ret = lock_raw_ref(refs, update->refname, mustexist,
2760                            affected_refnames, NULL,
2761                            &lock, &referent,
2762                            &update->type, err);
2763         if (ret) {
2764                 char *reason;
2765
2766                 reason = strbuf_detach(err, NULL);
2767                 strbuf_addf(err, "cannot lock ref '%s': %s",
2768                             original_update_refname(update), reason);
2769                 free(reason);
2770                 return ret;
2771         }
2772
2773         update->backend_data = lock;
2774
2775         if (update->type & REF_ISSYMREF) {
2776                 if (update->flags & REF_NODEREF) {
2777                         /*
2778                          * We won't be reading the referent as part of
2779                          * the transaction, so we have to read it here
2780                          * to record and possibly check old_sha1:
2781                          */
2782                         if (refs_read_ref_full(&refs->base,
2783                                                referent.buf, 0,
2784                                                lock->old_oid.hash, NULL)) {
2785                                 if (update->flags & REF_HAVE_OLD) {
2786                                         strbuf_addf(err, "cannot lock ref '%s': "
2787                                                     "error reading reference",
2788                                                     original_update_refname(update));
2789                                         return -1;
2790                                 }
2791                         } else if (check_old_oid(update, &lock->old_oid, err)) {
2792                                 return TRANSACTION_GENERIC_ERROR;
2793                         }
2794                 } else {
2795                         /*
2796                          * Create a new update for the reference this
2797                          * symref is pointing at. Also, we will record
2798                          * and verify old_sha1 for this update as part
2799                          * of processing the split-off update, so we
2800                          * don't have to do it here.
2801                          */
2802                         ret = split_symref_update(refs, update,
2803                                                   referent.buf, transaction,
2804                                                   affected_refnames, err);
2805                         if (ret)
2806                                 return ret;
2807                 }
2808         } else {
2809                 struct ref_update *parent_update;
2810
2811                 if (check_old_oid(update, &lock->old_oid, err))
2812                         return TRANSACTION_GENERIC_ERROR;
2813
2814                 /*
2815                  * If this update is happening indirectly because of a
2816                  * symref update, record the old SHA-1 in the parent
2817                  * update:
2818                  */
2819                 for (parent_update = update->parent_update;
2820                      parent_update;
2821                      parent_update = parent_update->parent_update) {
2822                         struct ref_lock *parent_lock = parent_update->backend_data;
2823                         oidcpy(&parent_lock->old_oid, &lock->old_oid);
2824                 }
2825         }
2826
2827         if ((update->flags & REF_HAVE_NEW) &&
2828             !(update->flags & REF_DELETING) &&
2829             !(update->flags & REF_LOG_ONLY)) {
2830                 if (!(update->type & REF_ISSYMREF) &&
2831                     !oidcmp(&lock->old_oid, &update->new_oid)) {
2832                         /*
2833                          * The reference already has the desired
2834                          * value, so we don't need to write it.
2835                          */
2836                 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2837                                                  err)) {
2838                         char *write_err = strbuf_detach(err, NULL);
2839
2840                         /*
2841                          * The lock was freed upon failure of
2842                          * write_ref_to_lockfile():
2843                          */
2844                         update->backend_data = NULL;
2845                         strbuf_addf(err,
2846                                     "cannot update ref '%s': %s",
2847                                     update->refname, write_err);
2848                         free(write_err);
2849                         return TRANSACTION_GENERIC_ERROR;
2850                 } else {
2851                         update->flags |= REF_NEEDS_COMMIT;
2852                 }
2853         }
2854         if (!(update->flags & REF_NEEDS_COMMIT)) {
2855                 /*
2856                  * We didn't call write_ref_to_lockfile(), so
2857                  * the lockfile is still open. Close it to
2858                  * free up the file descriptor:
2859                  */
2860                 if (close_ref(lock)) {
2861                         strbuf_addf(err, "couldn't close '%s.lock'",
2862                                     update->refname);
2863                         return TRANSACTION_GENERIC_ERROR;
2864                 }
2865         }
2866         return 0;
2867 }
2868
2869 /*
2870  * Unlock any references in `transaction` that are still locked, and
2871  * mark the transaction closed.
2872  */
2873 static void files_transaction_cleanup(struct ref_transaction *transaction)
2874 {
2875         size_t i;
2876
2877         for (i = 0; i < transaction->nr; i++) {
2878                 struct ref_update *update = transaction->updates[i];
2879                 struct ref_lock *lock = update->backend_data;
2880
2881                 if (lock) {
2882                         unlock_ref(lock);
2883                         update->backend_data = NULL;
2884                 }
2885         }
2886
2887         transaction->state = REF_TRANSACTION_CLOSED;
2888 }
2889
2890 static int files_transaction_prepare(struct ref_store *ref_store,
2891                                      struct ref_transaction *transaction,
2892                                      struct strbuf *err)
2893 {
2894         struct files_ref_store *refs =
2895                 files_downcast(ref_store, REF_STORE_WRITE,
2896                                "ref_transaction_prepare");
2897         size_t i;
2898         int ret = 0;
2899         struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2900         char *head_ref = NULL;
2901         int head_type;
2902         struct object_id head_oid;
2903
2904         assert(err);
2905
2906         if (!transaction->nr)
2907                 goto cleanup;
2908
2909         /*
2910          * Fail if a refname appears more than once in the
2911          * transaction. (If we end up splitting up any updates using
2912          * split_symref_update() or split_head_update(), those
2913          * functions will check that the new updates don't have the
2914          * same refname as any existing ones.)
2915          */
2916         for (i = 0; i < transaction->nr; i++) {
2917                 struct ref_update *update = transaction->updates[i];
2918                 struct string_list_item *item =
2919                         string_list_append(&affected_refnames, update->refname);
2920
2921                 /*
2922                  * We store a pointer to update in item->util, but at
2923                  * the moment we never use the value of this field
2924                  * except to check whether it is non-NULL.
2925                  */
2926                 item->util = update;
2927         }
2928         string_list_sort(&affected_refnames);
2929         if (ref_update_reject_duplicates(&affected_refnames, err)) {
2930                 ret = TRANSACTION_GENERIC_ERROR;
2931                 goto cleanup;
2932         }
2933
2934         /*
2935          * Special hack: If a branch is updated directly and HEAD
2936          * points to it (may happen on the remote side of a push
2937          * for example) then logically the HEAD reflog should be
2938          * updated too.
2939          *
2940          * A generic solution would require reverse symref lookups,
2941          * but finding all symrefs pointing to a given branch would be
2942          * rather costly for this rare event (the direct update of a
2943          * branch) to be worth it. So let's cheat and check with HEAD
2944          * only, which should cover 99% of all usage scenarios (even
2945          * 100% of the default ones).
2946          *
2947          * So if HEAD is a symbolic reference, then record the name of
2948          * the reference that it points to. If we see an update of
2949          * head_ref within the transaction, then split_head_update()
2950          * arranges for the reflog of HEAD to be updated, too.
2951          */
2952         head_ref = refs_resolve_refdup(ref_store, "HEAD",
2953                                        RESOLVE_REF_NO_RECURSE,
2954                                        head_oid.hash, &head_type);
2955
2956         if (head_ref && !(head_type & REF_ISSYMREF)) {
2957                 free(head_ref);
2958                 head_ref = NULL;
2959         }
2960
2961         /*
2962          * Acquire all locks, verify old values if provided, check
2963          * that new values are valid, and write new values to the
2964          * lockfiles, ready to be activated. Only keep one lockfile
2965          * open at a time to avoid running out of file descriptors.
2966          * Note that lock_ref_for_update() might append more updates
2967          * to the transaction.
2968          */
2969         for (i = 0; i < transaction->nr; i++) {
2970                 struct ref_update *update = transaction->updates[i];
2971
2972                 ret = lock_ref_for_update(refs, update, transaction,
2973                                           head_ref, &affected_refnames, err);
2974                 if (ret)
2975                         break;
2976         }
2977
2978 cleanup:
2979         free(head_ref);
2980         string_list_clear(&affected_refnames, 0);
2981
2982         if (ret)
2983                 files_transaction_cleanup(transaction);
2984         else
2985                 transaction->state = REF_TRANSACTION_PREPARED;
2986
2987         return ret;
2988 }
2989
2990 static int files_transaction_finish(struct ref_store *ref_store,
2991                                     struct ref_transaction *transaction,
2992                                     struct strbuf *err)
2993 {
2994         struct files_ref_store *refs =
2995                 files_downcast(ref_store, 0, "ref_transaction_finish");
2996         size_t i;
2997         int ret = 0;
2998         struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
2999         struct string_list_item *ref_to_delete;
3000         struct strbuf sb = STRBUF_INIT;
3001
3002         assert(err);
3003
3004         if (!transaction->nr) {
3005                 transaction->state = REF_TRANSACTION_CLOSED;
3006                 return 0;
3007         }
3008
3009         /* Perform updates first so live commits remain referenced */
3010         for (i = 0; i < transaction->nr; i++) {
3011                 struct ref_update *update = transaction->updates[i];
3012                 struct ref_lock *lock = update->backend_data;
3013
3014                 if (update->flags & REF_NEEDS_COMMIT ||
3015                     update->flags & REF_LOG_ONLY) {
3016                         if (files_log_ref_write(refs,
3017                                                 lock->ref_name,
3018                                                 &lock->old_oid,
3019                                                 &update->new_oid,
3020                                                 update->msg, update->flags,
3021                                                 err)) {
3022                                 char *old_msg = strbuf_detach(err, NULL);
3023
3024                                 strbuf_addf(err, "cannot update the ref '%s': %s",
3025                                             lock->ref_name, old_msg);
3026                                 free(old_msg);
3027                                 unlock_ref(lock);
3028                                 update->backend_data = NULL;
3029                                 ret = TRANSACTION_GENERIC_ERROR;
3030                                 goto cleanup;
3031                         }
3032                 }
3033                 if (update->flags & REF_NEEDS_COMMIT) {
3034                         clear_loose_ref_cache(refs);
3035                         if (commit_ref(lock)) {
3036                                 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
3037                                 unlock_ref(lock);
3038                                 update->backend_data = NULL;
3039                                 ret = TRANSACTION_GENERIC_ERROR;
3040                                 goto cleanup;
3041                         }
3042                 }
3043         }
3044         /* Perform deletes now that updates are safely completed */
3045         for (i = 0; i < transaction->nr; i++) {
3046                 struct ref_update *update = transaction->updates[i];
3047                 struct ref_lock *lock = update->backend_data;
3048
3049                 if (update->flags & REF_DELETING &&
3050                     !(update->flags & REF_LOG_ONLY)) {
3051                         if (!(update->type & REF_ISPACKED) ||
3052                             update->type & REF_ISSYMREF) {
3053                                 /* It is a loose reference. */
3054                                 strbuf_reset(&sb);
3055                                 files_ref_path(refs, &sb, lock->ref_name);
3056                                 if (unlink_or_msg(sb.buf, err)) {
3057                                         ret = TRANSACTION_GENERIC_ERROR;
3058                                         goto cleanup;
3059                                 }
3060                                 update->flags |= REF_DELETED_LOOSE;
3061                         }
3062
3063                         if (!(update->flags & REF_ISPRUNING))
3064                                 string_list_append(&refs_to_delete,
3065                                                    lock->ref_name);
3066                 }
3067         }
3068
3069         if (repack_without_refs(refs, &refs_to_delete, err)) {
3070                 ret = TRANSACTION_GENERIC_ERROR;
3071                 goto cleanup;
3072         }
3073
3074         /* Delete the reflogs of any references that were deleted: */
3075         for_each_string_list_item(ref_to_delete, &refs_to_delete) {
3076                 strbuf_reset(&sb);
3077                 files_reflog_path(refs, &sb, ref_to_delete->string);
3078                 if (!unlink_or_warn(sb.buf))
3079                         try_remove_empty_parents(refs, ref_to_delete->string,
3080                                                  REMOVE_EMPTY_PARENTS_REFLOG);
3081         }
3082
3083         clear_loose_ref_cache(refs);
3084
3085 cleanup:
3086         files_transaction_cleanup(transaction);
3087
3088         for (i = 0; i < transaction->nr; i++) {
3089                 struct ref_update *update = transaction->updates[i];
3090
3091                 if (update->flags & REF_DELETED_LOOSE) {
3092                         /*
3093                          * The loose reference was deleted. Delete any
3094                          * empty parent directories. (Note that this
3095                          * can only work because we have already
3096                          * removed the lockfile.)
3097                          */
3098                         try_remove_empty_parents(refs, update->refname,
3099                                                  REMOVE_EMPTY_PARENTS_REF);
3100                 }
3101         }
3102
3103         strbuf_release(&sb);
3104         string_list_clear(&refs_to_delete, 0);
3105         return ret;
3106 }
3107
3108 static int files_transaction_abort(struct ref_store *ref_store,
3109                                    struct ref_transaction *transaction,
3110                                    struct strbuf *err)
3111 {
3112         files_transaction_cleanup(transaction);
3113         return 0;
3114 }
3115
3116 static int ref_present(const char *refname,
3117                        const struct object_id *oid, int flags, void *cb_data)
3118 {
3119         struct string_list *affected_refnames = cb_data;
3120
3121         return string_list_has_string(affected_refnames, refname);
3122 }
3123
3124 static int files_initial_transaction_commit(struct ref_store *ref_store,
3125                                             struct ref_transaction *transaction,
3126                                             struct strbuf *err)
3127 {
3128         struct files_ref_store *refs =
3129                 files_downcast(ref_store, REF_STORE_WRITE,
3130                                "initial_ref_transaction_commit");
3131         size_t i;
3132         int ret = 0;
3133         struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3134
3135         assert(err);
3136
3137         if (transaction->state != REF_TRANSACTION_OPEN)
3138                 die("BUG: commit called for transaction that is not open");
3139
3140         /* Fail if a refname appears more than once in the transaction: */
3141         for (i = 0; i < transaction->nr; i++)
3142                 string_list_append(&affected_refnames,
3143                                    transaction->updates[i]->refname);
3144         string_list_sort(&affected_refnames);
3145         if (ref_update_reject_duplicates(&affected_refnames, err)) {
3146                 ret = TRANSACTION_GENERIC_ERROR;
3147                 goto cleanup;
3148         }
3149
3150         /*
3151          * It's really undefined to call this function in an active
3152          * repository or when there are existing references: we are
3153          * only locking and changing packed-refs, so (1) any
3154          * simultaneous processes might try to change a reference at
3155          * the same time we do, and (2) any existing loose versions of
3156          * the references that we are setting would have precedence
3157          * over our values. But some remote helpers create the remote
3158          * "HEAD" and "master" branches before calling this function,
3159          * so here we really only check that none of the references
3160          * that we are creating already exists.
3161          */
3162         if (refs_for_each_rawref(&refs->base, ref_present,
3163                                  &affected_refnames))
3164                 die("BUG: initial ref transaction called with existing refs");
3165
3166         for (i = 0; i < transaction->nr; i++) {
3167                 struct ref_update *update = transaction->updates[i];
3168
3169                 if ((update->flags & REF_HAVE_OLD) &&
3170                     !is_null_oid(&update->old_oid))
3171                         die("BUG: initial ref transaction with old_sha1 set");
3172                 if (refs_verify_refname_available(&refs->base, update->refname,
3173                                                   &affected_refnames, NULL,
3174                                                   err)) {
3175                         ret = TRANSACTION_NAME_CONFLICT;
3176                         goto cleanup;
3177                 }
3178         }
3179
3180         if (lock_packed_refs(refs, 0)) {
3181                 strbuf_addf(err, "unable to lock packed-refs file: %s",
3182                             strerror(errno));
3183                 ret = TRANSACTION_GENERIC_ERROR;
3184                 goto cleanup;
3185         }
3186
3187         for (i = 0; i < transaction->nr; i++) {
3188                 struct ref_update *update = transaction->updates[i];
3189
3190                 if ((update->flags & REF_HAVE_NEW) &&
3191                     !is_null_oid(&update->new_oid))
3192                         add_packed_ref(refs, update->refname,
3193                                        &update->new_oid);
3194         }
3195
3196         if (commit_packed_refs(refs)) {
3197                 strbuf_addf(err, "unable to commit packed-refs file: %s",
3198                             strerror(errno));
3199                 ret = TRANSACTION_GENERIC_ERROR;
3200                 goto cleanup;
3201         }
3202
3203 cleanup:
3204         transaction->state = REF_TRANSACTION_CLOSED;
3205         string_list_clear(&affected_refnames, 0);
3206         return ret;
3207 }
3208
3209 struct expire_reflog_cb {
3210         unsigned int flags;
3211         reflog_expiry_should_prune_fn *should_prune_fn;
3212         void *policy_cb;
3213         FILE *newlog;
3214         struct object_id last_kept_oid;
3215 };
3216
3217 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
3218                              const char *email, timestamp_t timestamp, int tz,
3219                              const char *message, void *cb_data)
3220 {
3221         struct expire_reflog_cb *cb = cb_data;
3222         struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3223
3224         if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3225                 ooid = &cb->last_kept_oid;
3226
3227         if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
3228                                    message, policy_cb)) {
3229                 if (!cb->newlog)
3230                         printf("would prune %s", message);
3231                 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3232                         printf("prune %s", message);
3233         } else {
3234                 if (cb->newlog) {
3235                         fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
3236                                 oid_to_hex(ooid), oid_to_hex(noid),
3237                                 email, timestamp, tz, message);
3238                         oidcpy(&cb->last_kept_oid, noid);
3239                 }
3240                 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3241                         printf("keep %s", message);
3242         }
3243         return 0;
3244 }
3245
3246 static int files_reflog_expire(struct ref_store *ref_store,
3247                                const char *refname, const unsigned char *sha1,
3248                                unsigned int flags,
3249                                reflog_expiry_prepare_fn prepare_fn,
3250                                reflog_expiry_should_prune_fn should_prune_fn,
3251                                reflog_expiry_cleanup_fn cleanup_fn,
3252                                void *policy_cb_data)
3253 {
3254         struct files_ref_store *refs =
3255                 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
3256         static struct lock_file reflog_lock;
3257         struct expire_reflog_cb cb;
3258         struct ref_lock *lock;
3259         struct strbuf log_file_sb = STRBUF_INIT;
3260         char *log_file;
3261         int status = 0;
3262         int type;
3263         struct strbuf err = STRBUF_INIT;
3264         struct object_id oid;
3265
3266         memset(&cb, 0, sizeof(cb));
3267         cb.flags = flags;
3268         cb.policy_cb = policy_cb_data;
3269         cb.should_prune_fn = should_prune_fn;
3270
3271         /*
3272          * The reflog file is locked by holding the lock on the
3273          * reference itself, plus we might need to update the
3274          * reference if --updateref was specified:
3275          */
3276         lock = lock_ref_sha1_basic(refs, refname, sha1,
3277                                    NULL, NULL, REF_NODEREF,
3278                                    &type, &err);
3279         if (!lock) {
3280                 error("cannot lock ref '%s': %s", refname, err.buf);
3281                 strbuf_release(&err);
3282                 return -1;
3283         }
3284         if (!refs_reflog_exists(ref_store, refname)) {
3285                 unlock_ref(lock);
3286                 return 0;
3287         }
3288
3289         files_reflog_path(refs, &log_file_sb, refname);
3290         log_file = strbuf_detach(&log_file_sb, NULL);
3291         if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3292                 /*
3293                  * Even though holding $GIT_DIR/logs/$reflog.lock has
3294                  * no locking implications, we use the lock_file
3295                  * machinery here anyway because it does a lot of the
3296                  * work we need, including cleaning up if the program
3297                  * exits unexpectedly.
3298                  */
3299                 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3300                         struct strbuf err = STRBUF_INIT;
3301                         unable_to_lock_message(log_file, errno, &err);
3302                         error("%s", err.buf);
3303                         strbuf_release(&err);
3304                         goto failure;
3305                 }
3306                 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3307                 if (!cb.newlog) {
3308                         error("cannot fdopen %s (%s)",
3309                               get_lock_file_path(&reflog_lock), strerror(errno));
3310                         goto failure;
3311                 }
3312         }
3313
3314         hashcpy(oid.hash, sha1);
3315
3316         (*prepare_fn)(refname, &oid, cb.policy_cb);
3317         refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3318         (*cleanup_fn)(cb.policy_cb);
3319
3320         if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3321                 /*
3322                  * It doesn't make sense to adjust a reference pointed
3323                  * to by a symbolic ref based on expiring entries in
3324                  * the symbolic reference's reflog. Nor can we update
3325                  * a reference if there are no remaining reflog
3326                  * entries.
3327                  */
3328                 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3329                         !(type & REF_ISSYMREF) &&
3330                         !is_null_oid(&cb.last_kept_oid);
3331
3332                 if (close_lock_file(&reflog_lock)) {
3333                         status |= error("couldn't write %s: %s", log_file,
3334                                         strerror(errno));
3335                 } else if (update &&
3336                            (write_in_full(get_lock_file_fd(lock->lk),
3337                                 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
3338                             write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3339                             close_ref(lock) < 0)) {
3340                         status |= error("couldn't write %s",
3341                                         get_lock_file_path(lock->lk));
3342                         rollback_lock_file(&reflog_lock);
3343                 } else if (commit_lock_file(&reflog_lock)) {
3344                         status |= error("unable to write reflog '%s' (%s)",
3345                                         log_file, strerror(errno));
3346                 } else if (update && commit_ref(lock)) {
3347                         status |= error("couldn't set %s", lock->ref_name);
3348                 }
3349         }
3350         free(log_file);
3351         unlock_ref(lock);
3352         return status;
3353
3354  failure:
3355         rollback_lock_file(&reflog_lock);
3356         free(log_file);
3357         unlock_ref(lock);
3358         return -1;
3359 }
3360
3361 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3362 {
3363         struct files_ref_store *refs =
3364                 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3365         struct strbuf sb = STRBUF_INIT;
3366
3367         /*
3368          * Create .git/refs/{heads,tags}
3369          */
3370         files_ref_path(refs, &sb, "refs/heads");
3371         safe_create_dir(sb.buf, 1);
3372
3373         strbuf_reset(&sb);
3374         files_ref_path(refs, &sb, "refs/tags");
3375         safe_create_dir(sb.buf, 1);
3376
3377         strbuf_release(&sb);
3378         return 0;
3379 }
3380
3381 struct ref_storage_be refs_be_files = {
3382         NULL,
3383         "files",
3384         files_ref_store_create,
3385         files_init_db,
3386         files_transaction_prepare,
3387         files_transaction_finish,
3388         files_transaction_abort,
3389         files_initial_transaction_commit,
3390
3391         files_pack_refs,
3392         files_peel_ref,
3393         files_create_symref,
3394         files_delete_refs,
3395         files_rename_ref,
3396
3397         files_ref_iterator_begin,
3398         files_read_raw_ref,
3399
3400         files_reflog_iterator_begin,
3401         files_for_each_reflog_ent,
3402         files_for_each_reflog_ent_reverse,
3403         files_reflog_exists,
3404         files_create_reflog,
3405         files_delete_reflog,
3406         files_reflog_expire
3407 };