1 /*
2  * Copyright (C) the libgit2 contributors. All rights reserved.
3  *
4  * This file is part of libgit2, distributed under the GNU GPL v2 with
5  * a Linking Exception. For full terms see the included COPYING file.
6  */
7 
8 #include "refs.h"
9 #include "hash.h"
10 #include "repository.h"
11 #include "futils.h"
12 #include "filebuf.h"
13 #include "pack.h"
14 #include "parse.h"
15 #include "reflog.h"
16 #include "refdb.h"
17 #include "iterator.h"
18 #include "sortedcache.h"
19 #include "signature.h"
20 #include "wildmatch.h"
21 
22 #include <git2/tag.h>
23 #include <git2/object.h>
24 #include <git2/refdb.h>
25 #include <git2/branch.h>
26 #include <git2/sys/refdb_backend.h>
27 #include <git2/sys/refs.h>
28 #include <git2/sys/reflog.h>
29 
30 #define DEFAULT_NESTING_LEVEL	5
31 #define MAX_NESTING_LEVEL		10
32 
33 enum {
34 	PACKREF_HAS_PEEL = 1,
35 	PACKREF_WAS_LOOSE = 2,
36 	PACKREF_CANNOT_PEEL = 4,
37 	PACKREF_SHADOWED = 8,
38 };
39 
40 enum {
41 	PEELING_NONE = 0,
42 	PEELING_STANDARD,
43 	PEELING_FULL
44 };
45 
46 struct packref {
47 	git_oid oid;
48 	git_oid peel;
49 	char flags;
50 	char name[GIT_FLEX_ARRAY];
51 };
52 
53 typedef struct refdb_fs_backend {
54 	git_refdb_backend parent;
55 
56 	git_repository *repo;
57 	/* path to git directory */
58 	char *gitpath;
59 	/* path to common objects' directory */
60 	char *commonpath;
61 
62 	git_sortedcache *refcache;
63 	int peeling_mode;
64 	git_iterator_flag_t iterator_flags;
65 	uint32_t direach_flags;
66 	int fsync;
67 } refdb_fs_backend;
68 
69 static int refdb_reflog_fs__delete(git_refdb_backend *_backend, const char *name);
70 
packref_cmp(const void * a_,const void * b_)71 static int packref_cmp(const void *a_, const void *b_)
72 {
73 	const struct packref *a = a_, *b = b_;
74 	return strcmp(a->name, b->name);
75 }
76 
packed_reload(refdb_fs_backend * backend)77 static int packed_reload(refdb_fs_backend *backend)
78 {
79 	int error;
80 	git_buf packedrefs = GIT_BUF_INIT;
81 	char *scan, *eof, *eol;
82 
83 	if (!backend->gitpath)
84 		return 0;
85 
86 	error = git_sortedcache_lockandload(backend->refcache, &packedrefs);
87 
88 	/*
89 	 * If we can't find the packed-refs, clear table and return.
90 	 * Any other error just gets passed through.
91 	 * If no error, and file wasn't changed, just return.
92 	 * Anything else means we need to refresh the packed refs.
93 	 */
94 	if (error <= 0) {
95 		if (error == GIT_ENOTFOUND) {
96 			git_sortedcache_clear(backend->refcache, true);
97 			git_error_clear();
98 			error = 0;
99 		}
100 		return error;
101 	}
102 
103 	/* At this point, refresh the packed refs from the loaded buffer. */
104 
105 	git_sortedcache_clear(backend->refcache, false);
106 
107 	scan = (char *)packedrefs.ptr;
108 	eof  = scan + packedrefs.size;
109 
110 	backend->peeling_mode = PEELING_NONE;
111 
112 	if (*scan == '#') {
113 		static const char *traits_header = "# pack-refs with: ";
114 
115 		if (git__prefixcmp(scan, traits_header) == 0) {
116 			scan += strlen(traits_header);
117 			eol = strchr(scan, '\n');
118 
119 			if (!eol)
120 				goto parse_failed;
121 			*eol = '\0';
122 
123 			if (strstr(scan, " fully-peeled ") != NULL) {
124 				backend->peeling_mode = PEELING_FULL;
125 			} else if (strstr(scan, " peeled ") != NULL) {
126 				backend->peeling_mode = PEELING_STANDARD;
127 			}
128 
129 			scan = eol + 1;
130 		}
131 	}
132 
133 	while (scan < eof && *scan == '#') {
134 		if (!(eol = strchr(scan, '\n')))
135 			goto parse_failed;
136 		scan = eol + 1;
137 	}
138 
139 	while (scan < eof) {
140 		struct packref *ref;
141 		git_oid oid;
142 
143 		/* parse "<OID> <refname>\n" */
144 
145 		if (git_oid_fromstr(&oid, scan) < 0)
146 			goto parse_failed;
147 		scan += GIT_OID_HEXSZ;
148 
149 		if (*scan++ != ' ')
150 			goto parse_failed;
151 		if (!(eol = strchr(scan, '\n')))
152 			goto parse_failed;
153 		*eol = '\0';
154 		if (eol[-1] == '\r')
155 			eol[-1] = '\0';
156 
157 		if (git_sortedcache_upsert((void **)&ref, backend->refcache, scan) < 0)
158 			goto parse_failed;
159 		scan = eol + 1;
160 
161 		git_oid_cpy(&ref->oid, &oid);
162 
163 		/* look for optional "^<OID>\n" */
164 
165 		if (*scan == '^') {
166 			if (git_oid_fromstr(&oid, scan + 1) < 0)
167 				goto parse_failed;
168 			scan += GIT_OID_HEXSZ + 1;
169 
170 			if (scan < eof) {
171 				if (!(eol = strchr(scan, '\n')))
172 					goto parse_failed;
173 				scan = eol + 1;
174 			}
175 
176 			git_oid_cpy(&ref->peel, &oid);
177 			ref->flags |= PACKREF_HAS_PEEL;
178 		}
179 		else if (backend->peeling_mode == PEELING_FULL ||
180 				(backend->peeling_mode == PEELING_STANDARD &&
181 				 git__prefixcmp(ref->name, GIT_REFS_TAGS_DIR) == 0))
182 			ref->flags |= PACKREF_CANNOT_PEEL;
183 	}
184 
185 	git_sortedcache_wunlock(backend->refcache);
186 	git_buf_dispose(&packedrefs);
187 
188 	return 0;
189 
190 parse_failed:
191 	git_error_set(GIT_ERROR_REFERENCE, "corrupted packed references file");
192 
193 	git_sortedcache_clear(backend->refcache, false);
194 	git_sortedcache_wunlock(backend->refcache);
195 	git_buf_dispose(&packedrefs);
196 
197 	return -1;
198 }
199 
loose_parse_oid(git_oid * oid,const char * filename,git_buf * file_content)200 static int loose_parse_oid(
201 	git_oid *oid, const char *filename, git_buf *file_content)
202 {
203 	const char *str = git_buf_cstr(file_content);
204 
205 	if (git_buf_len(file_content) < GIT_OID_HEXSZ)
206 		goto corrupted;
207 
208 	/* we need to get 40 OID characters from the file */
209 	if (git_oid_fromstr(oid, str) < 0)
210 		goto corrupted;
211 
212 	/* If the file is longer than 40 chars, the 41st must be a space */
213 	str += GIT_OID_HEXSZ;
214 	if (*str == '\0' || git__isspace(*str))
215 		return 0;
216 
217 corrupted:
218 	git_error_set(GIT_ERROR_REFERENCE, "corrupted loose reference file: %s", filename);
219 	return -1;
220 }
221 
loose_readbuffer(git_buf * buf,const char * base,const char * path)222 static int loose_readbuffer(git_buf *buf, const char *base, const char *path)
223 {
224 	int error;
225 
226 	/* build full path to file */
227 	if ((error = git_buf_joinpath(buf, base, path)) < 0 ||
228 		(error = git_futils_readbuffer(buf, buf->ptr)) < 0)
229 		git_buf_dispose(buf);
230 
231 	return error;
232 }
233 
loose_lookup_to_packfile(refdb_fs_backend * backend,const char * name)234 static int loose_lookup_to_packfile(refdb_fs_backend *backend, const char *name)
235 {
236 	int error = 0;
237 	git_buf ref_file = GIT_BUF_INIT;
238 	struct packref *ref = NULL;
239 	git_oid oid;
240 
241 	/* if we fail to load the loose reference, assume someone changed
242 	 * the filesystem under us and skip it...
243 	 */
244 	if (loose_readbuffer(&ref_file, backend->gitpath, name) < 0) {
245 		git_error_clear();
246 		goto done;
247 	}
248 
249 	/* skip symbolic refs */
250 	if (!git__prefixcmp(git_buf_cstr(&ref_file), GIT_SYMREF))
251 		goto done;
252 
253 	/* parse OID from file */
254 	if ((error = loose_parse_oid(&oid, name, &ref_file)) < 0)
255 		goto done;
256 
257 	git_sortedcache_wlock(backend->refcache);
258 
259 	if (!(error = git_sortedcache_upsert(
260 			(void **)&ref, backend->refcache, name))) {
261 
262 		git_oid_cpy(&ref->oid, &oid);
263 		ref->flags = PACKREF_WAS_LOOSE;
264 	}
265 
266 	git_sortedcache_wunlock(backend->refcache);
267 
268 done:
269 	git_buf_dispose(&ref_file);
270 	return error;
271 }
272 
_dirent_loose_load(void * payload,git_buf * full_path)273 static int _dirent_loose_load(void *payload, git_buf *full_path)
274 {
275 	refdb_fs_backend *backend = payload;
276 	const char *file_path;
277 
278 	if (git__suffixcmp(full_path->ptr, ".lock") == 0)
279 		return 0;
280 
281 	if (git_path_isdir(full_path->ptr)) {
282 		int error = git_path_direach(
283 			full_path, backend->direach_flags, _dirent_loose_load, backend);
284 		/* Race with the filesystem, ignore it */
285 		if (error == GIT_ENOTFOUND) {
286 			git_error_clear();
287 			return 0;
288 		}
289 
290 		return error;
291 	}
292 
293 	file_path = full_path->ptr + strlen(backend->gitpath);
294 
295 	return loose_lookup_to_packfile(backend, file_path);
296 }
297 
298 /*
299  * Load all the loose references from the repository
300  * into the in-memory Packfile, and build a vector with
301  * all the references so it can be written back to
302  * disk.
303  */
packed_loadloose(refdb_fs_backend * backend)304 static int packed_loadloose(refdb_fs_backend *backend)
305 {
306 	int error;
307 	git_buf refs_path = GIT_BUF_INIT;
308 
309 	if (git_buf_joinpath(&refs_path, backend->gitpath, GIT_REFS_DIR) < 0)
310 		return -1;
311 
312 	/*
313 	 * Load all the loose files from disk into the Packfile table.
314 	 * This will overwrite any old packed entries with their
315 	 * updated loose versions
316 	 */
317 	error = git_path_direach(
318 		&refs_path, backend->direach_flags, _dirent_loose_load, backend);
319 
320 	git_buf_dispose(&refs_path);
321 
322 	return error;
323 }
324 
refdb_fs_backend__exists(int * exists,git_refdb_backend * _backend,const char * ref_name)325 static int refdb_fs_backend__exists(
326 	int *exists,
327 	git_refdb_backend *_backend,
328 	const char *ref_name)
329 {
330 	refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
331 	git_buf ref_path = GIT_BUF_INIT;
332 	int error;
333 
334 	assert(backend);
335 
336 	*exists = 0;
337 
338 	if ((error = git_buf_joinpath(&ref_path, backend->gitpath, ref_name)) < 0)
339 		goto out;
340 
341 	if (git_path_isfile(ref_path.ptr)) {
342 		*exists = 1;
343 		goto out;
344 	}
345 
346 	if ((error = packed_reload(backend)) < 0)
347 		goto out;
348 
349 	if (git_sortedcache_lookup(backend->refcache, ref_name) != NULL) {
350 		*exists = 1;
351 		goto out;
352 	}
353 
354 out:
355 	git_buf_dispose(&ref_path);
356 	return error;
357 }
358 
loose_parse_symbolic(git_buf * file_content)359 static const char *loose_parse_symbolic(git_buf *file_content)
360 {
361 	const unsigned int header_len = (unsigned int)strlen(GIT_SYMREF);
362 	const char *refname_start;
363 
364 	refname_start = (const char *)file_content->ptr;
365 
366 	if (git_buf_len(file_content) < header_len + 1) {
367 		git_error_set(GIT_ERROR_REFERENCE, "corrupted loose reference file");
368 		return NULL;
369 	}
370 
371 	/*
372 	 * Assume we have already checked for the header
373 	 * before calling this function
374 	 */
375 	refname_start += header_len;
376 
377 	return refname_start;
378 }
379 
380 /*
381  * Returns whether a reference is stored per worktree or not.
382  * Per-worktree references are:
383  *
384  * - all pseudorefs, e.g. HEAD and MERGE_HEAD
385  * - all references stored inside of "refs/bisect/"
386  */
is_per_worktree_ref(const char * ref_name)387 static bool is_per_worktree_ref(const char *ref_name)
388 {
389 	return git__prefixcmp(ref_name, "refs/") != 0 ||
390 	    git__prefixcmp(ref_name, "refs/bisect/") == 0;
391 }
392 
loose_lookup(git_reference ** out,refdb_fs_backend * backend,const char * ref_name)393 static int loose_lookup(
394 	git_reference **out,
395 	refdb_fs_backend *backend,
396 	const char *ref_name)
397 {
398 	git_buf ref_file = GIT_BUF_INIT;
399 	int error = 0;
400 	const char *ref_dir;
401 
402 	if (out)
403 		*out = NULL;
404 
405 	if (is_per_worktree_ref(ref_name))
406 		ref_dir = backend->gitpath;
407 	else
408 		ref_dir = backend->commonpath;
409 
410 	if ((error = loose_readbuffer(&ref_file, ref_dir, ref_name)) < 0)
411 		/* cannot read loose ref file - gah */;
412 	else if (git__prefixcmp(git_buf_cstr(&ref_file), GIT_SYMREF) == 0) {
413 		const char *target;
414 
415 		git_buf_rtrim(&ref_file);
416 
417 		if (!(target = loose_parse_symbolic(&ref_file)))
418 			error = -1;
419 		else if (out != NULL)
420 			*out = git_reference__alloc_symbolic(ref_name, target);
421 	} else {
422 		git_oid oid;
423 
424 		if (!(error = loose_parse_oid(&oid, ref_name, &ref_file)) &&
425 			out != NULL)
426 			*out = git_reference__alloc(ref_name, &oid, NULL);
427 	}
428 
429 	git_buf_dispose(&ref_file);
430 	return error;
431 }
432 
ref_error_notfound(const char * name)433 static int ref_error_notfound(const char *name)
434 {
435 	git_error_set(GIT_ERROR_REFERENCE, "reference '%s' not found", name);
436 	return GIT_ENOTFOUND;
437 }
438 
packed_lookup(git_reference ** out,refdb_fs_backend * backend,const char * ref_name)439 static int packed_lookup(
440 	git_reference **out,
441 	refdb_fs_backend *backend,
442 	const char *ref_name)
443 {
444 	int error = 0;
445 	struct packref *entry;
446 
447 	if ((error = packed_reload(backend)) < 0)
448 		return error;
449 
450 	if (git_sortedcache_rlock(backend->refcache) < 0)
451 		return -1;
452 
453 	entry = git_sortedcache_lookup(backend->refcache, ref_name);
454 	if (!entry) {
455 		error = ref_error_notfound(ref_name);
456 	} else {
457 		*out = git_reference__alloc(ref_name, &entry->oid, &entry->peel);
458 		if (!*out)
459 			error = -1;
460 	}
461 
462 	git_sortedcache_runlock(backend->refcache);
463 
464 	return error;
465 }
466 
refdb_fs_backend__lookup(git_reference ** out,git_refdb_backend * _backend,const char * ref_name)467 static int refdb_fs_backend__lookup(
468 	git_reference **out,
469 	git_refdb_backend *_backend,
470 	const char *ref_name)
471 {
472 	refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
473 	int error;
474 
475 	assert(backend);
476 
477 	if (!(error = loose_lookup(out, backend, ref_name)))
478 		return 0;
479 
480 	/* only try to lookup this reference on the packfile if it
481 	 * wasn't found on the loose refs; not if there was a critical error */
482 	if (error == GIT_ENOTFOUND) {
483 		git_error_clear();
484 		error = packed_lookup(out, backend, ref_name);
485 	}
486 
487 	return error;
488 }
489 
490 typedef struct {
491 	git_reference_iterator parent;
492 
493 	char *glob;
494 
495 	git_pool pool;
496 	git_vector loose;
497 
498 	git_sortedcache *cache;
499 	size_t loose_pos;
500 	size_t packed_pos;
501 } refdb_fs_iter;
502 
refdb_fs_backend__iterator_free(git_reference_iterator * _iter)503 static void refdb_fs_backend__iterator_free(git_reference_iterator *_iter)
504 {
505 	refdb_fs_iter *iter = GIT_CONTAINER_OF(_iter, refdb_fs_iter, parent);
506 
507 	git_vector_free(&iter->loose);
508 	git_pool_clear(&iter->pool);
509 	git_sortedcache_free(iter->cache);
510 	git__free(iter);
511 }
512 
iter_load_loose_paths(refdb_fs_backend * backend,refdb_fs_iter * iter)513 static int iter_load_loose_paths(refdb_fs_backend *backend, refdb_fs_iter *iter)
514 {
515 	int error = 0;
516 	git_buf path = GIT_BUF_INIT;
517 	git_iterator *fsit = NULL;
518 	git_iterator_options fsit_opts = GIT_ITERATOR_OPTIONS_INIT;
519 	const git_index_entry *entry = NULL;
520 	const char *ref_prefix = GIT_REFS_DIR;
521 	size_t ref_prefix_len = strlen(ref_prefix);
522 
523 	if (!backend->commonpath) /* do nothing if no commonpath for loose refs */
524 		return 0;
525 
526 	fsit_opts.flags = backend->iterator_flags;
527 
528 	if (iter->glob) {
529 		const char *last_sep = NULL;
530 		const char *pos;
531 		for (pos = iter->glob; *pos; ++pos) {
532 			switch (*pos) {
533 			case '?':
534 			case '*':
535 			case '[':
536 			case '\\':
537 				break;
538 			case '/':
539 				last_sep = pos;
540 				/* FALLTHROUGH */
541 			default:
542 				continue;
543 			}
544 			break;
545 		}
546 		if (last_sep) {
547 			ref_prefix = iter->glob;
548 			ref_prefix_len = (last_sep - ref_prefix) + 1;
549 		}
550 	}
551 
552 	if ((error = git_buf_printf(&path, "%s/", backend->commonpath)) < 0 ||
553 		(error = git_buf_put(&path, ref_prefix, ref_prefix_len)) < 0) {
554 		git_buf_dispose(&path);
555 		return error;
556 	}
557 
558 	if ((error = git_iterator_for_filesystem(&fsit, path.ptr, &fsit_opts)) < 0) {
559 		git_buf_dispose(&path);
560 		return (iter->glob && error == GIT_ENOTFOUND)? 0 : error;
561 	}
562 
563 	error = git_buf_sets(&path, ref_prefix);
564 
565 	while (!error && !git_iterator_advance(&entry, fsit)) {
566 		const char *ref_name;
567 		char *ref_dup;
568 
569 		git_buf_truncate(&path, ref_prefix_len);
570 		git_buf_puts(&path, entry->path);
571 		ref_name = git_buf_cstr(&path);
572 
573 		if (git__suffixcmp(ref_name, ".lock") == 0 ||
574 			(iter->glob && wildmatch(iter->glob, ref_name, 0) != 0))
575 			continue;
576 
577 		ref_dup = git_pool_strdup(&iter->pool, ref_name);
578 		if (!ref_dup)
579 			error = -1;
580 		else
581 			error = git_vector_insert(&iter->loose, ref_dup);
582 	}
583 
584 	git_iterator_free(fsit);
585 	git_buf_dispose(&path);
586 
587 	return error;
588 }
589 
refdb_fs_backend__iterator_next(git_reference ** out,git_reference_iterator * _iter)590 static int refdb_fs_backend__iterator_next(
591 	git_reference **out, git_reference_iterator *_iter)
592 {
593 	int error = GIT_ITEROVER;
594 	refdb_fs_iter *iter = GIT_CONTAINER_OF(_iter, refdb_fs_iter, parent);
595 	refdb_fs_backend *backend = GIT_CONTAINER_OF(iter->parent.db->backend, refdb_fs_backend, parent);
596 	struct packref *ref;
597 
598 	while (iter->loose_pos < iter->loose.length) {
599 		const char *path = git_vector_get(&iter->loose, iter->loose_pos++);
600 
601 		if (loose_lookup(out, backend, path) == 0) {
602 			ref = git_sortedcache_lookup(iter->cache, path);
603 			if (ref)
604 				ref->flags |= PACKREF_SHADOWED;
605 
606 			return 0;
607 		}
608 
609 		git_error_clear();
610 	}
611 
612 	error = GIT_ITEROVER;
613 	while (iter->packed_pos < git_sortedcache_entrycount(iter->cache)) {
614 		ref = git_sortedcache_entry(iter->cache, iter->packed_pos++);
615 		if (!ref) /* stop now if another thread deleted refs and we past end */
616 			break;
617 
618 		if (ref->flags & PACKREF_SHADOWED)
619 			continue;
620 		if (iter->glob && wildmatch(iter->glob, ref->name, 0) != 0)
621 			continue;
622 
623 		*out = git_reference__alloc(ref->name, &ref->oid, &ref->peel);
624 		error = (*out != NULL) ? 0 : -1;
625 		break;
626 	}
627 
628 	return error;
629 }
630 
refdb_fs_backend__iterator_next_name(const char ** out,git_reference_iterator * _iter)631 static int refdb_fs_backend__iterator_next_name(
632 	const char **out, git_reference_iterator *_iter)
633 {
634 	int error = GIT_ITEROVER;
635 	refdb_fs_iter *iter = GIT_CONTAINER_OF(_iter, refdb_fs_iter, parent);
636 	refdb_fs_backend *backend = GIT_CONTAINER_OF(iter->parent.db->backend, refdb_fs_backend, parent);
637 	struct packref *ref;
638 
639 	while (iter->loose_pos < iter->loose.length) {
640 		const char *path = git_vector_get(&iter->loose, iter->loose_pos++);
641 		struct packref *ref;
642 
643 		if (loose_lookup(NULL, backend, path) == 0) {
644 			ref = git_sortedcache_lookup(iter->cache, path);
645 			if (ref)
646 				ref->flags |= PACKREF_SHADOWED;
647 
648 			*out = path;
649 			return 0;
650 		}
651 
652 		git_error_clear();
653 	}
654 
655 	error = GIT_ITEROVER;
656 	while (iter->packed_pos < git_sortedcache_entrycount(iter->cache)) {
657 		ref = git_sortedcache_entry(iter->cache, iter->packed_pos++);
658 		if (!ref) /* stop now if another thread deleted refs and we past end */
659 			break;
660 
661 		if (ref->flags & PACKREF_SHADOWED)
662 			continue;
663 		if (iter->glob && wildmatch(iter->glob, ref->name, 0) != 0)
664 			continue;
665 
666 		*out = ref->name;
667 		error = 0;
668 		break;
669 	}
670 
671 	return error;
672 }
673 
refdb_fs_backend__iterator(git_reference_iterator ** out,git_refdb_backend * _backend,const char * glob)674 static int refdb_fs_backend__iterator(
675 	git_reference_iterator **out, git_refdb_backend *_backend, const char *glob)
676 {
677 	refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
678 	refdb_fs_iter *iter = NULL;
679 	int error;
680 
681 	assert(backend);
682 
683 	iter = git__calloc(1, sizeof(refdb_fs_iter));
684 	GIT_ERROR_CHECK_ALLOC(iter);
685 
686 	if ((error = git_pool_init(&iter->pool, 1)) < 0)
687 		goto out;
688 
689 	if ((error = git_vector_init(&iter->loose, 8, NULL)) < 0)
690 		goto out;
691 
692 	if (glob != NULL &&
693 	    (iter->glob = git_pool_strdup(&iter->pool, glob)) == NULL) {
694 		error = GIT_ERROR_NOMEMORY;
695 		goto out;
696 	}
697 
698 	if ((error = iter_load_loose_paths(backend, iter)) < 0)
699 		goto out;
700 
701 	if ((error = packed_reload(backend)) < 0)
702 		goto out;
703 
704 	if ((error = git_sortedcache_copy(&iter->cache, backend->refcache, 1, NULL, NULL)) < 0)
705 		goto out;
706 
707 	iter->parent.next = refdb_fs_backend__iterator_next;
708 	iter->parent.next_name = refdb_fs_backend__iterator_next_name;
709 	iter->parent.free = refdb_fs_backend__iterator_free;
710 
711 	*out = (git_reference_iterator *)iter;
712 out:
713 	if (error)
714 		refdb_fs_backend__iterator_free((git_reference_iterator *)iter);
715 	return error;
716 }
717 
ref_is_available(const char * old_ref,const char * new_ref,const char * this_ref)718 static bool ref_is_available(
719 	const char *old_ref, const char *new_ref, const char *this_ref)
720 {
721 	if (old_ref == NULL || strcmp(old_ref, this_ref)) {
722 		size_t reflen = strlen(this_ref);
723 		size_t newlen = strlen(new_ref);
724 		size_t cmplen = reflen < newlen ? reflen : newlen;
725 		const char *lead = reflen < newlen ? new_ref : this_ref;
726 
727 		if (!strncmp(new_ref, this_ref, cmplen) && lead[cmplen] == '/') {
728 			return false;
729 		}
730 	}
731 
732 	return true;
733 }
734 
reference_path_available(refdb_fs_backend * backend,const char * new_ref,const char * old_ref,int force)735 static int reference_path_available(
736 	refdb_fs_backend *backend,
737 	const char *new_ref,
738 	const char* old_ref,
739 	int force)
740 {
741 	size_t i;
742 	int error;
743 
744 	if ((error = packed_reload(backend)) < 0)
745 		return error;
746 
747 	if (!force) {
748 		int exists;
749 
750 		if ((error = refdb_fs_backend__exists(
751 			&exists, (git_refdb_backend *)backend, new_ref)) < 0) {
752 			return error;
753 		}
754 
755 		if (exists) {
756 			git_error_set(GIT_ERROR_REFERENCE,
757 				"failed to write reference '%s': a reference with "
758 				"that name already exists.", new_ref);
759 			return GIT_EEXISTS;
760 		}
761 	}
762 
763 	git_sortedcache_rlock(backend->refcache);
764 
765 	for (i = 0; i < git_sortedcache_entrycount(backend->refcache); ++i) {
766 		struct packref *ref = git_sortedcache_entry(backend->refcache, i);
767 
768 		if (ref && !ref_is_available(old_ref, new_ref, ref->name)) {
769 			git_sortedcache_runlock(backend->refcache);
770 			git_error_set(GIT_ERROR_REFERENCE,
771 				"path to reference '%s' collides with existing one", new_ref);
772 			return -1;
773 		}
774 	}
775 
776 	git_sortedcache_runlock(backend->refcache);
777 	return 0;
778 }
779 
loose_lock(git_filebuf * file,refdb_fs_backend * backend,const char * name)780 static int loose_lock(git_filebuf *file, refdb_fs_backend *backend, const char *name)
781 {
782 	int error, filebuf_flags;
783 	git_buf ref_path = GIT_BUF_INIT;
784 	const char *basedir;
785 
786 	assert(file && backend && name);
787 
788 	if (!git_path_isvalid(backend->repo, name, 0, GIT_PATH_REJECT_FILESYSTEM_DEFAULTS)) {
789 		git_error_set(GIT_ERROR_INVALID, "invalid reference name '%s'", name);
790 		return GIT_EINVALIDSPEC;
791 	}
792 
793 	if (is_per_worktree_ref(name))
794 		basedir = backend->gitpath;
795 	else
796 		basedir = backend->commonpath;
797 
798 	/* Remove a possibly existing empty directory hierarchy
799 	 * which name would collide with the reference name
800 	 */
801 	if ((error = git_futils_rmdir_r(name, basedir, GIT_RMDIR_SKIP_NONEMPTY)) < 0)
802 		return error;
803 
804 	if (git_buf_joinpath(&ref_path, basedir, name) < 0)
805 		return -1;
806 
807 	filebuf_flags = GIT_FILEBUF_CREATE_LEADING_DIRS;
808 	if (backend->fsync)
809 		filebuf_flags |= GIT_FILEBUF_FSYNC;
810 
811 	error = git_filebuf_open(file, ref_path.ptr, filebuf_flags, GIT_REFS_FILE_MODE);
812 
813 	if (error == GIT_EDIRECTORY)
814 		git_error_set(GIT_ERROR_REFERENCE, "cannot lock ref '%s', there are refs beneath that folder", name);
815 
816 	git_buf_dispose(&ref_path);
817 	return error;
818 }
819 
loose_commit(git_filebuf * file,const git_reference * ref)820 static int loose_commit(git_filebuf *file, const git_reference *ref)
821 {
822 	assert(file && ref);
823 
824 	if (ref->type == GIT_REFERENCE_DIRECT) {
825 		char oid[GIT_OID_HEXSZ + 1];
826 		git_oid_nfmt(oid, sizeof(oid), &ref->target.oid);
827 
828 		git_filebuf_printf(file, "%s\n", oid);
829 	} else if (ref->type == GIT_REFERENCE_SYMBOLIC) {
830 		git_filebuf_printf(file, GIT_SYMREF "%s\n", ref->target.symbolic);
831 	} else {
832 		assert(0); /* don't let this happen */
833 	}
834 
835 	return git_filebuf_commit(file);
836 }
837 
refdb_fs_backend__lock(void ** out,git_refdb_backend * _backend,const char * refname)838 static int refdb_fs_backend__lock(void **out, git_refdb_backend *_backend, const char *refname)
839 {
840 	int error;
841 	git_filebuf *lock;
842 	refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
843 
844 	lock = git__calloc(1, sizeof(git_filebuf));
845 	GIT_ERROR_CHECK_ALLOC(lock);
846 
847 	if ((error = loose_lock(lock, backend, refname)) < 0) {
848 		git__free(lock);
849 		return error;
850 	}
851 
852 	*out = lock;
853 	return 0;
854 }
855 
856 static int refdb_fs_backend__write_tail(
857 	git_refdb_backend *_backend,
858 	const git_reference *ref,
859 	git_filebuf *file,
860 	int update_reflog,
861 	const git_oid *old_id,
862 	const char *old_target,
863 	const git_signature *who,
864 	const char *message);
865 
866 static int refdb_fs_backend__delete_tail(
867 	git_refdb_backend *_backend,
868 	git_filebuf *file,
869 	const char *ref_name,
870 	const git_oid *old_id,
871 	const char *old_target);
872 
refdb_fs_backend__unlock(git_refdb_backend * backend,void * payload,int success,int update_reflog,const git_reference * ref,const git_signature * sig,const char * message)873 static int refdb_fs_backend__unlock(git_refdb_backend *backend, void *payload, int success, int update_reflog,
874 				    const git_reference *ref, const git_signature *sig, const char *message)
875 {
876 	git_filebuf *lock = (git_filebuf *) payload;
877 	int error = 0;
878 
879 	if (success == 2)
880 		error = refdb_fs_backend__delete_tail(backend, lock, ref->name, NULL, NULL);
881 	else if (success)
882 		error = refdb_fs_backend__write_tail(backend, ref, lock, update_reflog, NULL, NULL, sig, message);
883 	else
884 		git_filebuf_cleanup(lock);
885 
886 	git__free(lock);
887 	return error;
888 }
889 
890 /*
891  * Find out what object this reference resolves to.
892  *
893  * For references that point to a 'big' tag (e.g. an
894  * actual tag object on the repository), we need to
895  * cache on the packfile the OID of the object to
896  * which that 'big tag' is pointing to.
897  */
packed_find_peel(refdb_fs_backend * backend,struct packref * ref)898 static int packed_find_peel(refdb_fs_backend *backend, struct packref *ref)
899 {
900 	git_object *object;
901 
902 	if (ref->flags & PACKREF_HAS_PEEL || ref->flags & PACKREF_CANNOT_PEEL)
903 		return 0;
904 
905 	/*
906 	 * Find the tagged object in the repository
907 	 */
908 	if (git_object_lookup(&object, backend->repo, &ref->oid, GIT_OBJECT_ANY) < 0)
909 		return -1;
910 
911 	/*
912 	 * If the tagged object is a Tag object, we need to resolve it;
913 	 * if the ref is actually a 'weak' ref, we don't need to resolve
914 	 * anything.
915 	 */
916 	if (git_object_type(object) == GIT_OBJECT_TAG) {
917 		git_tag *tag = (git_tag *)object;
918 
919 		/*
920 		 * Find the object pointed at by this tag
921 		 */
922 		git_oid_cpy(&ref->peel, git_tag_target_id(tag));
923 		ref->flags |= PACKREF_HAS_PEEL;
924 
925 		/*
926 		 * The reference has now cached the resolved OID, and is
927 		 * marked at such. When written to the packfile, it'll be
928 		 * accompanied by this resolved oid
929 		 */
930 	}
931 
932 	git_object_free(object);
933 	return 0;
934 }
935 
936 /*
937  * Write a single reference into a packfile
938  */
packed_write_ref(struct packref * ref,git_filebuf * file)939 static int packed_write_ref(struct packref *ref, git_filebuf *file)
940 {
941 	char oid[GIT_OID_HEXSZ + 1];
942 	git_oid_nfmt(oid, sizeof(oid), &ref->oid);
943 
944 	/*
945 	 * For references that peel to an object in the repo, we must
946 	 * write the resulting peel on a separate line, e.g.
947 	 *
948 	 *	6fa8a902cc1d18527e1355773c86721945475d37 refs/tags/libgit2-0.4
949 	 *	^2ec0cb7959b0bf965d54f95453f5b4b34e8d3100
950 	 *
951 	 * This obviously only applies to tags.
952 	 * The required peels have already been loaded into `ref->peel_target`.
953 	 */
954 	if (ref->flags & PACKREF_HAS_PEEL) {
955 		char peel[GIT_OID_HEXSZ + 1];
956 		git_oid_nfmt(peel, sizeof(peel), &ref->peel);
957 
958 		if (git_filebuf_printf(file, "%s %s\n^%s\n", oid, ref->name, peel) < 0)
959 			return -1;
960 	} else {
961 		if (git_filebuf_printf(file, "%s %s\n", oid, ref->name) < 0)
962 			return -1;
963 	}
964 
965 	return 0;
966 }
967 
968 /*
969  * Remove all loose references
970  *
971  * Once we have successfully written a packfile,
972  * all the loose references that were packed must be
973  * removed from disk.
974  *
975  * This is a dangerous method; make sure the packfile
976  * is well-written, because we are destructing references
977  * here otherwise.
978  */
packed_remove_loose(refdb_fs_backend * backend)979 static int packed_remove_loose(refdb_fs_backend *backend)
980 {
981 	size_t i;
982 	git_filebuf lock = GIT_FILEBUF_INIT;
983 	git_buf ref_content = GIT_BUF_INIT;
984 	int error = 0;
985 
986 	/* backend->refcache is already locked when this is called */
987 
988 	for (i = 0; i < git_sortedcache_entrycount(backend->refcache); ++i) {
989 		struct packref *ref = git_sortedcache_entry(backend->refcache, i);
990 		git_oid current_id;
991 
992 		if (!ref || !(ref->flags & PACKREF_WAS_LOOSE))
993 			continue;
994 
995 		git_filebuf_cleanup(&lock);
996 
997 		/* We need to stop anybody from updating the ref while we try to do a safe delete */
998 		error = loose_lock(&lock, backend, ref->name);
999 		/* If someone else is updating it, let them do it */
1000 		if (error == GIT_EEXISTS || error == GIT_ENOTFOUND)
1001 			continue;
1002 
1003 		if (error < 0) {
1004 			git_buf_dispose(&ref_content);
1005 			git_error_set(GIT_ERROR_REFERENCE, "failed to lock loose reference '%s'", ref->name);
1006 			return error;
1007 		}
1008 
1009 		error = git_futils_readbuffer(&ref_content, lock.path_original);
1010 		/* Someone else beat us to cleaning up the ref, let's simply continue */
1011 		if (error == GIT_ENOTFOUND)
1012 			continue;
1013 
1014 		/* This became a symref between us packing and trying to delete it, so ignore it */
1015 		if (!git__prefixcmp(ref_content.ptr, GIT_SYMREF))
1016 			continue;
1017 
1018 		/* Figure out the current id; if we find a bad ref file, skip it so we can do the rest */
1019 		if (loose_parse_oid(&current_id, lock.path_original, &ref_content) < 0)
1020 			continue;
1021 
1022 		/* If the ref moved since we packed it, we must not delete it */
1023 		if (!git_oid_equal(&current_id, &ref->oid))
1024 			continue;
1025 
1026 		/*
1027 		 * if we fail to remove a single file, this is *not* good,
1028 		 * but we should keep going and remove as many as possible.
1029 		 * If we fail to remove, the ref is still in the old state, so
1030 		 * we haven't lost information.
1031 		 */
1032 		p_unlink(lock.path_original);
1033 	}
1034 
1035 	git_buf_dispose(&ref_content);
1036 	git_filebuf_cleanup(&lock);
1037 	return 0;
1038 }
1039 
1040 /*
1041  * Write all the contents in the in-memory packfile to disk.
1042  */
packed_write(refdb_fs_backend * backend)1043 static int packed_write(refdb_fs_backend *backend)
1044 {
1045 	git_sortedcache *refcache = backend->refcache;
1046 	git_filebuf pack_file = GIT_FILEBUF_INIT;
1047 	int error, open_flags = 0;
1048 	size_t i;
1049 
1050 	/* lock the cache to updates while we do this */
1051 	if ((error = git_sortedcache_wlock(refcache)) < 0)
1052 		return error;
1053 
1054 	if (backend->fsync)
1055 		open_flags = GIT_FILEBUF_FSYNC;
1056 
1057 	/* Open the file! */
1058 	if ((error = git_filebuf_open(&pack_file, git_sortedcache_path(refcache), open_flags, GIT_PACKEDREFS_FILE_MODE)) < 0)
1059 		goto fail;
1060 
1061 	/* Packfiles have a header... apparently
1062 	 * This is in fact not required, but we might as well print it
1063 	 * just for kicks */
1064 	if ((error = git_filebuf_printf(&pack_file, "%s\n", GIT_PACKEDREFS_HEADER)) < 0)
1065 		goto fail;
1066 
1067 	for (i = 0; i < git_sortedcache_entrycount(refcache); ++i) {
1068 		struct packref *ref = git_sortedcache_entry(refcache, i);
1069 		assert(ref);
1070 
1071 		if ((error = packed_find_peel(backend, ref)) < 0)
1072 			goto fail;
1073 
1074 		if ((error = packed_write_ref(ref, &pack_file)) < 0)
1075 			goto fail;
1076 	}
1077 
1078 	/* if we've written all the references properly, we can commit
1079 	 * the packfile to make the changes effective */
1080 	if ((error = git_filebuf_commit(&pack_file)) < 0)
1081 		goto fail;
1082 
1083 	/* when and only when the packfile has been properly written,
1084 	 * we can go ahead and remove the loose refs */
1085 	if ((error = packed_remove_loose(backend)) < 0)
1086 		goto fail;
1087 
1088 	git_sortedcache_updated(refcache);
1089 	git_sortedcache_wunlock(refcache);
1090 
1091 	/* we're good now */
1092 	return 0;
1093 
1094 fail:
1095 	git_filebuf_cleanup(&pack_file);
1096 	git_sortedcache_wunlock(refcache);
1097 
1098 	return error;
1099 }
1100 
packed_delete(refdb_fs_backend * backend,const char * ref_name)1101 static int packed_delete(refdb_fs_backend *backend, const char *ref_name)
1102 {
1103 	size_t pack_pos;
1104 	int error, found = 0;
1105 
1106 	if ((error = packed_reload(backend)) < 0)
1107 		goto cleanup;
1108 
1109 	if ((error = git_sortedcache_wlock(backend->refcache)) < 0)
1110 		goto cleanup;
1111 
1112 	/* If a packed reference exists, remove it from the packfile and repack if necessary */
1113 	error = git_sortedcache_lookup_index(&pack_pos, backend->refcache, ref_name);
1114 	if (error == 0) {
1115 		error = git_sortedcache_remove(backend->refcache, pack_pos);
1116 		found = 1;
1117 	}
1118 	if (error == GIT_ENOTFOUND)
1119 		error = 0;
1120 
1121 	git_sortedcache_wunlock(backend->refcache);
1122 
1123 	if (found)
1124 		error = packed_write(backend);
1125 
1126 cleanup:
1127 	return error;
1128 }
1129 
1130 static int reflog_append(refdb_fs_backend *backend, const git_reference *ref, const git_oid *old, const git_oid *new, const git_signature *author, const char *message);
1131 static int has_reflog(git_repository *repo, const char *name);
1132 
should_write_reflog(int * write,git_repository * repo,const char * name)1133 static int should_write_reflog(int *write, git_repository *repo, const char *name)
1134 {
1135 	int error, logall;
1136 
1137 	error = git_repository__configmap_lookup(&logall, repo, GIT_CONFIGMAP_LOGALLREFUPDATES);
1138 	if (error < 0)
1139 		return error;
1140 
1141 	/* Defaults to the opposite of the repo being bare */
1142 	if (logall == GIT_LOGALLREFUPDATES_UNSET)
1143 		logall = !git_repository_is_bare(repo);
1144 
1145 	*write = 0;
1146 	switch (logall) {
1147 	case GIT_LOGALLREFUPDATES_FALSE:
1148 		*write = 0;
1149 		break;
1150 
1151 	case GIT_LOGALLREFUPDATES_TRUE:
1152 		/* Only write if it already has a log,
1153 		 * or if it's under heads/, remotes/ or notes/
1154 		 */
1155 		*write = has_reflog(repo, name) ||
1156 			!git__prefixcmp(name, GIT_REFS_HEADS_DIR) ||
1157 			!git__strcmp(name, GIT_HEAD_FILE) ||
1158 			!git__prefixcmp(name, GIT_REFS_REMOTES_DIR) ||
1159 			!git__prefixcmp(name, GIT_REFS_NOTES_DIR);
1160 		break;
1161 
1162 	case GIT_LOGALLREFUPDATES_ALWAYS:
1163 		*write = 1;
1164 		break;
1165 	}
1166 
1167 	return 0;
1168 }
1169 
cmp_old_ref(int * cmp,git_refdb_backend * backend,const char * name,const git_oid * old_id,const char * old_target)1170 static int cmp_old_ref(int *cmp, git_refdb_backend *backend, const char *name,
1171 	const git_oid *old_id, const char *old_target)
1172 {
1173 	int error = 0;
1174 	git_reference *old_ref = NULL;
1175 
1176 	*cmp = 0;
1177 	/* It "matches" if there is no old value to compare against */
1178 	if (!old_id && !old_target)
1179 		return 0;
1180 
1181 	if ((error = refdb_fs_backend__lookup(&old_ref, backend, name)) < 0)
1182 		goto out;
1183 
1184 	/* If the types don't match, there's no way the values do */
1185 	if (old_id && old_ref->type != GIT_REFERENCE_DIRECT) {
1186 		*cmp = -1;
1187 		goto out;
1188 	}
1189 	if (old_target && old_ref->type != GIT_REFERENCE_SYMBOLIC) {
1190 		*cmp = 1;
1191 		goto out;
1192 	}
1193 
1194 	if (old_id && old_ref->type == GIT_REFERENCE_DIRECT)
1195 		*cmp = git_oid_cmp(old_id, &old_ref->target.oid);
1196 
1197 	if (old_target && old_ref->type == GIT_REFERENCE_SYMBOLIC)
1198 		*cmp = git__strcmp(old_target, old_ref->target.symbolic);
1199 
1200 out:
1201 	git_reference_free(old_ref);
1202 
1203 	return error;
1204 }
1205 
1206 /*
1207  * The git.git comment regarding this, for your viewing pleasure:
1208  *
1209  * Special hack: If a branch is updated directly and HEAD
1210  * points to it (may happen on the remote side of a push
1211  * for example) then logically the HEAD reflog should be
1212  * updated too.
1213  * A generic solution implies reverse symref information,
1214  * but finding all symrefs pointing to the given branch
1215  * would be rather costly for this rare event (the direct
1216  * update of a branch) to be worth it.  So let's cheat and
1217  * check with HEAD only which should cover 99% of all usage
1218  * scenarios (even 100% of the default ones).
1219  */
maybe_append_head(refdb_fs_backend * backend,const git_reference * ref,const git_signature * who,const char * message)1220 static int maybe_append_head(refdb_fs_backend *backend, const git_reference *ref, const git_signature *who, const char *message)
1221 {
1222 	int error;
1223 	git_oid old_id;
1224 	git_reference *tmp = NULL, *head = NULL, *peeled = NULL;
1225 	const char *name;
1226 
1227 	if (ref->type == GIT_REFERENCE_SYMBOLIC)
1228 		return 0;
1229 
1230 	/* if we can't resolve, we use {0}*40 as old id */
1231 	if (git_reference_name_to_id(&old_id, backend->repo, ref->name) < 0)
1232 		memset(&old_id, 0, sizeof(old_id));
1233 
1234 	if ((error = git_reference_lookup(&head, backend->repo, GIT_HEAD_FILE)) < 0)
1235 		return error;
1236 
1237 	if (git_reference_type(head) == GIT_REFERENCE_DIRECT)
1238 		goto cleanup;
1239 
1240 	if ((error = git_reference_lookup(&tmp, backend->repo, GIT_HEAD_FILE)) < 0)
1241 		goto cleanup;
1242 
1243 	/* Go down the symref chain until we find the branch */
1244 	while (git_reference_type(tmp) == GIT_REFERENCE_SYMBOLIC) {
1245 		error = git_reference_lookup(&peeled, backend->repo, git_reference_symbolic_target(tmp));
1246 		if (error < 0)
1247 			break;
1248 
1249 		git_reference_free(tmp);
1250 		tmp = peeled;
1251 	}
1252 
1253 	if (error == GIT_ENOTFOUND) {
1254 		error = 0;
1255 		name = git_reference_symbolic_target(tmp);
1256 	} else if (error < 0) {
1257 		goto cleanup;
1258 	} else {
1259 		name = git_reference_name(tmp);
1260 	}
1261 
1262 	if (strcmp(name, ref->name))
1263 		goto cleanup;
1264 
1265 	error = reflog_append(backend, head, &old_id, git_reference_target(ref), who, message);
1266 
1267 cleanup:
1268 	git_reference_free(tmp);
1269 	git_reference_free(head);
1270 	return error;
1271 }
1272 
refdb_fs_backend__write(git_refdb_backend * _backend,const git_reference * ref,int force,const git_signature * who,const char * message,const git_oid * old_id,const char * old_target)1273 static int refdb_fs_backend__write(
1274 	git_refdb_backend *_backend,
1275 	const git_reference *ref,
1276 	int force,
1277 	const git_signature *who,
1278 	const char *message,
1279 	const git_oid *old_id,
1280 	const char *old_target)
1281 {
1282 	refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
1283 	git_filebuf file = GIT_FILEBUF_INIT;
1284 	int error = 0;
1285 
1286 	assert(backend);
1287 
1288 	if ((error = reference_path_available(backend, ref->name, NULL, force)) < 0)
1289 		return error;
1290 
1291 	/* We need to perform the reflog append and old value check under the ref's lock */
1292 	if ((error = loose_lock(&file, backend, ref->name)) < 0)
1293 		return error;
1294 
1295 	return refdb_fs_backend__write_tail(_backend, ref, &file, true, old_id, old_target, who, message);
1296 }
1297 
refdb_fs_backend__write_tail(git_refdb_backend * _backend,const git_reference * ref,git_filebuf * file,int update_reflog,const git_oid * old_id,const char * old_target,const git_signature * who,const char * message)1298 static int refdb_fs_backend__write_tail(
1299 	git_refdb_backend *_backend,
1300 	const git_reference *ref,
1301 	git_filebuf *file,
1302 	int update_reflog,
1303 	const git_oid *old_id,
1304 	const char *old_target,
1305 	const git_signature *who,
1306 	const char *message)
1307 {
1308 	refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
1309 	int error = 0, cmp = 0, should_write;
1310 	const char *new_target = NULL;
1311 	const git_oid *new_id = NULL;
1312 
1313 	if ((error = cmp_old_ref(&cmp, _backend, ref->name, old_id, old_target)) < 0)
1314 		goto on_error;
1315 
1316 	if (cmp) {
1317 		git_error_set(GIT_ERROR_REFERENCE, "old reference value does not match");
1318 		error = GIT_EMODIFIED;
1319 		goto on_error;
1320 	}
1321 
1322 	if (ref->type == GIT_REFERENCE_SYMBOLIC)
1323 		new_target = ref->target.symbolic;
1324 	else
1325 		new_id = &ref->target.oid;
1326 
1327 	error = cmp_old_ref(&cmp, _backend, ref->name, new_id, new_target);
1328 	if (error < 0 && error != GIT_ENOTFOUND)
1329 		goto on_error;
1330 
1331 	/* Don't update if we have the same value */
1332 	if (!error && !cmp) {
1333 		error = 0;
1334 		goto on_error; /* not really error */
1335 	}
1336 
1337 	if (update_reflog) {
1338 		if ((error = should_write_reflog(&should_write, backend->repo, ref->name)) < 0)
1339 			goto on_error;
1340 
1341 		if (should_write) {
1342 			if ((error = reflog_append(backend, ref, NULL, NULL, who, message)) < 0)
1343 				goto on_error;
1344 			if ((error = maybe_append_head(backend, ref, who, message)) < 0)
1345 				goto on_error;
1346 		}
1347 	}
1348 
1349 	return loose_commit(file, ref);
1350 
1351 on_error:
1352         git_filebuf_cleanup(file);
1353         return error;
1354 }
1355 
refdb_fs_backend__prune_refs(refdb_fs_backend * backend,const char * ref_name,const char * prefix)1356 static void refdb_fs_backend__prune_refs(
1357 	refdb_fs_backend *backend,
1358 	const char *ref_name,
1359 	const char *prefix)
1360 {
1361 	git_buf relative_path = GIT_BUF_INIT;
1362 	git_buf base_path = GIT_BUF_INIT;
1363 	size_t commonlen;
1364 
1365 	assert(backend && ref_name);
1366 
1367 	if (git_buf_sets(&relative_path, ref_name) < 0)
1368 		goto cleanup;
1369 
1370 	git_path_squash_slashes(&relative_path);
1371 	if ((commonlen = git_path_common_dirlen("refs/heads/", git_buf_cstr(&relative_path))) == strlen("refs/heads/") ||
1372 		(commonlen = git_path_common_dirlen("refs/tags/", git_buf_cstr(&relative_path))) == strlen("refs/tags/") ||
1373 		(commonlen = git_path_common_dirlen("refs/remotes/", git_buf_cstr(&relative_path))) == strlen("refs/remotes/")) {
1374 
1375 		git_buf_truncate(&relative_path, commonlen);
1376 
1377 		if (prefix) {
1378 			if (git_buf_join3(&base_path, '/', backend->commonpath, prefix, git_buf_cstr(&relative_path)) < 0)
1379 				goto cleanup;
1380 		} else {
1381 			if (git_buf_joinpath(&base_path, backend->commonpath, git_buf_cstr(&relative_path)) < 0)
1382 				goto cleanup;
1383 		}
1384 
1385 		git_futils_rmdir_r(ref_name + commonlen, git_buf_cstr(&base_path), GIT_RMDIR_EMPTY_PARENTS | GIT_RMDIR_SKIP_ROOT);
1386 	}
1387 
1388 cleanup:
1389 	git_buf_dispose(&relative_path);
1390 	git_buf_dispose(&base_path);
1391 }
1392 
refdb_fs_backend__delete(git_refdb_backend * _backend,const char * ref_name,const git_oid * old_id,const char * old_target)1393 static int refdb_fs_backend__delete(
1394 	git_refdb_backend *_backend,
1395 	const char *ref_name,
1396 	const git_oid *old_id, const char *old_target)
1397 {
1398 	refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
1399 	git_filebuf file = GIT_FILEBUF_INIT;
1400 	int error = 0;
1401 
1402 	assert(backend && ref_name);
1403 
1404 	if ((error = loose_lock(&file, backend, ref_name)) < 0)
1405 		return error;
1406 
1407 	if ((error = refdb_reflog_fs__delete(_backend, ref_name)) < 0) {
1408 		git_filebuf_cleanup(&file);
1409 		return error;
1410 	}
1411 
1412 	return refdb_fs_backend__delete_tail(_backend, &file, ref_name, old_id, old_target);
1413 }
1414 
loose_delete(refdb_fs_backend * backend,const char * ref_name)1415 static int loose_delete(refdb_fs_backend *backend, const char *ref_name)
1416 {
1417 	git_buf loose_path = GIT_BUF_INIT;
1418 	int error = 0;
1419 
1420 	if (git_buf_joinpath(&loose_path, backend->commonpath, ref_name) < 0)
1421 		return -1;
1422 
1423 	error = p_unlink(loose_path.ptr);
1424 	if (error < 0 && errno == ENOENT)
1425 		error = GIT_ENOTFOUND;
1426 	else if (error != 0)
1427 		error = -1;
1428 
1429 	git_buf_dispose(&loose_path);
1430 
1431 	return error;
1432 }
1433 
refdb_fs_backend__delete_tail(git_refdb_backend * _backend,git_filebuf * file,const char * ref_name,const git_oid * old_id,const char * old_target)1434 static int refdb_fs_backend__delete_tail(
1435 	git_refdb_backend *_backend,
1436 	git_filebuf *file,
1437 	const char *ref_name,
1438 	const git_oid *old_id, const char *old_target)
1439 {
1440 	refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
1441 	int error = 0, cmp = 0;
1442 	bool packed_deleted = 0;
1443 
1444 	error = cmp_old_ref(&cmp, _backend, ref_name, old_id, old_target);
1445 	if (error < 0)
1446 		goto cleanup;
1447 
1448 	if (cmp) {
1449 		git_error_set(GIT_ERROR_REFERENCE, "old reference value does not match");
1450 		error = GIT_EMODIFIED;
1451 		goto cleanup;
1452 	}
1453 
1454 	/*
1455 	 * To ensure that an external observer will see either the current ref value
1456 	 * (because the loose ref still exists), or a missing ref (after the packed-file is
1457 	 * unlocked, there will be nothing left), we must ensure things happen in the
1458 	 * following order:
1459 	 *
1460 	 * - the packed-ref file is locked and loaded, as well as a loose one, if it exists
1461 	 * - we optimistically delete a packed ref, keeping track of whether it existed
1462 	 * - we delete the loose ref, note that we have its .lock
1463 	 * - the loose ref is "unlocked", then the packed-ref file is rewritten and unlocked
1464 	 * - we should prune the path components if a loose ref was deleted
1465 	 *
1466 	 * Note that, because our packed backend doesn't expose its filesystem lock,
1467 	 * we might not be able to guarantee that this is what actually happens (ie.
1468 	 * as our current code never write packed-refs.lock, nothing stops observers
1469 	 * from grabbing a "stale" value from there).
1470 	 */
1471 	if ((error = packed_delete(backend, ref_name)) < 0 && error != GIT_ENOTFOUND)
1472 		goto cleanup;
1473 
1474 	if (error == 0)
1475 		packed_deleted = 1;
1476 
1477 	if ((error = loose_delete(backend, ref_name)) < 0 && error != GIT_ENOTFOUND)
1478 		goto cleanup;
1479 
1480 	if (error == GIT_ENOTFOUND) {
1481 		error = packed_deleted ? 0 : ref_error_notfound(ref_name);
1482 		goto cleanup;
1483 	}
1484 
1485 cleanup:
1486 	git_filebuf_cleanup(file);
1487 	if (error == 0)
1488 		refdb_fs_backend__prune_refs(backend, ref_name, "");
1489 	return error;
1490 }
1491 
1492 static int refdb_reflog_fs__rename(git_refdb_backend *_backend, const char *old_name, const char *new_name);
1493 
refdb_fs_backend__rename(git_reference ** out,git_refdb_backend * _backend,const char * old_name,const char * new_name,int force,const git_signature * who,const char * message)1494 static int refdb_fs_backend__rename(
1495 	git_reference **out,
1496 	git_refdb_backend *_backend,
1497 	const char *old_name,
1498 	const char *new_name,
1499 	int force,
1500 	const git_signature *who,
1501 	const char *message)
1502 {
1503 	refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
1504 	git_reference *old, *new = NULL;
1505 	git_filebuf file = GIT_FILEBUF_INIT;
1506 	int error;
1507 
1508 	assert(backend);
1509 
1510 	if ((error = reference_path_available(
1511 			backend, new_name, old_name, force)) < 0 ||
1512 		(error = refdb_fs_backend__lookup(&old, _backend, old_name)) < 0)
1513 		return error;
1514 
1515 	if ((error = refdb_fs_backend__delete(_backend, old_name, NULL, NULL)) < 0) {
1516 		git_reference_free(old);
1517 		return error;
1518 	}
1519 
1520 	new = git_reference__realloc(&old, new_name);
1521 	if (!new) {
1522 		git_reference_free(old);
1523 		return -1;
1524 	}
1525 
1526 	if ((error = loose_lock(&file, backend, new->name)) < 0) {
1527 		git_reference_free(new);
1528 		return error;
1529 	}
1530 
1531 	/* Try to rename the refog; it's ok if the old doesn't exist */
1532 	error = refdb_reflog_fs__rename(_backend, old_name, new_name);
1533 	if (((error == 0) || (error == GIT_ENOTFOUND)) &&
1534 	    ((error = reflog_append(backend, new, git_reference_target(new), NULL, who, message)) < 0)) {
1535 		git_reference_free(new);
1536 		git_filebuf_cleanup(&file);
1537 		return error;
1538 	}
1539 
1540 	if (error < 0) {
1541 		git_reference_free(new);
1542 		git_filebuf_cleanup(&file);
1543 		return error;
1544 	}
1545 
1546 
1547 	if ((error = loose_commit(&file, new)) < 0 || out == NULL) {
1548 		git_reference_free(new);
1549 		return error;
1550 	}
1551 
1552 	*out = new;
1553 	return 0;
1554 }
1555 
refdb_fs_backend__compress(git_refdb_backend * _backend)1556 static int refdb_fs_backend__compress(git_refdb_backend *_backend)
1557 {
1558 	int error;
1559 	refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
1560 
1561 	assert(backend);
1562 
1563 	if ((error = packed_reload(backend)) < 0 || /* load the existing packfile */
1564 	    (error = packed_loadloose(backend)) < 0 || /* add all the loose refs */
1565 	    (error = packed_write(backend)) < 0) /* write back to disk */
1566 		return error;
1567 
1568 	return 0;
1569 }
1570 
refdb_fs_backend__free(git_refdb_backend * _backend)1571 static void refdb_fs_backend__free(git_refdb_backend *_backend)
1572 {
1573 	refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
1574 
1575 	assert(backend);
1576 
1577 	git_sortedcache_free(backend->refcache);
1578 	git__free(backend->gitpath);
1579 	git__free(backend->commonpath);
1580 	git__free(backend);
1581 }
1582 
setup_namespace(git_repository * repo,const char * in)1583 static char *setup_namespace(git_repository *repo, const char *in)
1584 {
1585 	git_buf path = GIT_BUF_INIT;
1586 	char *parts, *start, *end, *out = NULL;
1587 
1588 	if (!in)
1589 		goto done;
1590 
1591 	git_buf_puts(&path, in);
1592 
1593 	/* if the repo is not namespaced, nothing else to do */
1594 	if (repo->namespace == NULL) {
1595 		out = git_buf_detach(&path);
1596 		goto done;
1597 	}
1598 
1599 	parts = end = git__strdup(repo->namespace);
1600 	if (parts == NULL)
1601 		goto done;
1602 
1603 	/*
1604 	 * From `man gitnamespaces`:
1605 	 *  namespaces which include a / will expand to a hierarchy
1606 	 *  of namespaces; for example, GIT_NAMESPACE=foo/bar will store
1607 	 *  refs under refs/namespaces/foo/refs/namespaces/bar/
1608 	 */
1609 	while ((start = git__strsep(&end, "/")) != NULL)
1610 		git_buf_printf(&path, "refs/namespaces/%s/", start);
1611 
1612 	git_buf_printf(&path, "refs/namespaces/%s/refs", end);
1613 	git__free(parts);
1614 
1615 	/* Make sure that the folder with the namespace exists */
1616 	if (git_futils_mkdir_relative(git_buf_cstr(&path), in, 0777,
1617 			GIT_MKDIR_PATH, NULL) < 0)
1618 		goto done;
1619 
1620 	/* Return root of the namespaced gitpath, i.e. without the trailing '/refs' */
1621 	git_buf_rtruncate_at_char(&path, '/');
1622 	out = git_buf_detach(&path);
1623 
1624 done:
1625 	git_buf_dispose(&path);
1626 	return out;
1627 }
1628 
reflog_alloc(git_reflog ** reflog,const char * name)1629 static int reflog_alloc(git_reflog **reflog, const char *name)
1630 {
1631 	git_reflog *log;
1632 
1633 	*reflog = NULL;
1634 
1635 	log = git__calloc(1, sizeof(git_reflog));
1636 	GIT_ERROR_CHECK_ALLOC(log);
1637 
1638 	log->ref_name = git__strdup(name);
1639 	GIT_ERROR_CHECK_ALLOC(log->ref_name);
1640 
1641 	if (git_vector_init(&log->entries, 0, NULL) < 0) {
1642 		git__free(log->ref_name);
1643 		git__free(log);
1644 		return -1;
1645 	}
1646 
1647 	*reflog = log;
1648 
1649 	return 0;
1650 }
1651 
reflog_parse(git_reflog * log,const char * buf,size_t buf_size)1652 static int reflog_parse(git_reflog *log, const char *buf, size_t buf_size)
1653 {
1654 	git_parse_ctx parser = GIT_PARSE_CTX_INIT;
1655 
1656 	if ((git_parse_ctx_init(&parser, buf, buf_size)) < 0)
1657 		return -1;
1658 
1659 	for (; parser.remain_len; git_parse_advance_line(&parser)) {
1660 		git_reflog_entry *entry;
1661 		const char *sig;
1662 		char c;
1663 
1664 		entry = git__calloc(1, sizeof(*entry));
1665 		GIT_ERROR_CHECK_ALLOC(entry);
1666 		entry->committer = git__calloc(1, sizeof(*entry->committer));
1667 		GIT_ERROR_CHECK_ALLOC(entry->committer);
1668 
1669 		if (git_parse_advance_oid(&entry->oid_old, &parser) < 0 ||
1670 		    git_parse_advance_expected(&parser, " ", 1) < 0 ||
1671 		    git_parse_advance_oid(&entry->oid_cur, &parser) < 0)
1672 			goto next;
1673 
1674 		sig = parser.line;
1675 		while (git_parse_peek(&c, &parser, 0) == 0 && c != '\t' && c != '\n')
1676 			git_parse_advance_chars(&parser, 1);
1677 
1678 		if (git_signature__parse(entry->committer, &sig, parser.line, NULL, 0) < 0)
1679 			goto next;
1680 
1681 		if (c == '\t') {
1682 			size_t len;
1683 			git_parse_advance_chars(&parser, 1);
1684 
1685 			len = parser.line_len;
1686 			if (parser.line[len - 1] == '\n')
1687 				len--;
1688 
1689 			entry->msg = git__strndup(parser.line, len);
1690 			GIT_ERROR_CHECK_ALLOC(entry->msg);
1691 		}
1692 
1693 		if ((git_vector_insert(&log->entries, entry)) < 0) {
1694 			git_reflog_entry__free(entry);
1695 			return -1;
1696 		}
1697 
1698 		continue;
1699 
1700 next:
1701 		git_reflog_entry__free(entry);
1702 	}
1703 
1704 	return 0;
1705 }
1706 
create_new_reflog_file(const char * filepath)1707 static int create_new_reflog_file(const char *filepath)
1708 {
1709 	int fd, error;
1710 
1711 	if ((error = git_futils_mkpath2file(filepath, GIT_REFLOG_DIR_MODE)) < 0)
1712 		return error;
1713 
1714 	if ((fd = p_open(filepath,
1715 			O_WRONLY | O_CREAT,
1716 			GIT_REFLOG_FILE_MODE)) < 0)
1717 		return -1;
1718 
1719 	return p_close(fd);
1720 }
1721 
retrieve_reflog_path(git_buf * path,git_repository * repo,const char * name)1722 GIT_INLINE(int) retrieve_reflog_path(git_buf *path, git_repository *repo, const char *name)
1723 {
1724 	if (strcmp(name, GIT_HEAD_FILE) == 0)
1725 		return git_buf_join3(path, '/', repo->gitdir, GIT_REFLOG_DIR, name);
1726 	return git_buf_join3(path, '/', repo->commondir, GIT_REFLOG_DIR, name);
1727 }
1728 
refdb_reflog_fs__ensure_log(git_refdb_backend * _backend,const char * name)1729 static int refdb_reflog_fs__ensure_log(git_refdb_backend *_backend, const char *name)
1730 {
1731 	refdb_fs_backend *backend;
1732 	git_repository *repo;
1733 	git_buf path = GIT_BUF_INIT;
1734 	int error;
1735 
1736 	assert(_backend && name);
1737 
1738 	backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
1739 	repo = backend->repo;
1740 
1741 	if ((error = retrieve_reflog_path(&path, repo, name)) < 0)
1742 		return error;
1743 
1744 	error = create_new_reflog_file(git_buf_cstr(&path));
1745 	git_buf_dispose(&path);
1746 
1747 	return error;
1748 }
1749 
has_reflog(git_repository * repo,const char * name)1750 static int has_reflog(git_repository *repo, const char *name)
1751 {
1752 	int ret = 0;
1753 	git_buf path = GIT_BUF_INIT;
1754 
1755 	if (retrieve_reflog_path(&path, repo, name) < 0)
1756 		goto cleanup;
1757 
1758 	ret = git_path_isfile(git_buf_cstr(&path));
1759 
1760 cleanup:
1761 	git_buf_dispose(&path);
1762 	return ret;
1763 }
1764 
refdb_reflog_fs__has_log(git_refdb_backend * _backend,const char * name)1765 static int refdb_reflog_fs__has_log(git_refdb_backend *_backend, const char *name)
1766 {
1767 	refdb_fs_backend *backend;
1768 
1769 	assert(_backend && name);
1770 
1771 	backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
1772 
1773 	return has_reflog(backend->repo, name);
1774 }
1775 
refdb_reflog_fs__read(git_reflog ** out,git_refdb_backend * _backend,const char * name)1776 static int refdb_reflog_fs__read(git_reflog **out, git_refdb_backend *_backend, const char *name)
1777 {
1778 	int error = -1;
1779 	git_buf log_path = GIT_BUF_INIT;
1780 	git_buf log_file = GIT_BUF_INIT;
1781 	git_reflog *log = NULL;
1782 	git_repository *repo;
1783 	refdb_fs_backend *backend;
1784 
1785 	assert(out && _backend && name);
1786 
1787 	backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
1788 	repo = backend->repo;
1789 
1790 	if (reflog_alloc(&log, name) < 0)
1791 		return -1;
1792 
1793 	if (retrieve_reflog_path(&log_path, repo, name) < 0)
1794 		goto cleanup;
1795 
1796 	error = git_futils_readbuffer(&log_file, git_buf_cstr(&log_path));
1797 	if (error < 0 && error != GIT_ENOTFOUND)
1798 		goto cleanup;
1799 
1800 	if ((error == GIT_ENOTFOUND) &&
1801 		((error = create_new_reflog_file(git_buf_cstr(&log_path))) < 0))
1802 		goto cleanup;
1803 
1804 	if ((error = reflog_parse(log,
1805 		git_buf_cstr(&log_file), git_buf_len(&log_file))) < 0)
1806 		goto cleanup;
1807 
1808 	*out = log;
1809 	goto success;
1810 
1811 cleanup:
1812 	git_reflog_free(log);
1813 
1814 success:
1815 	git_buf_dispose(&log_file);
1816 	git_buf_dispose(&log_path);
1817 
1818 	return error;
1819 }
1820 
serialize_reflog_entry(git_buf * buf,const git_oid * oid_old,const git_oid * oid_new,const git_signature * committer,const char * msg)1821 static int serialize_reflog_entry(
1822 	git_buf *buf,
1823 	const git_oid *oid_old,
1824 	const git_oid *oid_new,
1825 	const git_signature *committer,
1826 	const char *msg)
1827 {
1828 	char raw_old[GIT_OID_HEXSZ+1];
1829 	char raw_new[GIT_OID_HEXSZ+1];
1830 
1831 	git_oid_tostr(raw_old, GIT_OID_HEXSZ+1, oid_old);
1832 	git_oid_tostr(raw_new, GIT_OID_HEXSZ+1, oid_new);
1833 
1834 	git_buf_clear(buf);
1835 
1836 	git_buf_puts(buf, raw_old);
1837 	git_buf_putc(buf, ' ');
1838 	git_buf_puts(buf, raw_new);
1839 
1840 	git_signature__writebuf(buf, " ", committer);
1841 
1842 	/* drop trailing LF */
1843 	git_buf_rtrim(buf);
1844 
1845 	if (msg) {
1846 		size_t i;
1847 
1848 		git_buf_putc(buf, '\t');
1849 		git_buf_puts(buf, msg);
1850 
1851 		for (i = 0; i < buf->size - 2; i++)
1852 			if (buf->ptr[i] == '\n')
1853 				buf->ptr[i] = ' ';
1854 		git_buf_rtrim(buf);
1855 	}
1856 
1857 	git_buf_putc(buf, '\n');
1858 
1859 	return git_buf_oom(buf);
1860 }
1861 
lock_reflog(git_filebuf * file,refdb_fs_backend * backend,const char * refname)1862 static int lock_reflog(git_filebuf *file, refdb_fs_backend *backend, const char *refname)
1863 {
1864 	git_repository *repo;
1865 	git_buf log_path = GIT_BUF_INIT;
1866 	int error;
1867 
1868 	repo = backend->repo;
1869 
1870 	if (!git_path_isvalid(backend->repo, refname, 0, GIT_PATH_REJECT_FILESYSTEM_DEFAULTS)) {
1871 		git_error_set(GIT_ERROR_INVALID, "invalid reference name '%s'", refname);
1872 		return GIT_EINVALIDSPEC;
1873 	}
1874 
1875 	if (retrieve_reflog_path(&log_path, repo, refname) < 0)
1876 		return -1;
1877 
1878 	if (!git_path_isfile(git_buf_cstr(&log_path))) {
1879 		git_error_set(GIT_ERROR_INVALID,
1880 			"log file for reference '%s' doesn't exist", refname);
1881 		error = -1;
1882 		goto cleanup;
1883 	}
1884 
1885 	error = git_filebuf_open(file, git_buf_cstr(&log_path), 0, GIT_REFLOG_FILE_MODE);
1886 
1887 cleanup:
1888 	git_buf_dispose(&log_path);
1889 
1890 	return error;
1891 }
1892 
refdb_reflog_fs__write(git_refdb_backend * _backend,git_reflog * reflog)1893 static int refdb_reflog_fs__write(git_refdb_backend *_backend, git_reflog *reflog)
1894 {
1895 	int error = -1;
1896 	unsigned int i;
1897 	git_reflog_entry *entry;
1898 	refdb_fs_backend *backend;
1899 	git_buf log = GIT_BUF_INIT;
1900 	git_filebuf fbuf = GIT_FILEBUF_INIT;
1901 
1902 	assert(_backend && reflog);
1903 
1904 	backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
1905 
1906 	if ((error = lock_reflog(&fbuf, backend, reflog->ref_name)) < 0)
1907 		return -1;
1908 
1909 	git_vector_foreach(&reflog->entries, i, entry) {
1910 		if (serialize_reflog_entry(&log, &(entry->oid_old), &(entry->oid_cur), entry->committer, entry->msg) < 0)
1911 			goto cleanup;
1912 
1913 		if ((error = git_filebuf_write(&fbuf, log.ptr, log.size)) < 0)
1914 			goto cleanup;
1915 	}
1916 
1917 	error = git_filebuf_commit(&fbuf);
1918 	goto success;
1919 
1920 cleanup:
1921 	git_filebuf_cleanup(&fbuf);
1922 
1923 success:
1924 	git_buf_dispose(&log);
1925 
1926 	return error;
1927 }
1928 
1929 /* Append to the reflog, must be called under reference lock */
reflog_append(refdb_fs_backend * backend,const git_reference * ref,const git_oid * old,const git_oid * new,const git_signature * who,const char * message)1930 static int reflog_append(refdb_fs_backend *backend, const git_reference *ref, const git_oid *old, const git_oid *new, const git_signature *who, const char *message)
1931 {
1932 	int error, is_symbolic, open_flags;
1933 	git_oid old_id = {{0}}, new_id = {{0}};
1934 	git_buf buf = GIT_BUF_INIT, path = GIT_BUF_INIT;
1935 	git_repository *repo = backend->repo;
1936 
1937 	is_symbolic = ref->type == GIT_REFERENCE_SYMBOLIC;
1938 
1939 	/* "normal" symbolic updates do not write */
1940 	if (is_symbolic &&
1941 	    strcmp(ref->name, GIT_HEAD_FILE) &&
1942 	    !(old && new))
1943 		return 0;
1944 
1945 	/* From here on is_symbolic also means that it's HEAD */
1946 
1947 	if (old) {
1948 		git_oid_cpy(&old_id, old);
1949 	} else {
1950 		error = git_reference_name_to_id(&old_id, repo, ref->name);
1951 		if (error < 0 && error != GIT_ENOTFOUND)
1952 			return error;
1953 	}
1954 
1955 	if (new) {
1956 		git_oid_cpy(&new_id, new);
1957 	} else {
1958 		if (!is_symbolic) {
1959 			git_oid_cpy(&new_id, git_reference_target(ref));
1960 		} else {
1961 			error = git_reference_name_to_id(&new_id, repo, git_reference_symbolic_target(ref));
1962 			if (error < 0 && error != GIT_ENOTFOUND)
1963 				return error;
1964 			/* detaching HEAD does not create an entry */
1965 			if (error == GIT_ENOTFOUND)
1966 				return 0;
1967 
1968 			git_error_clear();
1969 		}
1970 	}
1971 
1972 	if ((error = serialize_reflog_entry(&buf, &old_id, &new_id, who, message)) < 0)
1973 		goto cleanup;
1974 
1975 	if ((error = retrieve_reflog_path(&path, repo, ref->name)) < 0)
1976 		goto cleanup;
1977 
1978 	if (((error = git_futils_mkpath2file(git_buf_cstr(&path), 0777)) < 0) &&
1979 	    (error != GIT_EEXISTS)) {
1980 		goto cleanup;
1981 	}
1982 
1983 	/* If the new branch matches part of the namespace of a previously deleted branch,
1984 	 * there maybe an obsolete/unused directory (or directory hierarchy) in the way.
1985 	 */
1986 	if (git_path_isdir(git_buf_cstr(&path))) {
1987 		if ((error = git_futils_rmdir_r(git_buf_cstr(&path), NULL, GIT_RMDIR_SKIP_NONEMPTY)) < 0) {
1988 			if (error == GIT_ENOTFOUND)
1989 				error = 0;
1990 		} else if (git_path_isdir(git_buf_cstr(&path))) {
1991 			git_error_set(GIT_ERROR_REFERENCE, "cannot create reflog at '%s', there are reflogs beneath that folder",
1992 				ref->name);
1993 			error = GIT_EDIRECTORY;
1994 		}
1995 
1996 		if (error != 0)
1997 			goto cleanup;
1998 	}
1999 
2000 	open_flags = O_WRONLY | O_CREAT | O_APPEND;
2001 
2002 	if (backend->fsync)
2003 		open_flags |= O_FSYNC;
2004 
2005 	error = git_futils_writebuffer(&buf, git_buf_cstr(&path), open_flags, GIT_REFLOG_FILE_MODE);
2006 
2007 cleanup:
2008 	git_buf_dispose(&buf);
2009 	git_buf_dispose(&path);
2010 
2011 	return error;
2012 }
2013 
refdb_reflog_fs__rename(git_refdb_backend * _backend,const char * old_name,const char * new_name)2014 static int refdb_reflog_fs__rename(git_refdb_backend *_backend, const char *old_name, const char *new_name)
2015 {
2016 	int error = 0, fd;
2017 	git_buf old_path = GIT_BUF_INIT;
2018 	git_buf new_path = GIT_BUF_INIT;
2019 	git_buf temp_path = GIT_BUF_INIT;
2020 	git_buf normalized = GIT_BUF_INIT;
2021 	git_repository *repo;
2022 	refdb_fs_backend *backend;
2023 
2024 	assert(_backend && old_name && new_name);
2025 
2026 	backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
2027 	repo = backend->repo;
2028 
2029 	if ((error = git_reference__normalize_name(
2030 		&normalized, new_name, GIT_REFERENCE_FORMAT_ALLOW_ONELEVEL)) < 0)
2031 			return error;
2032 
2033 	if (git_buf_joinpath(&temp_path, repo->gitdir, GIT_REFLOG_DIR) < 0)
2034 		return -1;
2035 
2036 	if (git_buf_joinpath(&old_path, git_buf_cstr(&temp_path), old_name) < 0)
2037 		return -1;
2038 
2039 	if (git_buf_joinpath(&new_path, git_buf_cstr(&temp_path), git_buf_cstr(&normalized)) < 0)
2040 		return -1;
2041 
2042 	if (!git_path_exists(git_buf_cstr(&old_path))) {
2043 		error = GIT_ENOTFOUND;
2044 		goto cleanup;
2045 	}
2046 
2047 	/*
2048 	 * Move the reflog to a temporary place. This two-phase renaming is required
2049 	 * in order to cope with funny renaming use cases when one tries to move a reference
2050 	 * to a partially colliding namespace:
2051 	 *  - a/b -> a/b/c
2052 	 *  - a/b/c/d -> a/b/c
2053 	 */
2054 	if (git_buf_joinpath(&temp_path, git_buf_cstr(&temp_path), "temp_reflog") < 0)
2055 		return -1;
2056 
2057 	if ((fd = git_futils_mktmp(&temp_path, git_buf_cstr(&temp_path), GIT_REFLOG_FILE_MODE)) < 0) {
2058 		error = -1;
2059 		goto cleanup;
2060 	}
2061 
2062 	p_close(fd);
2063 
2064 	if (p_rename(git_buf_cstr(&old_path), git_buf_cstr(&temp_path)) < 0) {
2065 		git_error_set(GIT_ERROR_OS, "failed to rename reflog for %s", new_name);
2066 		error = -1;
2067 		goto cleanup;
2068 	}
2069 
2070 	if (git_path_isdir(git_buf_cstr(&new_path)) &&
2071 		(git_futils_rmdir_r(git_buf_cstr(&new_path), NULL, GIT_RMDIR_SKIP_NONEMPTY) < 0)) {
2072 		error = -1;
2073 		goto cleanup;
2074 	}
2075 
2076 	if (git_futils_mkpath2file(git_buf_cstr(&new_path), GIT_REFLOG_DIR_MODE) < 0) {
2077 		error = -1;
2078 		goto cleanup;
2079 	}
2080 
2081 	if (p_rename(git_buf_cstr(&temp_path), git_buf_cstr(&new_path)) < 0) {
2082 		git_error_set(GIT_ERROR_OS, "failed to rename reflog for %s", new_name);
2083 		error = -1;
2084 	}
2085 
2086 cleanup:
2087 	git_buf_dispose(&temp_path);
2088 	git_buf_dispose(&old_path);
2089 	git_buf_dispose(&new_path);
2090 	git_buf_dispose(&normalized);
2091 
2092 	return error;
2093 }
2094 
refdb_reflog_fs__delete(git_refdb_backend * _backend,const char * name)2095 static int refdb_reflog_fs__delete(git_refdb_backend *_backend, const char *name)
2096 {
2097 	refdb_fs_backend *backend = GIT_CONTAINER_OF(_backend, refdb_fs_backend, parent);
2098 	git_buf path = GIT_BUF_INIT;
2099 	int error;
2100 
2101 	assert(_backend && name);
2102 
2103 	if ((error = retrieve_reflog_path(&path, backend->repo, name)) < 0)
2104 		goto out;
2105 
2106 	if (!git_path_exists(path.ptr))
2107 		goto out;
2108 
2109 	if ((error = p_unlink(path.ptr)) < 0)
2110 		goto out;
2111 
2112 	refdb_fs_backend__prune_refs(backend, name, GIT_REFLOG_DIR);
2113 
2114 out:
2115 	git_buf_dispose(&path);
2116 
2117 	return error;
2118 }
2119 
git_refdb_backend_fs(git_refdb_backend ** backend_out,git_repository * repository)2120 int git_refdb_backend_fs(
2121 	git_refdb_backend **backend_out,
2122 	git_repository *repository)
2123 {
2124 	int t = 0;
2125 	git_buf gitpath = GIT_BUF_INIT;
2126 	refdb_fs_backend *backend;
2127 
2128 	backend = git__calloc(1, sizeof(refdb_fs_backend));
2129 	GIT_ERROR_CHECK_ALLOC(backend);
2130 
2131 	if (git_refdb_init_backend(&backend->parent, GIT_REFDB_BACKEND_VERSION) < 0)
2132 		goto fail;
2133 
2134 	backend->repo = repository;
2135 
2136 	if (repository->gitdir) {
2137 		backend->gitpath = setup_namespace(repository, repository->gitdir);
2138 
2139 		if (backend->gitpath == NULL)
2140 			goto fail;
2141 	}
2142 
2143 	if (repository->commondir) {
2144 		backend->commonpath = setup_namespace(repository, repository->commondir);
2145 
2146 		if (backend->commonpath == NULL)
2147 			goto fail;
2148 	}
2149 
2150 	if (git_buf_joinpath(&gitpath, backend->commonpath, GIT_PACKEDREFS_FILE) < 0 ||
2151 		git_sortedcache_new(
2152 			&backend->refcache, offsetof(struct packref, name),
2153 			NULL, NULL, packref_cmp, git_buf_cstr(&gitpath)) < 0)
2154 		goto fail;
2155 
2156 	git_buf_dispose(&gitpath);
2157 
2158 	if (!git_repository__configmap_lookup(&t, backend->repo, GIT_CONFIGMAP_IGNORECASE) && t) {
2159 		backend->iterator_flags |= GIT_ITERATOR_IGNORE_CASE;
2160 		backend->direach_flags  |= GIT_PATH_DIR_IGNORE_CASE;
2161 	}
2162 	if (!git_repository__configmap_lookup(&t, backend->repo, GIT_CONFIGMAP_PRECOMPOSE) && t) {
2163 		backend->iterator_flags |= GIT_ITERATOR_PRECOMPOSE_UNICODE;
2164 		backend->direach_flags  |= GIT_PATH_DIR_PRECOMPOSE_UNICODE;
2165 	}
2166 	if ((!git_repository__configmap_lookup(&t, backend->repo, GIT_CONFIGMAP_FSYNCOBJECTFILES) && t) ||
2167 		git_repository__fsync_gitdir)
2168 		backend->fsync = 1;
2169 	backend->iterator_flags |= GIT_ITERATOR_DESCEND_SYMLINKS;
2170 
2171 	backend->parent.exists = &refdb_fs_backend__exists;
2172 	backend->parent.lookup = &refdb_fs_backend__lookup;
2173 	backend->parent.iterator = &refdb_fs_backend__iterator;
2174 	backend->parent.write = &refdb_fs_backend__write;
2175 	backend->parent.del = &refdb_fs_backend__delete;
2176 	backend->parent.rename = &refdb_fs_backend__rename;
2177 	backend->parent.compress = &refdb_fs_backend__compress;
2178 	backend->parent.lock = &refdb_fs_backend__lock;
2179 	backend->parent.unlock = &refdb_fs_backend__unlock;
2180 	backend->parent.has_log = &refdb_reflog_fs__has_log;
2181 	backend->parent.ensure_log = &refdb_reflog_fs__ensure_log;
2182 	backend->parent.free = &refdb_fs_backend__free;
2183 	backend->parent.reflog_read = &refdb_reflog_fs__read;
2184 	backend->parent.reflog_write = &refdb_reflog_fs__write;
2185 	backend->parent.reflog_rename = &refdb_reflog_fs__rename;
2186 	backend->parent.reflog_delete = &refdb_reflog_fs__delete;
2187 
2188 	*backend_out = (git_refdb_backend *)backend;
2189 	return 0;
2190 
2191 fail:
2192 	git_buf_dispose(&gitpath);
2193 	git__free(backend->gitpath);
2194 	git__free(backend->commonpath);
2195 	git__free(backend);
2196 	return -1;
2197 }
2198