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