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