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