refs: make errno output explicit for refs_resolve_ref_unsafe
[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,
387                                       oid, referent, type)) {
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,
427                                       oid, referent, type)) {
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
928         files_assert_main_repository(refs, "lock_ref_oid_basic");
929         assert(err);
930
931         CALLOC_ARRAY(lock, 1);
932
933         if (mustexist)
934                 resolve_flags |= RESOLVE_REF_READING;
935         if (flags & REF_DELETING)
936                 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
937
938         files_ref_path(refs, &ref_file, refname);
939         resolved = !!refs_resolve_ref_unsafe(&refs->base,
940                                              refname, resolve_flags,
941                                              &lock->old_oid, type);
942         if (!resolved && errno == EISDIR) {
943                 /*
944                  * we are trying to lock foo but we used to
945                  * have foo/bar which now does not exist;
946                  * it is normal for the empty directory 'foo'
947                  * to remain.
948                  */
949                 if (remove_empty_directories(&ref_file)) {
950                         if (!refs_verify_refname_available(
951                                             &refs->base,
952                                             refname, extras, skip, err))
953                                 strbuf_addf(err, "there are still refs under '%s'",
954                                             refname);
955                         goto error_return;
956                 }
957                 resolved = !!refs_resolve_ref_unsafe(&refs->base,
958                                                      refname, resolve_flags,
959                                                      &lock->old_oid, type);
960         }
961         if (!resolved) {
962                 int last_errno = errno;
963                 if (last_errno != ENOTDIR ||
964                     !refs_verify_refname_available(&refs->base, refname,
965                                                    extras, skip, err))
966                         strbuf_addf(err, "unable to resolve reference '%s': %s",
967                                     refname, strerror(last_errno));
968
969                 goto error_return;
970         }
971
972         /*
973          * If the ref did not exist and we are creating it, make sure
974          * there is no existing packed ref whose name begins with our
975          * refname, nor a packed ref whose name is a proper prefix of
976          * our refname.
977          */
978         if (is_null_oid(&lock->old_oid) &&
979             refs_verify_refname_available(refs->packed_ref_store, refname,
980                                           extras, skip, err)) {
981                 goto error_return;
982         }
983
984         lock->ref_name = xstrdup(refname);
985
986         if (raceproof_create_file(ref_file.buf, create_reflock, &lock->lk)) {
987                 unable_to_lock_message(ref_file.buf, errno, err);
988                 goto error_return;
989         }
990
991         if (verify_lock(&refs->base, lock, old_oid, mustexist, err)) {
992                 goto error_return;
993         }
994         goto out;
995
996  error_return:
997         unlock_ref(lock);
998         lock = NULL;
999
1000  out:
1001         strbuf_release(&ref_file);
1002         return lock;
1003 }
1004
1005 struct ref_to_prune {
1006         struct ref_to_prune *next;
1007         struct object_id oid;
1008         char name[FLEX_ARRAY];
1009 };
1010
1011 enum {
1012         REMOVE_EMPTY_PARENTS_REF = 0x01,
1013         REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1014 };
1015
1016 /*
1017  * Remove empty parent directories associated with the specified
1018  * reference and/or its reflog, but spare [logs/]refs/ and immediate
1019  * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1020  * REMOVE_EMPTY_PARENTS_REFLOG.
1021  */
1022 static void try_remove_empty_parents(struct files_ref_store *refs,
1023                                      const char *refname,
1024                                      unsigned int flags)
1025 {
1026         struct strbuf buf = STRBUF_INIT;
1027         struct strbuf sb = STRBUF_INIT;
1028         char *p, *q;
1029         int i;
1030
1031         strbuf_addstr(&buf, refname);
1032         p = buf.buf;
1033         for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1034                 while (*p && *p != '/')
1035                         p++;
1036                 /* tolerate duplicate slashes; see check_refname_format() */
1037                 while (*p == '/')
1038                         p++;
1039         }
1040         q = buf.buf + buf.len;
1041         while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1042                 while (q > p && *q != '/')
1043                         q--;
1044                 while (q > p && *(q-1) == '/')
1045                         q--;
1046                 if (q == p)
1047                         break;
1048                 strbuf_setlen(&buf, q - buf.buf);
1049
1050                 strbuf_reset(&sb);
1051                 files_ref_path(refs, &sb, buf.buf);
1052                 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1053                         flags &= ~REMOVE_EMPTY_PARENTS_REF;
1054
1055                 strbuf_reset(&sb);
1056                 files_reflog_path(refs, &sb, buf.buf);
1057                 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1058                         flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1059         }
1060         strbuf_release(&buf);
1061         strbuf_release(&sb);
1062 }
1063
1064 /* make sure nobody touched the ref, and unlink */
1065 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1066 {
1067         struct ref_transaction *transaction;
1068         struct strbuf err = STRBUF_INIT;
1069         int ret = -1;
1070
1071         if (check_refname_format(r->name, 0))
1072                 return;
1073
1074         transaction = ref_store_transaction_begin(&refs->base, &err);
1075         if (!transaction)
1076                 goto cleanup;
1077         ref_transaction_add_update(
1078                         transaction, r->name,
1079                         REF_NO_DEREF | REF_HAVE_NEW | REF_HAVE_OLD | REF_IS_PRUNING,
1080                         null_oid(), &r->oid, NULL);
1081         if (ref_transaction_commit(transaction, &err))
1082                 goto cleanup;
1083
1084         ret = 0;
1085
1086 cleanup:
1087         if (ret)
1088                 error("%s", err.buf);
1089         strbuf_release(&err);
1090         ref_transaction_free(transaction);
1091         return;
1092 }
1093
1094 /*
1095  * Prune the loose versions of the references in the linked list
1096  * `*refs_to_prune`, freeing the entries in the list as we go.
1097  */
1098 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune **refs_to_prune)
1099 {
1100         while (*refs_to_prune) {
1101                 struct ref_to_prune *r = *refs_to_prune;
1102                 *refs_to_prune = r->next;
1103                 prune_ref(refs, r);
1104                 free(r);
1105         }
1106 }
1107
1108 /*
1109  * Return true if the specified reference should be packed.
1110  */
1111 static int should_pack_ref(const char *refname,
1112                            const struct object_id *oid, unsigned int ref_flags,
1113                            unsigned int pack_flags)
1114 {
1115         /* Do not pack per-worktree refs: */
1116         if (ref_type(refname) != REF_TYPE_NORMAL)
1117                 return 0;
1118
1119         /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1120         if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1121                 return 0;
1122
1123         /* Do not pack symbolic refs: */
1124         if (ref_flags & REF_ISSYMREF)
1125                 return 0;
1126
1127         /* Do not pack broken refs: */
1128         if (!ref_resolves_to_object(refname, oid, ref_flags))
1129                 return 0;
1130
1131         return 1;
1132 }
1133
1134 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1135 {
1136         struct files_ref_store *refs =
1137                 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1138                                "pack_refs");
1139         struct ref_iterator *iter;
1140         int ok;
1141         struct ref_to_prune *refs_to_prune = NULL;
1142         struct strbuf err = STRBUF_INIT;
1143         struct ref_transaction *transaction;
1144
1145         transaction = ref_store_transaction_begin(refs->packed_ref_store, &err);
1146         if (!transaction)
1147                 return -1;
1148
1149         packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);
1150
1151         iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1152         while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1153                 /*
1154                  * If the loose reference can be packed, add an entry
1155                  * in the packed ref cache. If the reference should be
1156                  * pruned, also add it to refs_to_prune.
1157                  */
1158                 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1159                                      flags))
1160                         continue;
1161
1162                 /*
1163                  * Add a reference creation for this reference to the
1164                  * packed-refs transaction:
1165                  */
1166                 if (ref_transaction_update(transaction, iter->refname,
1167                                            iter->oid, NULL,
1168                                            REF_NO_DEREF, NULL, &err))
1169                         die("failure preparing to create packed reference %s: %s",
1170                             iter->refname, err.buf);
1171
1172                 /* Schedule the loose reference for pruning if requested. */
1173                 if ((flags & PACK_REFS_PRUNE)) {
1174                         struct ref_to_prune *n;
1175                         FLEX_ALLOC_STR(n, name, iter->refname);
1176                         oidcpy(&n->oid, iter->oid);
1177                         n->next = refs_to_prune;
1178                         refs_to_prune = n;
1179                 }
1180         }
1181         if (ok != ITER_DONE)
1182                 die("error while iterating over references");
1183
1184         if (ref_transaction_commit(transaction, &err))
1185                 die("unable to write new packed-refs: %s", err.buf);
1186
1187         ref_transaction_free(transaction);
1188
1189         packed_refs_unlock(refs->packed_ref_store);
1190
1191         prune_refs(refs, &refs_to_prune);
1192         strbuf_release(&err);
1193         return 0;
1194 }
1195
1196 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1197                              struct string_list *refnames, unsigned int flags)
1198 {
1199         struct files_ref_store *refs =
1200                 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1201         struct strbuf err = STRBUF_INIT;
1202         int i, result = 0;
1203
1204         if (!refnames->nr)
1205                 return 0;
1206
1207         if (packed_refs_lock(refs->packed_ref_store, 0, &err))
1208                 goto error;
1209
1210         if (refs_delete_refs(refs->packed_ref_store, msg, refnames, flags)) {
1211                 packed_refs_unlock(refs->packed_ref_store);
1212                 goto error;
1213         }
1214
1215         packed_refs_unlock(refs->packed_ref_store);
1216
1217         for (i = 0; i < refnames->nr; i++) {
1218                 const char *refname = refnames->items[i].string;
1219
1220                 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1221                         result |= error(_("could not remove reference %s"), refname);
1222         }
1223
1224         strbuf_release(&err);
1225         return result;
1226
1227 error:
1228         /*
1229          * If we failed to rewrite the packed-refs file, then it is
1230          * unsafe to try to remove loose refs, because doing so might
1231          * expose an obsolete packed value for a reference that might
1232          * even point at an object that has been garbage collected.
1233          */
1234         if (refnames->nr == 1)
1235                 error(_("could not delete reference %s: %s"),
1236                       refnames->items[0].string, err.buf);
1237         else
1238                 error(_("could not delete references: %s"), err.buf);
1239
1240         strbuf_release(&err);
1241         return -1;
1242 }
1243
1244 /*
1245  * People using contrib's git-new-workdir have .git/logs/refs ->
1246  * /some/other/path/.git/logs/refs, and that may live on another device.
1247  *
1248  * IOW, to avoid cross device rename errors, the temporary renamed log must
1249  * live into logs/refs.
1250  */
1251 #define TMP_RENAMED_LOG  "refs/.tmp-renamed-log"
1252
1253 struct rename_cb {
1254         const char *tmp_renamed_log;
1255         int true_errno;
1256 };
1257
1258 static int rename_tmp_log_callback(const char *path, void *cb_data)
1259 {
1260         struct rename_cb *cb = cb_data;
1261
1262         if (rename(cb->tmp_renamed_log, path)) {
1263                 /*
1264                  * rename(a, b) when b is an existing directory ought
1265                  * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1266                  * Sheesh. Record the true errno for error reporting,
1267                  * but report EISDIR to raceproof_create_file() so
1268                  * that it knows to retry.
1269                  */
1270                 cb->true_errno = errno;
1271                 if (errno == ENOTDIR)
1272                         errno = EISDIR;
1273                 return -1;
1274         } else {
1275                 return 0;
1276         }
1277 }
1278
1279 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1280 {
1281         struct strbuf path = STRBUF_INIT;
1282         struct strbuf tmp = STRBUF_INIT;
1283         struct rename_cb cb;
1284         int ret;
1285
1286         files_reflog_path(refs, &path, newrefname);
1287         files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1288         cb.tmp_renamed_log = tmp.buf;
1289         ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1290         if (ret) {
1291                 if (errno == EISDIR)
1292                         error("directory not empty: %s", path.buf);
1293                 else
1294                         error("unable to move logfile %s to %s: %s",
1295                               tmp.buf, path.buf,
1296                               strerror(cb.true_errno));
1297         }
1298
1299         strbuf_release(&path);
1300         strbuf_release(&tmp);
1301         return ret;
1302 }
1303
1304 static int write_ref_to_lockfile(struct ref_lock *lock,
1305                                  const struct object_id *oid, struct strbuf *err);
1306 static int commit_ref_update(struct files_ref_store *refs,
1307                              struct ref_lock *lock,
1308                              const struct object_id *oid, const char *logmsg,
1309                              struct strbuf *err);
1310
1311 static int files_copy_or_rename_ref(struct ref_store *ref_store,
1312                             const char *oldrefname, const char *newrefname,
1313                             const char *logmsg, int copy)
1314 {
1315         struct files_ref_store *refs =
1316                 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1317         struct object_id orig_oid;
1318         int flag = 0, logmoved = 0;
1319         struct ref_lock *lock;
1320         struct stat loginfo;
1321         struct strbuf sb_oldref = STRBUF_INIT;
1322         struct strbuf sb_newref = STRBUF_INIT;
1323         struct strbuf tmp_renamed_log = STRBUF_INIT;
1324         int log, ret;
1325         struct strbuf err = STRBUF_INIT;
1326
1327         files_reflog_path(refs, &sb_oldref, oldrefname);
1328         files_reflog_path(refs, &sb_newref, newrefname);
1329         files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1330
1331         log = !lstat(sb_oldref.buf, &loginfo);
1332         if (log && S_ISLNK(loginfo.st_mode)) {
1333                 ret = error("reflog for %s is a symlink", oldrefname);
1334                 goto out;
1335         }
1336
1337         if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1338                                      RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1339                                 &orig_oid, &flag)) {
1340                 ret = error("refname %s not found", oldrefname);
1341                 goto out;
1342         }
1343
1344         if (flag & REF_ISSYMREF) {
1345                 if (copy)
1346                         ret = error("refname %s is a symbolic ref, copying it is not supported",
1347                                     oldrefname);
1348                 else
1349                         ret = error("refname %s is a symbolic ref, renaming it is not supported",
1350                                     oldrefname);
1351                 goto out;
1352         }
1353         if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1354                 ret = 1;
1355                 goto out;
1356         }
1357
1358         if (!copy && log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1359                 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1360                             oldrefname, strerror(errno));
1361                 goto out;
1362         }
1363
1364         if (copy && log && copy_file(tmp_renamed_log.buf, sb_oldref.buf, 0644)) {
1365                 ret = error("unable to copy logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1366                             oldrefname, strerror(errno));
1367                 goto out;
1368         }
1369
1370         if (!copy && refs_delete_ref(&refs->base, logmsg, oldrefname,
1371                             &orig_oid, REF_NO_DEREF)) {
1372                 error("unable to delete old %s", oldrefname);
1373                 goto rollback;
1374         }
1375
1376         /*
1377          * Since we are doing a shallow lookup, oid is not the
1378          * correct value to pass to delete_ref as old_oid. But that
1379          * doesn't matter, because an old_oid check wouldn't add to
1380          * the safety anyway; we want to delete the reference whatever
1381          * its current value.
1382          */
1383         if (!copy && !refs_read_ref_full(&refs->base, newrefname,
1384                                 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1385                                 NULL, NULL) &&
1386             refs_delete_ref(&refs->base, NULL, newrefname,
1387                             NULL, REF_NO_DEREF)) {
1388                 if (errno == EISDIR) {
1389                         struct strbuf path = STRBUF_INIT;
1390                         int result;
1391
1392                         files_ref_path(refs, &path, newrefname);
1393                         result = remove_empty_directories(&path);
1394                         strbuf_release(&path);
1395
1396                         if (result) {
1397                                 error("Directory not empty: %s", newrefname);
1398                                 goto rollback;
1399                         }
1400                 } else {
1401                         error("unable to delete existing %s", newrefname);
1402                         goto rollback;
1403                 }
1404         }
1405
1406         if (log && rename_tmp_log(refs, newrefname))
1407                 goto rollback;
1408
1409         logmoved = log;
1410
1411         lock = lock_ref_oid_basic(refs, newrefname, NULL, NULL, NULL,
1412                                   REF_NO_DEREF, NULL, &err);
1413         if (!lock) {
1414                 if (copy)
1415                         error("unable to copy '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1416                 else
1417                         error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1418                 strbuf_release(&err);
1419                 goto rollback;
1420         }
1421         oidcpy(&lock->old_oid, &orig_oid);
1422
1423         if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1424             commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1425                 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1426                 strbuf_release(&err);
1427                 goto rollback;
1428         }
1429
1430         ret = 0;
1431         goto out;
1432
1433  rollback:
1434         lock = lock_ref_oid_basic(refs, oldrefname, NULL, NULL, NULL,
1435                                   REF_NO_DEREF, NULL, &err);
1436         if (!lock) {
1437                 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1438                 strbuf_release(&err);
1439                 goto rollbacklog;
1440         }
1441
1442         flag = log_all_ref_updates;
1443         log_all_ref_updates = LOG_REFS_NONE;
1444         if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1445             commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1446                 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1447                 strbuf_release(&err);
1448         }
1449         log_all_ref_updates = flag;
1450
1451  rollbacklog:
1452         if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1453                 error("unable to restore logfile %s from %s: %s",
1454                         oldrefname, newrefname, strerror(errno));
1455         if (!logmoved && log &&
1456             rename(tmp_renamed_log.buf, sb_oldref.buf))
1457                 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1458                         oldrefname, strerror(errno));
1459         ret = 1;
1460  out:
1461         strbuf_release(&sb_newref);
1462         strbuf_release(&sb_oldref);
1463         strbuf_release(&tmp_renamed_log);
1464
1465         return ret;
1466 }
1467
1468 static int files_rename_ref(struct ref_store *ref_store,
1469                             const char *oldrefname, const char *newrefname,
1470                             const char *logmsg)
1471 {
1472         return files_copy_or_rename_ref(ref_store, oldrefname,
1473                                  newrefname, logmsg, 0);
1474 }
1475
1476 static int files_copy_ref(struct ref_store *ref_store,
1477                             const char *oldrefname, const char *newrefname,
1478                             const char *logmsg)
1479 {
1480         return files_copy_or_rename_ref(ref_store, oldrefname,
1481                                  newrefname, logmsg, 1);
1482 }
1483
1484 static int close_ref_gently(struct ref_lock *lock)
1485 {
1486         if (close_lock_file_gently(&lock->lk))
1487                 return -1;
1488         return 0;
1489 }
1490
1491 static int commit_ref(struct ref_lock *lock)
1492 {
1493         char *path = get_locked_file_path(&lock->lk);
1494         struct stat st;
1495
1496         if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1497                 /*
1498                  * There is a directory at the path we want to rename
1499                  * the lockfile to. Hopefully it is empty; try to
1500                  * delete it.
1501                  */
1502                 size_t len = strlen(path);
1503                 struct strbuf sb_path = STRBUF_INIT;
1504
1505                 strbuf_attach(&sb_path, path, len, len);
1506
1507                 /*
1508                  * If this fails, commit_lock_file() will also fail
1509                  * and will report the problem.
1510                  */
1511                 remove_empty_directories(&sb_path);
1512                 strbuf_release(&sb_path);
1513         } else {
1514                 free(path);
1515         }
1516
1517         if (commit_lock_file(&lock->lk))
1518                 return -1;
1519         return 0;
1520 }
1521
1522 static int open_or_create_logfile(const char *path, void *cb)
1523 {
1524         int *fd = cb;
1525
1526         *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1527         return (*fd < 0) ? -1 : 0;
1528 }
1529
1530 /*
1531  * Create a reflog for a ref. If force_create = 0, only create the
1532  * reflog for certain refs (those for which should_autocreate_reflog
1533  * returns non-zero). Otherwise, create it regardless of the reference
1534  * name. If the logfile already existed or was created, return 0 and
1535  * set *logfd to the file descriptor opened for appending to the file.
1536  * If no logfile exists and we decided not to create one, return 0 and
1537  * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1538  * return -1.
1539  */
1540 static int log_ref_setup(struct files_ref_store *refs,
1541                          const char *refname, int force_create,
1542                          int *logfd, struct strbuf *err)
1543 {
1544         struct strbuf logfile_sb = STRBUF_INIT;
1545         char *logfile;
1546
1547         files_reflog_path(refs, &logfile_sb, refname);
1548         logfile = strbuf_detach(&logfile_sb, NULL);
1549
1550         if (force_create || should_autocreate_reflog(refname)) {
1551                 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1552                         if (errno == ENOENT)
1553                                 strbuf_addf(err, "unable to create directory for '%s': "
1554                                             "%s", logfile, strerror(errno));
1555                         else if (errno == EISDIR)
1556                                 strbuf_addf(err, "there are still logs under '%s'",
1557                                             logfile);
1558                         else
1559                                 strbuf_addf(err, "unable to append to '%s': %s",
1560                                             logfile, strerror(errno));
1561
1562                         goto error;
1563                 }
1564         } else {
1565                 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
1566                 if (*logfd < 0) {
1567                         if (errno == ENOENT || errno == EISDIR) {
1568                                 /*
1569                                  * The logfile doesn't already exist,
1570                                  * but that is not an error; it only
1571                                  * means that we won't write log
1572                                  * entries to it.
1573                                  */
1574                                 ;
1575                         } else {
1576                                 strbuf_addf(err, "unable to append to '%s': %s",
1577                                             logfile, strerror(errno));
1578                                 goto error;
1579                         }
1580                 }
1581         }
1582
1583         if (*logfd >= 0)
1584                 adjust_shared_perm(logfile);
1585
1586         free(logfile);
1587         return 0;
1588
1589 error:
1590         free(logfile);
1591         return -1;
1592 }
1593
1594 static int files_create_reflog(struct ref_store *ref_store,
1595                                const char *refname, int force_create,
1596                                struct strbuf *err)
1597 {
1598         struct files_ref_store *refs =
1599                 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
1600         int fd;
1601
1602         if (log_ref_setup(refs, refname, force_create, &fd, err))
1603                 return -1;
1604
1605         if (fd >= 0)
1606                 close(fd);
1607
1608         return 0;
1609 }
1610
1611 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
1612                             const struct object_id *new_oid,
1613                             const char *committer, const char *msg)
1614 {
1615         struct strbuf sb = STRBUF_INIT;
1616         int ret = 0;
1617
1618         strbuf_addf(&sb, "%s %s %s", oid_to_hex(old_oid), oid_to_hex(new_oid), committer);
1619         if (msg && *msg) {
1620                 strbuf_addch(&sb, '\t');
1621                 strbuf_addstr(&sb, msg);
1622         }
1623         strbuf_addch(&sb, '\n');
1624         if (write_in_full(fd, sb.buf, sb.len) < 0)
1625                 ret = -1;
1626         strbuf_release(&sb);
1627         return ret;
1628 }
1629
1630 static int files_log_ref_write(struct files_ref_store *refs,
1631                                const char *refname, const struct object_id *old_oid,
1632                                const struct object_id *new_oid, const char *msg,
1633                                int flags, struct strbuf *err)
1634 {
1635         int logfd, result;
1636
1637         if (log_all_ref_updates == LOG_REFS_UNSET)
1638                 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
1639
1640         result = log_ref_setup(refs, refname,
1641                                flags & REF_FORCE_CREATE_REFLOG,
1642                                &logfd, err);
1643
1644         if (result)
1645                 return result;
1646
1647         if (logfd < 0)
1648                 return 0;
1649         result = log_ref_write_fd(logfd, old_oid, new_oid,
1650                                   git_committer_info(0), msg);
1651         if (result) {
1652                 struct strbuf sb = STRBUF_INIT;
1653                 int save_errno = errno;
1654
1655                 files_reflog_path(refs, &sb, refname);
1656                 strbuf_addf(err, "unable to append to '%s': %s",
1657                             sb.buf, strerror(save_errno));
1658                 strbuf_release(&sb);
1659                 close(logfd);
1660                 return -1;
1661         }
1662         if (close(logfd)) {
1663                 struct strbuf sb = STRBUF_INIT;
1664                 int save_errno = errno;
1665
1666                 files_reflog_path(refs, &sb, refname);
1667                 strbuf_addf(err, "unable to append to '%s': %s",
1668                             sb.buf, strerror(save_errno));
1669                 strbuf_release(&sb);
1670                 return -1;
1671         }
1672         return 0;
1673 }
1674
1675 /*
1676  * Write oid into the open lockfile, then close the lockfile. On
1677  * errors, rollback the lockfile, fill in *err and return -1.
1678  */
1679 static int write_ref_to_lockfile(struct ref_lock *lock,
1680                                  const struct object_id *oid, struct strbuf *err)
1681 {
1682         static char term = '\n';
1683         struct object *o;
1684         int fd;
1685
1686         o = parse_object(the_repository, oid);
1687         if (!o) {
1688                 strbuf_addf(err,
1689                             "trying to write ref '%s' with nonexistent object %s",
1690                             lock->ref_name, oid_to_hex(oid));
1691                 unlock_ref(lock);
1692                 return -1;
1693         }
1694         if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
1695                 strbuf_addf(err,
1696                             "trying to write non-commit object %s to branch '%s'",
1697                             oid_to_hex(oid), lock->ref_name);
1698                 unlock_ref(lock);
1699                 return -1;
1700         }
1701         fd = get_lock_file_fd(&lock->lk);
1702         if (write_in_full(fd, oid_to_hex(oid), the_hash_algo->hexsz) < 0 ||
1703             write_in_full(fd, &term, 1) < 0 ||
1704             close_ref_gently(lock) < 0) {
1705                 strbuf_addf(err,
1706                             "couldn't write '%s'", get_lock_file_path(&lock->lk));
1707                 unlock_ref(lock);
1708                 return -1;
1709         }
1710         return 0;
1711 }
1712
1713 /*
1714  * Commit a change to a loose reference that has already been written
1715  * to the loose reference lockfile. Also update the reflogs if
1716  * necessary, using the specified lockmsg (which can be NULL).
1717  */
1718 static int commit_ref_update(struct files_ref_store *refs,
1719                              struct ref_lock *lock,
1720                              const struct object_id *oid, const char *logmsg,
1721                              struct strbuf *err)
1722 {
1723         files_assert_main_repository(refs, "commit_ref_update");
1724
1725         clear_loose_ref_cache(refs);
1726         if (files_log_ref_write(refs, lock->ref_name,
1727                                 &lock->old_oid, oid,
1728                                 logmsg, 0, err)) {
1729                 char *old_msg = strbuf_detach(err, NULL);
1730                 strbuf_addf(err, "cannot update the ref '%s': %s",
1731                             lock->ref_name, old_msg);
1732                 free(old_msg);
1733                 unlock_ref(lock);
1734                 return -1;
1735         }
1736
1737         if (strcmp(lock->ref_name, "HEAD") != 0) {
1738                 /*
1739                  * Special hack: If a branch is updated directly and HEAD
1740                  * points to it (may happen on the remote side of a push
1741                  * for example) then logically the HEAD reflog should be
1742                  * updated too.
1743                  * A generic solution implies reverse symref information,
1744                  * but finding all symrefs pointing to the given branch
1745                  * would be rather costly for this rare event (the direct
1746                  * update of a branch) to be worth it.  So let's cheat and
1747                  * check with HEAD only which should cover 99% of all usage
1748                  * scenarios (even 100% of the default ones).
1749                  */
1750                 int head_flag;
1751                 const char *head_ref;
1752
1753                 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
1754                                                    RESOLVE_REF_READING,
1755                                                    NULL, &head_flag);
1756                 if (head_ref && (head_flag & REF_ISSYMREF) &&
1757                     !strcmp(head_ref, lock->ref_name)) {
1758                         struct strbuf log_err = STRBUF_INIT;
1759                         if (files_log_ref_write(refs, "HEAD",
1760                                                 &lock->old_oid, oid,
1761                                                 logmsg, 0, &log_err)) {
1762                                 error("%s", log_err.buf);
1763                                 strbuf_release(&log_err);
1764                         }
1765                 }
1766         }
1767
1768         if (commit_ref(lock)) {
1769                 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
1770                 unlock_ref(lock);
1771                 return -1;
1772         }
1773
1774         unlock_ref(lock);
1775         return 0;
1776 }
1777
1778 static int create_ref_symlink(struct ref_lock *lock, const char *target)
1779 {
1780         int ret = -1;
1781 #ifndef NO_SYMLINK_HEAD
1782         char *ref_path = get_locked_file_path(&lock->lk);
1783         unlink(ref_path);
1784         ret = symlink(target, ref_path);
1785         free(ref_path);
1786
1787         if (ret)
1788                 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
1789 #endif
1790         return ret;
1791 }
1792
1793 static void update_symref_reflog(struct files_ref_store *refs,
1794                                  struct ref_lock *lock, const char *refname,
1795                                  const char *target, const char *logmsg)
1796 {
1797         struct strbuf err = STRBUF_INIT;
1798         struct object_id new_oid;
1799         if (logmsg &&
1800             !refs_read_ref_full(&refs->base, target,
1801                                 RESOLVE_REF_READING, &new_oid, NULL) &&
1802             files_log_ref_write(refs, refname, &lock->old_oid,
1803                                 &new_oid, logmsg, 0, &err)) {
1804                 error("%s", err.buf);
1805                 strbuf_release(&err);
1806         }
1807 }
1808
1809 static int create_symref_locked(struct files_ref_store *refs,
1810                                 struct ref_lock *lock, const char *refname,
1811                                 const char *target, const char *logmsg)
1812 {
1813         if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
1814                 update_symref_reflog(refs, lock, refname, target, logmsg);
1815                 return 0;
1816         }
1817
1818         if (!fdopen_lock_file(&lock->lk, "w"))
1819                 return error("unable to fdopen %s: %s",
1820                              get_lock_file_path(&lock->lk), strerror(errno));
1821
1822         update_symref_reflog(refs, lock, refname, target, logmsg);
1823
1824         /* no error check; commit_ref will check ferror */
1825         fprintf(get_lock_file_fp(&lock->lk), "ref: %s\n", target);
1826         if (commit_ref(lock) < 0)
1827                 return error("unable to write symref for %s: %s", refname,
1828                              strerror(errno));
1829         return 0;
1830 }
1831
1832 static int files_create_symref(struct ref_store *ref_store,
1833                                const char *refname, const char *target,
1834                                const char *logmsg)
1835 {
1836         struct files_ref_store *refs =
1837                 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
1838         struct strbuf err = STRBUF_INIT;
1839         struct ref_lock *lock;
1840         int ret;
1841
1842         lock = lock_ref_oid_basic(refs, refname, NULL,
1843                                   NULL, NULL, REF_NO_DEREF, NULL,
1844                                   &err);
1845         if (!lock) {
1846                 error("%s", err.buf);
1847                 strbuf_release(&err);
1848                 return -1;
1849         }
1850
1851         ret = create_symref_locked(refs, lock, refname, target, logmsg);
1852         unlock_ref(lock);
1853         return ret;
1854 }
1855
1856 static int files_reflog_exists(struct ref_store *ref_store,
1857                                const char *refname)
1858 {
1859         struct files_ref_store *refs =
1860                 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
1861         struct strbuf sb = STRBUF_INIT;
1862         struct stat st;
1863         int ret;
1864
1865         files_reflog_path(refs, &sb, refname);
1866         ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
1867         strbuf_release(&sb);
1868         return ret;
1869 }
1870
1871 static int files_delete_reflog(struct ref_store *ref_store,
1872                                const char *refname)
1873 {
1874         struct files_ref_store *refs =
1875                 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
1876         struct strbuf sb = STRBUF_INIT;
1877         int ret;
1878
1879         files_reflog_path(refs, &sb, refname);
1880         ret = remove_path(sb.buf);
1881         strbuf_release(&sb);
1882         return ret;
1883 }
1884
1885 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
1886 {
1887         struct object_id ooid, noid;
1888         char *email_end, *message;
1889         timestamp_t timestamp;
1890         int tz;
1891         const char *p = sb->buf;
1892
1893         /* old SP new SP name <email> SP time TAB msg LF */
1894         if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
1895             parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
1896             parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
1897             !(email_end = strchr(p, '>')) ||
1898             email_end[1] != ' ' ||
1899             !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
1900             !message || message[0] != ' ' ||
1901             (message[1] != '+' && message[1] != '-') ||
1902             !isdigit(message[2]) || !isdigit(message[3]) ||
1903             !isdigit(message[4]) || !isdigit(message[5]))
1904                 return 0; /* corrupt? */
1905         email_end[1] = '\0';
1906         tz = strtol(message + 1, NULL, 10);
1907         if (message[6] != '\t')
1908                 message += 6;
1909         else
1910                 message += 7;
1911         return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
1912 }
1913
1914 static char *find_beginning_of_line(char *bob, char *scan)
1915 {
1916         while (bob < scan && *(--scan) != '\n')
1917                 ; /* keep scanning backwards */
1918         /*
1919          * Return either beginning of the buffer, or LF at the end of
1920          * the previous line.
1921          */
1922         return scan;
1923 }
1924
1925 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
1926                                              const char *refname,
1927                                              each_reflog_ent_fn fn,
1928                                              void *cb_data)
1929 {
1930         struct files_ref_store *refs =
1931                 files_downcast(ref_store, REF_STORE_READ,
1932                                "for_each_reflog_ent_reverse");
1933         struct strbuf sb = STRBUF_INIT;
1934         FILE *logfp;
1935         long pos;
1936         int ret = 0, at_tail = 1;
1937
1938         files_reflog_path(refs, &sb, refname);
1939         logfp = fopen(sb.buf, "r");
1940         strbuf_release(&sb);
1941         if (!logfp)
1942                 return -1;
1943
1944         /* Jump to the end */
1945         if (fseek(logfp, 0, SEEK_END) < 0)
1946                 ret = error("cannot seek back reflog for %s: %s",
1947                             refname, strerror(errno));
1948         pos = ftell(logfp);
1949         while (!ret && 0 < pos) {
1950                 int cnt;
1951                 size_t nread;
1952                 char buf[BUFSIZ];
1953                 char *endp, *scanp;
1954
1955                 /* Fill next block from the end */
1956                 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
1957                 if (fseek(logfp, pos - cnt, SEEK_SET)) {
1958                         ret = error("cannot seek back reflog for %s: %s",
1959                                     refname, strerror(errno));
1960                         break;
1961                 }
1962                 nread = fread(buf, cnt, 1, logfp);
1963                 if (nread != 1) {
1964                         ret = error("cannot read %d bytes from reflog for %s: %s",
1965                                     cnt, refname, strerror(errno));
1966                         break;
1967                 }
1968                 pos -= cnt;
1969
1970                 scanp = endp = buf + cnt;
1971                 if (at_tail && scanp[-1] == '\n')
1972                         /* Looking at the final LF at the end of the file */
1973                         scanp--;
1974                 at_tail = 0;
1975
1976                 while (buf < scanp) {
1977                         /*
1978                          * terminating LF of the previous line, or the beginning
1979                          * of the buffer.
1980                          */
1981                         char *bp;
1982
1983                         bp = find_beginning_of_line(buf, scanp);
1984
1985                         if (*bp == '\n') {
1986                                 /*
1987                                  * The newline is the end of the previous line,
1988                                  * so we know we have complete line starting
1989                                  * at (bp + 1). Prefix it onto any prior data
1990                                  * we collected for the line and process it.
1991                                  */
1992                                 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
1993                                 scanp = bp;
1994                                 endp = bp + 1;
1995                                 ret = show_one_reflog_ent(&sb, fn, cb_data);
1996                                 strbuf_reset(&sb);
1997                                 if (ret)
1998                                         break;
1999                         } else if (!pos) {
2000                                 /*
2001                                  * We are at the start of the buffer, and the
2002                                  * start of the file; there is no previous
2003                                  * line, and we have everything for this one.
2004                                  * Process it, and we can end the loop.
2005                                  */
2006                                 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2007                                 ret = show_one_reflog_ent(&sb, fn, cb_data);
2008                                 strbuf_reset(&sb);
2009                                 break;
2010                         }
2011
2012                         if (bp == buf) {
2013                                 /*
2014                                  * We are at the start of the buffer, and there
2015                                  * is more file to read backwards. Which means
2016                                  * we are in the middle of a line. Note that we
2017                                  * may get here even if *bp was a newline; that
2018                                  * just means we are at the exact end of the
2019                                  * previous line, rather than some spot in the
2020                                  * middle.
2021                                  *
2022                                  * Save away what we have to be combined with
2023                                  * the data from the next read.
2024                                  */
2025                                 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2026                                 break;
2027                         }
2028                 }
2029
2030         }
2031         if (!ret && sb.len)
2032                 BUG("reverse reflog parser had leftover data");
2033
2034         fclose(logfp);
2035         strbuf_release(&sb);
2036         return ret;
2037 }
2038
2039 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2040                                      const char *refname,
2041                                      each_reflog_ent_fn fn, void *cb_data)
2042 {
2043         struct files_ref_store *refs =
2044                 files_downcast(ref_store, REF_STORE_READ,
2045                                "for_each_reflog_ent");
2046         FILE *logfp;
2047         struct strbuf sb = STRBUF_INIT;
2048         int ret = 0;
2049
2050         files_reflog_path(refs, &sb, refname);
2051         logfp = fopen(sb.buf, "r");
2052         strbuf_release(&sb);
2053         if (!logfp)
2054                 return -1;
2055
2056         while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2057                 ret = show_one_reflog_ent(&sb, fn, cb_data);
2058         fclose(logfp);
2059         strbuf_release(&sb);
2060         return ret;
2061 }
2062
2063 struct files_reflog_iterator {
2064         struct ref_iterator base;
2065
2066         struct ref_store *ref_store;
2067         struct dir_iterator *dir_iterator;
2068         struct object_id oid;
2069 };
2070
2071 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2072 {
2073         struct files_reflog_iterator *iter =
2074                 (struct files_reflog_iterator *)ref_iterator;
2075         struct dir_iterator *diter = iter->dir_iterator;
2076         int ok;
2077
2078         while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2079                 int flags;
2080
2081                 if (!S_ISREG(diter->st.st_mode))
2082                         continue;
2083                 if (diter->basename[0] == '.')
2084                         continue;
2085                 if (ends_with(diter->basename, ".lock"))
2086                         continue;
2087
2088                 if (refs_read_ref_full(iter->ref_store,
2089                                        diter->relative_path, 0,
2090                                        &iter->oid, &flags)) {
2091                         error("bad ref for %s", diter->path.buf);
2092                         continue;
2093                 }
2094
2095                 iter->base.refname = diter->relative_path;
2096                 iter->base.oid = &iter->oid;
2097                 iter->base.flags = flags;
2098                 return ITER_OK;
2099         }
2100
2101         iter->dir_iterator = NULL;
2102         if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2103                 ok = ITER_ERROR;
2104         return ok;
2105 }
2106
2107 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2108                                    struct object_id *peeled)
2109 {
2110         BUG("ref_iterator_peel() called for reflog_iterator");
2111 }
2112
2113 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2114 {
2115         struct files_reflog_iterator *iter =
2116                 (struct files_reflog_iterator *)ref_iterator;
2117         int ok = ITER_DONE;
2118
2119         if (iter->dir_iterator)
2120                 ok = dir_iterator_abort(iter->dir_iterator);
2121
2122         base_ref_iterator_free(ref_iterator);
2123         return ok;
2124 }
2125
2126 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2127         files_reflog_iterator_advance,
2128         files_reflog_iterator_peel,
2129         files_reflog_iterator_abort
2130 };
2131
2132 static struct ref_iterator *reflog_iterator_begin(struct ref_store *ref_store,
2133                                                   const char *gitdir)
2134 {
2135         struct dir_iterator *diter;
2136         struct files_reflog_iterator *iter;
2137         struct ref_iterator *ref_iterator;
2138         struct strbuf sb = STRBUF_INIT;
2139
2140         strbuf_addf(&sb, "%s/logs", gitdir);
2141
2142         diter = dir_iterator_begin(sb.buf, 0);
2143         if (!diter) {
2144                 strbuf_release(&sb);
2145                 return empty_ref_iterator_begin();
2146         }
2147
2148         CALLOC_ARRAY(iter, 1);
2149         ref_iterator = &iter->base;
2150
2151         base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable, 0);
2152         iter->dir_iterator = diter;
2153         iter->ref_store = ref_store;
2154         strbuf_release(&sb);
2155
2156         return ref_iterator;
2157 }
2158
2159 static enum iterator_selection reflog_iterator_select(
2160         struct ref_iterator *iter_worktree,
2161         struct ref_iterator *iter_common,
2162         void *cb_data)
2163 {
2164         if (iter_worktree) {
2165                 /*
2166                  * We're a bit loose here. We probably should ignore
2167                  * common refs if they are accidentally added as
2168                  * per-worktree refs.
2169                  */
2170                 return ITER_SELECT_0;
2171         } else if (iter_common) {
2172                 if (ref_type(iter_common->refname) == REF_TYPE_NORMAL)
2173                         return ITER_SELECT_1;
2174
2175                 /*
2176                  * The main ref store may contain main worktree's
2177                  * per-worktree refs, which should be ignored
2178                  */
2179                 return ITER_SKIP_1;
2180         } else
2181                 return ITER_DONE;
2182 }
2183
2184 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2185 {
2186         struct files_ref_store *refs =
2187                 files_downcast(ref_store, REF_STORE_READ,
2188                                "reflog_iterator_begin");
2189
2190         if (!strcmp(refs->base.gitdir, refs->gitcommondir)) {
2191                 return reflog_iterator_begin(ref_store, refs->gitcommondir);
2192         } else {
2193                 return merge_ref_iterator_begin(
2194                         0, reflog_iterator_begin(ref_store, refs->base.gitdir),
2195                         reflog_iterator_begin(ref_store, refs->gitcommondir),
2196                         reflog_iterator_select, refs);
2197         }
2198 }
2199
2200 /*
2201  * If update is a direct update of head_ref (the reference pointed to
2202  * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2203  */
2204 static int split_head_update(struct ref_update *update,
2205                              struct ref_transaction *transaction,
2206                              const char *head_ref,
2207                              struct string_list *affected_refnames,
2208                              struct strbuf *err)
2209 {
2210         struct string_list_item *item;
2211         struct ref_update *new_update;
2212
2213         if ((update->flags & REF_LOG_ONLY) ||
2214             (update->flags & REF_IS_PRUNING) ||
2215             (update->flags & REF_UPDATE_VIA_HEAD))
2216                 return 0;
2217
2218         if (strcmp(update->refname, head_ref))
2219                 return 0;
2220
2221         /*
2222          * First make sure that HEAD is not already in the
2223          * transaction. This check is O(lg N) in the transaction
2224          * size, but it happens at most once per transaction.
2225          */
2226         if (string_list_has_string(affected_refnames, "HEAD")) {
2227                 /* An entry already existed */
2228                 strbuf_addf(err,
2229                             "multiple updates for 'HEAD' (including one "
2230                             "via its referent '%s') are not allowed",
2231                             update->refname);
2232                 return TRANSACTION_NAME_CONFLICT;
2233         }
2234
2235         new_update = ref_transaction_add_update(
2236                         transaction, "HEAD",
2237                         update->flags | REF_LOG_ONLY | REF_NO_DEREF,
2238                         &update->new_oid, &update->old_oid,
2239                         update->msg);
2240
2241         /*
2242          * Add "HEAD". This insertion is O(N) in the transaction
2243          * size, but it happens at most once per transaction.
2244          * Add new_update->refname instead of a literal "HEAD".
2245          */
2246         if (strcmp(new_update->refname, "HEAD"))
2247                 BUG("%s unexpectedly not 'HEAD'", new_update->refname);
2248         item = string_list_insert(affected_refnames, new_update->refname);
2249         item->util = new_update;
2250
2251         return 0;
2252 }
2253
2254 /*
2255  * update is for a symref that points at referent and doesn't have
2256  * REF_NO_DEREF set. Split it into two updates:
2257  * - The original update, but with REF_LOG_ONLY and REF_NO_DEREF set
2258  * - A new, separate update for the referent reference
2259  * Note that the new update will itself be subject to splitting when
2260  * the iteration gets to it.
2261  */
2262 static int split_symref_update(struct ref_update *update,
2263                                const char *referent,
2264                                struct ref_transaction *transaction,
2265                                struct string_list *affected_refnames,
2266                                struct strbuf *err)
2267 {
2268         struct string_list_item *item;
2269         struct ref_update *new_update;
2270         unsigned int new_flags;
2271
2272         /*
2273          * First make sure that referent is not already in the
2274          * transaction. This check is O(lg N) in the transaction
2275          * size, but it happens at most once per symref in a
2276          * transaction.
2277          */
2278         if (string_list_has_string(affected_refnames, referent)) {
2279                 /* An entry already exists */
2280                 strbuf_addf(err,
2281                             "multiple updates for '%s' (including one "
2282                             "via symref '%s') are not allowed",
2283                             referent, update->refname);
2284                 return TRANSACTION_NAME_CONFLICT;
2285         }
2286
2287         new_flags = update->flags;
2288         if (!strcmp(update->refname, "HEAD")) {
2289                 /*
2290                  * Record that the new update came via HEAD, so that
2291                  * when we process it, split_head_update() doesn't try
2292                  * to add another reflog update for HEAD. Note that
2293                  * this bit will be propagated if the new_update
2294                  * itself needs to be split.
2295                  */
2296                 new_flags |= REF_UPDATE_VIA_HEAD;
2297         }
2298
2299         new_update = ref_transaction_add_update(
2300                         transaction, referent, new_flags,
2301                         &update->new_oid, &update->old_oid,
2302                         update->msg);
2303
2304         new_update->parent_update = update;
2305
2306         /*
2307          * Change the symbolic ref update to log only. Also, it
2308          * doesn't need to check its old OID value, as that will be
2309          * done when new_update is processed.
2310          */
2311         update->flags |= REF_LOG_ONLY | REF_NO_DEREF;
2312         update->flags &= ~REF_HAVE_OLD;
2313
2314         /*
2315          * Add the referent. This insertion is O(N) in the transaction
2316          * size, but it happens at most once per symref in a
2317          * transaction. Make sure to add new_update->refname, which will
2318          * be valid as long as affected_refnames is in use, and NOT
2319          * referent, which might soon be freed by our caller.
2320          */
2321         item = string_list_insert(affected_refnames, new_update->refname);
2322         if (item->util)
2323                 BUG("%s unexpectedly found in affected_refnames",
2324                     new_update->refname);
2325         item->util = new_update;
2326
2327         return 0;
2328 }
2329
2330 /*
2331  * Return the refname under which update was originally requested.
2332  */
2333 static const char *original_update_refname(struct ref_update *update)
2334 {
2335         while (update->parent_update)
2336                 update = update->parent_update;
2337
2338         return update->refname;
2339 }
2340
2341 /*
2342  * Check whether the REF_HAVE_OLD and old_oid values stored in update
2343  * are consistent with oid, which is the reference's current value. If
2344  * everything is OK, return 0; otherwise, write an error message to
2345  * err and return -1.
2346  */
2347 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2348                          struct strbuf *err)
2349 {
2350         if (!(update->flags & REF_HAVE_OLD) ||
2351                    oideq(oid, &update->old_oid))
2352                 return 0;
2353
2354         if (is_null_oid(&update->old_oid))
2355                 strbuf_addf(err, "cannot lock ref '%s': "
2356                             "reference already exists",
2357                             original_update_refname(update));
2358         else if (is_null_oid(oid))
2359                 strbuf_addf(err, "cannot lock ref '%s': "
2360                             "reference is missing but expected %s",
2361                             original_update_refname(update),
2362                             oid_to_hex(&update->old_oid));
2363         else
2364                 strbuf_addf(err, "cannot lock ref '%s': "
2365                             "is at %s but expected %s",
2366                             original_update_refname(update),
2367                             oid_to_hex(oid),
2368                             oid_to_hex(&update->old_oid));
2369
2370         return -1;
2371 }
2372
2373 /*
2374  * Prepare for carrying out update:
2375  * - Lock the reference referred to by update.
2376  * - Read the reference under lock.
2377  * - Check that its old OID value (if specified) is correct, and in
2378  *   any case record it in update->lock->old_oid for later use when
2379  *   writing the reflog.
2380  * - If it is a symref update without REF_NO_DEREF, split it up into a
2381  *   REF_LOG_ONLY update of the symref and add a separate update for
2382  *   the referent to transaction.
2383  * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2384  *   update of HEAD.
2385  */
2386 static int lock_ref_for_update(struct files_ref_store *refs,
2387                                struct ref_update *update,
2388                                struct ref_transaction *transaction,
2389                                const char *head_ref,
2390                                struct string_list *affected_refnames,
2391                                struct strbuf *err)
2392 {
2393         struct strbuf referent = STRBUF_INIT;
2394         int mustexist = (update->flags & REF_HAVE_OLD) &&
2395                 !is_null_oid(&update->old_oid);
2396         int ret = 0;
2397         struct ref_lock *lock;
2398
2399         files_assert_main_repository(refs, "lock_ref_for_update");
2400
2401         if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2402                 update->flags |= REF_DELETING;
2403
2404         if (head_ref) {
2405                 ret = split_head_update(update, transaction, head_ref,
2406                                         affected_refnames, err);
2407                 if (ret)
2408                         goto out;
2409         }
2410
2411         ret = lock_raw_ref(refs, update->refname, mustexist,
2412                            affected_refnames, NULL,
2413                            &lock, &referent,
2414                            &update->type, err);
2415         if (ret) {
2416                 char *reason;
2417
2418                 reason = strbuf_detach(err, NULL);
2419                 strbuf_addf(err, "cannot lock ref '%s': %s",
2420                             original_update_refname(update), reason);
2421                 free(reason);
2422                 goto out;
2423         }
2424
2425         update->backend_data = lock;
2426
2427         if (update->type & REF_ISSYMREF) {
2428                 if (update->flags & REF_NO_DEREF) {
2429                         /*
2430                          * We won't be reading the referent as part of
2431                          * the transaction, so we have to read it here
2432                          * to record and possibly check old_oid:
2433                          */
2434                         if (refs_read_ref_full(&refs->base,
2435                                                referent.buf, 0,
2436                                                &lock->old_oid, NULL)) {
2437                                 if (update->flags & REF_HAVE_OLD) {
2438                                         strbuf_addf(err, "cannot lock ref '%s': "
2439                                                     "error reading reference",
2440                                                     original_update_refname(update));
2441                                         ret = TRANSACTION_GENERIC_ERROR;
2442                                         goto out;
2443                                 }
2444                         } else if (check_old_oid(update, &lock->old_oid, err)) {
2445                                 ret = TRANSACTION_GENERIC_ERROR;
2446                                 goto out;
2447                         }
2448                 } else {
2449                         /*
2450                          * Create a new update for the reference this
2451                          * symref is pointing at. Also, we will record
2452                          * and verify old_oid for this update as part
2453                          * of processing the split-off update, so we
2454                          * don't have to do it here.
2455                          */
2456                         ret = split_symref_update(update,
2457                                                   referent.buf, transaction,
2458                                                   affected_refnames, err);
2459                         if (ret)
2460                                 goto out;
2461                 }
2462         } else {
2463                 struct ref_update *parent_update;
2464
2465                 if (check_old_oid(update, &lock->old_oid, err)) {
2466                         ret = TRANSACTION_GENERIC_ERROR;
2467                         goto out;
2468                 }
2469
2470                 /*
2471                  * If this update is happening indirectly because of a
2472                  * symref update, record the old OID in the parent
2473                  * update:
2474                  */
2475                 for (parent_update = update->parent_update;
2476                      parent_update;
2477                      parent_update = parent_update->parent_update) {
2478                         struct ref_lock *parent_lock = parent_update->backend_data;
2479                         oidcpy(&parent_lock->old_oid, &lock->old_oid);
2480                 }
2481         }
2482
2483         if ((update->flags & REF_HAVE_NEW) &&
2484             !(update->flags & REF_DELETING) &&
2485             !(update->flags & REF_LOG_ONLY)) {
2486                 if (!(update->type & REF_ISSYMREF) &&
2487                     oideq(&lock->old_oid, &update->new_oid)) {
2488                         /*
2489                          * The reference already has the desired
2490                          * value, so we don't need to write it.
2491                          */
2492                 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2493                                                  err)) {
2494                         char *write_err = strbuf_detach(err, NULL);
2495
2496                         /*
2497                          * The lock was freed upon failure of
2498                          * write_ref_to_lockfile():
2499                          */
2500                         update->backend_data = NULL;
2501                         strbuf_addf(err,
2502                                     "cannot update ref '%s': %s",
2503                                     update->refname, write_err);
2504                         free(write_err);
2505                         ret = TRANSACTION_GENERIC_ERROR;
2506                         goto out;
2507                 } else {
2508                         update->flags |= REF_NEEDS_COMMIT;
2509                 }
2510         }
2511         if (!(update->flags & REF_NEEDS_COMMIT)) {
2512                 /*
2513                  * We didn't call write_ref_to_lockfile(), so
2514                  * the lockfile is still open. Close it to
2515                  * free up the file descriptor:
2516                  */
2517                 if (close_ref_gently(lock)) {
2518                         strbuf_addf(err, "couldn't close '%s.lock'",
2519                                     update->refname);
2520                         ret = TRANSACTION_GENERIC_ERROR;
2521                         goto out;
2522                 }
2523         }
2524
2525 out:
2526         strbuf_release(&referent);
2527         return ret;
2528 }
2529
2530 struct files_transaction_backend_data {
2531         struct ref_transaction *packed_transaction;
2532         int packed_refs_locked;
2533 };
2534
2535 /*
2536  * Unlock any references in `transaction` that are still locked, and
2537  * mark the transaction closed.
2538  */
2539 static void files_transaction_cleanup(struct files_ref_store *refs,
2540                                       struct ref_transaction *transaction)
2541 {
2542         size_t i;
2543         struct files_transaction_backend_data *backend_data =
2544                 transaction->backend_data;
2545         struct strbuf err = STRBUF_INIT;
2546
2547         for (i = 0; i < transaction->nr; i++) {
2548                 struct ref_update *update = transaction->updates[i];
2549                 struct ref_lock *lock = update->backend_data;
2550
2551                 if (lock) {
2552                         unlock_ref(lock);
2553                         update->backend_data = NULL;
2554                 }
2555         }
2556
2557         if (backend_data) {
2558                 if (backend_data->packed_transaction &&
2559                     ref_transaction_abort(backend_data->packed_transaction, &err)) {
2560                         error("error aborting transaction: %s", err.buf);
2561                         strbuf_release(&err);
2562                 }
2563
2564                 if (backend_data->packed_refs_locked)
2565                         packed_refs_unlock(refs->packed_ref_store);
2566
2567                 free(backend_data);
2568         }
2569
2570         transaction->state = REF_TRANSACTION_CLOSED;
2571 }
2572
2573 static int files_transaction_prepare(struct ref_store *ref_store,
2574                                      struct ref_transaction *transaction,
2575                                      struct strbuf *err)
2576 {
2577         struct files_ref_store *refs =
2578                 files_downcast(ref_store, REF_STORE_WRITE,
2579                                "ref_transaction_prepare");
2580         size_t i;
2581         int ret = 0;
2582         struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2583         char *head_ref = NULL;
2584         int head_type;
2585         struct files_transaction_backend_data *backend_data;
2586         struct ref_transaction *packed_transaction = NULL;
2587
2588         assert(err);
2589
2590         if (!transaction->nr)
2591                 goto cleanup;
2592
2593         CALLOC_ARRAY(backend_data, 1);
2594         transaction->backend_data = backend_data;
2595
2596         /*
2597          * Fail if a refname appears more than once in the
2598          * transaction. (If we end up splitting up any updates using
2599          * split_symref_update() or split_head_update(), those
2600          * functions will check that the new updates don't have the
2601          * same refname as any existing ones.) Also fail if any of the
2602          * updates use REF_IS_PRUNING without REF_NO_DEREF.
2603          */
2604         for (i = 0; i < transaction->nr; i++) {
2605                 struct ref_update *update = transaction->updates[i];
2606                 struct string_list_item *item =
2607                         string_list_append(&affected_refnames, update->refname);
2608
2609                 if ((update->flags & REF_IS_PRUNING) &&
2610                     !(update->flags & REF_NO_DEREF))
2611                         BUG("REF_IS_PRUNING set without REF_NO_DEREF");
2612
2613                 /*
2614                  * We store a pointer to update in item->util, but at
2615                  * the moment we never use the value of this field
2616                  * except to check whether it is non-NULL.
2617                  */
2618                 item->util = update;
2619         }
2620         string_list_sort(&affected_refnames);
2621         if (ref_update_reject_duplicates(&affected_refnames, err)) {
2622                 ret = TRANSACTION_GENERIC_ERROR;
2623                 goto cleanup;
2624         }
2625
2626         /*
2627          * Special hack: If a branch is updated directly and HEAD
2628          * points to it (may happen on the remote side of a push
2629          * for example) then logically the HEAD reflog should be
2630          * updated too.
2631          *
2632          * A generic solution would require reverse symref lookups,
2633          * but finding all symrefs pointing to a given branch would be
2634          * rather costly for this rare event (the direct update of a
2635          * branch) to be worth it. So let's cheat and check with HEAD
2636          * only, which should cover 99% of all usage scenarios (even
2637          * 100% of the default ones).
2638          *
2639          * So if HEAD is a symbolic reference, then record the name of
2640          * the reference that it points to. If we see an update of
2641          * head_ref within the transaction, then split_head_update()
2642          * arranges for the reflog of HEAD to be updated, too.
2643          */
2644         head_ref = refs_resolve_refdup(ref_store, "HEAD",
2645                                        RESOLVE_REF_NO_RECURSE,
2646                                        NULL, &head_type);
2647
2648         if (head_ref && !(head_type & REF_ISSYMREF)) {
2649                 FREE_AND_NULL(head_ref);
2650         }
2651
2652         /*
2653          * Acquire all locks, verify old values if provided, check
2654          * that new values are valid, and write new values to the
2655          * lockfiles, ready to be activated. Only keep one lockfile
2656          * open at a time to avoid running out of file descriptors.
2657          * Note that lock_ref_for_update() might append more updates
2658          * to the transaction.
2659          */
2660         for (i = 0; i < transaction->nr; i++) {
2661                 struct ref_update *update = transaction->updates[i];
2662
2663                 ret = lock_ref_for_update(refs, update, transaction,
2664                                           head_ref, &affected_refnames, err);
2665                 if (ret)
2666                         goto cleanup;
2667
2668                 if (update->flags & REF_DELETING &&
2669                     !(update->flags & REF_LOG_ONLY) &&
2670                     !(update->flags & REF_IS_PRUNING)) {
2671                         /*
2672                          * This reference has to be deleted from
2673                          * packed-refs if it exists there.
2674                          */
2675                         if (!packed_transaction) {
2676                                 packed_transaction = ref_store_transaction_begin(
2677                                                 refs->packed_ref_store, err);
2678                                 if (!packed_transaction) {
2679                                         ret = TRANSACTION_GENERIC_ERROR;
2680                                         goto cleanup;
2681                                 }
2682
2683                                 backend_data->packed_transaction =
2684                                         packed_transaction;
2685                         }
2686
2687                         ref_transaction_add_update(
2688                                         packed_transaction, update->refname,
2689                                         REF_HAVE_NEW | REF_NO_DEREF,
2690                                         &update->new_oid, NULL,
2691                                         NULL);
2692                 }
2693         }
2694
2695         if (packed_transaction) {
2696                 if (packed_refs_lock(refs->packed_ref_store, 0, err)) {
2697                         ret = TRANSACTION_GENERIC_ERROR;
2698                         goto cleanup;
2699                 }
2700                 backend_data->packed_refs_locked = 1;
2701
2702                 if (is_packed_transaction_needed(refs->packed_ref_store,
2703                                                  packed_transaction)) {
2704                         ret = ref_transaction_prepare(packed_transaction, err);
2705                         /*
2706                          * A failure during the prepare step will abort
2707                          * itself, but not free. Do that now, and disconnect
2708                          * from the files_transaction so it does not try to
2709                          * abort us when we hit the cleanup code below.
2710                          */
2711                         if (ret) {
2712                                 ref_transaction_free(packed_transaction);
2713                                 backend_data->packed_transaction = NULL;
2714                         }
2715                 } else {
2716                         /*
2717                          * We can skip rewriting the `packed-refs`
2718                          * file. But we do need to leave it locked, so
2719                          * that somebody else doesn't pack a reference
2720                          * that we are trying to delete.
2721                          *
2722                          * We need to disconnect our transaction from
2723                          * backend_data, since the abort (whether successful or
2724                          * not) will free it.
2725                          */
2726                         backend_data->packed_transaction = NULL;
2727                         if (ref_transaction_abort(packed_transaction, err)) {
2728                                 ret = TRANSACTION_GENERIC_ERROR;
2729                                 goto cleanup;
2730                         }
2731                 }
2732         }
2733
2734 cleanup:
2735         free(head_ref);
2736         string_list_clear(&affected_refnames, 0);
2737
2738         if (ret)
2739                 files_transaction_cleanup(refs, transaction);
2740         else
2741                 transaction->state = REF_TRANSACTION_PREPARED;
2742
2743         return ret;
2744 }
2745
2746 static int files_transaction_finish(struct ref_store *ref_store,
2747                                     struct ref_transaction *transaction,
2748                                     struct strbuf *err)
2749 {
2750         struct files_ref_store *refs =
2751                 files_downcast(ref_store, 0, "ref_transaction_finish");
2752         size_t i;
2753         int ret = 0;
2754         struct strbuf sb = STRBUF_INIT;
2755         struct files_transaction_backend_data *backend_data;
2756         struct ref_transaction *packed_transaction;
2757
2758
2759         assert(err);
2760
2761         if (!transaction->nr) {
2762                 transaction->state = REF_TRANSACTION_CLOSED;
2763                 return 0;
2764         }
2765
2766         backend_data = transaction->backend_data;
2767         packed_transaction = backend_data->packed_transaction;
2768
2769         /* Perform updates first so live commits remain referenced */
2770         for (i = 0; i < transaction->nr; i++) {
2771                 struct ref_update *update = transaction->updates[i];
2772                 struct ref_lock *lock = update->backend_data;
2773
2774                 if (update->flags & REF_NEEDS_COMMIT ||
2775                     update->flags & REF_LOG_ONLY) {
2776                         if (files_log_ref_write(refs,
2777                                                 lock->ref_name,
2778                                                 &lock->old_oid,
2779                                                 &update->new_oid,
2780                                                 update->msg, update->flags,
2781                                                 err)) {
2782                                 char *old_msg = strbuf_detach(err, NULL);
2783
2784                                 strbuf_addf(err, "cannot update the ref '%s': %s",
2785                                             lock->ref_name, old_msg);
2786                                 free(old_msg);
2787                                 unlock_ref(lock);
2788                                 update->backend_data = NULL;
2789                                 ret = TRANSACTION_GENERIC_ERROR;
2790                                 goto cleanup;
2791                         }
2792                 }
2793                 if (update->flags & REF_NEEDS_COMMIT) {
2794                         clear_loose_ref_cache(refs);
2795                         if (commit_ref(lock)) {
2796                                 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2797                                 unlock_ref(lock);
2798                                 update->backend_data = NULL;
2799                                 ret = TRANSACTION_GENERIC_ERROR;
2800                                 goto cleanup;
2801                         }
2802                 }
2803         }
2804
2805         /*
2806          * Now that updates are safely completed, we can perform
2807          * deletes. First delete the reflogs of any references that
2808          * will be deleted, since (in the unexpected event of an
2809          * error) leaving a reference without a reflog is less bad
2810          * than leaving a reflog without a reference (the latter is a
2811          * mildly invalid repository state):
2812          */
2813         for (i = 0; i < transaction->nr; i++) {
2814                 struct ref_update *update = transaction->updates[i];
2815                 if (update->flags & REF_DELETING &&
2816                     !(update->flags & REF_LOG_ONLY) &&
2817                     !(update->flags & REF_IS_PRUNING)) {
2818                         strbuf_reset(&sb);
2819                         files_reflog_path(refs, &sb, update->refname);
2820                         if (!unlink_or_warn(sb.buf))
2821                                 try_remove_empty_parents(refs, update->refname,
2822                                                          REMOVE_EMPTY_PARENTS_REFLOG);
2823                 }
2824         }
2825
2826         /*
2827          * Perform deletes now that updates are safely completed.
2828          *
2829          * First delete any packed versions of the references, while
2830          * retaining the packed-refs lock:
2831          */
2832         if (packed_transaction) {
2833                 ret = ref_transaction_commit(packed_transaction, err);
2834                 ref_transaction_free(packed_transaction);
2835                 packed_transaction = NULL;
2836                 backend_data->packed_transaction = NULL;
2837                 if (ret)
2838                         goto cleanup;
2839         }
2840
2841         /* Now delete the loose versions of the references: */
2842         for (i = 0; i < transaction->nr; i++) {
2843                 struct ref_update *update = transaction->updates[i];
2844                 struct ref_lock *lock = update->backend_data;
2845
2846                 if (update->flags & REF_DELETING &&
2847                     !(update->flags & REF_LOG_ONLY)) {
2848                         update->flags |= REF_DELETED_RMDIR;
2849                         if (!(update->type & REF_ISPACKED) ||
2850                             update->type & REF_ISSYMREF) {
2851                                 /* It is a loose reference. */
2852                                 strbuf_reset(&sb);
2853                                 files_ref_path(refs, &sb, lock->ref_name);
2854                                 if (unlink_or_msg(sb.buf, err)) {
2855                                         ret = TRANSACTION_GENERIC_ERROR;
2856                                         goto cleanup;
2857                                 }
2858                         }
2859                 }
2860         }
2861
2862         clear_loose_ref_cache(refs);
2863
2864 cleanup:
2865         files_transaction_cleanup(refs, transaction);
2866
2867         for (i = 0; i < transaction->nr; i++) {
2868                 struct ref_update *update = transaction->updates[i];
2869
2870                 if (update->flags & REF_DELETED_RMDIR) {
2871                         /*
2872                          * The reference was deleted. Delete any
2873                          * empty parent directories. (Note that this
2874                          * can only work because we have already
2875                          * removed the lockfile.)
2876                          */
2877                         try_remove_empty_parents(refs, update->refname,
2878                                                  REMOVE_EMPTY_PARENTS_REF);
2879                 }
2880         }
2881
2882         strbuf_release(&sb);
2883         return ret;
2884 }
2885
2886 static int files_transaction_abort(struct ref_store *ref_store,
2887                                    struct ref_transaction *transaction,
2888                                    struct strbuf *err)
2889 {
2890         struct files_ref_store *refs =
2891                 files_downcast(ref_store, 0, "ref_transaction_abort");
2892
2893         files_transaction_cleanup(refs, transaction);
2894         return 0;
2895 }
2896
2897 static int ref_present(const char *refname,
2898                        const struct object_id *oid, int flags, void *cb_data)
2899 {
2900         struct string_list *affected_refnames = cb_data;
2901
2902         return string_list_has_string(affected_refnames, refname);
2903 }
2904
2905 static int files_initial_transaction_commit(struct ref_store *ref_store,
2906                                             struct ref_transaction *transaction,
2907                                             struct strbuf *err)
2908 {
2909         struct files_ref_store *refs =
2910                 files_downcast(ref_store, REF_STORE_WRITE,
2911                                "initial_ref_transaction_commit");
2912         size_t i;
2913         int ret = 0;
2914         struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2915         struct ref_transaction *packed_transaction = NULL;
2916
2917         assert(err);
2918
2919         if (transaction->state != REF_TRANSACTION_OPEN)
2920                 BUG("commit called for transaction that is not open");
2921
2922         /* Fail if a refname appears more than once in the transaction: */
2923         for (i = 0; i < transaction->nr; i++)
2924                 string_list_append(&affected_refnames,
2925                                    transaction->updates[i]->refname);
2926         string_list_sort(&affected_refnames);
2927         if (ref_update_reject_duplicates(&affected_refnames, err)) {
2928                 ret = TRANSACTION_GENERIC_ERROR;
2929                 goto cleanup;
2930         }
2931
2932         /*
2933          * It's really undefined to call this function in an active
2934          * repository or when there are existing references: we are
2935          * only locking and changing packed-refs, so (1) any
2936          * simultaneous processes might try to change a reference at
2937          * the same time we do, and (2) any existing loose versions of
2938          * the references that we are setting would have precedence
2939          * over our values. But some remote helpers create the remote
2940          * "HEAD" and "master" branches before calling this function,
2941          * so here we really only check that none of the references
2942          * that we are creating already exists.
2943          */
2944         if (refs_for_each_rawref(&refs->base, ref_present,
2945                                  &affected_refnames))
2946                 BUG("initial ref transaction called with existing refs");
2947
2948         packed_transaction = ref_store_transaction_begin(refs->packed_ref_store, err);
2949         if (!packed_transaction) {
2950                 ret = TRANSACTION_GENERIC_ERROR;
2951                 goto cleanup;
2952         }
2953
2954         for (i = 0; i < transaction->nr; i++) {
2955                 struct ref_update *update = transaction->updates[i];
2956
2957                 if ((update->flags & REF_HAVE_OLD) &&
2958                     !is_null_oid(&update->old_oid))
2959                         BUG("initial ref transaction with old_sha1 set");
2960                 if (refs_verify_refname_available(&refs->base, update->refname,
2961                                                   &affected_refnames, NULL,
2962                                                   err)) {
2963                         ret = TRANSACTION_NAME_CONFLICT;
2964                         goto cleanup;
2965                 }
2966
2967                 /*
2968                  * Add a reference creation for this reference to the
2969                  * packed-refs transaction:
2970                  */
2971                 ref_transaction_add_update(packed_transaction, update->refname,
2972                                            update->flags & ~REF_HAVE_OLD,
2973                                            &update->new_oid, &update->old_oid,
2974                                            NULL);
2975         }
2976
2977         if (packed_refs_lock(refs->packed_ref_store, 0, err)) {
2978                 ret = TRANSACTION_GENERIC_ERROR;
2979                 goto cleanup;
2980         }
2981
2982         if (initial_ref_transaction_commit(packed_transaction, err)) {
2983                 ret = TRANSACTION_GENERIC_ERROR;
2984         }
2985
2986         packed_refs_unlock(refs->packed_ref_store);
2987 cleanup:
2988         if (packed_transaction)
2989                 ref_transaction_free(packed_transaction);
2990         transaction->state = REF_TRANSACTION_CLOSED;
2991         string_list_clear(&affected_refnames, 0);
2992         return ret;
2993 }
2994
2995 struct expire_reflog_cb {
2996         unsigned int flags;
2997         reflog_expiry_should_prune_fn *should_prune_fn;
2998         void *policy_cb;
2999         FILE *newlog;
3000         struct object_id last_kept_oid;
3001 };
3002
3003 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
3004                              const char *email, timestamp_t timestamp, int tz,
3005                              const char *message, void *cb_data)
3006 {
3007         struct expire_reflog_cb *cb = cb_data;
3008         struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3009
3010         if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3011                 ooid = &cb->last_kept_oid;
3012
3013         if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
3014                                    message, policy_cb)) {
3015                 if (!cb->newlog)
3016                         printf("would prune %s", message);
3017                 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3018                         printf("prune %s", message);
3019         } else {
3020                 if (cb->newlog) {
3021                         fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
3022                                 oid_to_hex(ooid), oid_to_hex(noid),
3023                                 email, timestamp, tz, message);
3024                         oidcpy(&cb->last_kept_oid, noid);
3025                 }
3026                 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3027                         printf("keep %s", message);
3028         }
3029         return 0;
3030 }
3031
3032 static int files_reflog_expire(struct ref_store *ref_store,
3033                                const char *refname, const struct object_id *oid,
3034                                unsigned int flags,
3035                                reflog_expiry_prepare_fn prepare_fn,
3036                                reflog_expiry_should_prune_fn should_prune_fn,
3037                                reflog_expiry_cleanup_fn cleanup_fn,
3038                                void *policy_cb_data)
3039 {
3040         struct files_ref_store *refs =
3041                 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
3042         struct lock_file reflog_lock = LOCK_INIT;
3043         struct expire_reflog_cb cb;
3044         struct ref_lock *lock;
3045         struct strbuf log_file_sb = STRBUF_INIT;
3046         char *log_file;
3047         int status = 0;
3048         int type;
3049         struct strbuf err = STRBUF_INIT;
3050
3051         memset(&cb, 0, sizeof(cb));
3052         cb.flags = flags;
3053         cb.policy_cb = policy_cb_data;
3054         cb.should_prune_fn = should_prune_fn;
3055
3056         /*
3057          * The reflog file is locked by holding the lock on the
3058          * reference itself, plus we might need to update the
3059          * reference if --updateref was specified:
3060          */
3061         lock = lock_ref_oid_basic(refs, refname, oid,
3062                                   NULL, NULL, REF_NO_DEREF,
3063                                   &type, &err);
3064         if (!lock) {
3065                 error("cannot lock ref '%s': %s", refname, err.buf);
3066                 strbuf_release(&err);
3067                 return -1;
3068         }
3069         if (!refs_reflog_exists(ref_store, refname)) {
3070                 unlock_ref(lock);
3071                 return 0;
3072         }
3073
3074         files_reflog_path(refs, &log_file_sb, refname);
3075         log_file = strbuf_detach(&log_file_sb, NULL);
3076         if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3077                 /*
3078                  * Even though holding $GIT_DIR/logs/$reflog.lock has
3079                  * no locking implications, we use the lock_file
3080                  * machinery here anyway because it does a lot of the
3081                  * work we need, including cleaning up if the program
3082                  * exits unexpectedly.
3083                  */
3084                 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3085                         struct strbuf err = STRBUF_INIT;
3086                         unable_to_lock_message(log_file, errno, &err);
3087                         error("%s", err.buf);
3088                         strbuf_release(&err);
3089                         goto failure;
3090                 }
3091                 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3092                 if (!cb.newlog) {
3093                         error("cannot fdopen %s (%s)",
3094                               get_lock_file_path(&reflog_lock), strerror(errno));
3095                         goto failure;
3096                 }
3097         }
3098
3099         (*prepare_fn)(refname, oid, cb.policy_cb);
3100         refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3101         (*cleanup_fn)(cb.policy_cb);
3102
3103         if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3104                 /*
3105                  * It doesn't make sense to adjust a reference pointed
3106                  * to by a symbolic ref based on expiring entries in
3107                  * the symbolic reference's reflog. Nor can we update
3108                  * a reference if there are no remaining reflog
3109                  * entries.
3110                  */
3111                 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3112                         !(type & REF_ISSYMREF) &&
3113                         !is_null_oid(&cb.last_kept_oid);
3114
3115                 if (close_lock_file_gently(&reflog_lock)) {
3116                         status |= error("couldn't write %s: %s", log_file,
3117                                         strerror(errno));
3118                         rollback_lock_file(&reflog_lock);
3119                 } else if (update &&
3120                            (write_in_full(get_lock_file_fd(&lock->lk),
3121                                 oid_to_hex(&cb.last_kept_oid), the_hash_algo->hexsz) < 0 ||
3122                             write_str_in_full(get_lock_file_fd(&lock->lk), "\n") < 0 ||
3123                             close_ref_gently(lock) < 0)) {
3124                         status |= error("couldn't write %s",
3125                                         get_lock_file_path(&lock->lk));
3126                         rollback_lock_file(&reflog_lock);
3127                 } else if (commit_lock_file(&reflog_lock)) {
3128                         status |= error("unable to write reflog '%s' (%s)",
3129                                         log_file, strerror(errno));
3130                 } else if (update && commit_ref(lock)) {
3131                         status |= error("couldn't set %s", lock->ref_name);
3132                 }
3133         }
3134         free(log_file);
3135         unlock_ref(lock);
3136         return status;
3137
3138  failure:
3139         rollback_lock_file(&reflog_lock);
3140         free(log_file);
3141         unlock_ref(lock);
3142         return -1;
3143 }
3144
3145 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3146 {
3147         struct files_ref_store *refs =
3148                 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3149         struct strbuf sb = STRBUF_INIT;
3150
3151         /*
3152          * Create .git/refs/{heads,tags}
3153          */
3154         files_ref_path(refs, &sb, "refs/heads");
3155         safe_create_dir(sb.buf, 1);
3156
3157         strbuf_reset(&sb);
3158         files_ref_path(refs, &sb, "refs/tags");
3159         safe_create_dir(sb.buf, 1);
3160
3161         strbuf_release(&sb);
3162         return 0;
3163 }
3164
3165 struct ref_storage_be refs_be_files = {
3166         NULL,
3167         "files",
3168         files_ref_store_create,
3169         files_init_db,
3170         files_transaction_prepare,
3171         files_transaction_finish,
3172         files_transaction_abort,
3173         files_initial_transaction_commit,
3174
3175         files_pack_refs,
3176         files_create_symref,
3177         files_delete_refs,
3178         files_rename_ref,
3179         files_copy_ref,
3180
3181         files_ref_iterator_begin,
3182         files_read_raw_ref,
3183
3184         files_reflog_iterator_begin,
3185         files_for_each_reflog_ent,
3186         files_for_each_reflog_ent_reverse,
3187         files_reflog_exists,
3188         files_create_reflog,
3189         files_delete_reflog,
3190         files_reflog_expire
3191 };