1 #include "../cache.h"
2 #include "../config.h"
3 #include "../refs.h"
4 #include "refs-internal.h"
5 #include "packed-backend.h"
6 #include "../iterator.h"
7 #include "../lockfile.h"
8 #include "../chdir-notify.h"
9 
10 enum mmap_strategy {
11 	/*
12 	 * Don't use mmap() at all for reading `packed-refs`.
13 	 */
14 	MMAP_NONE,
15 
16 	/*
17 	 * Can use mmap() for reading `packed-refs`, but the file must
18 	 * not remain mmapped. This is the usual option on Windows,
19 	 * where you cannot rename a new version of a file onto a file
20 	 * that is currently mmapped.
21 	 */
22 	MMAP_TEMPORARY,
23 
24 	/*
25 	 * It is OK to leave the `packed-refs` file mmapped while
26 	 * arbitrary other code is running.
27 	 */
28 	MMAP_OK
29 };
30 
31 #if defined(NO_MMAP)
32 static enum mmap_strategy mmap_strategy = MMAP_NONE;
33 #elif defined(MMAP_PREVENTS_DELETE)
34 static enum mmap_strategy mmap_strategy = MMAP_TEMPORARY;
35 #else
36 static enum mmap_strategy mmap_strategy = MMAP_OK;
37 #endif
38 
39 struct packed_ref_store;
40 
41 /*
42  * A `snapshot` represents one snapshot of a `packed-refs` file.
43  *
44  * Normally, this will be a mmapped view of the contents of the
45  * `packed-refs` file at the time the snapshot was created. However,
46  * if the `packed-refs` file was not sorted, this might point at heap
47  * memory holding the contents of the `packed-refs` file with its
48  * records sorted by refname.
49  *
50  * `snapshot` instances are reference counted (via
51  * `acquire_snapshot()` and `release_snapshot()`). This is to prevent
52  * an instance from disappearing while an iterator is still iterating
53  * over it. Instances are garbage collected when their `referrers`
54  * count goes to zero.
55  *
56  * The most recent `snapshot`, if available, is referenced by the
57  * `packed_ref_store`. Its freshness is checked whenever
58  * `get_snapshot()` is called; if the existing snapshot is obsolete, a
59  * new snapshot is taken.
60  */
61 struct snapshot {
62 	/*
63 	 * A back-pointer to the packed_ref_store with which this
64 	 * snapshot is associated:
65 	 */
66 	struct packed_ref_store *refs;
67 
68 	/* Is the `packed-refs` file currently mmapped? */
69 	int mmapped;
70 
71 	/*
72 	 * The contents of the `packed-refs` file:
73 	 *
74 	 * - buf -- a pointer to the start of the memory
75 	 * - start -- a pointer to the first byte of actual references
76 	 *   (i.e., after the header line, if one is present)
77 	 * - eof -- a pointer just past the end of the reference
78 	 *   contents
79 	 *
80 	 * If the `packed-refs` file was already sorted, `buf` points
81 	 * at the mmapped contents of the file. If not, it points at
82 	 * heap-allocated memory containing the contents, sorted. If
83 	 * there were no contents (e.g., because the file didn't
84 	 * exist), `buf`, `start`, and `eof` are all NULL.
85 	 */
86 	char *buf, *start, *eof;
87 
88 	/*
89 	 * What is the peeled state of the `packed-refs` file that
90 	 * this snapshot represents? (This is usually determined from
91 	 * the file's header.)
92 	 */
93 	enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled;
94 
95 	/*
96 	 * Count of references to this instance, including the pointer
97 	 * from `packed_ref_store::snapshot`, if any. The instance
98 	 * will not be freed as long as the reference count is
99 	 * nonzero.
100 	 */
101 	unsigned int referrers;
102 
103 	/*
104 	 * The metadata of the `packed-refs` file from which this
105 	 * snapshot was created, used to tell if the file has been
106 	 * replaced since we read it.
107 	 */
108 	struct stat_validity validity;
109 };
110 
111 /*
112  * A `ref_store` representing references stored in a `packed-refs`
113  * file. It implements the `ref_store` interface, though it has some
114  * limitations:
115  *
116  * - It cannot store symbolic references.
117  *
118  * - It cannot store reflogs.
119  *
120  * - It does not support reference renaming (though it could).
121  *
122  * On the other hand, it can be locked outside of a reference
123  * transaction. In that case, it remains locked even after the
124  * transaction is done and the new `packed-refs` file is activated.
125  */
126 struct packed_ref_store {
127 	struct ref_store base;
128 
129 	unsigned int store_flags;
130 
131 	/* The path of the "packed-refs" file: */
132 	char *path;
133 
134 	/*
135 	 * A snapshot of the values read from the `packed-refs` file,
136 	 * if it might still be current; otherwise, NULL.
137 	 */
138 	struct snapshot *snapshot;
139 
140 	/*
141 	 * Lock used for the "packed-refs" file. Note that this (and
142 	 * thus the enclosing `packed_ref_store`) must not be freed.
143 	 */
144 	struct lock_file lock;
145 
146 	/*
147 	 * Temporary file used when rewriting new contents to the
148 	 * "packed-refs" file. Note that this (and thus the enclosing
149 	 * `packed_ref_store`) must not be freed.
150 	 */
151 	struct tempfile *tempfile;
152 };
153 
154 /*
155  * Increment the reference count of `*snapshot`.
156  */
acquire_snapshot(struct snapshot * snapshot)157 static void acquire_snapshot(struct snapshot *snapshot)
158 {
159 	snapshot->referrers++;
160 }
161 
162 /*
163  * If the buffer in `snapshot` is active, then either munmap the
164  * memory and close the file, or free the memory. Then set the buffer
165  * pointers to NULL.
166  */
clear_snapshot_buffer(struct snapshot * snapshot)167 static void clear_snapshot_buffer(struct snapshot *snapshot)
168 {
169 	if (snapshot->mmapped) {
170 		if (munmap(snapshot->buf, snapshot->eof - snapshot->buf))
171 			die_errno("error ummapping packed-refs file %s",
172 				  snapshot->refs->path);
173 		snapshot->mmapped = 0;
174 	} else {
175 		free(snapshot->buf);
176 	}
177 	snapshot->buf = snapshot->start = snapshot->eof = NULL;
178 }
179 
180 /*
181  * Decrease the reference count of `*snapshot`. If it goes to zero,
182  * free `*snapshot` and return true; otherwise return false.
183  */
release_snapshot(struct snapshot * snapshot)184 static int release_snapshot(struct snapshot *snapshot)
185 {
186 	if (!--snapshot->referrers) {
187 		stat_validity_clear(&snapshot->validity);
188 		clear_snapshot_buffer(snapshot);
189 		free(snapshot);
190 		return 1;
191 	} else {
192 		return 0;
193 	}
194 }
195 
packed_ref_store_create(struct repository * repo,const char * path,unsigned int store_flags)196 struct ref_store *packed_ref_store_create(struct repository *repo,
197 					  const char *path,
198 					  unsigned int store_flags)
199 {
200 	struct packed_ref_store *refs = xcalloc(1, sizeof(*refs));
201 	struct ref_store *ref_store = (struct ref_store *)refs;
202 
203 	base_ref_store_init(ref_store, &refs_be_packed);
204 	ref_store->repo = repo;
205 	ref_store->gitdir = xstrdup(path);
206 	refs->store_flags = store_flags;
207 
208 	refs->path = xstrdup(path);
209 	chdir_notify_reparent("packed-refs", &refs->path);
210 
211 	return ref_store;
212 }
213 
214 /*
215  * Downcast `ref_store` to `packed_ref_store`. Die if `ref_store` is
216  * not a `packed_ref_store`. Also die if `packed_ref_store` doesn't
217  * support at least the flags specified in `required_flags`. `caller`
218  * is used in any necessary error messages.
219  */
packed_downcast(struct ref_store * ref_store,unsigned int required_flags,const char * caller)220 static struct packed_ref_store *packed_downcast(struct ref_store *ref_store,
221 						unsigned int required_flags,
222 						const char *caller)
223 {
224 	struct packed_ref_store *refs;
225 
226 	if (ref_store->be != &refs_be_packed)
227 		BUG("ref_store is type \"%s\" not \"packed\" in %s",
228 		    ref_store->be->name, caller);
229 
230 	refs = (struct packed_ref_store *)ref_store;
231 
232 	if ((refs->store_flags & required_flags) != required_flags)
233 		BUG("unallowed operation (%s), requires %x, has %x\n",
234 		    caller, required_flags, refs->store_flags);
235 
236 	return refs;
237 }
238 
clear_snapshot(struct packed_ref_store * refs)239 static void clear_snapshot(struct packed_ref_store *refs)
240 {
241 	if (refs->snapshot) {
242 		struct snapshot *snapshot = refs->snapshot;
243 
244 		refs->snapshot = NULL;
245 		release_snapshot(snapshot);
246 	}
247 }
248 
die_unterminated_line(const char * path,const char * p,size_t len)249 static NORETURN void die_unterminated_line(const char *path,
250 					   const char *p, size_t len)
251 {
252 	if (len < 80)
253 		die("unterminated line in %s: %.*s", path, (int)len, p);
254 	else
255 		die("unterminated line in %s: %.75s...", path, p);
256 }
257 
die_invalid_line(const char * path,const char * p,size_t len)258 static NORETURN void die_invalid_line(const char *path,
259 				      const char *p, size_t len)
260 {
261 	const char *eol = memchr(p, '\n', len);
262 
263 	if (!eol)
264 		die_unterminated_line(path, p, len);
265 	else if (eol - p < 80)
266 		die("unexpected line in %s: %.*s", path, (int)(eol - p), p);
267 	else
268 		die("unexpected line in %s: %.75s...", path, p);
269 
270 }
271 
272 struct snapshot_record {
273 	const char *start;
274 	size_t len;
275 };
276 
cmp_packed_ref_records(const void * v1,const void * v2)277 static int cmp_packed_ref_records(const void *v1, const void *v2)
278 {
279 	const struct snapshot_record *e1 = v1, *e2 = v2;
280 	const char *r1 = e1->start + the_hash_algo->hexsz + 1;
281 	const char *r2 = e2->start + the_hash_algo->hexsz + 1;
282 
283 	while (1) {
284 		if (*r1 == '\n')
285 			return *r2 == '\n' ? 0 : -1;
286 		if (*r1 != *r2) {
287 			if (*r2 == '\n')
288 				return 1;
289 			else
290 				return (unsigned char)*r1 < (unsigned char)*r2 ? -1 : +1;
291 		}
292 		r1++;
293 		r2++;
294 	}
295 }
296 
297 /*
298  * Compare a snapshot record at `rec` to the specified NUL-terminated
299  * refname.
300  */
cmp_record_to_refname(const char * rec,const char * refname)301 static int cmp_record_to_refname(const char *rec, const char *refname)
302 {
303 	const char *r1 = rec + the_hash_algo->hexsz + 1;
304 	const char *r2 = refname;
305 
306 	while (1) {
307 		if (*r1 == '\n')
308 			return *r2 ? -1 : 0;
309 		if (!*r2)
310 			return 1;
311 		if (*r1 != *r2)
312 			return (unsigned char)*r1 < (unsigned char)*r2 ? -1 : +1;
313 		r1++;
314 		r2++;
315 	}
316 }
317 
318 /*
319  * `snapshot->buf` is not known to be sorted. Check whether it is, and
320  * if not, sort it into new memory and munmap/free the old storage.
321  */
sort_snapshot(struct snapshot * snapshot)322 static void sort_snapshot(struct snapshot *snapshot)
323 {
324 	struct snapshot_record *records = NULL;
325 	size_t alloc = 0, nr = 0;
326 	int sorted = 1;
327 	const char *pos, *eof, *eol;
328 	size_t len, i;
329 	char *new_buffer, *dst;
330 
331 	pos = snapshot->start;
332 	eof = snapshot->eof;
333 
334 	if (pos == eof)
335 		return;
336 
337 	len = eof - pos;
338 
339 	/*
340 	 * Initialize records based on a crude estimate of the number
341 	 * of references in the file (we'll grow it below if needed):
342 	 */
343 	ALLOC_GROW(records, len / 80 + 20, alloc);
344 
345 	while (pos < eof) {
346 		eol = memchr(pos, '\n', eof - pos);
347 		if (!eol)
348 			/* The safety check should prevent this. */
349 			BUG("unterminated line found in packed-refs");
350 		if (eol - pos < the_hash_algo->hexsz + 2)
351 			die_invalid_line(snapshot->refs->path,
352 					 pos, eof - pos);
353 		eol++;
354 		if (eol < eof && *eol == '^') {
355 			/*
356 			 * Keep any peeled line together with its
357 			 * reference:
358 			 */
359 			const char *peeled_start = eol;
360 
361 			eol = memchr(peeled_start, '\n', eof - peeled_start);
362 			if (!eol)
363 				/* The safety check should prevent this. */
364 				BUG("unterminated peeled line found in packed-refs");
365 			eol++;
366 		}
367 
368 		ALLOC_GROW(records, nr + 1, alloc);
369 		records[nr].start = pos;
370 		records[nr].len = eol - pos;
371 		nr++;
372 
373 		if (sorted &&
374 		    nr > 1 &&
375 		    cmp_packed_ref_records(&records[nr - 2],
376 					   &records[nr - 1]) >= 0)
377 			sorted = 0;
378 
379 		pos = eol;
380 	}
381 
382 	if (sorted)
383 		goto cleanup;
384 
385 	/* We need to sort the memory. First we sort the records array: */
386 	QSORT(records, nr, cmp_packed_ref_records);
387 
388 	/*
389 	 * Allocate a new chunk of memory, and copy the old memory to
390 	 * the new in the order indicated by `records` (not bothering
391 	 * with the header line):
392 	 */
393 	new_buffer = xmalloc(len);
394 	for (dst = new_buffer, i = 0; i < nr; i++) {
395 		memcpy(dst, records[i].start, records[i].len);
396 		dst += records[i].len;
397 	}
398 
399 	/*
400 	 * Now munmap the old buffer and use the sorted buffer in its
401 	 * place:
402 	 */
403 	clear_snapshot_buffer(snapshot);
404 	snapshot->buf = snapshot->start = new_buffer;
405 	snapshot->eof = new_buffer + len;
406 
407 cleanup:
408 	free(records);
409 }
410 
411 /*
412  * Return a pointer to the start of the record that contains the
413  * character `*p` (which must be within the buffer). If no other
414  * record start is found, return `buf`.
415  */
find_start_of_record(const char * buf,const char * p)416 static const char *find_start_of_record(const char *buf, const char *p)
417 {
418 	while (p > buf && (p[-1] != '\n' || p[0] == '^'))
419 		p--;
420 	return p;
421 }
422 
423 /*
424  * Return a pointer to the start of the record following the record
425  * that contains `*p`. If none is found before `end`, return `end`.
426  */
find_end_of_record(const char * p,const char * end)427 static const char *find_end_of_record(const char *p, const char *end)
428 {
429 	while (++p < end && (p[-1] != '\n' || p[0] == '^'))
430 		;
431 	return p;
432 }
433 
434 /*
435  * We want to be able to compare mmapped reference records quickly,
436  * without totally parsing them. We can do so because the records are
437  * LF-terminated, and the refname should start exactly (GIT_SHA1_HEXSZ
438  * + 1) bytes past the beginning of the record.
439  *
440  * But what if the `packed-refs` file contains garbage? We're willing
441  * to tolerate not detecting the problem, as long as we don't produce
442  * totally garbled output (we can't afford to check the integrity of
443  * the whole file during every Git invocation). But we do want to be
444  * sure that we never read past the end of the buffer in memory and
445  * perform an illegal memory access.
446  *
447  * Guarantee that minimum level of safety by verifying that the last
448  * record in the file is LF-terminated, and that it has at least
449  * (GIT_SHA1_HEXSZ + 1) characters before the LF. Die if either of
450  * these checks fails.
451  */
verify_buffer_safe(struct snapshot * snapshot)452 static void verify_buffer_safe(struct snapshot *snapshot)
453 {
454 	const char *start = snapshot->start;
455 	const char *eof = snapshot->eof;
456 	const char *last_line;
457 
458 	if (start == eof)
459 		return;
460 
461 	last_line = find_start_of_record(start, eof - 1);
462 	if (*(eof - 1) != '\n' || eof - last_line < the_hash_algo->hexsz + 2)
463 		die_invalid_line(snapshot->refs->path,
464 				 last_line, eof - last_line);
465 }
466 
467 #define SMALL_FILE_SIZE (32*1024)
468 
469 /*
470  * Depending on `mmap_strategy`, either mmap or read the contents of
471  * the `packed-refs` file into the snapshot. Return 1 if the file
472  * existed and was read, or 0 if the file was absent or empty. Die on
473  * errors.
474  */
load_contents(struct snapshot * snapshot)475 static int load_contents(struct snapshot *snapshot)
476 {
477 	int fd;
478 	struct stat st;
479 	size_t size;
480 	ssize_t bytes_read;
481 
482 	fd = open(snapshot->refs->path, O_RDONLY);
483 	if (fd < 0) {
484 		if (errno == ENOENT) {
485 			/*
486 			 * This is OK; it just means that no
487 			 * "packed-refs" file has been written yet,
488 			 * which is equivalent to it being empty,
489 			 * which is its state when initialized with
490 			 * zeros.
491 			 */
492 			return 0;
493 		} else {
494 			die_errno("couldn't read %s", snapshot->refs->path);
495 		}
496 	}
497 
498 	stat_validity_update(&snapshot->validity, fd);
499 
500 	if (fstat(fd, &st) < 0)
501 		die_errno("couldn't stat %s", snapshot->refs->path);
502 	size = xsize_t(st.st_size);
503 
504 	if (!size) {
505 		close(fd);
506 		return 0;
507 	} else if (mmap_strategy == MMAP_NONE || size <= SMALL_FILE_SIZE) {
508 		snapshot->buf = xmalloc(size);
509 		bytes_read = read_in_full(fd, snapshot->buf, size);
510 		if (bytes_read < 0 || bytes_read != size)
511 			die_errno("couldn't read %s", snapshot->refs->path);
512 		snapshot->mmapped = 0;
513 	} else {
514 		snapshot->buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
515 		snapshot->mmapped = 1;
516 	}
517 	close(fd);
518 
519 	snapshot->start = snapshot->buf;
520 	snapshot->eof = snapshot->buf + size;
521 
522 	return 1;
523 }
524 
525 /*
526  * Find the place in `snapshot->buf` where the start of the record for
527  * `refname` starts. If `mustexist` is true and the reference doesn't
528  * exist, then return NULL. If `mustexist` is false and the reference
529  * doesn't exist, then return the point where that reference would be
530  * inserted, or `snapshot->eof` (which might be NULL) if it would be
531  * inserted at the end of the file. In the latter mode, `refname`
532  * doesn't have to be a proper reference name; for example, one could
533  * search for "refs/replace/" to find the start of any replace
534  * references.
535  *
536  * The record is sought using a binary search, so `snapshot->buf` must
537  * be sorted.
538  */
find_reference_location(struct snapshot * snapshot,const char * refname,int mustexist)539 static const char *find_reference_location(struct snapshot *snapshot,
540 					   const char *refname, int mustexist)
541 {
542 	/*
543 	 * This is not *quite* a garden-variety binary search, because
544 	 * the data we're searching is made up of records, and we
545 	 * always need to find the beginning of a record to do a
546 	 * comparison. A "record" here is one line for the reference
547 	 * itself and zero or one peel lines that start with '^'. Our
548 	 * loop invariant is described in the next two comments.
549 	 */
550 
551 	/*
552 	 * A pointer to the character at the start of a record whose
553 	 * preceding records all have reference names that come
554 	 * *before* `refname`.
555 	 */
556 	const char *lo = snapshot->start;
557 
558 	/*
559 	 * A pointer to a the first character of a record whose
560 	 * reference name comes *after* `refname`.
561 	 */
562 	const char *hi = snapshot->eof;
563 
564 	while (lo != hi) {
565 		const char *mid, *rec;
566 		int cmp;
567 
568 		mid = lo + (hi - lo) / 2;
569 		rec = find_start_of_record(lo, mid);
570 		cmp = cmp_record_to_refname(rec, refname);
571 		if (cmp < 0) {
572 			lo = find_end_of_record(mid, hi);
573 		} else if (cmp > 0) {
574 			hi = rec;
575 		} else {
576 			return rec;
577 		}
578 	}
579 
580 	if (mustexist)
581 		return NULL;
582 	else
583 		return lo;
584 }
585 
586 /*
587  * Create a newly-allocated `snapshot` of the `packed-refs` file in
588  * its current state and return it. The return value will already have
589  * its reference count incremented.
590  *
591  * A comment line of the form "# pack-refs with: " may contain zero or
592  * more traits. We interpret the traits as follows:
593  *
594  *   Neither `peeled` nor `fully-peeled`:
595  *
596  *      Probably no references are peeled. But if the file contains a
597  *      peeled value for a reference, we will use it.
598  *
599  *   `peeled`:
600  *
601  *      References under "refs/tags/", if they *can* be peeled, *are*
602  *      peeled in this file. References outside of "refs/tags/" are
603  *      probably not peeled even if they could have been, but if we find
604  *      a peeled value for such a reference we will use it.
605  *
606  *   `fully-peeled`:
607  *
608  *      All references in the file that can be peeled are peeled.
609  *      Inversely (and this is more important), any references in the
610  *      file for which no peeled value is recorded is not peelable. This
611  *      trait should typically be written alongside "peeled" for
612  *      compatibility with older clients, but we do not require it
613  *      (i.e., "peeled" is a no-op if "fully-peeled" is set).
614  *
615  *   `sorted`:
616  *
617  *      The references in this file are known to be sorted by refname.
618  */
create_snapshot(struct packed_ref_store * refs)619 static struct snapshot *create_snapshot(struct packed_ref_store *refs)
620 {
621 	struct snapshot *snapshot = xcalloc(1, sizeof(*snapshot));
622 	int sorted = 0;
623 
624 	snapshot->refs = refs;
625 	acquire_snapshot(snapshot);
626 	snapshot->peeled = PEELED_NONE;
627 
628 	if (!load_contents(snapshot))
629 		return snapshot;
630 
631 	/* If the file has a header line, process it: */
632 	if (snapshot->buf < snapshot->eof && *snapshot->buf == '#') {
633 		char *tmp, *p, *eol;
634 		struct string_list traits = STRING_LIST_INIT_NODUP;
635 
636 		eol = memchr(snapshot->buf, '\n',
637 			     snapshot->eof - snapshot->buf);
638 		if (!eol)
639 			die_unterminated_line(refs->path,
640 					      snapshot->buf,
641 					      snapshot->eof - snapshot->buf);
642 
643 		tmp = xmemdupz(snapshot->buf, eol - snapshot->buf);
644 
645 		if (!skip_prefix(tmp, "# pack-refs with:", (const char **)&p))
646 			die_invalid_line(refs->path,
647 					 snapshot->buf,
648 					 snapshot->eof - snapshot->buf);
649 
650 		string_list_split_in_place(&traits, p, ' ', -1);
651 
652 		if (unsorted_string_list_has_string(&traits, "fully-peeled"))
653 			snapshot->peeled = PEELED_FULLY;
654 		else if (unsorted_string_list_has_string(&traits, "peeled"))
655 			snapshot->peeled = PEELED_TAGS;
656 
657 		sorted = unsorted_string_list_has_string(&traits, "sorted");
658 
659 		/* perhaps other traits later as well */
660 
661 		/* The "+ 1" is for the LF character. */
662 		snapshot->start = eol + 1;
663 
664 		string_list_clear(&traits, 0);
665 		free(tmp);
666 	}
667 
668 	verify_buffer_safe(snapshot);
669 
670 	if (!sorted) {
671 		sort_snapshot(snapshot);
672 
673 		/*
674 		 * Reordering the records might have moved a short one
675 		 * to the end of the buffer, so verify the buffer's
676 		 * safety again:
677 		 */
678 		verify_buffer_safe(snapshot);
679 	}
680 
681 	if (mmap_strategy != MMAP_OK && snapshot->mmapped) {
682 		/*
683 		 * We don't want to leave the file mmapped, so we are
684 		 * forced to make a copy now:
685 		 */
686 		size_t size = snapshot->eof - snapshot->start;
687 		char *buf_copy = xmalloc(size);
688 
689 		memcpy(buf_copy, snapshot->start, size);
690 		clear_snapshot_buffer(snapshot);
691 		snapshot->buf = snapshot->start = buf_copy;
692 		snapshot->eof = buf_copy + size;
693 	}
694 
695 	return snapshot;
696 }
697 
698 /*
699  * Check that `refs->snapshot` (if present) still reflects the
700  * contents of the `packed-refs` file. If not, clear the snapshot.
701  */
validate_snapshot(struct packed_ref_store * refs)702 static void validate_snapshot(struct packed_ref_store *refs)
703 {
704 	if (refs->snapshot &&
705 	    !stat_validity_check(&refs->snapshot->validity, refs->path))
706 		clear_snapshot(refs);
707 }
708 
709 /*
710  * Get the `snapshot` for the specified packed_ref_store, creating and
711  * populating it if it hasn't been read before or if the file has been
712  * changed (according to its `validity` field) since it was last read.
713  * On the other hand, if we hold the lock, then assume that the file
714  * hasn't been changed out from under us, so skip the extra `stat()`
715  * call in `stat_validity_check()`. This function does *not* increase
716  * the snapshot's reference count on behalf of the caller.
717  */
get_snapshot(struct packed_ref_store * refs)718 static struct snapshot *get_snapshot(struct packed_ref_store *refs)
719 {
720 	if (!is_lock_file_locked(&refs->lock))
721 		validate_snapshot(refs);
722 
723 	if (!refs->snapshot)
724 		refs->snapshot = create_snapshot(refs);
725 
726 	return refs->snapshot;
727 }
728 
packed_read_raw_ref(struct ref_store * ref_store,const char * refname,struct object_id * oid,struct strbuf * referent,unsigned int * type,int * failure_errno)729 static int packed_read_raw_ref(struct ref_store *ref_store, const char *refname,
730 			       struct object_id *oid, struct strbuf *referent,
731 			       unsigned int *type, int *failure_errno)
732 {
733 	struct packed_ref_store *refs =
734 		packed_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
735 	struct snapshot *snapshot = get_snapshot(refs);
736 	const char *rec;
737 
738 	*type = 0;
739 
740 	rec = find_reference_location(snapshot, refname, 1);
741 
742 	if (!rec) {
743 		/* refname is not a packed reference. */
744 		*failure_errno = ENOENT;
745 		return -1;
746 	}
747 
748 	if (get_oid_hex(rec, oid))
749 		die_invalid_line(refs->path, rec, snapshot->eof - rec);
750 
751 	*type = REF_ISPACKED;
752 	return 0;
753 }
754 
755 /*
756  * This value is set in `base.flags` if the peeled value of the
757  * current reference is known. In that case, `peeled` contains the
758  * correct peeled value for the reference, which might be `null_oid`
759  * if the reference is not a tag or if it is broken.
760  */
761 #define REF_KNOWS_PEELED 0x40
762 
763 /*
764  * An iterator over a snapshot of a `packed-refs` file.
765  */
766 struct packed_ref_iterator {
767 	struct ref_iterator base;
768 
769 	struct snapshot *snapshot;
770 
771 	/* The current position in the snapshot's buffer: */
772 	const char *pos;
773 
774 	/* The end of the part of the buffer that will be iterated over: */
775 	const char *eof;
776 
777 	/* Scratch space for current values: */
778 	struct object_id oid, peeled;
779 	struct strbuf refname_buf;
780 
781 	struct repository *repo;
782 	unsigned int flags;
783 };
784 
785 /*
786  * Move the iterator to the next record in the snapshot, without
787  * respect for whether the record is actually required by the current
788  * iteration. Adjust the fields in `iter` and return `ITER_OK` or
789  * `ITER_DONE`. This function does not free the iterator in the case
790  * of `ITER_DONE`.
791  */
next_record(struct packed_ref_iterator * iter)792 static int next_record(struct packed_ref_iterator *iter)
793 {
794 	const char *p = iter->pos, *eol;
795 
796 	strbuf_reset(&iter->refname_buf);
797 
798 	if (iter->pos == iter->eof)
799 		return ITER_DONE;
800 
801 	iter->base.flags = REF_ISPACKED;
802 
803 	if (iter->eof - p < the_hash_algo->hexsz + 2 ||
804 	    parse_oid_hex(p, &iter->oid, &p) ||
805 	    !isspace(*p++))
806 		die_invalid_line(iter->snapshot->refs->path,
807 				 iter->pos, iter->eof - iter->pos);
808 
809 	eol = memchr(p, '\n', iter->eof - p);
810 	if (!eol)
811 		die_unterminated_line(iter->snapshot->refs->path,
812 				      iter->pos, iter->eof - iter->pos);
813 
814 	strbuf_add(&iter->refname_buf, p, eol - p);
815 	iter->base.refname = iter->refname_buf.buf;
816 
817 	if (check_refname_format(iter->base.refname, REFNAME_ALLOW_ONELEVEL)) {
818 		if (!refname_is_safe(iter->base.refname))
819 			die("packed refname is dangerous: %s",
820 			    iter->base.refname);
821 		oidclr(&iter->oid);
822 		iter->base.flags |= REF_BAD_NAME | REF_ISBROKEN;
823 	}
824 	if (iter->snapshot->peeled == PEELED_FULLY ||
825 	    (iter->snapshot->peeled == PEELED_TAGS &&
826 	     starts_with(iter->base.refname, "refs/tags/")))
827 		iter->base.flags |= REF_KNOWS_PEELED;
828 
829 	iter->pos = eol + 1;
830 
831 	if (iter->pos < iter->eof && *iter->pos == '^') {
832 		p = iter->pos + 1;
833 		if (iter->eof - p < the_hash_algo->hexsz + 1 ||
834 		    parse_oid_hex(p, &iter->peeled, &p) ||
835 		    *p++ != '\n')
836 			die_invalid_line(iter->snapshot->refs->path,
837 					 iter->pos, iter->eof - iter->pos);
838 		iter->pos = p;
839 
840 		/*
841 		 * Regardless of what the file header said, we
842 		 * definitely know the value of *this* reference. But
843 		 * we suppress it if the reference is broken:
844 		 */
845 		if ((iter->base.flags & REF_ISBROKEN)) {
846 			oidclr(&iter->peeled);
847 			iter->base.flags &= ~REF_KNOWS_PEELED;
848 		} else {
849 			iter->base.flags |= REF_KNOWS_PEELED;
850 		}
851 	} else {
852 		oidclr(&iter->peeled);
853 	}
854 
855 	return ITER_OK;
856 }
857 
packed_ref_iterator_advance(struct ref_iterator * ref_iterator)858 static int packed_ref_iterator_advance(struct ref_iterator *ref_iterator)
859 {
860 	struct packed_ref_iterator *iter =
861 		(struct packed_ref_iterator *)ref_iterator;
862 	int ok;
863 
864 	while ((ok = next_record(iter)) == ITER_OK) {
865 		if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
866 		    ref_type(iter->base.refname) != REF_TYPE_PER_WORKTREE)
867 			continue;
868 
869 		if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
870 		    !ref_resolves_to_object(iter->base.refname, iter->repo,
871 					    &iter->oid, iter->flags))
872 			continue;
873 
874 		return ITER_OK;
875 	}
876 
877 	if (ref_iterator_abort(ref_iterator) != ITER_DONE)
878 		ok = ITER_ERROR;
879 
880 	return ok;
881 }
882 
packed_ref_iterator_peel(struct ref_iterator * ref_iterator,struct object_id * peeled)883 static int packed_ref_iterator_peel(struct ref_iterator *ref_iterator,
884 				   struct object_id *peeled)
885 {
886 	struct packed_ref_iterator *iter =
887 		(struct packed_ref_iterator *)ref_iterator;
888 
889 	if (iter->repo != the_repository)
890 		BUG("peeling for non-the_repository is not supported");
891 
892 	if ((iter->base.flags & REF_KNOWS_PEELED)) {
893 		oidcpy(peeled, &iter->peeled);
894 		return is_null_oid(&iter->peeled) ? -1 : 0;
895 	} else if ((iter->base.flags & (REF_ISBROKEN | REF_ISSYMREF))) {
896 		return -1;
897 	} else {
898 		return peel_object(&iter->oid, peeled) ? -1 : 0;
899 	}
900 }
901 
packed_ref_iterator_abort(struct ref_iterator * ref_iterator)902 static int packed_ref_iterator_abort(struct ref_iterator *ref_iterator)
903 {
904 	struct packed_ref_iterator *iter =
905 		(struct packed_ref_iterator *)ref_iterator;
906 	int ok = ITER_DONE;
907 
908 	strbuf_release(&iter->refname_buf);
909 	release_snapshot(iter->snapshot);
910 	base_ref_iterator_free(ref_iterator);
911 	return ok;
912 }
913 
914 static struct ref_iterator_vtable packed_ref_iterator_vtable = {
915 	packed_ref_iterator_advance,
916 	packed_ref_iterator_peel,
917 	packed_ref_iterator_abort
918 };
919 
packed_ref_iterator_begin(struct ref_store * ref_store,const char * prefix,unsigned int flags)920 static struct ref_iterator *packed_ref_iterator_begin(
921 		struct ref_store *ref_store,
922 		const char *prefix, unsigned int flags)
923 {
924 	struct packed_ref_store *refs;
925 	struct snapshot *snapshot;
926 	const char *start;
927 	struct packed_ref_iterator *iter;
928 	struct ref_iterator *ref_iterator;
929 	unsigned int required_flags = REF_STORE_READ;
930 
931 	if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
932 		required_flags |= REF_STORE_ODB;
933 	refs = packed_downcast(ref_store, required_flags, "ref_iterator_begin");
934 
935 	/*
936 	 * Note that `get_snapshot()` internally checks whether the
937 	 * snapshot is up to date with what is on disk, and re-reads
938 	 * it if not.
939 	 */
940 	snapshot = get_snapshot(refs);
941 
942 	if (prefix && *prefix)
943 		start = find_reference_location(snapshot, prefix, 0);
944 	else
945 		start = snapshot->start;
946 
947 	if (start == snapshot->eof)
948 		return empty_ref_iterator_begin();
949 
950 	CALLOC_ARRAY(iter, 1);
951 	ref_iterator = &iter->base;
952 	base_ref_iterator_init(ref_iterator, &packed_ref_iterator_vtable, 1);
953 
954 	iter->snapshot = snapshot;
955 	acquire_snapshot(snapshot);
956 
957 	iter->pos = start;
958 	iter->eof = snapshot->eof;
959 	strbuf_init(&iter->refname_buf, 0);
960 
961 	iter->base.oid = &iter->oid;
962 
963 	iter->repo = ref_store->repo;
964 	iter->flags = flags;
965 
966 	if (prefix && *prefix)
967 		/* Stop iteration after we've gone *past* prefix: */
968 		ref_iterator = prefix_ref_iterator_begin(ref_iterator, prefix, 0);
969 
970 	return ref_iterator;
971 }
972 
973 /*
974  * Write an entry to the packed-refs file for the specified refname.
975  * If peeled is non-NULL, write it as the entry's peeled value. On
976  * error, return a nonzero value and leave errno set at the value left
977  * by the failing call to `fprintf()`.
978  */
write_packed_entry(FILE * fh,const char * refname,const struct object_id * oid,const struct object_id * peeled)979 static int write_packed_entry(FILE *fh, const char *refname,
980 			      const struct object_id *oid,
981 			      const struct object_id *peeled)
982 {
983 	if (fprintf(fh, "%s %s\n", oid_to_hex(oid), refname) < 0 ||
984 	    (peeled && fprintf(fh, "^%s\n", oid_to_hex(peeled)) < 0))
985 		return -1;
986 
987 	return 0;
988 }
989 
packed_refs_lock(struct ref_store * ref_store,int flags,struct strbuf * err)990 int packed_refs_lock(struct ref_store *ref_store, int flags, struct strbuf *err)
991 {
992 	struct packed_ref_store *refs =
993 		packed_downcast(ref_store, REF_STORE_WRITE | REF_STORE_MAIN,
994 				"packed_refs_lock");
995 	static int timeout_configured = 0;
996 	static int timeout_value = 1000;
997 
998 	if (!timeout_configured) {
999 		git_config_get_int("core.packedrefstimeout", &timeout_value);
1000 		timeout_configured = 1;
1001 	}
1002 
1003 	/*
1004 	 * Note that we close the lockfile immediately because we
1005 	 * don't write new content to it, but rather to a separate
1006 	 * tempfile.
1007 	 */
1008 	if (hold_lock_file_for_update_timeout(
1009 			    &refs->lock,
1010 			    refs->path,
1011 			    flags, timeout_value) < 0) {
1012 		unable_to_lock_message(refs->path, errno, err);
1013 		return -1;
1014 	}
1015 
1016 	if (close_lock_file_gently(&refs->lock)) {
1017 		strbuf_addf(err, "unable to close %s: %s", refs->path, strerror(errno));
1018 		rollback_lock_file(&refs->lock);
1019 		return -1;
1020 	}
1021 
1022 	/*
1023 	 * There is a stat-validity problem might cause `update-ref -d`
1024 	 * lost the newly commit of a ref, because a new `packed-refs`
1025 	 * file might has the same on-disk file attributes such as
1026 	 * timestamp, file size and inode value, but has a changed
1027 	 * ref value.
1028 	 *
1029 	 * This could happen with a very small chance when
1030 	 * `update-ref -d` is called and at the same time another
1031 	 * `pack-refs --all` process is running.
1032 	 *
1033 	 * Now that we hold the `packed-refs` lock, it is important
1034 	 * to make sure we could read the latest version of
1035 	 * `packed-refs` file no matter we have just mmap it or not.
1036 	 * So what need to do is clear the snapshot if we hold it
1037 	 * already.
1038 	 */
1039 	clear_snapshot(refs);
1040 
1041 	/*
1042 	 * Now make sure that the packed-refs file as it exists in the
1043 	 * locked state is loaded into the snapshot:
1044 	 */
1045 	get_snapshot(refs);
1046 	return 0;
1047 }
1048 
packed_refs_unlock(struct ref_store * ref_store)1049 void packed_refs_unlock(struct ref_store *ref_store)
1050 {
1051 	struct packed_ref_store *refs = packed_downcast(
1052 			ref_store,
1053 			REF_STORE_READ | REF_STORE_WRITE,
1054 			"packed_refs_unlock");
1055 
1056 	if (!is_lock_file_locked(&refs->lock))
1057 		BUG("packed_refs_unlock() called when not locked");
1058 	rollback_lock_file(&refs->lock);
1059 }
1060 
packed_refs_is_locked(struct ref_store * ref_store)1061 int packed_refs_is_locked(struct ref_store *ref_store)
1062 {
1063 	struct packed_ref_store *refs = packed_downcast(
1064 			ref_store,
1065 			REF_STORE_READ | REF_STORE_WRITE,
1066 			"packed_refs_is_locked");
1067 
1068 	return is_lock_file_locked(&refs->lock);
1069 }
1070 
1071 /*
1072  * The packed-refs header line that we write out. Perhaps other traits
1073  * will be added later.
1074  *
1075  * Note that earlier versions of Git used to parse these traits by
1076  * looking for " trait " in the line. For this reason, the space after
1077  * the colon and the trailing space are required.
1078  */
1079 static const char PACKED_REFS_HEADER[] =
1080 	"# pack-refs with: peeled fully-peeled sorted \n";
1081 
packed_init_db(struct ref_store * ref_store,struct strbuf * err)1082 static int packed_init_db(struct ref_store *ref_store, struct strbuf *err)
1083 {
1084 	/* Nothing to do. */
1085 	return 0;
1086 }
1087 
1088 /*
1089  * Write the packed refs from the current snapshot to the packed-refs
1090  * tempfile, incorporating any changes from `updates`. `updates` must
1091  * be a sorted string list whose keys are the refnames and whose util
1092  * values are `struct ref_update *`. On error, rollback the tempfile,
1093  * write an error message to `err`, and return a nonzero value.
1094  *
1095  * The packfile must be locked before calling this function and will
1096  * remain locked when it is done.
1097  */
write_with_updates(struct packed_ref_store * refs,struct string_list * updates,struct strbuf * err)1098 static int write_with_updates(struct packed_ref_store *refs,
1099 			      struct string_list *updates,
1100 			      struct strbuf *err)
1101 {
1102 	struct ref_iterator *iter = NULL;
1103 	size_t i;
1104 	int ok;
1105 	FILE *out;
1106 	struct strbuf sb = STRBUF_INIT;
1107 	char *packed_refs_path;
1108 
1109 	if (!is_lock_file_locked(&refs->lock))
1110 		BUG("write_with_updates() called while unlocked");
1111 
1112 	/*
1113 	 * If packed-refs is a symlink, we want to overwrite the
1114 	 * symlinked-to file, not the symlink itself. Also, put the
1115 	 * staging file next to it:
1116 	 */
1117 	packed_refs_path = get_locked_file_path(&refs->lock);
1118 	strbuf_addf(&sb, "%s.new", packed_refs_path);
1119 	free(packed_refs_path);
1120 	refs->tempfile = create_tempfile(sb.buf);
1121 	if (!refs->tempfile) {
1122 		strbuf_addf(err, "unable to create file %s: %s",
1123 			    sb.buf, strerror(errno));
1124 		strbuf_release(&sb);
1125 		return -1;
1126 	}
1127 	strbuf_release(&sb);
1128 
1129 	out = fdopen_tempfile(refs->tempfile, "w");
1130 	if (!out) {
1131 		strbuf_addf(err, "unable to fdopen packed-refs tempfile: %s",
1132 			    strerror(errno));
1133 		goto error;
1134 	}
1135 
1136 	if (fprintf(out, "%s", PACKED_REFS_HEADER) < 0)
1137 		goto write_error;
1138 
1139 	/*
1140 	 * We iterate in parallel through the current list of refs and
1141 	 * the list of updates, processing an entry from at least one
1142 	 * of the lists each time through the loop. When the current
1143 	 * list of refs is exhausted, set iter to NULL. When the list
1144 	 * of updates is exhausted, leave i set to updates->nr.
1145 	 */
1146 	iter = packed_ref_iterator_begin(&refs->base, "",
1147 					 DO_FOR_EACH_INCLUDE_BROKEN);
1148 	if ((ok = ref_iterator_advance(iter)) != ITER_OK)
1149 		iter = NULL;
1150 
1151 	i = 0;
1152 
1153 	while (iter || i < updates->nr) {
1154 		struct ref_update *update = NULL;
1155 		int cmp;
1156 
1157 		if (i >= updates->nr) {
1158 			cmp = -1;
1159 		} else {
1160 			update = updates->items[i].util;
1161 
1162 			if (!iter)
1163 				cmp = +1;
1164 			else
1165 				cmp = strcmp(iter->refname, update->refname);
1166 		}
1167 
1168 		if (!cmp) {
1169 			/*
1170 			 * There is both an old value and an update
1171 			 * for this reference. Check the old value if
1172 			 * necessary:
1173 			 */
1174 			if ((update->flags & REF_HAVE_OLD)) {
1175 				if (is_null_oid(&update->old_oid)) {
1176 					strbuf_addf(err, "cannot update ref '%s': "
1177 						    "reference already exists",
1178 						    update->refname);
1179 					goto error;
1180 				} else if (!oideq(&update->old_oid, iter->oid)) {
1181 					strbuf_addf(err, "cannot update ref '%s': "
1182 						    "is at %s but expected %s",
1183 						    update->refname,
1184 						    oid_to_hex(iter->oid),
1185 						    oid_to_hex(&update->old_oid));
1186 					goto error;
1187 				}
1188 			}
1189 
1190 			/* Now figure out what to use for the new value: */
1191 			if ((update->flags & REF_HAVE_NEW)) {
1192 				/*
1193 				 * The update takes precedence. Skip
1194 				 * the iterator over the unneeded
1195 				 * value.
1196 				 */
1197 				if ((ok = ref_iterator_advance(iter)) != ITER_OK)
1198 					iter = NULL;
1199 				cmp = +1;
1200 			} else {
1201 				/*
1202 				 * The update doesn't actually want to
1203 				 * change anything. We're done with it.
1204 				 */
1205 				i++;
1206 				cmp = -1;
1207 			}
1208 		} else if (cmp > 0) {
1209 			/*
1210 			 * There is no old value but there is an
1211 			 * update for this reference. Make sure that
1212 			 * the update didn't expect an existing value:
1213 			 */
1214 			if ((update->flags & REF_HAVE_OLD) &&
1215 			    !is_null_oid(&update->old_oid)) {
1216 				strbuf_addf(err, "cannot update ref '%s': "
1217 					    "reference is missing but expected %s",
1218 					    update->refname,
1219 					    oid_to_hex(&update->old_oid));
1220 				goto error;
1221 			}
1222 		}
1223 
1224 		if (cmp < 0) {
1225 			/* Pass the old reference through. */
1226 
1227 			struct object_id peeled;
1228 			int peel_error = ref_iterator_peel(iter, &peeled);
1229 
1230 			if (write_packed_entry(out, iter->refname,
1231 					       iter->oid,
1232 					       peel_error ? NULL : &peeled))
1233 				goto write_error;
1234 
1235 			if ((ok = ref_iterator_advance(iter)) != ITER_OK)
1236 				iter = NULL;
1237 		} else if (is_null_oid(&update->new_oid)) {
1238 			/*
1239 			 * The update wants to delete the reference,
1240 			 * and the reference either didn't exist or we
1241 			 * have already skipped it. So we're done with
1242 			 * the update (and don't have to write
1243 			 * anything).
1244 			 */
1245 			i++;
1246 		} else {
1247 			struct object_id peeled;
1248 			int peel_error = peel_object(&update->new_oid,
1249 						     &peeled);
1250 
1251 			if (write_packed_entry(out, update->refname,
1252 					       &update->new_oid,
1253 					       peel_error ? NULL : &peeled))
1254 				goto write_error;
1255 
1256 			i++;
1257 		}
1258 	}
1259 
1260 	if (ok != ITER_DONE) {
1261 		strbuf_addstr(err, "unable to write packed-refs file: "
1262 			      "error iterating over old contents");
1263 		goto error;
1264 	}
1265 
1266 	if (close_tempfile_gently(refs->tempfile)) {
1267 		strbuf_addf(err, "error closing file %s: %s",
1268 			    get_tempfile_path(refs->tempfile),
1269 			    strerror(errno));
1270 		strbuf_release(&sb);
1271 		delete_tempfile(&refs->tempfile);
1272 		return -1;
1273 	}
1274 
1275 	return 0;
1276 
1277 write_error:
1278 	strbuf_addf(err, "error writing to %s: %s",
1279 		    get_tempfile_path(refs->tempfile), strerror(errno));
1280 
1281 error:
1282 	if (iter)
1283 		ref_iterator_abort(iter);
1284 
1285 	delete_tempfile(&refs->tempfile);
1286 	return -1;
1287 }
1288 
is_packed_transaction_needed(struct ref_store * ref_store,struct ref_transaction * transaction)1289 int is_packed_transaction_needed(struct ref_store *ref_store,
1290 				 struct ref_transaction *transaction)
1291 {
1292 	struct packed_ref_store *refs = packed_downcast(
1293 			ref_store,
1294 			REF_STORE_READ,
1295 			"is_packed_transaction_needed");
1296 	struct strbuf referent = STRBUF_INIT;
1297 	size_t i;
1298 	int ret;
1299 
1300 	if (!is_lock_file_locked(&refs->lock))
1301 		BUG("is_packed_transaction_needed() called while unlocked");
1302 
1303 	/*
1304 	 * We're only going to bother returning false for the common,
1305 	 * trivial case that references are only being deleted, their
1306 	 * old values are not being checked, and the old `packed-refs`
1307 	 * file doesn't contain any of those reference(s). This gives
1308 	 * false positives for some other cases that could
1309 	 * theoretically be optimized away:
1310 	 *
1311 	 * 1. It could be that the old value is being verified without
1312 	 *    setting a new value. In this case, we could verify the
1313 	 *    old value here and skip the update if it agrees. If it
1314 	 *    disagrees, we could either let the update go through
1315 	 *    (the actual commit would re-detect and report the
1316 	 *    problem), or come up with a way of reporting such an
1317 	 *    error to *our* caller.
1318 	 *
1319 	 * 2. It could be that a new value is being set, but that it
1320 	 *    is identical to the current packed value of the
1321 	 *    reference.
1322 	 *
1323 	 * Neither of these cases will come up in the current code,
1324 	 * because the only caller of this function passes to it a
1325 	 * transaction that only includes `delete` updates with no
1326 	 * `old_id`. Even if that ever changes, false positives only
1327 	 * cause an optimization to be missed; they do not affect
1328 	 * correctness.
1329 	 */
1330 
1331 	/*
1332 	 * Start with the cheap checks that don't require old
1333 	 * reference values to be read:
1334 	 */
1335 	for (i = 0; i < transaction->nr; i++) {
1336 		struct ref_update *update = transaction->updates[i];
1337 
1338 		if (update->flags & REF_HAVE_OLD)
1339 			/* Have to check the old value -> needed. */
1340 			return 1;
1341 
1342 		if ((update->flags & REF_HAVE_NEW) && !is_null_oid(&update->new_oid))
1343 			/* Have to set a new value -> needed. */
1344 			return 1;
1345 	}
1346 
1347 	/*
1348 	 * The transaction isn't checking any old values nor is it
1349 	 * setting any nonzero new values, so it still might be able
1350 	 * to be skipped. Now do the more expensive check: the update
1351 	 * is needed if any of the updates is a delete, and the old
1352 	 * `packed-refs` file contains a value for that reference.
1353 	 */
1354 	ret = 0;
1355 	for (i = 0; i < transaction->nr; i++) {
1356 		struct ref_update *update = transaction->updates[i];
1357 		unsigned int type;
1358 		struct object_id oid;
1359 
1360 		if (!(update->flags & REF_HAVE_NEW))
1361 			/*
1362 			 * This reference isn't being deleted -> not
1363 			 * needed.
1364 			 */
1365 			continue;
1366 
1367 		if (!refs_read_raw_ref(ref_store, update->refname,
1368 				       &oid, &referent, &type) ||
1369 		    errno != ENOENT) {
1370 			/*
1371 			 * We have to actually delete that reference
1372 			 * -> this transaction is needed.
1373 			 */
1374 			ret = 1;
1375 			break;
1376 		}
1377 	}
1378 
1379 	strbuf_release(&referent);
1380 	return ret;
1381 }
1382 
1383 struct packed_transaction_backend_data {
1384 	/* True iff the transaction owns the packed-refs lock. */
1385 	int own_lock;
1386 
1387 	struct string_list updates;
1388 };
1389 
packed_transaction_cleanup(struct packed_ref_store * refs,struct ref_transaction * transaction)1390 static void packed_transaction_cleanup(struct packed_ref_store *refs,
1391 				       struct ref_transaction *transaction)
1392 {
1393 	struct packed_transaction_backend_data *data = transaction->backend_data;
1394 
1395 	if (data) {
1396 		string_list_clear(&data->updates, 0);
1397 
1398 		if (is_tempfile_active(refs->tempfile))
1399 			delete_tempfile(&refs->tempfile);
1400 
1401 		if (data->own_lock && is_lock_file_locked(&refs->lock)) {
1402 			packed_refs_unlock(&refs->base);
1403 			data->own_lock = 0;
1404 		}
1405 
1406 		free(data);
1407 		transaction->backend_data = NULL;
1408 	}
1409 
1410 	transaction->state = REF_TRANSACTION_CLOSED;
1411 }
1412 
packed_transaction_prepare(struct ref_store * ref_store,struct ref_transaction * transaction,struct strbuf * err)1413 static int packed_transaction_prepare(struct ref_store *ref_store,
1414 				      struct ref_transaction *transaction,
1415 				      struct strbuf *err)
1416 {
1417 	struct packed_ref_store *refs = packed_downcast(
1418 			ref_store,
1419 			REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
1420 			"ref_transaction_prepare");
1421 	struct packed_transaction_backend_data *data;
1422 	size_t i;
1423 	int ret = TRANSACTION_GENERIC_ERROR;
1424 
1425 	/*
1426 	 * Note that we *don't* skip transactions with zero updates,
1427 	 * because such a transaction might be executed for the side
1428 	 * effect of ensuring that all of the references are peeled or
1429 	 * ensuring that the `packed-refs` file is sorted. If the
1430 	 * caller wants to optimize away empty transactions, it should
1431 	 * do so itself.
1432 	 */
1433 
1434 	CALLOC_ARRAY(data, 1);
1435 	string_list_init_nodup(&data->updates);
1436 
1437 	transaction->backend_data = data;
1438 
1439 	/*
1440 	 * Stick the updates in a string list by refname so that we
1441 	 * can sort them:
1442 	 */
1443 	for (i = 0; i < transaction->nr; i++) {
1444 		struct ref_update *update = transaction->updates[i];
1445 		struct string_list_item *item =
1446 			string_list_append(&data->updates, update->refname);
1447 
1448 		/* Store a pointer to update in item->util: */
1449 		item->util = update;
1450 	}
1451 	string_list_sort(&data->updates);
1452 
1453 	if (ref_update_reject_duplicates(&data->updates, err))
1454 		goto failure;
1455 
1456 	if (!is_lock_file_locked(&refs->lock)) {
1457 		if (packed_refs_lock(ref_store, 0, err))
1458 			goto failure;
1459 		data->own_lock = 1;
1460 	}
1461 
1462 	if (write_with_updates(refs, &data->updates, err))
1463 		goto failure;
1464 
1465 	transaction->state = REF_TRANSACTION_PREPARED;
1466 	return 0;
1467 
1468 failure:
1469 	packed_transaction_cleanup(refs, transaction);
1470 	return ret;
1471 }
1472 
packed_transaction_abort(struct ref_store * ref_store,struct ref_transaction * transaction,struct strbuf * err)1473 static int packed_transaction_abort(struct ref_store *ref_store,
1474 				    struct ref_transaction *transaction,
1475 				    struct strbuf *err)
1476 {
1477 	struct packed_ref_store *refs = packed_downcast(
1478 			ref_store,
1479 			REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
1480 			"ref_transaction_abort");
1481 
1482 	packed_transaction_cleanup(refs, transaction);
1483 	return 0;
1484 }
1485 
packed_transaction_finish(struct ref_store * ref_store,struct ref_transaction * transaction,struct strbuf * err)1486 static int packed_transaction_finish(struct ref_store *ref_store,
1487 				     struct ref_transaction *transaction,
1488 				     struct strbuf *err)
1489 {
1490 	struct packed_ref_store *refs = packed_downcast(
1491 			ref_store,
1492 			REF_STORE_READ | REF_STORE_WRITE | REF_STORE_ODB,
1493 			"ref_transaction_finish");
1494 	int ret = TRANSACTION_GENERIC_ERROR;
1495 	char *packed_refs_path;
1496 
1497 	clear_snapshot(refs);
1498 
1499 	packed_refs_path = get_locked_file_path(&refs->lock);
1500 	if (rename_tempfile(&refs->tempfile, packed_refs_path)) {
1501 		strbuf_addf(err, "error replacing %s: %s",
1502 			    refs->path, strerror(errno));
1503 		goto cleanup;
1504 	}
1505 
1506 	ret = 0;
1507 
1508 cleanup:
1509 	free(packed_refs_path);
1510 	packed_transaction_cleanup(refs, transaction);
1511 	return ret;
1512 }
1513 
packed_initial_transaction_commit(struct ref_store * ref_store,struct ref_transaction * transaction,struct strbuf * err)1514 static int packed_initial_transaction_commit(struct ref_store *ref_store,
1515 					    struct ref_transaction *transaction,
1516 					    struct strbuf *err)
1517 {
1518 	return ref_transaction_commit(transaction, err);
1519 }
1520 
packed_delete_refs(struct ref_store * ref_store,const char * msg,struct string_list * refnames,unsigned int flags)1521 static int packed_delete_refs(struct ref_store *ref_store, const char *msg,
1522 			     struct string_list *refnames, unsigned int flags)
1523 {
1524 	struct packed_ref_store *refs =
1525 		packed_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1526 	struct strbuf err = STRBUF_INIT;
1527 	struct ref_transaction *transaction;
1528 	struct string_list_item *item;
1529 	int ret;
1530 
1531 	(void)refs; /* We need the check above, but don't use the variable */
1532 
1533 	if (!refnames->nr)
1534 		return 0;
1535 
1536 	/*
1537 	 * Since we don't check the references' old_oids, the
1538 	 * individual updates can't fail, so we can pack all of the
1539 	 * updates into a single transaction.
1540 	 */
1541 
1542 	transaction = ref_store_transaction_begin(ref_store, &err);
1543 	if (!transaction)
1544 		return -1;
1545 
1546 	for_each_string_list_item(item, refnames) {
1547 		if (ref_transaction_delete(transaction, item->string, NULL,
1548 					   flags, msg, &err)) {
1549 			warning(_("could not delete reference %s: %s"),
1550 				item->string, err.buf);
1551 			strbuf_reset(&err);
1552 		}
1553 	}
1554 
1555 	ret = ref_transaction_commit(transaction, &err);
1556 
1557 	if (ret) {
1558 		if (refnames->nr == 1)
1559 			error(_("could not delete reference %s: %s"),
1560 			      refnames->items[0].string, err.buf);
1561 		else
1562 			error(_("could not delete references: %s"), err.buf);
1563 	}
1564 
1565 	ref_transaction_free(transaction);
1566 	strbuf_release(&err);
1567 	return ret;
1568 }
1569 
packed_pack_refs(struct ref_store * ref_store,unsigned int flags)1570 static int packed_pack_refs(struct ref_store *ref_store, unsigned int flags)
1571 {
1572 	/*
1573 	 * Packed refs are already packed. It might be that loose refs
1574 	 * are packed *into* a packed refs store, but that is done by
1575 	 * updating the packed references via a transaction.
1576 	 */
1577 	return 0;
1578 }
1579 
packed_create_symref(struct ref_store * ref_store,const char * refname,const char * target,const char * logmsg)1580 static int packed_create_symref(struct ref_store *ref_store,
1581 			       const char *refname, const char *target,
1582 			       const char *logmsg)
1583 {
1584 	BUG("packed reference store does not support symrefs");
1585 }
1586 
packed_rename_ref(struct ref_store * ref_store,const char * oldrefname,const char * newrefname,const char * logmsg)1587 static int packed_rename_ref(struct ref_store *ref_store,
1588 			    const char *oldrefname, const char *newrefname,
1589 			    const char *logmsg)
1590 {
1591 	BUG("packed reference store does not support renaming references");
1592 }
1593 
packed_copy_ref(struct ref_store * ref_store,const char * oldrefname,const char * newrefname,const char * logmsg)1594 static int packed_copy_ref(struct ref_store *ref_store,
1595 			   const char *oldrefname, const char *newrefname,
1596 			   const char *logmsg)
1597 {
1598 	BUG("packed reference store does not support copying references");
1599 }
1600 
packed_reflog_iterator_begin(struct ref_store * ref_store)1601 static struct ref_iterator *packed_reflog_iterator_begin(struct ref_store *ref_store)
1602 {
1603 	return empty_ref_iterator_begin();
1604 }
1605 
packed_for_each_reflog_ent(struct ref_store * ref_store,const char * refname,each_reflog_ent_fn fn,void * cb_data)1606 static int packed_for_each_reflog_ent(struct ref_store *ref_store,
1607 				      const char *refname,
1608 				      each_reflog_ent_fn fn, void *cb_data)
1609 {
1610 	BUG("packed reference store does not support reflogs");
1611 	return 0;
1612 }
1613 
packed_for_each_reflog_ent_reverse(struct ref_store * ref_store,const char * refname,each_reflog_ent_fn fn,void * cb_data)1614 static int packed_for_each_reflog_ent_reverse(struct ref_store *ref_store,
1615 					      const char *refname,
1616 					      each_reflog_ent_fn fn,
1617 					      void *cb_data)
1618 {
1619 	BUG("packed reference store does not support reflogs");
1620 	return 0;
1621 }
1622 
packed_reflog_exists(struct ref_store * ref_store,const char * refname)1623 static int packed_reflog_exists(struct ref_store *ref_store,
1624 			       const char *refname)
1625 {
1626 	BUG("packed reference store does not support reflogs");
1627 	return 0;
1628 }
1629 
packed_create_reflog(struct ref_store * ref_store,const char * refname,int force_create,struct strbuf * err)1630 static int packed_create_reflog(struct ref_store *ref_store,
1631 			       const char *refname, int force_create,
1632 			       struct strbuf *err)
1633 {
1634 	BUG("packed reference store does not support reflogs");
1635 }
1636 
packed_delete_reflog(struct ref_store * ref_store,const char * refname)1637 static int packed_delete_reflog(struct ref_store *ref_store,
1638 			       const char *refname)
1639 {
1640 	BUG("packed reference store does not support reflogs");
1641 	return 0;
1642 }
1643 
packed_reflog_expire(struct ref_store * ref_store,const char * refname,unsigned int flags,reflog_expiry_prepare_fn prepare_fn,reflog_expiry_should_prune_fn should_prune_fn,reflog_expiry_cleanup_fn cleanup_fn,void * policy_cb_data)1644 static int packed_reflog_expire(struct ref_store *ref_store,
1645 				const char *refname,
1646 				unsigned int flags,
1647 				reflog_expiry_prepare_fn prepare_fn,
1648 				reflog_expiry_should_prune_fn should_prune_fn,
1649 				reflog_expiry_cleanup_fn cleanup_fn,
1650 				void *policy_cb_data)
1651 {
1652 	BUG("packed reference store does not support reflogs");
1653 	return 0;
1654 }
1655 
1656 struct ref_storage_be refs_be_packed = {
1657 	NULL,
1658 	"packed",
1659 	packed_ref_store_create,
1660 	packed_init_db,
1661 	packed_transaction_prepare,
1662 	packed_transaction_finish,
1663 	packed_transaction_abort,
1664 	packed_initial_transaction_commit,
1665 
1666 	packed_pack_refs,
1667 	packed_create_symref,
1668 	packed_delete_refs,
1669 	packed_rename_ref,
1670 	packed_copy_ref,
1671 
1672 	packed_ref_iterator_begin,
1673 	packed_read_raw_ref,
1674 
1675 	packed_reflog_iterator_begin,
1676 	packed_for_each_reflog_ent,
1677 	packed_for_each_reflog_ent_reverse,
1678 	packed_reflog_exists,
1679 	packed_create_reflog,
1680 	packed_delete_reflog,
1681 	packed_reflog_expire
1682 };
1683