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