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