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