split_symref_update(): add a files_ref_store argument
[git] / refs / files-backend.c
1 #include "../cache.h"
2 #include "../refs.h"
3 #include "refs-internal.h"
4 #include "../iterator.h"
5 #include "../dir-iterator.h"
6 #include "../lockfile.h"
7 #include "../object.h"
8 #include "../dir.h"
9
10 struct ref_lock {
11         char *ref_name;
12         struct lock_file *lk;
13         struct object_id old_oid;
14 };
15
16 struct ref_entry;
17
18 /*
19  * Information used (along with the information in ref_entry) to
20  * describe a single cached reference.  This data structure only
21  * occurs embedded in a union in struct ref_entry, and only when
22  * (ref_entry->flag & REF_DIR) is zero.
23  */
24 struct ref_value {
25         /*
26          * The name of the object to which this reference resolves
27          * (which may be a tag object).  If REF_ISBROKEN, this is
28          * null.  If REF_ISSYMREF, then this is the name of the object
29          * referred to by the last reference in the symlink chain.
30          */
31         struct object_id oid;
32
33         /*
34          * If REF_KNOWS_PEELED, then this field holds the peeled value
35          * of this reference, or null if the reference is known not to
36          * be peelable.  See the documentation for peel_ref() for an
37          * exact definition of "peelable".
38          */
39         struct object_id peeled;
40 };
41
42 struct files_ref_store;
43
44 /*
45  * Information used (along with the information in ref_entry) to
46  * describe a level in the hierarchy of references.  This data
47  * structure only occurs embedded in a union in struct ref_entry, and
48  * only when (ref_entry.flag & REF_DIR) is set.  In that case,
49  * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
50  * in the directory have already been read:
51  *
52  *     (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
53  *         or packed references, already read.
54  *
55  *     (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
56  *         references that hasn't been read yet (nor has any of its
57  *         subdirectories).
58  *
59  * Entries within a directory are stored within a growable array of
60  * pointers to ref_entries (entries, nr, alloc).  Entries 0 <= i <
61  * sorted are sorted by their component name in strcmp() order and the
62  * remaining entries are unsorted.
63  *
64  * Loose references are read lazily, one directory at a time.  When a
65  * directory of loose references is read, then all of the references
66  * in that directory are stored, and REF_INCOMPLETE stubs are created
67  * for any subdirectories, but the subdirectories themselves are not
68  * read.  The reading is triggered by get_ref_dir().
69  */
70 struct ref_dir {
71         int nr, alloc;
72
73         /*
74          * Entries with index 0 <= i < sorted are sorted by name.  New
75          * entries are appended to the list unsorted, and are sorted
76          * only when required; thus we avoid the need to sort the list
77          * after the addition of every reference.
78          */
79         int sorted;
80
81         /* A pointer to the files_ref_store that contains this ref_dir. */
82         struct files_ref_store *ref_store;
83
84         struct ref_entry **entries;
85 };
86
87 /*
88  * Bit values for ref_entry::flag.  REF_ISSYMREF=0x01,
89  * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
90  * public values; see refs.h.
91  */
92
93 /*
94  * The field ref_entry->u.value.peeled of this value entry contains
95  * the correct peeled value for the reference, which might be
96  * null_sha1 if the reference is not a tag or if it is broken.
97  */
98 #define REF_KNOWS_PEELED 0x10
99
100 /* ref_entry represents a directory of references */
101 #define REF_DIR 0x20
102
103 /*
104  * Entry has not yet been read from disk (used only for REF_DIR
105  * entries representing loose references)
106  */
107 #define REF_INCOMPLETE 0x40
108
109 /*
110  * A ref_entry represents either a reference or a "subdirectory" of
111  * references.
112  *
113  * Each directory in the reference namespace is represented by a
114  * ref_entry with (flags & REF_DIR) set and containing a subdir member
115  * that holds the entries in that directory that have been read so
116  * far.  If (flags & REF_INCOMPLETE) is set, then the directory and
117  * its subdirectories haven't been read yet.  REF_INCOMPLETE is only
118  * used for loose reference directories.
119  *
120  * References are represented by a ref_entry with (flags & REF_DIR)
121  * unset and a value member that describes the reference's value.  The
122  * flag member is at the ref_entry level, but it is also needed to
123  * interpret the contents of the value field (in other words, a
124  * ref_value object is not very much use without the enclosing
125  * ref_entry).
126  *
127  * Reference names cannot end with slash and directories' names are
128  * always stored with a trailing slash (except for the top-level
129  * directory, which is always denoted by "").  This has two nice
130  * consequences: (1) when the entries in each subdir are sorted
131  * lexicographically by name (as they usually are), the references in
132  * a whole tree can be generated in lexicographic order by traversing
133  * the tree in left-to-right, depth-first order; (2) the names of
134  * references and subdirectories cannot conflict, and therefore the
135  * presence of an empty subdirectory does not block the creation of a
136  * similarly-named reference.  (The fact that reference names with the
137  * same leading components can conflict *with each other* is a
138  * separate issue that is regulated by verify_refname_available().)
139  *
140  * Please note that the name field contains the fully-qualified
141  * reference (or subdirectory) name.  Space could be saved by only
142  * storing the relative names.  But that would require the full names
143  * to be generated on the fly when iterating in do_for_each_ref(), and
144  * would break callback functions, who have always been able to assume
145  * that the name strings that they are passed will not be freed during
146  * the iteration.
147  */
148 struct ref_entry {
149         unsigned char flag; /* ISSYMREF? ISPACKED? */
150         union {
151                 struct ref_value value; /* if not (flags&REF_DIR) */
152                 struct ref_dir subdir; /* if (flags&REF_DIR) */
153         } u;
154         /*
155          * The full name of the reference (e.g., "refs/heads/master")
156          * or the full name of the directory with a trailing slash
157          * (e.g., "refs/heads/"):
158          */
159         char name[FLEX_ARRAY];
160 };
161
162 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
163 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len);
164 static struct ref_entry *create_dir_entry(struct files_ref_store *ref_store,
165                                           const char *dirname, size_t len,
166                                           int incomplete);
167 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry);
168
169 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
170 {
171         struct ref_dir *dir;
172         assert(entry->flag & REF_DIR);
173         dir = &entry->u.subdir;
174         if (entry->flag & REF_INCOMPLETE) {
175                 read_loose_refs(entry->name, dir);
176
177                 /*
178                  * Manually add refs/bisect, which, being
179                  * per-worktree, might not appear in the directory
180                  * listing for refs/ in the main repo.
181                  */
182                 if (!strcmp(entry->name, "refs/")) {
183                         int pos = search_ref_dir(dir, "refs/bisect/", 12);
184                         if (pos < 0) {
185                                 struct ref_entry *child_entry;
186                                 child_entry = create_dir_entry(dir->ref_store,
187                                                                "refs/bisect/",
188                                                                12, 1);
189                                 add_entry_to_dir(dir, child_entry);
190                                 read_loose_refs("refs/bisect",
191                                                 &child_entry->u.subdir);
192                         }
193                 }
194                 entry->flag &= ~REF_INCOMPLETE;
195         }
196         return dir;
197 }
198
199 static struct ref_entry *create_ref_entry(const char *refname,
200                                           const unsigned char *sha1, int flag,
201                                           int check_name)
202 {
203         struct ref_entry *ref;
204
205         if (check_name &&
206             check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
207                 die("Reference has invalid format: '%s'", refname);
208         FLEX_ALLOC_STR(ref, name, refname);
209         hashcpy(ref->u.value.oid.hash, sha1);
210         oidclr(&ref->u.value.peeled);
211         ref->flag = flag;
212         return ref;
213 }
214
215 static void clear_ref_dir(struct ref_dir *dir);
216
217 static void free_ref_entry(struct ref_entry *entry)
218 {
219         if (entry->flag & REF_DIR) {
220                 /*
221                  * Do not use get_ref_dir() here, as that might
222                  * trigger the reading of loose refs.
223                  */
224                 clear_ref_dir(&entry->u.subdir);
225         }
226         free(entry);
227 }
228
229 /*
230  * Add a ref_entry to the end of dir (unsorted).  Entry is always
231  * stored directly in dir; no recursion into subdirectories is
232  * done.
233  */
234 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
235 {
236         ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
237         dir->entries[dir->nr++] = entry;
238         /* optimize for the case that entries are added in order */
239         if (dir->nr == 1 ||
240             (dir->nr == dir->sorted + 1 &&
241              strcmp(dir->entries[dir->nr - 2]->name,
242                     dir->entries[dir->nr - 1]->name) < 0))
243                 dir->sorted = dir->nr;
244 }
245
246 /*
247  * Clear and free all entries in dir, recursively.
248  */
249 static void clear_ref_dir(struct ref_dir *dir)
250 {
251         int i;
252         for (i = 0; i < dir->nr; i++)
253                 free_ref_entry(dir->entries[i]);
254         free(dir->entries);
255         dir->sorted = dir->nr = dir->alloc = 0;
256         dir->entries = NULL;
257 }
258
259 /*
260  * Create a struct ref_entry object for the specified dirname.
261  * dirname is the name of the directory with a trailing slash (e.g.,
262  * "refs/heads/") or "" for the top-level directory.
263  */
264 static struct ref_entry *create_dir_entry(struct files_ref_store *ref_store,
265                                           const char *dirname, size_t len,
266                                           int incomplete)
267 {
268         struct ref_entry *direntry;
269         FLEX_ALLOC_MEM(direntry, name, dirname, len);
270         direntry->u.subdir.ref_store = ref_store;
271         direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
272         return direntry;
273 }
274
275 static int ref_entry_cmp(const void *a, const void *b)
276 {
277         struct ref_entry *one = *(struct ref_entry **)a;
278         struct ref_entry *two = *(struct ref_entry **)b;
279         return strcmp(one->name, two->name);
280 }
281
282 static void sort_ref_dir(struct ref_dir *dir);
283
284 struct string_slice {
285         size_t len;
286         const char *str;
287 };
288
289 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
290 {
291         const struct string_slice *key = key_;
292         const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
293         int cmp = strncmp(key->str, ent->name, key->len);
294         if (cmp)
295                 return cmp;
296         return '\0' - (unsigned char)ent->name[key->len];
297 }
298
299 /*
300  * Return the index of the entry with the given refname from the
301  * ref_dir (non-recursively), sorting dir if necessary.  Return -1 if
302  * no such entry is found.  dir must already be complete.
303  */
304 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
305 {
306         struct ref_entry **r;
307         struct string_slice key;
308
309         if (refname == NULL || !dir->nr)
310                 return -1;
311
312         sort_ref_dir(dir);
313         key.len = len;
314         key.str = refname;
315         r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
316                     ref_entry_cmp_sslice);
317
318         if (r == NULL)
319                 return -1;
320
321         return r - dir->entries;
322 }
323
324 /*
325  * Search for a directory entry directly within dir (without
326  * recursing).  Sort dir if necessary.  subdirname must be a directory
327  * name (i.e., end in '/').  If mkdir is set, then create the
328  * directory if it is missing; otherwise, return NULL if the desired
329  * directory cannot be found.  dir must already be complete.
330  */
331 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
332                                          const char *subdirname, size_t len,
333                                          int mkdir)
334 {
335         int entry_index = search_ref_dir(dir, subdirname, len);
336         struct ref_entry *entry;
337         if (entry_index == -1) {
338                 if (!mkdir)
339                         return NULL;
340                 /*
341                  * Since dir is complete, the absence of a subdir
342                  * means that the subdir really doesn't exist;
343                  * therefore, create an empty record for it but mark
344                  * the record complete.
345                  */
346                 entry = create_dir_entry(dir->ref_store, subdirname, len, 0);
347                 add_entry_to_dir(dir, entry);
348         } else {
349                 entry = dir->entries[entry_index];
350         }
351         return get_ref_dir(entry);
352 }
353
354 /*
355  * If refname is a reference name, find the ref_dir within the dir
356  * tree that should hold refname.  If refname is a directory name
357  * (i.e., ends in '/'), then return that ref_dir itself.  dir must
358  * represent the top-level directory and must already be complete.
359  * Sort ref_dirs and recurse into subdirectories as necessary.  If
360  * mkdir is set, then create any missing directories; otherwise,
361  * return NULL if the desired directory cannot be found.
362  */
363 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
364                                            const char *refname, int mkdir)
365 {
366         const char *slash;
367         for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
368                 size_t dirnamelen = slash - refname + 1;
369                 struct ref_dir *subdir;
370                 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
371                 if (!subdir) {
372                         dir = NULL;
373                         break;
374                 }
375                 dir = subdir;
376         }
377
378         return dir;
379 }
380
381 /*
382  * Find the value entry with the given name in dir, sorting ref_dirs
383  * and recursing into subdirectories as necessary.  If the name is not
384  * found or it corresponds to a directory entry, return NULL.
385  */
386 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
387 {
388         int entry_index;
389         struct ref_entry *entry;
390         dir = find_containing_dir(dir, refname, 0);
391         if (!dir)
392                 return NULL;
393         entry_index = search_ref_dir(dir, refname, strlen(refname));
394         if (entry_index == -1)
395                 return NULL;
396         entry = dir->entries[entry_index];
397         return (entry->flag & REF_DIR) ? NULL : entry;
398 }
399
400 /*
401  * Remove the entry with the given name from dir, recursing into
402  * subdirectories as necessary.  If refname is the name of a directory
403  * (i.e., ends with '/'), then remove the directory and its contents.
404  * If the removal was successful, return the number of entries
405  * remaining in the directory entry that contained the deleted entry.
406  * If the name was not found, return -1.  Please note that this
407  * function only deletes the entry from the cache; it does not delete
408  * it from the filesystem or ensure that other cache entries (which
409  * might be symbolic references to the removed entry) are updated.
410  * Nor does it remove any containing dir entries that might be made
411  * empty by the removal.  dir must represent the top-level directory
412  * and must already be complete.
413  */
414 static int remove_entry(struct ref_dir *dir, const char *refname)
415 {
416         int refname_len = strlen(refname);
417         int entry_index;
418         struct ref_entry *entry;
419         int is_dir = refname[refname_len - 1] == '/';
420         if (is_dir) {
421                 /*
422                  * refname represents a reference directory.  Remove
423                  * the trailing slash; otherwise we will get the
424                  * directory *representing* refname rather than the
425                  * one *containing* it.
426                  */
427                 char *dirname = xmemdupz(refname, refname_len - 1);
428                 dir = find_containing_dir(dir, dirname, 0);
429                 free(dirname);
430         } else {
431                 dir = find_containing_dir(dir, refname, 0);
432         }
433         if (!dir)
434                 return -1;
435         entry_index = search_ref_dir(dir, refname, refname_len);
436         if (entry_index == -1)
437                 return -1;
438         entry = dir->entries[entry_index];
439
440         memmove(&dir->entries[entry_index],
441                 &dir->entries[entry_index + 1],
442                 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
443                 );
444         dir->nr--;
445         if (dir->sorted > entry_index)
446                 dir->sorted--;
447         free_ref_entry(entry);
448         return dir->nr;
449 }
450
451 /*
452  * Add a ref_entry to the ref_dir (unsorted), recursing into
453  * subdirectories as necessary.  dir must represent the top-level
454  * directory.  Return 0 on success.
455  */
456 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
457 {
458         dir = find_containing_dir(dir, ref->name, 1);
459         if (!dir)
460                 return -1;
461         add_entry_to_dir(dir, ref);
462         return 0;
463 }
464
465 /*
466  * Emit a warning and return true iff ref1 and ref2 have the same name
467  * and the same sha1.  Die if they have the same name but different
468  * sha1s.
469  */
470 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
471 {
472         if (strcmp(ref1->name, ref2->name))
473                 return 0;
474
475         /* Duplicate name; make sure that they don't conflict: */
476
477         if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
478                 /* This is impossible by construction */
479                 die("Reference directory conflict: %s", ref1->name);
480
481         if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid))
482                 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
483
484         warning("Duplicated ref: %s", ref1->name);
485         return 1;
486 }
487
488 /*
489  * Sort the entries in dir non-recursively (if they are not already
490  * sorted) and remove any duplicate entries.
491  */
492 static void sort_ref_dir(struct ref_dir *dir)
493 {
494         int i, j;
495         struct ref_entry *last = NULL;
496
497         /*
498          * This check also prevents passing a zero-length array to qsort(),
499          * which is a problem on some platforms.
500          */
501         if (dir->sorted == dir->nr)
502                 return;
503
504         qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
505
506         /* Remove any duplicates: */
507         for (i = 0, j = 0; j < dir->nr; j++) {
508                 struct ref_entry *entry = dir->entries[j];
509                 if (last && is_dup_ref(last, entry))
510                         free_ref_entry(entry);
511                 else
512                         last = dir->entries[i++] = entry;
513         }
514         dir->sorted = dir->nr = i;
515 }
516
517 /*
518  * Return true if refname, which has the specified oid and flags, can
519  * be resolved to an object in the database. If the referred-to object
520  * does not exist, emit a warning and return false.
521  */
522 static int ref_resolves_to_object(const char *refname,
523                                   const struct object_id *oid,
524                                   unsigned int flags)
525 {
526         if (flags & REF_ISBROKEN)
527                 return 0;
528         if (!has_sha1_file(oid->hash)) {
529                 error("%s does not point to a valid object!", refname);
530                 return 0;
531         }
532         return 1;
533 }
534
535 /*
536  * Return true if the reference described by entry can be resolved to
537  * an object in the database; otherwise, emit a warning and return
538  * false.
539  */
540 static int entry_resolves_to_object(struct ref_entry *entry)
541 {
542         return ref_resolves_to_object(entry->name,
543                                       &entry->u.value.oid, entry->flag);
544 }
545
546 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
547
548 /*
549  * Call fn for each reference in dir that has index in the range
550  * offset <= index < dir->nr.  Recurse into subdirectories that are in
551  * that index range, sorting them before iterating.  This function
552  * does not sort dir itself; it should be sorted beforehand.  fn is
553  * called for all references, including broken ones.
554  */
555 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
556                                     each_ref_entry_fn fn, void *cb_data)
557 {
558         int i;
559         assert(dir->sorted == dir->nr);
560         for (i = offset; i < dir->nr; i++) {
561                 struct ref_entry *entry = dir->entries[i];
562                 int retval;
563                 if (entry->flag & REF_DIR) {
564                         struct ref_dir *subdir = get_ref_dir(entry);
565                         sort_ref_dir(subdir);
566                         retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
567                 } else {
568                         retval = fn(entry, cb_data);
569                 }
570                 if (retval)
571                         return retval;
572         }
573         return 0;
574 }
575
576 /*
577  * Load all of the refs from the dir into our in-memory cache. The hard work
578  * of loading loose refs is done by get_ref_dir(), so we just need to recurse
579  * through all of the sub-directories. We do not even need to care about
580  * sorting, as traversal order does not matter to us.
581  */
582 static void prime_ref_dir(struct ref_dir *dir)
583 {
584         int i;
585         for (i = 0; i < dir->nr; i++) {
586                 struct ref_entry *entry = dir->entries[i];
587                 if (entry->flag & REF_DIR)
588                         prime_ref_dir(get_ref_dir(entry));
589         }
590 }
591
592 /*
593  * A level in the reference hierarchy that is currently being iterated
594  * through.
595  */
596 struct cache_ref_iterator_level {
597         /*
598          * The ref_dir being iterated over at this level. The ref_dir
599          * is sorted before being stored here.
600          */
601         struct ref_dir *dir;
602
603         /*
604          * The index of the current entry within dir (which might
605          * itself be a directory). If index == -1, then the iteration
606          * hasn't yet begun. If index == dir->nr, then the iteration
607          * through this level is over.
608          */
609         int index;
610 };
611
612 /*
613  * Represent an iteration through a ref_dir in the memory cache. The
614  * iteration recurses through subdirectories.
615  */
616 struct cache_ref_iterator {
617         struct ref_iterator base;
618
619         /*
620          * The number of levels currently on the stack. This is always
621          * at least 1, because when it becomes zero the iteration is
622          * ended and this struct is freed.
623          */
624         size_t levels_nr;
625
626         /* The number of levels that have been allocated on the stack */
627         size_t levels_alloc;
628
629         /*
630          * A stack of levels. levels[0] is the uppermost level that is
631          * being iterated over in this iteration. (This is not
632          * necessary the top level in the references hierarchy. If we
633          * are iterating through a subtree, then levels[0] will hold
634          * the ref_dir for that subtree, and subsequent levels will go
635          * on from there.)
636          */
637         struct cache_ref_iterator_level *levels;
638 };
639
640 static int cache_ref_iterator_advance(struct ref_iterator *ref_iterator)
641 {
642         struct cache_ref_iterator *iter =
643                 (struct cache_ref_iterator *)ref_iterator;
644
645         while (1) {
646                 struct cache_ref_iterator_level *level =
647                         &iter->levels[iter->levels_nr - 1];
648                 struct ref_dir *dir = level->dir;
649                 struct ref_entry *entry;
650
651                 if (level->index == -1)
652                         sort_ref_dir(dir);
653
654                 if (++level->index == level->dir->nr) {
655                         /* This level is exhausted; pop up a level */
656                         if (--iter->levels_nr == 0)
657                                 return ref_iterator_abort(ref_iterator);
658
659                         continue;
660                 }
661
662                 entry = dir->entries[level->index];
663
664                 if (entry->flag & REF_DIR) {
665                         /* push down a level */
666                         ALLOC_GROW(iter->levels, iter->levels_nr + 1,
667                                    iter->levels_alloc);
668
669                         level = &iter->levels[iter->levels_nr++];
670                         level->dir = get_ref_dir(entry);
671                         level->index = -1;
672                 } else {
673                         iter->base.refname = entry->name;
674                         iter->base.oid = &entry->u.value.oid;
675                         iter->base.flags = entry->flag;
676                         return ITER_OK;
677                 }
678         }
679 }
680
681 static enum peel_status peel_entry(struct ref_entry *entry, int repeel);
682
683 static int cache_ref_iterator_peel(struct ref_iterator *ref_iterator,
684                                    struct object_id *peeled)
685 {
686         struct cache_ref_iterator *iter =
687                 (struct cache_ref_iterator *)ref_iterator;
688         struct cache_ref_iterator_level *level;
689         struct ref_entry *entry;
690
691         level = &iter->levels[iter->levels_nr - 1];
692
693         if (level->index == -1)
694                 die("BUG: peel called before advance for cache iterator");
695
696         entry = level->dir->entries[level->index];
697
698         if (peel_entry(entry, 0))
699                 return -1;
700         hashcpy(peeled->hash, entry->u.value.peeled.hash);
701         return 0;
702 }
703
704 static int cache_ref_iterator_abort(struct ref_iterator *ref_iterator)
705 {
706         struct cache_ref_iterator *iter =
707                 (struct cache_ref_iterator *)ref_iterator;
708
709         free(iter->levels);
710         base_ref_iterator_free(ref_iterator);
711         return ITER_DONE;
712 }
713
714 static struct ref_iterator_vtable cache_ref_iterator_vtable = {
715         cache_ref_iterator_advance,
716         cache_ref_iterator_peel,
717         cache_ref_iterator_abort
718 };
719
720 static struct ref_iterator *cache_ref_iterator_begin(struct ref_dir *dir)
721 {
722         struct cache_ref_iterator *iter;
723         struct ref_iterator *ref_iterator;
724         struct cache_ref_iterator_level *level;
725
726         iter = xcalloc(1, sizeof(*iter));
727         ref_iterator = &iter->base;
728         base_ref_iterator_init(ref_iterator, &cache_ref_iterator_vtable);
729         ALLOC_GROW(iter->levels, 10, iter->levels_alloc);
730
731         iter->levels_nr = 1;
732         level = &iter->levels[0];
733         level->index = -1;
734         level->dir = dir;
735
736         return ref_iterator;
737 }
738
739 struct nonmatching_ref_data {
740         const struct string_list *skip;
741         const char *conflicting_refname;
742 };
743
744 static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
745 {
746         struct nonmatching_ref_data *data = vdata;
747
748         if (data->skip && string_list_has_string(data->skip, entry->name))
749                 return 0;
750
751         data->conflicting_refname = entry->name;
752         return 1;
753 }
754
755 /*
756  * Return 0 if a reference named refname could be created without
757  * conflicting with the name of an existing reference in dir.
758  * See verify_refname_available for more information.
759  */
760 static int verify_refname_available_dir(const char *refname,
761                                         const struct string_list *extras,
762                                         const struct string_list *skip,
763                                         struct ref_dir *dir,
764                                         struct strbuf *err)
765 {
766         const char *slash;
767         const char *extra_refname;
768         int pos;
769         struct strbuf dirname = STRBUF_INIT;
770         int ret = -1;
771
772         /*
773          * For the sake of comments in this function, suppose that
774          * refname is "refs/foo/bar".
775          */
776
777         assert(err);
778
779         strbuf_grow(&dirname, strlen(refname) + 1);
780         for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
781                 /* Expand dirname to the new prefix, not including the trailing slash: */
782                 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
783
784                 /*
785                  * We are still at a leading dir of the refname (e.g.,
786                  * "refs/foo"; if there is a reference with that name,
787                  * it is a conflict, *unless* it is in skip.
788                  */
789                 if (dir) {
790                         pos = search_ref_dir(dir, dirname.buf, dirname.len);
791                         if (pos >= 0 &&
792                             (!skip || !string_list_has_string(skip, dirname.buf))) {
793                                 /*
794                                  * We found a reference whose name is
795                                  * a proper prefix of refname; e.g.,
796                                  * "refs/foo", and is not in skip.
797                                  */
798                                 strbuf_addf(err, "'%s' exists; cannot create '%s'",
799                                             dirname.buf, refname);
800                                 goto cleanup;
801                         }
802                 }
803
804                 if (extras && string_list_has_string(extras, dirname.buf) &&
805                     (!skip || !string_list_has_string(skip, dirname.buf))) {
806                         strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
807                                     refname, dirname.buf);
808                         goto cleanup;
809                 }
810
811                 /*
812                  * Otherwise, we can try to continue our search with
813                  * the next component. So try to look up the
814                  * directory, e.g., "refs/foo/". If we come up empty,
815                  * we know there is nothing under this whole prefix,
816                  * but even in that case we still have to continue the
817                  * search for conflicts with extras.
818                  */
819                 strbuf_addch(&dirname, '/');
820                 if (dir) {
821                         pos = search_ref_dir(dir, dirname.buf, dirname.len);
822                         if (pos < 0) {
823                                 /*
824                                  * There was no directory "refs/foo/",
825                                  * so there is nothing under this
826                                  * whole prefix. So there is no need
827                                  * to continue looking for conflicting
828                                  * references. But we need to continue
829                                  * looking for conflicting extras.
830                                  */
831                                 dir = NULL;
832                         } else {
833                                 dir = get_ref_dir(dir->entries[pos]);
834                         }
835                 }
836         }
837
838         /*
839          * We are at the leaf of our refname (e.g., "refs/foo/bar").
840          * There is no point in searching for a reference with that
841          * name, because a refname isn't considered to conflict with
842          * itself. But we still need to check for references whose
843          * names are in the "refs/foo/bar/" namespace, because they
844          * *do* conflict.
845          */
846         strbuf_addstr(&dirname, refname + dirname.len);
847         strbuf_addch(&dirname, '/');
848
849         if (dir) {
850                 pos = search_ref_dir(dir, dirname.buf, dirname.len);
851
852                 if (pos >= 0) {
853                         /*
854                          * We found a directory named "$refname/"
855                          * (e.g., "refs/foo/bar/"). It is a problem
856                          * iff it contains any ref that is not in
857                          * "skip".
858                          */
859                         struct nonmatching_ref_data data;
860
861                         data.skip = skip;
862                         data.conflicting_refname = NULL;
863                         dir = get_ref_dir(dir->entries[pos]);
864                         sort_ref_dir(dir);
865                         if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
866                                 strbuf_addf(err, "'%s' exists; cannot create '%s'",
867                                             data.conflicting_refname, refname);
868                                 goto cleanup;
869                         }
870                 }
871         }
872
873         extra_refname = find_descendant_ref(dirname.buf, extras, skip);
874         if (extra_refname)
875                 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
876                             refname, extra_refname);
877         else
878                 ret = 0;
879
880 cleanup:
881         strbuf_release(&dirname);
882         return ret;
883 }
884
885 struct packed_ref_cache {
886         struct ref_entry *root;
887
888         /*
889          * Count of references to the data structure in this instance,
890          * including the pointer from files_ref_store::packed if any.
891          * The data will not be freed as long as the reference count
892          * is nonzero.
893          */
894         unsigned int referrers;
895
896         /*
897          * Iff the packed-refs file associated with this instance is
898          * currently locked for writing, this points at the associated
899          * lock (which is owned by somebody else).  The referrer count
900          * is also incremented when the file is locked and decremented
901          * when it is unlocked.
902          */
903         struct lock_file *lock;
904
905         /* The metadata from when this packed-refs cache was read */
906         struct stat_validity validity;
907 };
908
909 /*
910  * Future: need to be in "struct repository"
911  * when doing a full libification.
912  */
913 struct files_ref_store {
914         struct ref_store base;
915         struct ref_entry *loose;
916         struct packed_ref_cache *packed;
917 };
918
919 /* Lock used for the main packed-refs file: */
920 static struct lock_file packlock;
921
922 /*
923  * Increment the reference count of *packed_refs.
924  */
925 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
926 {
927         packed_refs->referrers++;
928 }
929
930 /*
931  * Decrease the reference count of *packed_refs.  If it goes to zero,
932  * free *packed_refs and return true; otherwise return false.
933  */
934 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
935 {
936         if (!--packed_refs->referrers) {
937                 free_ref_entry(packed_refs->root);
938                 stat_validity_clear(&packed_refs->validity);
939                 free(packed_refs);
940                 return 1;
941         } else {
942                 return 0;
943         }
944 }
945
946 static void clear_packed_ref_cache(struct files_ref_store *refs)
947 {
948         if (refs->packed) {
949                 struct packed_ref_cache *packed_refs = refs->packed;
950
951                 if (packed_refs->lock)
952                         die("internal error: packed-ref cache cleared while locked");
953                 refs->packed = NULL;
954                 release_packed_ref_cache(packed_refs);
955         }
956 }
957
958 static void clear_loose_ref_cache(struct files_ref_store *refs)
959 {
960         if (refs->loose) {
961                 free_ref_entry(refs->loose);
962                 refs->loose = NULL;
963         }
964 }
965
966 /*
967  * Create a new submodule ref cache and add it to the internal
968  * set of caches.
969  */
970 static struct ref_store *files_ref_store_create(const char *submodule)
971 {
972         struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
973         struct ref_store *ref_store = (struct ref_store *)refs;
974
975         base_ref_store_init(ref_store, &refs_be_files, submodule);
976
977         return ref_store;
978 }
979
980 /*
981  * Downcast ref_store to files_ref_store. Die if ref_store is not a
982  * files_ref_store. If submodule_allowed is not true, then also die if
983  * files_ref_store is for a submodule (i.e., not for the main
984  * repository). caller is used in any necessary error messages.
985  */
986 static struct files_ref_store *files_downcast(
987                 struct ref_store *ref_store, int submodule_allowed,
988                 const char *caller)
989 {
990         if (ref_store->be != &refs_be_files)
991                 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
992                     ref_store->be->name, caller);
993
994         if (!submodule_allowed)
995                 assert_main_repository(ref_store, caller);
996
997         return (struct files_ref_store *)ref_store;
998 }
999
1000 /*
1001  * Return a pointer to the reference store for the specified
1002  * submodule. For the main repository, use submodule==NULL; such a
1003  * call cannot fail. For a submodule, the submodule must exist and be
1004  * a nonbare repository, otherwise return NULL. Verify that the
1005  * reference store is a files_ref_store, and cast it to that type
1006  * before returning it.
1007  */
1008 static struct files_ref_store *get_files_ref_store(const char *submodule,
1009                                                    const char *caller)
1010 {
1011         struct ref_store *refs = get_ref_store(submodule);
1012
1013         return refs ? files_downcast(refs, 1, caller) : NULL;
1014 }
1015
1016 /* The length of a peeled reference line in packed-refs, including EOL: */
1017 #define PEELED_LINE_LENGTH 42
1018
1019 /*
1020  * The packed-refs header line that we write out.  Perhaps other
1021  * traits will be added later.  The trailing space is required.
1022  */
1023 static const char PACKED_REFS_HEADER[] =
1024         "# pack-refs with: peeled fully-peeled \n";
1025
1026 /*
1027  * Parse one line from a packed-refs file.  Write the SHA1 to sha1.
1028  * Return a pointer to the refname within the line (null-terminated),
1029  * or NULL if there was a problem.
1030  */
1031 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1032 {
1033         const char *ref;
1034
1035         /*
1036          * 42: the answer to everything.
1037          *
1038          * In this case, it happens to be the answer to
1039          *  40 (length of sha1 hex representation)
1040          *  +1 (space in between hex and name)
1041          *  +1 (newline at the end of the line)
1042          */
1043         if (line->len <= 42)
1044                 return NULL;
1045
1046         if (get_sha1_hex(line->buf, sha1) < 0)
1047                 return NULL;
1048         if (!isspace(line->buf[40]))
1049                 return NULL;
1050
1051         ref = line->buf + 41;
1052         if (isspace(*ref))
1053                 return NULL;
1054
1055         if (line->buf[line->len - 1] != '\n')
1056                 return NULL;
1057         line->buf[--line->len] = 0;
1058
1059         return ref;
1060 }
1061
1062 /*
1063  * Read f, which is a packed-refs file, into dir.
1064  *
1065  * A comment line of the form "# pack-refs with: " may contain zero or
1066  * more traits. We interpret the traits as follows:
1067  *
1068  *   No traits:
1069  *
1070  *      Probably no references are peeled. But if the file contains a
1071  *      peeled value for a reference, we will use it.
1072  *
1073  *   peeled:
1074  *
1075  *      References under "refs/tags/", if they *can* be peeled, *are*
1076  *      peeled in this file. References outside of "refs/tags/" are
1077  *      probably not peeled even if they could have been, but if we find
1078  *      a peeled value for such a reference we will use it.
1079  *
1080  *   fully-peeled:
1081  *
1082  *      All references in the file that can be peeled are peeled.
1083  *      Inversely (and this is more important), any references in the
1084  *      file for which no peeled value is recorded is not peelable. This
1085  *      trait should typically be written alongside "peeled" for
1086  *      compatibility with older clients, but we do not require it
1087  *      (i.e., "peeled" is a no-op if "fully-peeled" is set).
1088  */
1089 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1090 {
1091         struct ref_entry *last = NULL;
1092         struct strbuf line = STRBUF_INIT;
1093         enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1094
1095         while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1096                 unsigned char sha1[20];
1097                 const char *refname;
1098                 const char *traits;
1099
1100                 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1101                         if (strstr(traits, " fully-peeled "))
1102                                 peeled = PEELED_FULLY;
1103                         else if (strstr(traits, " peeled "))
1104                                 peeled = PEELED_TAGS;
1105                         /* perhaps other traits later as well */
1106                         continue;
1107                 }
1108
1109                 refname = parse_ref_line(&line, sha1);
1110                 if (refname) {
1111                         int flag = REF_ISPACKED;
1112
1113                         if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1114                                 if (!refname_is_safe(refname))
1115                                         die("packed refname is dangerous: %s", refname);
1116                                 hashclr(sha1);
1117                                 flag |= REF_BAD_NAME | REF_ISBROKEN;
1118                         }
1119                         last = create_ref_entry(refname, sha1, flag, 0);
1120                         if (peeled == PEELED_FULLY ||
1121                             (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1122                                 last->flag |= REF_KNOWS_PEELED;
1123                         add_ref(dir, last);
1124                         continue;
1125                 }
1126                 if (last &&
1127                     line.buf[0] == '^' &&
1128                     line.len == PEELED_LINE_LENGTH &&
1129                     line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1130                     !get_sha1_hex(line.buf + 1, sha1)) {
1131                         hashcpy(last->u.value.peeled.hash, sha1);
1132                         /*
1133                          * Regardless of what the file header said,
1134                          * we definitely know the value of *this*
1135                          * reference:
1136                          */
1137                         last->flag |= REF_KNOWS_PEELED;
1138                 }
1139         }
1140
1141         strbuf_release(&line);
1142 }
1143
1144 /*
1145  * Get the packed_ref_cache for the specified files_ref_store,
1146  * creating it if necessary.
1147  */
1148 static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs)
1149 {
1150         char *packed_refs_file;
1151
1152         if (*refs->base.submodule)
1153                 packed_refs_file = git_pathdup_submodule(refs->base.submodule,
1154                                                          "packed-refs");
1155         else
1156                 packed_refs_file = git_pathdup("packed-refs");
1157
1158         if (refs->packed &&
1159             !stat_validity_check(&refs->packed->validity, packed_refs_file))
1160                 clear_packed_ref_cache(refs);
1161
1162         if (!refs->packed) {
1163                 FILE *f;
1164
1165                 refs->packed = xcalloc(1, sizeof(*refs->packed));
1166                 acquire_packed_ref_cache(refs->packed);
1167                 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1168                 f = fopen(packed_refs_file, "r");
1169                 if (f) {
1170                         stat_validity_update(&refs->packed->validity, fileno(f));
1171                         read_packed_refs(f, get_ref_dir(refs->packed->root));
1172                         fclose(f);
1173                 }
1174         }
1175         free(packed_refs_file);
1176         return refs->packed;
1177 }
1178
1179 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1180 {
1181         return get_ref_dir(packed_ref_cache->root);
1182 }
1183
1184 static struct ref_dir *get_packed_refs(struct files_ref_store *refs)
1185 {
1186         return get_packed_ref_dir(get_packed_ref_cache(refs));
1187 }
1188
1189 /*
1190  * Add a reference to the in-memory packed reference cache.  This may
1191  * only be called while the packed-refs file is locked (see
1192  * lock_packed_refs()).  To actually write the packed-refs file, call
1193  * commit_packed_refs().
1194  */
1195 static void add_packed_ref(struct files_ref_store *refs,
1196                            const char *refname, const unsigned char *sha1)
1197 {
1198         struct packed_ref_cache *packed_ref_cache = get_packed_ref_cache(refs);
1199
1200         if (!packed_ref_cache->lock)
1201                 die("internal error: packed refs not locked");
1202         add_ref(get_packed_ref_dir(packed_ref_cache),
1203                 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1204 }
1205
1206 /*
1207  * Read the loose references from the namespace dirname into dir
1208  * (without recursing).  dirname must end with '/'.  dir must be the
1209  * directory entry corresponding to dirname.
1210  */
1211 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1212 {
1213         struct files_ref_store *refs = dir->ref_store;
1214         DIR *d;
1215         struct dirent *de;
1216         int dirnamelen = strlen(dirname);
1217         struct strbuf refname;
1218         struct strbuf path = STRBUF_INIT;
1219         size_t path_baselen;
1220
1221         if (*refs->base.submodule)
1222                 strbuf_git_path_submodule(&path, refs->base.submodule, "%s", dirname);
1223         else
1224                 strbuf_git_path(&path, "%s", dirname);
1225         path_baselen = path.len;
1226
1227         d = opendir(path.buf);
1228         if (!d) {
1229                 strbuf_release(&path);
1230                 return;
1231         }
1232
1233         strbuf_init(&refname, dirnamelen + 257);
1234         strbuf_add(&refname, dirname, dirnamelen);
1235
1236         while ((de = readdir(d)) != NULL) {
1237                 unsigned char sha1[20];
1238                 struct stat st;
1239                 int flag;
1240
1241                 if (de->d_name[0] == '.')
1242                         continue;
1243                 if (ends_with(de->d_name, ".lock"))
1244                         continue;
1245                 strbuf_addstr(&refname, de->d_name);
1246                 strbuf_addstr(&path, de->d_name);
1247                 if (stat(path.buf, &st) < 0) {
1248                         ; /* silently ignore */
1249                 } else if (S_ISDIR(st.st_mode)) {
1250                         strbuf_addch(&refname, '/');
1251                         add_entry_to_dir(dir,
1252                                          create_dir_entry(refs, refname.buf,
1253                                                           refname.len, 1));
1254                 } else {
1255                         int read_ok;
1256
1257                         if (*refs->base.submodule) {
1258                                 hashclr(sha1);
1259                                 flag = 0;
1260                                 read_ok = !resolve_gitlink_ref(refs->base.submodule,
1261                                                                refname.buf, sha1);
1262                         } else {
1263                                 read_ok = !read_ref_full(refname.buf,
1264                                                          RESOLVE_REF_READING,
1265                                                          sha1, &flag);
1266                         }
1267
1268                         if (!read_ok) {
1269                                 hashclr(sha1);
1270                                 flag |= REF_ISBROKEN;
1271                         } else if (is_null_sha1(sha1)) {
1272                                 /*
1273                                  * It is so astronomically unlikely
1274                                  * that NULL_SHA1 is the SHA-1 of an
1275                                  * actual object that we consider its
1276                                  * appearance in a loose reference
1277                                  * file to be repo corruption
1278                                  * (probably due to a software bug).
1279                                  */
1280                                 flag |= REF_ISBROKEN;
1281                         }
1282
1283                         if (check_refname_format(refname.buf,
1284                                                  REFNAME_ALLOW_ONELEVEL)) {
1285                                 if (!refname_is_safe(refname.buf))
1286                                         die("loose refname is dangerous: %s", refname.buf);
1287                                 hashclr(sha1);
1288                                 flag |= REF_BAD_NAME | REF_ISBROKEN;
1289                         }
1290                         add_entry_to_dir(dir,
1291                                          create_ref_entry(refname.buf, sha1, flag, 0));
1292                 }
1293                 strbuf_setlen(&refname, dirnamelen);
1294                 strbuf_setlen(&path, path_baselen);
1295         }
1296         strbuf_release(&refname);
1297         strbuf_release(&path);
1298         closedir(d);
1299 }
1300
1301 static struct ref_dir *get_loose_refs(struct files_ref_store *refs)
1302 {
1303         if (!refs->loose) {
1304                 /*
1305                  * Mark the top-level directory complete because we
1306                  * are about to read the only subdirectory that can
1307                  * hold references:
1308                  */
1309                 refs->loose = create_dir_entry(refs, "", 0, 0);
1310                 /*
1311                  * Create an incomplete entry for "refs/":
1312                  */
1313                 add_entry_to_dir(get_ref_dir(refs->loose),
1314                                  create_dir_entry(refs, "refs/", 5, 1));
1315         }
1316         return get_ref_dir(refs->loose);
1317 }
1318
1319 /*
1320  * Return the ref_entry for the given refname from the packed
1321  * references.  If it does not exist, return NULL.
1322  */
1323 static struct ref_entry *get_packed_ref(struct files_ref_store *refs,
1324                                         const char *refname)
1325 {
1326         return find_ref(get_packed_refs(refs), refname);
1327 }
1328
1329 /*
1330  * A loose ref file doesn't exist; check for a packed ref.
1331  */
1332 static int resolve_packed_ref(struct files_ref_store *refs,
1333                               const char *refname,
1334                               unsigned char *sha1, unsigned int *flags)
1335 {
1336         struct ref_entry *entry;
1337
1338         /*
1339          * The loose reference file does not exist; check for a packed
1340          * reference.
1341          */
1342         entry = get_packed_ref(refs, refname);
1343         if (entry) {
1344                 hashcpy(sha1, entry->u.value.oid.hash);
1345                 *flags |= REF_ISPACKED;
1346                 return 0;
1347         }
1348         /* refname is not a packed reference. */
1349         return -1;
1350 }
1351
1352 static int files_read_raw_ref(struct ref_store *ref_store,
1353                               const char *refname, unsigned char *sha1,
1354                               struct strbuf *referent, unsigned int *type)
1355 {
1356         struct files_ref_store *refs =
1357                 files_downcast(ref_store, 1, "read_raw_ref");
1358         struct strbuf sb_contents = STRBUF_INIT;
1359         struct strbuf sb_path = STRBUF_INIT;
1360         const char *path;
1361         const char *buf;
1362         struct stat st;
1363         int fd;
1364         int ret = -1;
1365         int save_errno;
1366
1367         *type = 0;
1368         strbuf_reset(&sb_path);
1369
1370         if (*refs->base.submodule)
1371                 strbuf_git_path_submodule(&sb_path, refs->base.submodule, "%s", refname);
1372         else
1373                 strbuf_git_path(&sb_path, "%s", refname);
1374
1375         path = sb_path.buf;
1376
1377 stat_ref:
1378         /*
1379          * We might have to loop back here to avoid a race
1380          * condition: first we lstat() the file, then we try
1381          * to read it as a link or as a file.  But if somebody
1382          * changes the type of the file (file <-> directory
1383          * <-> symlink) between the lstat() and reading, then
1384          * we don't want to report that as an error but rather
1385          * try again starting with the lstat().
1386          */
1387
1388         if (lstat(path, &st) < 0) {
1389                 if (errno != ENOENT)
1390                         goto out;
1391                 if (resolve_packed_ref(refs, refname, sha1, type)) {
1392                         errno = ENOENT;
1393                         goto out;
1394                 }
1395                 ret = 0;
1396                 goto out;
1397         }
1398
1399         /* Follow "normalized" - ie "refs/.." symlinks by hand */
1400         if (S_ISLNK(st.st_mode)) {
1401                 strbuf_reset(&sb_contents);
1402                 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
1403                         if (errno == ENOENT || errno == EINVAL)
1404                                 /* inconsistent with lstat; retry */
1405                                 goto stat_ref;
1406                         else
1407                                 goto out;
1408                 }
1409                 if (starts_with(sb_contents.buf, "refs/") &&
1410                     !check_refname_format(sb_contents.buf, 0)) {
1411                         strbuf_swap(&sb_contents, referent);
1412                         *type |= REF_ISSYMREF;
1413                         ret = 0;
1414                         goto out;
1415                 }
1416         }
1417
1418         /* Is it a directory? */
1419         if (S_ISDIR(st.st_mode)) {
1420                 /*
1421                  * Even though there is a directory where the loose
1422                  * ref is supposed to be, there could still be a
1423                  * packed ref:
1424                  */
1425                 if (resolve_packed_ref(refs, refname, sha1, type)) {
1426                         errno = EISDIR;
1427                         goto out;
1428                 }
1429                 ret = 0;
1430                 goto out;
1431         }
1432
1433         /*
1434          * Anything else, just open it and try to use it as
1435          * a ref
1436          */
1437         fd = open(path, O_RDONLY);
1438         if (fd < 0) {
1439                 if (errno == ENOENT)
1440                         /* inconsistent with lstat; retry */
1441                         goto stat_ref;
1442                 else
1443                         goto out;
1444         }
1445         strbuf_reset(&sb_contents);
1446         if (strbuf_read(&sb_contents, fd, 256) < 0) {
1447                 int save_errno = errno;
1448                 close(fd);
1449                 errno = save_errno;
1450                 goto out;
1451         }
1452         close(fd);
1453         strbuf_rtrim(&sb_contents);
1454         buf = sb_contents.buf;
1455         if (starts_with(buf, "ref:")) {
1456                 buf += 4;
1457                 while (isspace(*buf))
1458                         buf++;
1459
1460                 strbuf_reset(referent);
1461                 strbuf_addstr(referent, buf);
1462                 *type |= REF_ISSYMREF;
1463                 ret = 0;
1464                 goto out;
1465         }
1466
1467         /*
1468          * Please note that FETCH_HEAD has additional
1469          * data after the sha.
1470          */
1471         if (get_sha1_hex(buf, sha1) ||
1472             (buf[40] != '\0' && !isspace(buf[40]))) {
1473                 *type |= REF_ISBROKEN;
1474                 errno = EINVAL;
1475                 goto out;
1476         }
1477
1478         ret = 0;
1479
1480 out:
1481         save_errno = errno;
1482         strbuf_release(&sb_path);
1483         strbuf_release(&sb_contents);
1484         errno = save_errno;
1485         return ret;
1486 }
1487
1488 static void unlock_ref(struct ref_lock *lock)
1489 {
1490         /* Do not free lock->lk -- atexit() still looks at them */
1491         if (lock->lk)
1492                 rollback_lock_file(lock->lk);
1493         free(lock->ref_name);
1494         free(lock);
1495 }
1496
1497 /*
1498  * Lock refname, without following symrefs, and set *lock_p to point
1499  * at a newly-allocated lock object. Fill in lock->old_oid, referent,
1500  * and type similarly to read_raw_ref().
1501  *
1502  * The caller must verify that refname is a "safe" reference name (in
1503  * the sense of refname_is_safe()) before calling this function.
1504  *
1505  * If the reference doesn't already exist, verify that refname doesn't
1506  * have a D/F conflict with any existing references. extras and skip
1507  * are passed to verify_refname_available_dir() for this check.
1508  *
1509  * If mustexist is not set and the reference is not found or is
1510  * broken, lock the reference anyway but clear sha1.
1511  *
1512  * Return 0 on success. On failure, write an error message to err and
1513  * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
1514  *
1515  * Implementation note: This function is basically
1516  *
1517  *     lock reference
1518  *     read_raw_ref()
1519  *
1520  * but it includes a lot more code to
1521  * - Deal with possible races with other processes
1522  * - Avoid calling verify_refname_available_dir() when it can be
1523  *   avoided, namely if we were successfully able to read the ref
1524  * - Generate informative error messages in the case of failure
1525  */
1526 static int lock_raw_ref(struct files_ref_store *refs,
1527                         const char *refname, int mustexist,
1528                         const struct string_list *extras,
1529                         const struct string_list *skip,
1530                         struct ref_lock **lock_p,
1531                         struct strbuf *referent,
1532                         unsigned int *type,
1533                         struct strbuf *err)
1534 {
1535         struct ref_lock *lock;
1536         struct strbuf ref_file = STRBUF_INIT;
1537         int attempts_remaining = 3;
1538         int ret = TRANSACTION_GENERIC_ERROR;
1539
1540         assert(err);
1541         assert_main_repository(&refs->base, "lock_raw_ref");
1542
1543         *type = 0;
1544
1545         /* First lock the file so it can't change out from under us. */
1546
1547         *lock_p = lock = xcalloc(1, sizeof(*lock));
1548
1549         lock->ref_name = xstrdup(refname);
1550         strbuf_git_path(&ref_file, "%s", refname);
1551
1552 retry:
1553         switch (safe_create_leading_directories(ref_file.buf)) {
1554         case SCLD_OK:
1555                 break; /* success */
1556         case SCLD_EXISTS:
1557                 /*
1558                  * Suppose refname is "refs/foo/bar". We just failed
1559                  * to create the containing directory, "refs/foo",
1560                  * because there was a non-directory in the way. This
1561                  * indicates a D/F conflict, probably because of
1562                  * another reference such as "refs/foo". There is no
1563                  * reason to expect this error to be transitory.
1564                  */
1565                 if (verify_refname_available(refname, extras, skip, err)) {
1566                         if (mustexist) {
1567                                 /*
1568                                  * To the user the relevant error is
1569                                  * that the "mustexist" reference is
1570                                  * missing:
1571                                  */
1572                                 strbuf_reset(err);
1573                                 strbuf_addf(err, "unable to resolve reference '%s'",
1574                                             refname);
1575                         } else {
1576                                 /*
1577                                  * The error message set by
1578                                  * verify_refname_available_dir() is OK.
1579                                  */
1580                                 ret = TRANSACTION_NAME_CONFLICT;
1581                         }
1582                 } else {
1583                         /*
1584                          * The file that is in the way isn't a loose
1585                          * reference. Report it as a low-level
1586                          * failure.
1587                          */
1588                         strbuf_addf(err, "unable to create lock file %s.lock; "
1589                                     "non-directory in the way",
1590                                     ref_file.buf);
1591                 }
1592                 goto error_return;
1593         case SCLD_VANISHED:
1594                 /* Maybe another process was tidying up. Try again. */
1595                 if (--attempts_remaining > 0)
1596                         goto retry;
1597                 /* fall through */
1598         default:
1599                 strbuf_addf(err, "unable to create directory for %s",
1600                             ref_file.buf);
1601                 goto error_return;
1602         }
1603
1604         if (!lock->lk)
1605                 lock->lk = xcalloc(1, sizeof(struct lock_file));
1606
1607         if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
1608                 if (errno == ENOENT && --attempts_remaining > 0) {
1609                         /*
1610                          * Maybe somebody just deleted one of the
1611                          * directories leading to ref_file.  Try
1612                          * again:
1613                          */
1614                         goto retry;
1615                 } else {
1616                         unable_to_lock_message(ref_file.buf, errno, err);
1617                         goto error_return;
1618                 }
1619         }
1620
1621         /*
1622          * Now we hold the lock and can read the reference without
1623          * fear that its value will change.
1624          */
1625
1626         if (files_read_raw_ref(&refs->base, refname,
1627                                lock->old_oid.hash, referent, type)) {
1628                 if (errno == ENOENT) {
1629                         if (mustexist) {
1630                                 /* Garden variety missing reference. */
1631                                 strbuf_addf(err, "unable to resolve reference '%s'",
1632                                             refname);
1633                                 goto error_return;
1634                         } else {
1635                                 /*
1636                                  * Reference is missing, but that's OK. We
1637                                  * know that there is not a conflict with
1638                                  * another loose reference because
1639                                  * (supposing that we are trying to lock
1640                                  * reference "refs/foo/bar"):
1641                                  *
1642                                  * - We were successfully able to create
1643                                  *   the lockfile refs/foo/bar.lock, so we
1644                                  *   know there cannot be a loose reference
1645                                  *   named "refs/foo".
1646                                  *
1647                                  * - We got ENOENT and not EISDIR, so we
1648                                  *   know that there cannot be a loose
1649                                  *   reference named "refs/foo/bar/baz".
1650                                  */
1651                         }
1652                 } else if (errno == EISDIR) {
1653                         /*
1654                          * There is a directory in the way. It might have
1655                          * contained references that have been deleted. If
1656                          * we don't require that the reference already
1657                          * exists, try to remove the directory so that it
1658                          * doesn't cause trouble when we want to rename the
1659                          * lockfile into place later.
1660                          */
1661                         if (mustexist) {
1662                                 /* Garden variety missing reference. */
1663                                 strbuf_addf(err, "unable to resolve reference '%s'",
1664                                             refname);
1665                                 goto error_return;
1666                         } else if (remove_dir_recursively(&ref_file,
1667                                                           REMOVE_DIR_EMPTY_ONLY)) {
1668                                 if (verify_refname_available_dir(
1669                                                     refname, extras, skip,
1670                                                     get_loose_refs(refs),
1671                                                     err)) {
1672                                         /*
1673                                          * The error message set by
1674                                          * verify_refname_available() is OK.
1675                                          */
1676                                         ret = TRANSACTION_NAME_CONFLICT;
1677                                         goto error_return;
1678                                 } else {
1679                                         /*
1680                                          * We can't delete the directory,
1681                                          * but we also don't know of any
1682                                          * references that it should
1683                                          * contain.
1684                                          */
1685                                         strbuf_addf(err, "there is a non-empty directory '%s' "
1686                                                     "blocking reference '%s'",
1687                                                     ref_file.buf, refname);
1688                                         goto error_return;
1689                                 }
1690                         }
1691                 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
1692                         strbuf_addf(err, "unable to resolve reference '%s': "
1693                                     "reference broken", refname);
1694                         goto error_return;
1695                 } else {
1696                         strbuf_addf(err, "unable to resolve reference '%s': %s",
1697                                     refname, strerror(errno));
1698                         goto error_return;
1699                 }
1700
1701                 /*
1702                  * If the ref did not exist and we are creating it,
1703                  * make sure there is no existing packed ref whose
1704                  * name begins with our refname, nor a packed ref
1705                  * whose name is a proper prefix of our refname.
1706                  */
1707                 if (verify_refname_available_dir(
1708                                     refname, extras, skip,
1709                                     get_packed_refs(refs),
1710                                     err)) {
1711                         goto error_return;
1712                 }
1713         }
1714
1715         ret = 0;
1716         goto out;
1717
1718 error_return:
1719         unlock_ref(lock);
1720         *lock_p = NULL;
1721
1722 out:
1723         strbuf_release(&ref_file);
1724         return ret;
1725 }
1726
1727 /*
1728  * Peel the entry (if possible) and return its new peel_status.  If
1729  * repeel is true, re-peel the entry even if there is an old peeled
1730  * value that is already stored in it.
1731  *
1732  * It is OK to call this function with a packed reference entry that
1733  * might be stale and might even refer to an object that has since
1734  * been garbage-collected.  In such a case, if the entry has
1735  * REF_KNOWS_PEELED then leave the status unchanged and return
1736  * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1737  */
1738 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1739 {
1740         enum peel_status status;
1741
1742         if (entry->flag & REF_KNOWS_PEELED) {
1743                 if (repeel) {
1744                         entry->flag &= ~REF_KNOWS_PEELED;
1745                         oidclr(&entry->u.value.peeled);
1746                 } else {
1747                         return is_null_oid(&entry->u.value.peeled) ?
1748                                 PEEL_NON_TAG : PEEL_PEELED;
1749                 }
1750         }
1751         if (entry->flag & REF_ISBROKEN)
1752                 return PEEL_BROKEN;
1753         if (entry->flag & REF_ISSYMREF)
1754                 return PEEL_IS_SYMREF;
1755
1756         status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1757         if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1758                 entry->flag |= REF_KNOWS_PEELED;
1759         return status;
1760 }
1761
1762 static int files_peel_ref(struct ref_store *ref_store,
1763                           const char *refname, unsigned char *sha1)
1764 {
1765         struct files_ref_store *refs = files_downcast(ref_store, 0, "peel_ref");
1766         int flag;
1767         unsigned char base[20];
1768
1769         if (current_ref_iter && current_ref_iter->refname == refname) {
1770                 struct object_id peeled;
1771
1772                 if (ref_iterator_peel(current_ref_iter, &peeled))
1773                         return -1;
1774                 hashcpy(sha1, peeled.hash);
1775                 return 0;
1776         }
1777
1778         if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1779                 return -1;
1780
1781         /*
1782          * If the reference is packed, read its ref_entry from the
1783          * cache in the hope that we already know its peeled value.
1784          * We only try this optimization on packed references because
1785          * (a) forcing the filling of the loose reference cache could
1786          * be expensive and (b) loose references anyway usually do not
1787          * have REF_KNOWS_PEELED.
1788          */
1789         if (flag & REF_ISPACKED) {
1790                 struct ref_entry *r = get_packed_ref(refs, refname);
1791                 if (r) {
1792                         if (peel_entry(r, 0))
1793                                 return -1;
1794                         hashcpy(sha1, r->u.value.peeled.hash);
1795                         return 0;
1796                 }
1797         }
1798
1799         return peel_object(base, sha1);
1800 }
1801
1802 struct files_ref_iterator {
1803         struct ref_iterator base;
1804
1805         struct packed_ref_cache *packed_ref_cache;
1806         struct ref_iterator *iter0;
1807         unsigned int flags;
1808 };
1809
1810 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
1811 {
1812         struct files_ref_iterator *iter =
1813                 (struct files_ref_iterator *)ref_iterator;
1814         int ok;
1815
1816         while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1817                 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1818                     !ref_resolves_to_object(iter->iter0->refname,
1819                                             iter->iter0->oid,
1820                                             iter->iter0->flags))
1821                         continue;
1822
1823                 iter->base.refname = iter->iter0->refname;
1824                 iter->base.oid = iter->iter0->oid;
1825                 iter->base.flags = iter->iter0->flags;
1826                 return ITER_OK;
1827         }
1828
1829         iter->iter0 = NULL;
1830         if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1831                 ok = ITER_ERROR;
1832
1833         return ok;
1834 }
1835
1836 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1837                                    struct object_id *peeled)
1838 {
1839         struct files_ref_iterator *iter =
1840                 (struct files_ref_iterator *)ref_iterator;
1841
1842         return ref_iterator_peel(iter->iter0, peeled);
1843 }
1844
1845 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1846 {
1847         struct files_ref_iterator *iter =
1848                 (struct files_ref_iterator *)ref_iterator;
1849         int ok = ITER_DONE;
1850
1851         if (iter->iter0)
1852                 ok = ref_iterator_abort(iter->iter0);
1853
1854         release_packed_ref_cache(iter->packed_ref_cache);
1855         base_ref_iterator_free(ref_iterator);
1856         return ok;
1857 }
1858
1859 static struct ref_iterator_vtable files_ref_iterator_vtable = {
1860         files_ref_iterator_advance,
1861         files_ref_iterator_peel,
1862         files_ref_iterator_abort
1863 };
1864
1865 struct ref_iterator *files_ref_iterator_begin(
1866                 const char *submodule,
1867                 const char *prefix, unsigned int flags)
1868 {
1869         struct files_ref_store *refs =
1870                 get_files_ref_store(submodule, "ref_iterator_begin");
1871         struct ref_dir *loose_dir, *packed_dir;
1872         struct ref_iterator *loose_iter, *packed_iter;
1873         struct files_ref_iterator *iter;
1874         struct ref_iterator *ref_iterator;
1875
1876         if (!refs)
1877                 return empty_ref_iterator_begin();
1878
1879         if (ref_paranoia < 0)
1880                 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1881         if (ref_paranoia)
1882                 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1883
1884         iter = xcalloc(1, sizeof(*iter));
1885         ref_iterator = &iter->base;
1886         base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1887
1888         /*
1889          * We must make sure that all loose refs are read before
1890          * accessing the packed-refs file; this avoids a race
1891          * condition if loose refs are migrated to the packed-refs
1892          * file by a simultaneous process, but our in-memory view is
1893          * from before the migration. We ensure this as follows:
1894          * First, we call prime_ref_dir(), which pre-reads the loose
1895          * references for the subtree into the cache. (If they've
1896          * already been read, that's OK; we only need to guarantee
1897          * that they're read before the packed refs, not *how much*
1898          * before.) After that, we call get_packed_ref_cache(), which
1899          * internally checks whether the packed-ref cache is up to
1900          * date with what is on disk, and re-reads it if not.
1901          */
1902
1903         loose_dir = get_loose_refs(refs);
1904
1905         if (prefix && *prefix)
1906                 loose_dir = find_containing_dir(loose_dir, prefix, 0);
1907
1908         if (loose_dir) {
1909                 prime_ref_dir(loose_dir);
1910                 loose_iter = cache_ref_iterator_begin(loose_dir);
1911         } else {
1912                 /* There's nothing to iterate over. */
1913                 loose_iter = empty_ref_iterator_begin();
1914         }
1915
1916         iter->packed_ref_cache = get_packed_ref_cache(refs);
1917         acquire_packed_ref_cache(iter->packed_ref_cache);
1918         packed_dir = get_packed_ref_dir(iter->packed_ref_cache);
1919
1920         if (prefix && *prefix)
1921                 packed_dir = find_containing_dir(packed_dir, prefix, 0);
1922
1923         if (packed_dir) {
1924                 packed_iter = cache_ref_iterator_begin(packed_dir);
1925         } else {
1926                 /* There's nothing to iterate over. */
1927                 packed_iter = empty_ref_iterator_begin();
1928         }
1929
1930         iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1931         iter->flags = flags;
1932
1933         return ref_iterator;
1934 }
1935
1936 /*
1937  * Verify that the reference locked by lock has the value old_sha1.
1938  * Fail if the reference doesn't exist and mustexist is set. Return 0
1939  * on success. On error, write an error message to err, set errno, and
1940  * return a negative value.
1941  */
1942 static int verify_lock(struct ref_lock *lock,
1943                        const unsigned char *old_sha1, int mustexist,
1944                        struct strbuf *err)
1945 {
1946         assert(err);
1947
1948         if (read_ref_full(lock->ref_name,
1949                           mustexist ? RESOLVE_REF_READING : 0,
1950                           lock->old_oid.hash, NULL)) {
1951                 if (old_sha1) {
1952                         int save_errno = errno;
1953                         strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
1954                         errno = save_errno;
1955                         return -1;
1956                 } else {
1957                         hashclr(lock->old_oid.hash);
1958                         return 0;
1959                 }
1960         }
1961         if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1962                 strbuf_addf(err, "ref '%s' is at %s but expected %s",
1963                             lock->ref_name,
1964                             sha1_to_hex(lock->old_oid.hash),
1965                             sha1_to_hex(old_sha1));
1966                 errno = EBUSY;
1967                 return -1;
1968         }
1969         return 0;
1970 }
1971
1972 static int remove_empty_directories(struct strbuf *path)
1973 {
1974         /*
1975          * we want to create a file but there is a directory there;
1976          * if that is an empty directory (or a directory that contains
1977          * only empty directories), remove them.
1978          */
1979         return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1980 }
1981
1982 /*
1983  * Locks a ref returning the lock on success and NULL on failure.
1984  * On failure errno is set to something meaningful.
1985  */
1986 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1987                                             const char *refname,
1988                                             const unsigned char *old_sha1,
1989                                             const struct string_list *extras,
1990                                             const struct string_list *skip,
1991                                             unsigned int flags, int *type,
1992                                             struct strbuf *err)
1993 {
1994         struct strbuf ref_file = STRBUF_INIT;
1995         struct ref_lock *lock;
1996         int last_errno = 0;
1997         int lflags = LOCK_NO_DEREF;
1998         int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1999         int resolve_flags = RESOLVE_REF_NO_RECURSE;
2000         int attempts_remaining = 3;
2001         int resolved;
2002
2003         assert_main_repository(&refs->base, "lock_ref_sha1_basic");
2004         assert(err);
2005
2006         lock = xcalloc(1, sizeof(struct ref_lock));
2007
2008         if (mustexist)
2009                 resolve_flags |= RESOLVE_REF_READING;
2010         if (flags & REF_DELETING)
2011                 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2012
2013         strbuf_git_path(&ref_file, "%s", refname);
2014         resolved = !!resolve_ref_unsafe(refname, resolve_flags,
2015                                         lock->old_oid.hash, type);
2016         if (!resolved && errno == EISDIR) {
2017                 /*
2018                  * we are trying to lock foo but we used to
2019                  * have foo/bar which now does not exist;
2020                  * it is normal for the empty directory 'foo'
2021                  * to remain.
2022                  */
2023                 if (remove_empty_directories(&ref_file)) {
2024                         last_errno = errno;
2025                         if (!verify_refname_available_dir(
2026                                             refname, extras, skip,
2027                                             get_loose_refs(refs), err))
2028                                 strbuf_addf(err, "there are still refs under '%s'",
2029                                             refname);
2030                         goto error_return;
2031                 }
2032                 resolved = !!resolve_ref_unsafe(refname, resolve_flags,
2033                                                 lock->old_oid.hash, type);
2034         }
2035         if (!resolved) {
2036                 last_errno = errno;
2037                 if (last_errno != ENOTDIR ||
2038                     !verify_refname_available_dir(
2039                                     refname, extras, skip,
2040                                     get_loose_refs(refs), err))
2041                         strbuf_addf(err, "unable to resolve reference '%s': %s",
2042                                     refname, strerror(last_errno));
2043
2044                 goto error_return;
2045         }
2046
2047         /*
2048          * If the ref did not exist and we are creating it, make sure
2049          * there is no existing packed ref whose name begins with our
2050          * refname, nor a packed ref whose name is a proper prefix of
2051          * our refname.
2052          */
2053         if (is_null_oid(&lock->old_oid) &&
2054             verify_refname_available_dir(refname, extras, skip,
2055                                          get_packed_refs(refs),
2056                                          err)) {
2057                 last_errno = ENOTDIR;
2058                 goto error_return;
2059         }
2060
2061         lock->lk = xcalloc(1, sizeof(struct lock_file));
2062
2063         lock->ref_name = xstrdup(refname);
2064
2065  retry:
2066         switch (safe_create_leading_directories_const(ref_file.buf)) {
2067         case SCLD_OK:
2068                 break; /* success */
2069         case SCLD_VANISHED:
2070                 if (--attempts_remaining > 0)
2071                         goto retry;
2072                 /* fall through */
2073         default:
2074                 last_errno = errno;
2075                 strbuf_addf(err, "unable to create directory for '%s'",
2076                             ref_file.buf);
2077                 goto error_return;
2078         }
2079
2080         if (hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) < 0) {
2081                 last_errno = errno;
2082                 if (errno == ENOENT && --attempts_remaining > 0)
2083                         /*
2084                          * Maybe somebody just deleted one of the
2085                          * directories leading to ref_file.  Try
2086                          * again:
2087                          */
2088                         goto retry;
2089                 else {
2090                         unable_to_lock_message(ref_file.buf, errno, err);
2091                         goto error_return;
2092                 }
2093         }
2094         if (verify_lock(lock, old_sha1, mustexist, err)) {
2095                 last_errno = errno;
2096                 goto error_return;
2097         }
2098         goto out;
2099
2100  error_return:
2101         unlock_ref(lock);
2102         lock = NULL;
2103
2104  out:
2105         strbuf_release(&ref_file);
2106         errno = last_errno;
2107         return lock;
2108 }
2109
2110 /*
2111  * Write an entry to the packed-refs file for the specified refname.
2112  * If peeled is non-NULL, write it as the entry's peeled value.
2113  */
2114 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2115                                unsigned char *peeled)
2116 {
2117         fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2118         if (peeled)
2119                 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2120 }
2121
2122 /*
2123  * An each_ref_entry_fn that writes the entry to a packed-refs file.
2124  */
2125 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2126 {
2127         enum peel_status peel_status = peel_entry(entry, 0);
2128
2129         if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2130                 error("internal error: %s is not a valid packed reference!",
2131                       entry->name);
2132         write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2133                            peel_status == PEEL_PEELED ?
2134                            entry->u.value.peeled.hash : NULL);
2135         return 0;
2136 }
2137
2138 /*
2139  * Lock the packed-refs file for writing. Flags is passed to
2140  * hold_lock_file_for_update(). Return 0 on success. On errors, set
2141  * errno appropriately and return a nonzero value.
2142  */
2143 static int lock_packed_refs(struct files_ref_store *refs, int flags)
2144 {
2145         static int timeout_configured = 0;
2146         static int timeout_value = 1000;
2147         struct packed_ref_cache *packed_ref_cache;
2148
2149         assert_main_repository(&refs->base, "lock_packed_refs");
2150
2151         if (!timeout_configured) {
2152                 git_config_get_int("core.packedrefstimeout", &timeout_value);
2153                 timeout_configured = 1;
2154         }
2155
2156         if (hold_lock_file_for_update_timeout(
2157                             &packlock, git_path("packed-refs"),
2158                             flags, timeout_value) < 0)
2159                 return -1;
2160         /*
2161          * Get the current packed-refs while holding the lock.  If the
2162          * packed-refs file has been modified since we last read it,
2163          * this will automatically invalidate the cache and re-read
2164          * the packed-refs file.
2165          */
2166         packed_ref_cache = get_packed_ref_cache(refs);
2167         packed_ref_cache->lock = &packlock;
2168         /* Increment the reference count to prevent it from being freed: */
2169         acquire_packed_ref_cache(packed_ref_cache);
2170         return 0;
2171 }
2172
2173 /*
2174  * Write the current version of the packed refs cache from memory to
2175  * disk. The packed-refs file must already be locked for writing (see
2176  * lock_packed_refs()). Return zero on success. On errors, set errno
2177  * and return a nonzero value
2178  */
2179 static int commit_packed_refs(struct files_ref_store *refs)
2180 {
2181         struct packed_ref_cache *packed_ref_cache =
2182                 get_packed_ref_cache(refs);
2183         int error = 0;
2184         int save_errno = 0;
2185         FILE *out;
2186
2187         assert_main_repository(&refs->base, "commit_packed_refs");
2188
2189         if (!packed_ref_cache->lock)
2190                 die("internal error: packed-refs not locked");
2191
2192         out = fdopen_lock_file(packed_ref_cache->lock, "w");
2193         if (!out)
2194                 die_errno("unable to fdopen packed-refs descriptor");
2195
2196         fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2197         do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2198                                  0, write_packed_entry_fn, out);
2199
2200         if (commit_lock_file(packed_ref_cache->lock)) {
2201                 save_errno = errno;
2202                 error = -1;
2203         }
2204         packed_ref_cache->lock = NULL;
2205         release_packed_ref_cache(packed_ref_cache);
2206         errno = save_errno;
2207         return error;
2208 }
2209
2210 /*
2211  * Rollback the lockfile for the packed-refs file, and discard the
2212  * in-memory packed reference cache.  (The packed-refs file will be
2213  * read anew if it is needed again after this function is called.)
2214  */
2215 static void rollback_packed_refs(struct files_ref_store *refs)
2216 {
2217         struct packed_ref_cache *packed_ref_cache =
2218                 get_packed_ref_cache(refs);
2219
2220         assert_main_repository(&refs->base, "rollback_packed_refs");
2221
2222         if (!packed_ref_cache->lock)
2223                 die("internal error: packed-refs not locked");
2224         rollback_lock_file(packed_ref_cache->lock);
2225         packed_ref_cache->lock = NULL;
2226         release_packed_ref_cache(packed_ref_cache);
2227         clear_packed_ref_cache(refs);
2228 }
2229
2230 struct ref_to_prune {
2231         struct ref_to_prune *next;
2232         unsigned char sha1[20];
2233         char name[FLEX_ARRAY];
2234 };
2235
2236 struct pack_refs_cb_data {
2237         unsigned int flags;
2238         struct ref_dir *packed_refs;
2239         struct ref_to_prune *ref_to_prune;
2240 };
2241
2242 /*
2243  * An each_ref_entry_fn that is run over loose references only.  If
2244  * the loose reference can be packed, add an entry in the packed ref
2245  * cache.  If the reference should be pruned, also add it to
2246  * ref_to_prune in the pack_refs_cb_data.
2247  */
2248 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2249 {
2250         struct pack_refs_cb_data *cb = cb_data;
2251         enum peel_status peel_status;
2252         struct ref_entry *packed_entry;
2253         int is_tag_ref = starts_with(entry->name, "refs/tags/");
2254
2255         /* Do not pack per-worktree refs: */
2256         if (ref_type(entry->name) != REF_TYPE_NORMAL)
2257                 return 0;
2258
2259         /* ALWAYS pack tags */
2260         if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2261                 return 0;
2262
2263         /* Do not pack symbolic or broken refs: */
2264         if ((entry->flag & REF_ISSYMREF) || !entry_resolves_to_object(entry))
2265                 return 0;
2266
2267         /* Add a packed ref cache entry equivalent to the loose entry. */
2268         peel_status = peel_entry(entry, 1);
2269         if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2270                 die("internal error peeling reference %s (%s)",
2271                     entry->name, oid_to_hex(&entry->u.value.oid));
2272         packed_entry = find_ref(cb->packed_refs, entry->name);
2273         if (packed_entry) {
2274                 /* Overwrite existing packed entry with info from loose entry */
2275                 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2276                 oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2277         } else {
2278                 packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2279                                                 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2280                 add_ref(cb->packed_refs, packed_entry);
2281         }
2282         oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2283
2284         /* Schedule the loose reference for pruning if requested. */
2285         if ((cb->flags & PACK_REFS_PRUNE)) {
2286                 struct ref_to_prune *n;
2287                 FLEX_ALLOC_STR(n, name, entry->name);
2288                 hashcpy(n->sha1, entry->u.value.oid.hash);
2289                 n->next = cb->ref_to_prune;
2290                 cb->ref_to_prune = n;
2291         }
2292         return 0;
2293 }
2294
2295 /*
2296  * Remove empty parents, but spare refs/ and immediate subdirs.
2297  * Note: munges *name.
2298  */
2299 static void try_remove_empty_parents(char *name)
2300 {
2301         char *p, *q;
2302         int i;
2303         p = name;
2304         for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2305                 while (*p && *p != '/')
2306                         p++;
2307                 /* tolerate duplicate slashes; see check_refname_format() */
2308                 while (*p == '/')
2309                         p++;
2310         }
2311         for (q = p; *q; q++)
2312                 ;
2313         while (1) {
2314                 while (q > p && *q != '/')
2315                         q--;
2316                 while (q > p && *(q-1) == '/')
2317                         q--;
2318                 if (q == p)
2319                         break;
2320                 *q = '\0';
2321                 if (rmdir(git_path("%s", name)))
2322                         break;
2323         }
2324 }
2325
2326 /* make sure nobody touched the ref, and unlink */
2327 static void prune_ref(struct ref_to_prune *r)
2328 {
2329         struct ref_transaction *transaction;
2330         struct strbuf err = STRBUF_INIT;
2331
2332         if (check_refname_format(r->name, 0))
2333                 return;
2334
2335         transaction = ref_transaction_begin(&err);
2336         if (!transaction ||
2337             ref_transaction_delete(transaction, r->name, r->sha1,
2338                                    REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
2339             ref_transaction_commit(transaction, &err)) {
2340                 ref_transaction_free(transaction);
2341                 error("%s", err.buf);
2342                 strbuf_release(&err);
2343                 return;
2344         }
2345         ref_transaction_free(transaction);
2346         strbuf_release(&err);
2347         try_remove_empty_parents(r->name);
2348 }
2349
2350 static void prune_refs(struct ref_to_prune *r)
2351 {
2352         while (r) {
2353                 prune_ref(r);
2354                 r = r->next;
2355         }
2356 }
2357
2358 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
2359 {
2360         struct files_ref_store *refs =
2361                 files_downcast(ref_store, 0, "pack_refs");
2362         struct pack_refs_cb_data cbdata;
2363
2364         memset(&cbdata, 0, sizeof(cbdata));
2365         cbdata.flags = flags;
2366
2367         lock_packed_refs(refs, LOCK_DIE_ON_ERROR);
2368         cbdata.packed_refs = get_packed_refs(refs);
2369
2370         do_for_each_entry_in_dir(get_loose_refs(refs), 0,
2371                                  pack_if_possible_fn, &cbdata);
2372
2373         if (commit_packed_refs(refs))
2374                 die_errno("unable to overwrite old ref-pack file");
2375
2376         prune_refs(cbdata.ref_to_prune);
2377         return 0;
2378 }
2379
2380 /*
2381  * Rewrite the packed-refs file, omitting any refs listed in
2382  * 'refnames'. On error, leave packed-refs unchanged, write an error
2383  * message to 'err', and return a nonzero value.
2384  *
2385  * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2386  */
2387 static int repack_without_refs(struct files_ref_store *refs,
2388                                struct string_list *refnames, struct strbuf *err)
2389 {
2390         struct ref_dir *packed;
2391         struct string_list_item *refname;
2392         int ret, needs_repacking = 0, removed = 0;
2393
2394         assert_main_repository(&refs->base, "repack_without_refs");
2395         assert(err);
2396
2397         /* Look for a packed ref */
2398         for_each_string_list_item(refname, refnames) {
2399                 if (get_packed_ref(refs, refname->string)) {
2400                         needs_repacking = 1;
2401                         break;
2402                 }
2403         }
2404
2405         /* Avoid locking if we have nothing to do */
2406         if (!needs_repacking)
2407                 return 0; /* no refname exists in packed refs */
2408
2409         if (lock_packed_refs(refs, 0)) {
2410                 unable_to_lock_message(git_path("packed-refs"), errno, err);
2411                 return -1;
2412         }
2413         packed = get_packed_refs(refs);
2414
2415         /* Remove refnames from the cache */
2416         for_each_string_list_item(refname, refnames)
2417                 if (remove_entry(packed, refname->string) != -1)
2418                         removed = 1;
2419         if (!removed) {
2420                 /*
2421                  * All packed entries disappeared while we were
2422                  * acquiring the lock.
2423                  */
2424                 rollback_packed_refs(refs);
2425                 return 0;
2426         }
2427
2428         /* Write what remains */
2429         ret = commit_packed_refs(refs);
2430         if (ret)
2431                 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2432                             strerror(errno));
2433         return ret;
2434 }
2435
2436 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2437 {
2438         assert(err);
2439
2440         if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2441                 /*
2442                  * loose.  The loose file name is the same as the
2443                  * lockfile name, minus ".lock":
2444                  */
2445                 char *loose_filename = get_locked_file_path(lock->lk);
2446                 int res = unlink_or_msg(loose_filename, err);
2447                 free(loose_filename);
2448                 if (res)
2449                         return 1;
2450         }
2451         return 0;
2452 }
2453
2454 int delete_refs(struct string_list *refnames, unsigned int flags)
2455 {
2456         struct files_ref_store *refs =
2457                 get_files_ref_store(NULL, "delete_refs");
2458         struct strbuf err = STRBUF_INIT;
2459         int i, result = 0;
2460
2461         if (!refnames->nr)
2462                 return 0;
2463
2464         result = repack_without_refs(refs, refnames, &err);
2465         if (result) {
2466                 /*
2467                  * If we failed to rewrite the packed-refs file, then
2468                  * it is unsafe to try to remove loose refs, because
2469                  * doing so might expose an obsolete packed value for
2470                  * a reference that might even point at an object that
2471                  * has been garbage collected.
2472                  */
2473                 if (refnames->nr == 1)
2474                         error(_("could not delete reference %s: %s"),
2475                               refnames->items[0].string, err.buf);
2476                 else
2477                         error(_("could not delete references: %s"), err.buf);
2478
2479                 goto out;
2480         }
2481
2482         for (i = 0; i < refnames->nr; i++) {
2483                 const char *refname = refnames->items[i].string;
2484
2485                 if (delete_ref(refname, NULL, flags))
2486                         result |= error(_("could not remove reference %s"), refname);
2487         }
2488
2489 out:
2490         strbuf_release(&err);
2491         return result;
2492 }
2493
2494 /*
2495  * People using contrib's git-new-workdir have .git/logs/refs ->
2496  * /some/other/path/.git/logs/refs, and that may live on another device.
2497  *
2498  * IOW, to avoid cross device rename errors, the temporary renamed log must
2499  * live into logs/refs.
2500  */
2501 #define TMP_RENAMED_LOG  "logs/refs/.tmp-renamed-log"
2502
2503 static int rename_tmp_log(const char *newrefname)
2504 {
2505         int attempts_remaining = 4;
2506         struct strbuf path = STRBUF_INIT;
2507         int ret = -1;
2508
2509  retry:
2510         strbuf_reset(&path);
2511         strbuf_git_path(&path, "logs/%s", newrefname);
2512         switch (safe_create_leading_directories_const(path.buf)) {
2513         case SCLD_OK:
2514                 break; /* success */
2515         case SCLD_VANISHED:
2516                 if (--attempts_remaining > 0)
2517                         goto retry;
2518                 /* fall through */
2519         default:
2520                 error("unable to create directory for %s", newrefname);
2521                 goto out;
2522         }
2523
2524         if (rename(git_path(TMP_RENAMED_LOG), path.buf)) {
2525                 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2526                         /*
2527                          * rename(a, b) when b is an existing
2528                          * directory ought to result in ISDIR, but
2529                          * Solaris 5.8 gives ENOTDIR.  Sheesh.
2530                          */
2531                         if (remove_empty_directories(&path)) {
2532                                 error("Directory not empty: logs/%s", newrefname);
2533                                 goto out;
2534                         }
2535                         goto retry;
2536                 } else if (errno == ENOENT && --attempts_remaining > 0) {
2537                         /*
2538                          * Maybe another process just deleted one of
2539                          * the directories in the path to newrefname.
2540                          * Try again from the beginning.
2541                          */
2542                         goto retry;
2543                 } else {
2544                         error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2545                                 newrefname, strerror(errno));
2546                         goto out;
2547                 }
2548         }
2549         ret = 0;
2550 out:
2551         strbuf_release(&path);
2552         return ret;
2553 }
2554
2555 static int files_verify_refname_available(struct ref_store *ref_store,
2556                                           const char *newname,
2557                                           const struct string_list *extras,
2558                                           const struct string_list *skip,
2559                                           struct strbuf *err)
2560 {
2561         struct files_ref_store *refs =
2562                 files_downcast(ref_store, 1, "verify_refname_available");
2563         struct ref_dir *packed_refs = get_packed_refs(refs);
2564         struct ref_dir *loose_refs = get_loose_refs(refs);
2565
2566         if (verify_refname_available_dir(newname, extras, skip,
2567                                          packed_refs, err) ||
2568             verify_refname_available_dir(newname, extras, skip,
2569                                          loose_refs, err))
2570                 return -1;
2571
2572         return 0;
2573 }
2574
2575 static int write_ref_to_lockfile(struct ref_lock *lock,
2576                                  const unsigned char *sha1, struct strbuf *err);
2577 static int commit_ref_update(struct files_ref_store *refs,
2578                              struct ref_lock *lock,
2579                              const unsigned char *sha1, const char *logmsg,
2580                              struct strbuf *err);
2581
2582 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2583 {
2584         struct files_ref_store *refs = get_files_ref_store(NULL, "rename_ref");
2585         unsigned char sha1[20], orig_sha1[20];
2586         int flag = 0, logmoved = 0;
2587         struct ref_lock *lock;
2588         struct stat loginfo;
2589         int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2590         struct strbuf err = STRBUF_INIT;
2591
2592         if (log && S_ISLNK(loginfo.st_mode))
2593                 return error("reflog for %s is a symlink", oldrefname);
2594
2595         if (!resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
2596                                 orig_sha1, &flag))
2597                 return error("refname %s not found", oldrefname);
2598
2599         if (flag & REF_ISSYMREF)
2600                 return error("refname %s is a symbolic ref, renaming it is not supported",
2601                         oldrefname);
2602         if (!rename_ref_available(oldrefname, newrefname))
2603                 return 1;
2604
2605         if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2606                 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2607                         oldrefname, strerror(errno));
2608
2609         if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2610                 error("unable to delete old %s", oldrefname);
2611                 goto rollback;
2612         }
2613
2614         /*
2615          * Since we are doing a shallow lookup, sha1 is not the
2616          * correct value to pass to delete_ref as old_sha1. But that
2617          * doesn't matter, because an old_sha1 check wouldn't add to
2618          * the safety anyway; we want to delete the reference whatever
2619          * its current value.
2620          */
2621         if (!read_ref_full(newrefname, RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
2622                            sha1, NULL) &&
2623             delete_ref(newrefname, NULL, REF_NODEREF)) {
2624                 if (errno==EISDIR) {
2625                         struct strbuf path = STRBUF_INIT;
2626                         int result;
2627
2628                         strbuf_git_path(&path, "%s", newrefname);
2629                         result = remove_empty_directories(&path);
2630                         strbuf_release(&path);
2631
2632                         if (result) {
2633                                 error("Directory not empty: %s", newrefname);
2634                                 goto rollback;
2635                         }
2636                 } else {
2637                         error("unable to delete existing %s", newrefname);
2638                         goto rollback;
2639                 }
2640         }
2641
2642         if (log && rename_tmp_log(newrefname))
2643                 goto rollback;
2644
2645         logmoved = log;
2646
2647         lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
2648                                    REF_NODEREF, NULL, &err);
2649         if (!lock) {
2650                 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
2651                 strbuf_release(&err);
2652                 goto rollback;
2653         }
2654         hashcpy(lock->old_oid.hash, orig_sha1);
2655
2656         if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2657             commit_ref_update(refs, lock, orig_sha1, logmsg, &err)) {
2658                 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
2659                 strbuf_release(&err);
2660                 goto rollback;
2661         }
2662
2663         return 0;
2664
2665  rollback:
2666         lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
2667                                    REF_NODEREF, NULL, &err);
2668         if (!lock) {
2669                 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
2670                 strbuf_release(&err);
2671                 goto rollbacklog;
2672         }
2673
2674         flag = log_all_ref_updates;
2675         log_all_ref_updates = 0;
2676         if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
2677             commit_ref_update(refs, lock, orig_sha1, NULL, &err)) {
2678                 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
2679                 strbuf_release(&err);
2680         }
2681         log_all_ref_updates = flag;
2682
2683  rollbacklog:
2684         if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2685                 error("unable to restore logfile %s from %s: %s",
2686                         oldrefname, newrefname, strerror(errno));
2687         if (!logmoved && log &&
2688             rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2689                 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2690                         oldrefname, strerror(errno));
2691
2692         return 1;
2693 }
2694
2695 static int close_ref(struct ref_lock *lock)
2696 {
2697         if (close_lock_file(lock->lk))
2698                 return -1;
2699         return 0;
2700 }
2701
2702 static int commit_ref(struct ref_lock *lock)
2703 {
2704         char *path = get_locked_file_path(lock->lk);
2705         struct stat st;
2706
2707         if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
2708                 /*
2709                  * There is a directory at the path we want to rename
2710                  * the lockfile to. Hopefully it is empty; try to
2711                  * delete it.
2712                  */
2713                 size_t len = strlen(path);
2714                 struct strbuf sb_path = STRBUF_INIT;
2715
2716                 strbuf_attach(&sb_path, path, len, len);
2717
2718                 /*
2719                  * If this fails, commit_lock_file() will also fail
2720                  * and will report the problem.
2721                  */
2722                 remove_empty_directories(&sb_path);
2723                 strbuf_release(&sb_path);
2724         } else {
2725                 free(path);
2726         }
2727
2728         if (commit_lock_file(lock->lk))
2729                 return -1;
2730         return 0;
2731 }
2732
2733 /*
2734  * Create a reflog for a ref.  If force_create = 0, the reflog will
2735  * only be created for certain refs (those for which
2736  * should_autocreate_reflog returns non-zero.  Otherwise, create it
2737  * regardless of the ref name.  Fill in *err and return -1 on failure.
2738  */
2739 static int log_ref_setup(const char *refname, struct strbuf *logfile, struct strbuf *err, int force_create)
2740 {
2741         int logfd, oflags = O_APPEND | O_WRONLY;
2742
2743         strbuf_git_path(logfile, "logs/%s", refname);
2744         if (force_create || should_autocreate_reflog(refname)) {
2745                 if (safe_create_leading_directories(logfile->buf) < 0) {
2746                         strbuf_addf(err, "unable to create directory for '%s': "
2747                                     "%s", logfile->buf, strerror(errno));
2748                         return -1;
2749                 }
2750                 oflags |= O_CREAT;
2751         }
2752
2753         logfd = open(logfile->buf, oflags, 0666);
2754         if (logfd < 0) {
2755                 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
2756                         return 0;
2757
2758                 if (errno == EISDIR) {
2759                         if (remove_empty_directories(logfile)) {
2760                                 strbuf_addf(err, "there are still logs under "
2761                                             "'%s'", logfile->buf);
2762                                 return -1;
2763                         }
2764                         logfd = open(logfile->buf, oflags, 0666);
2765                 }
2766
2767                 if (logfd < 0) {
2768                         strbuf_addf(err, "unable to append to '%s': %s",
2769                                     logfile->buf, strerror(errno));
2770                         return -1;
2771                 }
2772         }
2773
2774         adjust_shared_perm(logfile->buf);
2775         close(logfd);
2776         return 0;
2777 }
2778
2779
2780 int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
2781 {
2782         int ret;
2783         struct strbuf sb = STRBUF_INIT;
2784
2785         ret = log_ref_setup(refname, &sb, err, force_create);
2786         strbuf_release(&sb);
2787         return ret;
2788 }
2789
2790 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
2791                             const unsigned char *new_sha1,
2792                             const char *committer, const char *msg)
2793 {
2794         int msglen, written;
2795         unsigned maxlen, len;
2796         char *logrec;
2797
2798         msglen = msg ? strlen(msg) : 0;
2799         maxlen = strlen(committer) + msglen + 100;
2800         logrec = xmalloc(maxlen);
2801         len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2802                         sha1_to_hex(old_sha1),
2803                         sha1_to_hex(new_sha1),
2804                         committer);
2805         if (msglen)
2806                 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2807
2808         written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2809         free(logrec);
2810         if (written != len)
2811                 return -1;
2812
2813         return 0;
2814 }
2815
2816 static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
2817                            const unsigned char *new_sha1, const char *msg,
2818                            struct strbuf *logfile, int flags,
2819                            struct strbuf *err)
2820 {
2821         int logfd, result, oflags = O_APPEND | O_WRONLY;
2822
2823         if (log_all_ref_updates < 0)
2824                 log_all_ref_updates = !is_bare_repository();
2825
2826         result = log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);
2827
2828         if (result)
2829                 return result;
2830
2831         logfd = open(logfile->buf, oflags);
2832         if (logfd < 0)
2833                 return 0;
2834         result = log_ref_write_fd(logfd, old_sha1, new_sha1,
2835                                   git_committer_info(0), msg);
2836         if (result) {
2837                 strbuf_addf(err, "unable to append to '%s': %s", logfile->buf,
2838                             strerror(errno));
2839                 close(logfd);
2840                 return -1;
2841         }
2842         if (close(logfd)) {
2843                 strbuf_addf(err, "unable to append to '%s': %s", logfile->buf,
2844                             strerror(errno));
2845                 return -1;
2846         }
2847         return 0;
2848 }
2849
2850 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2851                          const unsigned char *new_sha1, const char *msg,
2852                          int flags, struct strbuf *err)
2853 {
2854         return files_log_ref_write(refname, old_sha1, new_sha1, msg, flags,
2855                                    err);
2856 }
2857
2858 int files_log_ref_write(const char *refname, const unsigned char *old_sha1,
2859                         const unsigned char *new_sha1, const char *msg,
2860                         int flags, struct strbuf *err)
2861 {
2862         struct strbuf sb = STRBUF_INIT;
2863         int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
2864                                   err);
2865         strbuf_release(&sb);
2866         return ret;
2867 }
2868
2869 /*
2870  * Write sha1 into the open lockfile, then close the lockfile. On
2871  * errors, rollback the lockfile, fill in *err and
2872  * return -1.
2873  */
2874 static int write_ref_to_lockfile(struct ref_lock *lock,
2875                                  const unsigned char *sha1, struct strbuf *err)
2876 {
2877         static char term = '\n';
2878         struct object *o;
2879         int fd;
2880
2881         o = parse_object(sha1);
2882         if (!o) {
2883                 strbuf_addf(err,
2884                             "trying to write ref '%s' with nonexistent object %s",
2885                             lock->ref_name, sha1_to_hex(sha1));
2886                 unlock_ref(lock);
2887                 return -1;
2888         }
2889         if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2890                 strbuf_addf(err,
2891                             "trying to write non-commit object %s to branch '%s'",
2892                             sha1_to_hex(sha1), lock->ref_name);
2893                 unlock_ref(lock);
2894                 return -1;
2895         }
2896         fd = get_lock_file_fd(lock->lk);
2897         if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
2898             write_in_full(fd, &term, 1) != 1 ||
2899             close_ref(lock) < 0) {
2900                 strbuf_addf(err,
2901                             "couldn't write '%s'", get_lock_file_path(lock->lk));
2902                 unlock_ref(lock);
2903                 return -1;
2904         }
2905         return 0;
2906 }
2907
2908 /*
2909  * Commit a change to a loose reference that has already been written
2910  * to the loose reference lockfile. Also update the reflogs if
2911  * necessary, using the specified lockmsg (which can be NULL).
2912  */
2913 static int commit_ref_update(struct files_ref_store *refs,
2914                              struct ref_lock *lock,
2915                              const unsigned char *sha1, const char *logmsg,
2916                              struct strbuf *err)
2917 {
2918         assert_main_repository(&refs->base, "commit_ref_update");
2919
2920         clear_loose_ref_cache(refs);
2921         if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, 0, err)) {
2922                 char *old_msg = strbuf_detach(err, NULL);
2923                 strbuf_addf(err, "cannot update the ref '%s': %s",
2924                             lock->ref_name, old_msg);
2925                 free(old_msg);
2926                 unlock_ref(lock);
2927                 return -1;
2928         }
2929
2930         if (strcmp(lock->ref_name, "HEAD") != 0) {
2931                 /*
2932                  * Special hack: If a branch is updated directly and HEAD
2933                  * points to it (may happen on the remote side of a push
2934                  * for example) then logically the HEAD reflog should be
2935                  * updated too.
2936                  * A generic solution implies reverse symref information,
2937                  * but finding all symrefs pointing to the given branch
2938                  * would be rather costly for this rare event (the direct
2939                  * update of a branch) to be worth it.  So let's cheat and
2940                  * check with HEAD only which should cover 99% of all usage
2941                  * scenarios (even 100% of the default ones).
2942                  */
2943                 unsigned char head_sha1[20];
2944                 int head_flag;
2945                 const char *head_ref;
2946
2947                 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
2948                                               head_sha1, &head_flag);
2949                 if (head_ref && (head_flag & REF_ISSYMREF) &&
2950                     !strcmp(head_ref, lock->ref_name)) {
2951                         struct strbuf log_err = STRBUF_INIT;
2952                         if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
2953                                           logmsg, 0, &log_err)) {
2954                                 error("%s", log_err.buf);
2955                                 strbuf_release(&log_err);
2956                         }
2957                 }
2958         }
2959
2960         if (commit_ref(lock)) {
2961                 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2962                 unlock_ref(lock);
2963                 return -1;
2964         }
2965
2966         unlock_ref(lock);
2967         return 0;
2968 }
2969
2970 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2971 {
2972         int ret = -1;
2973 #ifndef NO_SYMLINK_HEAD
2974         char *ref_path = get_locked_file_path(lock->lk);
2975         unlink(ref_path);
2976         ret = symlink(target, ref_path);
2977         free(ref_path);
2978
2979         if (ret)
2980                 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2981 #endif
2982         return ret;
2983 }
2984
2985 static void update_symref_reflog(struct ref_lock *lock, const char *refname,
2986                                  const char *target, const char *logmsg)
2987 {
2988         struct strbuf err = STRBUF_INIT;
2989         unsigned char new_sha1[20];
2990         if (logmsg && !read_ref(target, new_sha1) &&
2991             log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg, 0, &err)) {
2992                 error("%s", err.buf);
2993                 strbuf_release(&err);
2994         }
2995 }
2996
2997 static int create_symref_locked(struct ref_lock *lock, const char *refname,
2998                                 const char *target, const char *logmsg)
2999 {
3000         if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
3001                 update_symref_reflog(lock, refname, target, logmsg);
3002                 return 0;
3003         }
3004
3005         if (!fdopen_lock_file(lock->lk, "w"))
3006                 return error("unable to fdopen %s: %s",
3007                              lock->lk->tempfile.filename.buf, strerror(errno));
3008
3009         update_symref_reflog(lock, refname, target, logmsg);
3010
3011         /* no error check; commit_ref will check ferror */
3012         fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
3013         if (commit_ref(lock) < 0)
3014                 return error("unable to write symref for %s: %s", refname,
3015                              strerror(errno));
3016         return 0;
3017 }
3018
3019 static int files_create_symref(struct ref_store *ref_store,
3020                                const char *refname, const char *target,
3021                                const char *logmsg)
3022 {
3023         struct files_ref_store *refs =
3024                 files_downcast(ref_store, 0, "create_symref");
3025         struct strbuf err = STRBUF_INIT;
3026         struct ref_lock *lock;
3027         int ret;
3028
3029         lock = lock_ref_sha1_basic(refs, refname, NULL,
3030                                    NULL, NULL, REF_NODEREF, NULL,
3031                                    &err);
3032         if (!lock) {
3033                 error("%s", err.buf);
3034                 strbuf_release(&err);
3035                 return -1;
3036         }
3037
3038         ret = create_symref_locked(lock, refname, target, logmsg);
3039         unlock_ref(lock);
3040         return ret;
3041 }
3042
3043 int set_worktree_head_symref(const char *gitdir, const char *target)
3044 {
3045         static struct lock_file head_lock;
3046         struct ref_lock *lock;
3047         struct strbuf head_path = STRBUF_INIT;
3048         const char *head_rel;
3049         int ret;
3050
3051         strbuf_addf(&head_path, "%s/HEAD", absolute_path(gitdir));
3052         if (hold_lock_file_for_update(&head_lock, head_path.buf,
3053                                       LOCK_NO_DEREF) < 0) {
3054                 struct strbuf err = STRBUF_INIT;
3055                 unable_to_lock_message(head_path.buf, errno, &err);
3056                 error("%s", err.buf);
3057                 strbuf_release(&err);
3058                 strbuf_release(&head_path);
3059                 return -1;
3060         }
3061
3062         /* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for
3063            linked trees */
3064         head_rel = remove_leading_path(head_path.buf,
3065                                        absolute_path(get_git_common_dir()));
3066         /* to make use of create_symref_locked(), initialize ref_lock */
3067         lock = xcalloc(1, sizeof(struct ref_lock));
3068         lock->lk = &head_lock;
3069         lock->ref_name = xstrdup(head_rel);
3070
3071         ret = create_symref_locked(lock, head_rel, target, NULL);
3072
3073         unlock_ref(lock); /* will free lock */
3074         strbuf_release(&head_path);
3075         return ret;
3076 }
3077
3078 int reflog_exists(const char *refname)
3079 {
3080         struct stat st;
3081
3082         return !lstat(git_path("logs/%s", refname), &st) &&
3083                 S_ISREG(st.st_mode);
3084 }
3085
3086 int delete_reflog(const char *refname)
3087 {
3088         return remove_path(git_path("logs/%s", refname));
3089 }
3090
3091 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3092 {
3093         unsigned char osha1[20], nsha1[20];
3094         char *email_end, *message;
3095         unsigned long timestamp;
3096         int tz;
3097
3098         /* old SP new SP name <email> SP time TAB msg LF */
3099         if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3100             get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3101             get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3102             !(email_end = strchr(sb->buf + 82, '>')) ||
3103             email_end[1] != ' ' ||
3104             !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3105             !message || message[0] != ' ' ||
3106             (message[1] != '+' && message[1] != '-') ||
3107             !isdigit(message[2]) || !isdigit(message[3]) ||
3108             !isdigit(message[4]) || !isdigit(message[5]))
3109                 return 0; /* corrupt? */
3110         email_end[1] = '\0';
3111         tz = strtol(message + 1, NULL, 10);
3112         if (message[6] != '\t')
3113                 message += 6;
3114         else
3115                 message += 7;
3116         return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3117 }
3118
3119 static char *find_beginning_of_line(char *bob, char *scan)
3120 {
3121         while (bob < scan && *(--scan) != '\n')
3122                 ; /* keep scanning backwards */
3123         /*
3124          * Return either beginning of the buffer, or LF at the end of
3125          * the previous line.
3126          */
3127         return scan;
3128 }
3129
3130 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3131 {
3132         struct strbuf sb = STRBUF_INIT;
3133         FILE *logfp;
3134         long pos;
3135         int ret = 0, at_tail = 1;
3136
3137         logfp = fopen(git_path("logs/%s", refname), "r");
3138         if (!logfp)
3139                 return -1;
3140
3141         /* Jump to the end */
3142         if (fseek(logfp, 0, SEEK_END) < 0)
3143                 return error("cannot seek back reflog for %s: %s",
3144                              refname, strerror(errno));
3145         pos = ftell(logfp);
3146         while (!ret && 0 < pos) {
3147                 int cnt;
3148                 size_t nread;
3149                 char buf[BUFSIZ];
3150                 char *endp, *scanp;
3151
3152                 /* Fill next block from the end */
3153                 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3154                 if (fseek(logfp, pos - cnt, SEEK_SET))
3155                         return error("cannot seek back reflog for %s: %s",
3156                                      refname, strerror(errno));
3157                 nread = fread(buf, cnt, 1, logfp);
3158                 if (nread != 1)
3159                         return error("cannot read %d bytes from reflog for %s: %s",
3160                                      cnt, refname, strerror(errno));
3161                 pos -= cnt;
3162
3163                 scanp = endp = buf + cnt;
3164                 if (at_tail && scanp[-1] == '\n')
3165                         /* Looking at the final LF at the end of the file */
3166                         scanp--;
3167                 at_tail = 0;
3168
3169                 while (buf < scanp) {
3170                         /*
3171                          * terminating LF of the previous line, or the beginning
3172                          * of the buffer.
3173                          */
3174                         char *bp;
3175
3176                         bp = find_beginning_of_line(buf, scanp);
3177
3178                         if (*bp == '\n') {
3179                                 /*
3180                                  * The newline is the end of the previous line,
3181                                  * so we know we have complete line starting
3182                                  * at (bp + 1). Prefix it onto any prior data
3183                                  * we collected for the line and process it.
3184                                  */
3185                                 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3186                                 scanp = bp;
3187                                 endp = bp + 1;
3188                                 ret = show_one_reflog_ent(&sb, fn, cb_data);
3189                                 strbuf_reset(&sb);
3190                                 if (ret)
3191                                         break;
3192                         } else if (!pos) {
3193                                 /*
3194                                  * We are at the start of the buffer, and the
3195                                  * start of the file; there is no previous
3196                                  * line, and we have everything for this one.
3197                                  * Process it, and we can end the loop.
3198                                  */
3199                                 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3200                                 ret = show_one_reflog_ent(&sb, fn, cb_data);
3201                                 strbuf_reset(&sb);
3202                                 break;
3203                         }
3204
3205                         if (bp == buf) {
3206                                 /*
3207                                  * We are at the start of the buffer, and there
3208                                  * is more file to read backwards. Which means
3209                                  * we are in the middle of a line. Note that we
3210                                  * may get here even if *bp was a newline; that
3211                                  * just means we are at the exact end of the
3212                                  * previous line, rather than some spot in the
3213                                  * middle.
3214                                  *
3215                                  * Save away what we have to be combined with
3216                                  * the data from the next read.
3217                                  */
3218                                 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3219                                 break;
3220                         }
3221                 }
3222
3223         }
3224         if (!ret && sb.len)
3225                 die("BUG: reverse reflog parser had leftover data");
3226
3227         fclose(logfp);
3228         strbuf_release(&sb);
3229         return ret;
3230 }
3231
3232 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3233 {
3234         FILE *logfp;
3235         struct strbuf sb = STRBUF_INIT;
3236         int ret = 0;
3237
3238         logfp = fopen(git_path("logs/%s", refname), "r");
3239         if (!logfp)
3240                 return -1;
3241
3242         while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3243                 ret = show_one_reflog_ent(&sb, fn, cb_data);
3244         fclose(logfp);
3245         strbuf_release(&sb);
3246         return ret;
3247 }
3248
3249 struct files_reflog_iterator {
3250         struct ref_iterator base;
3251
3252         struct dir_iterator *dir_iterator;
3253         struct object_id oid;
3254 };
3255
3256 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
3257 {
3258         struct files_reflog_iterator *iter =
3259                 (struct files_reflog_iterator *)ref_iterator;
3260         struct dir_iterator *diter = iter->dir_iterator;
3261         int ok;
3262
3263         while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
3264                 int flags;
3265
3266                 if (!S_ISREG(diter->st.st_mode))
3267                         continue;
3268                 if (diter->basename[0] == '.')
3269                         continue;
3270                 if (ends_with(diter->basename, ".lock"))
3271                         continue;
3272
3273                 if (read_ref_full(diter->relative_path, 0,
3274                                   iter->oid.hash, &flags)) {
3275                         error("bad ref for %s", diter->path.buf);
3276                         continue;
3277                 }
3278
3279                 iter->base.refname = diter->relative_path;
3280                 iter->base.oid = &iter->oid;
3281                 iter->base.flags = flags;
3282                 return ITER_OK;
3283         }
3284
3285         iter->dir_iterator = NULL;
3286         if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
3287                 ok = ITER_ERROR;
3288         return ok;
3289 }
3290
3291 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
3292                                    struct object_id *peeled)
3293 {
3294         die("BUG: ref_iterator_peel() called for reflog_iterator");
3295 }
3296
3297 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
3298 {
3299         struct files_reflog_iterator *iter =
3300                 (struct files_reflog_iterator *)ref_iterator;
3301         int ok = ITER_DONE;
3302
3303         if (iter->dir_iterator)
3304                 ok = dir_iterator_abort(iter->dir_iterator);
3305
3306         base_ref_iterator_free(ref_iterator);
3307         return ok;
3308 }
3309
3310 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
3311         files_reflog_iterator_advance,
3312         files_reflog_iterator_peel,
3313         files_reflog_iterator_abort
3314 };
3315
3316 struct ref_iterator *files_reflog_iterator_begin(void)
3317 {
3318         struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
3319         struct ref_iterator *ref_iterator = &iter->base;
3320
3321         base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
3322         iter->dir_iterator = dir_iterator_begin(git_path("logs"));
3323         return ref_iterator;
3324 }
3325
3326 int for_each_reflog(each_ref_fn fn, void *cb_data)
3327 {
3328         return do_for_each_ref_iterator(files_reflog_iterator_begin(),
3329                                         fn, cb_data);
3330 }
3331
3332 static int ref_update_reject_duplicates(struct string_list *refnames,
3333                                         struct strbuf *err)
3334 {
3335         int i, n = refnames->nr;
3336
3337         assert(err);
3338
3339         for (i = 1; i < n; i++)
3340                 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
3341                         strbuf_addf(err,
3342                                     "multiple updates for ref '%s' not allowed.",
3343                                     refnames->items[i].string);
3344                         return 1;
3345                 }
3346         return 0;
3347 }
3348
3349 /*
3350  * If update is a direct update of head_ref (the reference pointed to
3351  * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
3352  */
3353 static int split_head_update(struct ref_update *update,
3354                              struct ref_transaction *transaction,
3355                              const char *head_ref,
3356                              struct string_list *affected_refnames,
3357                              struct strbuf *err)
3358 {
3359         struct string_list_item *item;
3360         struct ref_update *new_update;
3361
3362         if ((update->flags & REF_LOG_ONLY) ||
3363             (update->flags & REF_ISPRUNING) ||
3364             (update->flags & REF_UPDATE_VIA_HEAD))
3365                 return 0;
3366
3367         if (strcmp(update->refname, head_ref))
3368                 return 0;
3369
3370         /*
3371          * First make sure that HEAD is not already in the
3372          * transaction. This insertion is O(N) in the transaction
3373          * size, but it happens at most once per transaction.
3374          */
3375         item = string_list_insert(affected_refnames, "HEAD");
3376         if (item->util) {
3377                 /* An entry already existed */
3378                 strbuf_addf(err,
3379                             "multiple updates for 'HEAD' (including one "
3380                             "via its referent '%s') are not allowed",
3381                             update->refname);
3382                 return TRANSACTION_NAME_CONFLICT;
3383         }
3384
3385         new_update = ref_transaction_add_update(
3386                         transaction, "HEAD",
3387                         update->flags | REF_LOG_ONLY | REF_NODEREF,
3388                         update->new_sha1, update->old_sha1,
3389                         update->msg);
3390
3391         item->util = new_update;
3392
3393         return 0;
3394 }
3395
3396 /*
3397  * update is for a symref that points at referent and doesn't have
3398  * REF_NODEREF set. Split it into two updates:
3399  * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
3400  * - A new, separate update for the referent reference
3401  * Note that the new update will itself be subject to splitting when
3402  * the iteration gets to it.
3403  */
3404 static int split_symref_update(struct files_ref_store *refs,
3405                                struct ref_update *update,
3406                                const char *referent,
3407                                struct ref_transaction *transaction,
3408                                struct string_list *affected_refnames,
3409                                struct strbuf *err)
3410 {
3411         struct string_list_item *item;
3412         struct ref_update *new_update;
3413         unsigned int new_flags;
3414
3415         /*
3416          * First make sure that referent is not already in the
3417          * transaction. This insertion is O(N) in the transaction
3418          * size, but it happens at most once per symref in a
3419          * transaction.
3420          */
3421         item = string_list_insert(affected_refnames, referent);
3422         if (item->util) {
3423                 /* An entry already existed */
3424                 strbuf_addf(err,
3425                             "multiple updates for '%s' (including one "
3426                             "via symref '%s') are not allowed",
3427                             referent, update->refname);
3428                 return TRANSACTION_NAME_CONFLICT;
3429         }
3430
3431         new_flags = update->flags;
3432         if (!strcmp(update->refname, "HEAD")) {
3433                 /*
3434                  * Record that the new update came via HEAD, so that
3435                  * when we process it, split_head_update() doesn't try
3436                  * to add another reflog update for HEAD. Note that
3437                  * this bit will be propagated if the new_update
3438                  * itself needs to be split.
3439                  */
3440                 new_flags |= REF_UPDATE_VIA_HEAD;
3441         }
3442
3443         new_update = ref_transaction_add_update(
3444                         transaction, referent, new_flags,
3445                         update->new_sha1, update->old_sha1,
3446                         update->msg);
3447
3448         new_update->parent_update = update;
3449
3450         /*
3451          * Change the symbolic ref update to log only. Also, it
3452          * doesn't need to check its old SHA-1 value, as that will be
3453          * done when new_update is processed.
3454          */
3455         update->flags |= REF_LOG_ONLY | REF_NODEREF;
3456         update->flags &= ~REF_HAVE_OLD;
3457
3458         item->util = new_update;
3459
3460         return 0;
3461 }
3462
3463 /*
3464  * Return the refname under which update was originally requested.
3465  */
3466 static const char *original_update_refname(struct ref_update *update)
3467 {
3468         while (update->parent_update)
3469                 update = update->parent_update;
3470
3471         return update->refname;
3472 }
3473
3474 /*
3475  * Prepare for carrying out update:
3476  * - Lock the reference referred to by update.
3477  * - Read the reference under lock.
3478  * - Check that its old SHA-1 value (if specified) is correct, and in
3479  *   any case record it in update->lock->old_oid for later use when
3480  *   writing the reflog.
3481  * - If it is a symref update without REF_NODEREF, split it up into a
3482  *   REF_LOG_ONLY update of the symref and add a separate update for
3483  *   the referent to transaction.
3484  * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
3485  *   update of HEAD.
3486  */
3487 static int lock_ref_for_update(struct files_ref_store *refs,
3488                                struct ref_update *update,
3489                                struct ref_transaction *transaction,
3490                                const char *head_ref,
3491                                struct string_list *affected_refnames,
3492                                struct strbuf *err)
3493 {
3494         struct strbuf referent = STRBUF_INIT;
3495         int mustexist = (update->flags & REF_HAVE_OLD) &&
3496                 !is_null_sha1(update->old_sha1);
3497         int ret;
3498         struct ref_lock *lock;
3499
3500         assert_main_repository(&refs->base, "lock_ref_for_update");
3501
3502         if ((update->flags & REF_HAVE_NEW) && is_null_sha1(update->new_sha1))
3503                 update->flags |= REF_DELETING;
3504
3505         if (head_ref) {
3506                 ret = split_head_update(update, transaction, head_ref,
3507                                         affected_refnames, err);
3508                 if (ret)
3509                         return ret;
3510         }
3511
3512         ret = lock_raw_ref(refs, update->refname, mustexist,
3513                            affected_refnames, NULL,
3514                            &update->lock, &referent,
3515                            &update->type, err);
3516
3517         if (ret) {
3518                 char *reason;
3519
3520                 reason = strbuf_detach(err, NULL);
3521                 strbuf_addf(err, "cannot lock ref '%s': %s",
3522                             update->refname, reason);
3523                 free(reason);
3524                 return ret;
3525         }
3526
3527         lock = update->lock;
3528
3529         if (update->type & REF_ISSYMREF) {
3530                 if (update->flags & REF_NODEREF) {
3531                         /*
3532                          * We won't be reading the referent as part of
3533                          * the transaction, so we have to read it here
3534                          * to record and possibly check old_sha1:
3535                          */
3536                         if (read_ref_full(update->refname,
3537                                           mustexist ? RESOLVE_REF_READING : 0,
3538                                           lock->old_oid.hash, NULL)) {
3539                                 if (update->flags & REF_HAVE_OLD) {
3540                                         strbuf_addf(err, "cannot lock ref '%s': "
3541                                                     "can't resolve old value",
3542                                                     update->refname);
3543                                         return TRANSACTION_GENERIC_ERROR;
3544                                 } else {
3545                                         hashclr(lock->old_oid.hash);
3546                                 }
3547                         }
3548                         if ((update->flags & REF_HAVE_OLD) &&
3549                             hashcmp(lock->old_oid.hash, update->old_sha1)) {
3550                                 strbuf_addf(err, "cannot lock ref '%s': "
3551                                             "is at %s but expected %s",
3552                                             update->refname,
3553                                             sha1_to_hex(lock->old_oid.hash),
3554                                             sha1_to_hex(update->old_sha1));
3555                                 return TRANSACTION_GENERIC_ERROR;
3556                         }
3557
3558                 } else {
3559                         /*
3560                          * Create a new update for the reference this
3561                          * symref is pointing at. Also, we will record
3562                          * and verify old_sha1 for this update as part
3563                          * of processing the split-off update, so we
3564                          * don't have to do it here.
3565                          */
3566                         ret = split_symref_update(refs, update,
3567                                                   referent.buf, transaction,
3568                                                   affected_refnames, err);
3569                         if (ret)
3570                                 return ret;
3571                 }
3572         } else {
3573                 struct ref_update *parent_update;
3574
3575                 /*
3576                  * If this update is happening indirectly because of a
3577                  * symref update, record the old SHA-1 in the parent
3578                  * update:
3579                  */
3580                 for (parent_update = update->parent_update;
3581                      parent_update;
3582                      parent_update = parent_update->parent_update) {
3583                         oidcpy(&parent_update->lock->old_oid, &lock->old_oid);
3584                 }
3585
3586                 if ((update->flags & REF_HAVE_OLD) &&
3587                     hashcmp(lock->old_oid.hash, update->old_sha1)) {
3588                         if (is_null_sha1(update->old_sha1))
3589                                 strbuf_addf(err, "cannot lock ref '%s': reference already exists",
3590                                             original_update_refname(update));
3591                         else
3592                                 strbuf_addf(err, "cannot lock ref '%s': is at %s but expected %s",
3593                                             original_update_refname(update),
3594                                             sha1_to_hex(lock->old_oid.hash),
3595                                             sha1_to_hex(update->old_sha1));
3596
3597                         return TRANSACTION_GENERIC_ERROR;
3598                 }
3599         }
3600
3601         if ((update->flags & REF_HAVE_NEW) &&
3602             !(update->flags & REF_DELETING) &&
3603             !(update->flags & REF_LOG_ONLY)) {
3604                 if (!(update->type & REF_ISSYMREF) &&
3605                     !hashcmp(lock->old_oid.hash, update->new_sha1)) {
3606                         /*
3607                          * The reference already has the desired
3608                          * value, so we don't need to write it.
3609                          */
3610                 } else if (write_ref_to_lockfile(lock, update->new_sha1,
3611                                                  err)) {
3612                         char *write_err = strbuf_detach(err, NULL);
3613
3614                         /*
3615                          * The lock was freed upon failure of
3616                          * write_ref_to_lockfile():
3617                          */
3618                         update->lock = NULL;
3619                         strbuf_addf(err,
3620                                     "cannot update the ref '%s': %s",
3621                                     update->refname, write_err);
3622                         free(write_err);
3623                         return TRANSACTION_GENERIC_ERROR;
3624                 } else {
3625                         update->flags |= REF_NEEDS_COMMIT;
3626                 }
3627         }
3628         if (!(update->flags & REF_NEEDS_COMMIT)) {
3629                 /*
3630                  * We didn't call write_ref_to_lockfile(), so
3631                  * the lockfile is still open. Close it to
3632                  * free up the file descriptor:
3633                  */
3634                 if (close_ref(lock)) {
3635                         strbuf_addf(err, "couldn't close '%s.lock'",
3636                                     update->refname);
3637                         return TRANSACTION_GENERIC_ERROR;
3638                 }
3639         }
3640         return 0;
3641 }
3642
3643 static int files_transaction_commit(struct ref_store *ref_store,
3644                                     struct ref_transaction *transaction,
3645                                     struct strbuf *err)
3646 {
3647         struct files_ref_store *refs =
3648                 files_downcast(ref_store, 0, "ref_transaction_commit");
3649         int ret = 0, i;
3650         struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3651         struct string_list_item *ref_to_delete;
3652         struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3653         char *head_ref = NULL;
3654         int head_type;
3655         struct object_id head_oid;
3656
3657         assert(err);
3658
3659         if (transaction->state != REF_TRANSACTION_OPEN)
3660                 die("BUG: commit called for transaction that is not open");
3661
3662         if (!transaction->nr) {
3663                 transaction->state = REF_TRANSACTION_CLOSED;
3664                 return 0;
3665         }
3666
3667         /*
3668          * Fail if a refname appears more than once in the
3669          * transaction. (If we end up splitting up any updates using
3670          * split_symref_update() or split_head_update(), those
3671          * functions will check that the new updates don't have the
3672          * same refname as any existing ones.)
3673          */
3674         for (i = 0; i < transaction->nr; i++) {
3675                 struct ref_update *update = transaction->updates[i];
3676                 struct string_list_item *item =
3677                         string_list_append(&affected_refnames, update->refname);
3678
3679                 /*
3680                  * We store a pointer to update in item->util, but at
3681                  * the moment we never use the value of this field
3682                  * except to check whether it is non-NULL.
3683                  */
3684                 item->util = update;
3685         }
3686         string_list_sort(&affected_refnames);
3687         if (ref_update_reject_duplicates(&affected_refnames, err)) {
3688                 ret = TRANSACTION_GENERIC_ERROR;
3689                 goto cleanup;
3690         }
3691
3692         /*
3693          * Special hack: If a branch is updated directly and HEAD
3694          * points to it (may happen on the remote side of a push
3695          * for example) then logically the HEAD reflog should be
3696          * updated too.
3697          *
3698          * A generic solution would require reverse symref lookups,
3699          * but finding all symrefs pointing to a given branch would be
3700          * rather costly for this rare event (the direct update of a
3701          * branch) to be worth it. So let's cheat and check with HEAD
3702          * only, which should cover 99% of all usage scenarios (even
3703          * 100% of the default ones).
3704          *
3705          * So if HEAD is a symbolic reference, then record the name of
3706          * the reference that it points to. If we see an update of
3707          * head_ref within the transaction, then split_head_update()
3708          * arranges for the reflog of HEAD to be updated, too.
3709          */
3710         head_ref = resolve_refdup("HEAD", RESOLVE_REF_NO_RECURSE,
3711                                   head_oid.hash, &head_type);
3712
3713         if (head_ref && !(head_type & REF_ISSYMREF)) {
3714                 free(head_ref);
3715                 head_ref = NULL;
3716         }
3717
3718         /*
3719          * Acquire all locks, verify old values if provided, check
3720          * that new values are valid, and write new values to the
3721          * lockfiles, ready to be activated. Only keep one lockfile
3722          * open at a time to avoid running out of file descriptors.
3723          */
3724         for (i = 0; i < transaction->nr; i++) {
3725                 struct ref_update *update = transaction->updates[i];
3726
3727                 ret = lock_ref_for_update(refs, update, transaction,
3728                                           head_ref, &affected_refnames, err);
3729                 if (ret)
3730                         goto cleanup;
3731         }
3732
3733         /* Perform updates first so live commits remain referenced */
3734         for (i = 0; i < transaction->nr; i++) {
3735                 struct ref_update *update = transaction->updates[i];
3736                 struct ref_lock *lock = update->lock;
3737
3738                 if (update->flags & REF_NEEDS_COMMIT ||
3739                     update->flags & REF_LOG_ONLY) {
3740                         if (log_ref_write(lock->ref_name, lock->old_oid.hash,
3741                                           update->new_sha1,
3742                                           update->msg, update->flags, err)) {
3743                                 char *old_msg = strbuf_detach(err, NULL);
3744
3745                                 strbuf_addf(err, "cannot update the ref '%s': %s",
3746                                             lock->ref_name, old_msg);
3747                                 free(old_msg);
3748                                 unlock_ref(lock);
3749                                 update->lock = NULL;
3750                                 ret = TRANSACTION_GENERIC_ERROR;
3751                                 goto cleanup;
3752                         }
3753                 }
3754                 if (update->flags & REF_NEEDS_COMMIT) {
3755                         clear_loose_ref_cache(refs);
3756                         if (commit_ref(lock)) {
3757                                 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
3758                                 unlock_ref(lock);
3759                                 update->lock = NULL;
3760                                 ret = TRANSACTION_GENERIC_ERROR;
3761                                 goto cleanup;
3762                         }
3763                 }
3764         }
3765         /* Perform deletes now that updates are safely completed */
3766         for (i = 0; i < transaction->nr; i++) {
3767                 struct ref_update *update = transaction->updates[i];
3768
3769                 if (update->flags & REF_DELETING &&
3770                     !(update->flags & REF_LOG_ONLY)) {
3771                         if (delete_ref_loose(update->lock, update->type, err)) {
3772                                 ret = TRANSACTION_GENERIC_ERROR;
3773                                 goto cleanup;
3774                         }
3775
3776                         if (!(update->flags & REF_ISPRUNING))
3777                                 string_list_append(&refs_to_delete,
3778                                                    update->lock->ref_name);
3779                 }
3780         }
3781
3782         if (repack_without_refs(refs, &refs_to_delete, err)) {
3783                 ret = TRANSACTION_GENERIC_ERROR;
3784                 goto cleanup;
3785         }
3786         for_each_string_list_item(ref_to_delete, &refs_to_delete)
3787                 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
3788         clear_loose_ref_cache(refs);
3789
3790 cleanup:
3791         transaction->state = REF_TRANSACTION_CLOSED;
3792
3793         for (i = 0; i < transaction->nr; i++)
3794                 if (transaction->updates[i]->lock)
3795                         unlock_ref(transaction->updates[i]->lock);
3796         string_list_clear(&refs_to_delete, 0);
3797         free(head_ref);
3798         string_list_clear(&affected_refnames, 0);
3799
3800         return ret;
3801 }
3802
3803 static int ref_present(const char *refname,
3804                        const struct object_id *oid, int flags, void *cb_data)
3805 {
3806         struct string_list *affected_refnames = cb_data;
3807
3808         return string_list_has_string(affected_refnames, refname);
3809 }
3810
3811 int initial_ref_transaction_commit(struct ref_transaction *transaction,
3812                                    struct strbuf *err)
3813 {
3814         struct files_ref_store *refs =
3815                 get_files_ref_store(NULL, "initial_ref_transaction_commit");
3816         int ret = 0, i;
3817         struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3818
3819         assert(err);
3820
3821         if (transaction->state != REF_TRANSACTION_OPEN)
3822                 die("BUG: commit called for transaction that is not open");
3823
3824         /* Fail if a refname appears more than once in the transaction: */
3825         for (i = 0; i < transaction->nr; i++)
3826                 string_list_append(&affected_refnames,
3827                                    transaction->updates[i]->refname);
3828         string_list_sort(&affected_refnames);
3829         if (ref_update_reject_duplicates(&affected_refnames, err)) {
3830                 ret = TRANSACTION_GENERIC_ERROR;
3831                 goto cleanup;
3832         }
3833
3834         /*
3835          * It's really undefined to call this function in an active
3836          * repository or when there are existing references: we are
3837          * only locking and changing packed-refs, so (1) any
3838          * simultaneous processes might try to change a reference at
3839          * the same time we do, and (2) any existing loose versions of
3840          * the references that we are setting would have precedence
3841          * over our values. But some remote helpers create the remote
3842          * "HEAD" and "master" branches before calling this function,
3843          * so here we really only check that none of the references
3844          * that we are creating already exists.
3845          */
3846         if (for_each_rawref(ref_present, &affected_refnames))
3847                 die("BUG: initial ref transaction called with existing refs");
3848
3849         for (i = 0; i < transaction->nr; i++) {
3850                 struct ref_update *update = transaction->updates[i];
3851
3852                 if ((update->flags & REF_HAVE_OLD) &&
3853                     !is_null_sha1(update->old_sha1))
3854                         die("BUG: initial ref transaction with old_sha1 set");
3855                 if (verify_refname_available(update->refname,
3856                                              &affected_refnames, NULL,
3857                                              err)) {
3858                         ret = TRANSACTION_NAME_CONFLICT;
3859                         goto cleanup;
3860                 }
3861         }
3862
3863         if (lock_packed_refs(refs, 0)) {
3864                 strbuf_addf(err, "unable to lock packed-refs file: %s",
3865                             strerror(errno));
3866                 ret = TRANSACTION_GENERIC_ERROR;
3867                 goto cleanup;
3868         }
3869
3870         for (i = 0; i < transaction->nr; i++) {
3871                 struct ref_update *update = transaction->updates[i];
3872
3873                 if ((update->flags & REF_HAVE_NEW) &&
3874                     !is_null_sha1(update->new_sha1))
3875                         add_packed_ref(refs, update->refname, update->new_sha1);
3876         }
3877
3878         if (commit_packed_refs(refs)) {
3879                 strbuf_addf(err, "unable to commit packed-refs file: %s",
3880                             strerror(errno));
3881                 ret = TRANSACTION_GENERIC_ERROR;
3882                 goto cleanup;
3883         }
3884
3885 cleanup:
3886         transaction->state = REF_TRANSACTION_CLOSED;
3887         string_list_clear(&affected_refnames, 0);
3888         return ret;
3889 }
3890
3891 struct expire_reflog_cb {
3892         unsigned int flags;
3893         reflog_expiry_should_prune_fn *should_prune_fn;
3894         void *policy_cb;
3895         FILE *newlog;
3896         unsigned char last_kept_sha1[20];
3897 };
3898
3899 static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
3900                              const char *email, unsigned long timestamp, int tz,
3901                              const char *message, void *cb_data)
3902 {
3903         struct expire_reflog_cb *cb = cb_data;
3904         struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3905
3906         if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3907                 osha1 = cb->last_kept_sha1;
3908
3909         if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
3910                                    message, policy_cb)) {
3911                 if (!cb->newlog)
3912                         printf("would prune %s", message);
3913                 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3914                         printf("prune %s", message);
3915         } else {
3916                 if (cb->newlog) {
3917                         fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
3918                                 sha1_to_hex(osha1), sha1_to_hex(nsha1),
3919                                 email, timestamp, tz, message);
3920                         hashcpy(cb->last_kept_sha1, nsha1);
3921                 }
3922                 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3923                         printf("keep %s", message);
3924         }
3925         return 0;
3926 }
3927
3928 int reflog_expire(const char *refname, const unsigned char *sha1,
3929                  unsigned int flags,
3930                  reflog_expiry_prepare_fn prepare_fn,
3931                  reflog_expiry_should_prune_fn should_prune_fn,
3932                  reflog_expiry_cleanup_fn cleanup_fn,
3933                  void *policy_cb_data)
3934 {
3935         struct files_ref_store *refs =
3936                 get_files_ref_store(NULL, "reflog_expire");
3937         static struct lock_file reflog_lock;
3938         struct expire_reflog_cb cb;
3939         struct ref_lock *lock;
3940         char *log_file;
3941         int status = 0;
3942         int type;
3943         struct strbuf err = STRBUF_INIT;
3944
3945         memset(&cb, 0, sizeof(cb));
3946         cb.flags = flags;
3947         cb.policy_cb = policy_cb_data;
3948         cb.should_prune_fn = should_prune_fn;
3949
3950         /*
3951          * The reflog file is locked by holding the lock on the
3952          * reference itself, plus we might need to update the
3953          * reference if --updateref was specified:
3954          */
3955         lock = lock_ref_sha1_basic(refs, refname, sha1,
3956                                    NULL, NULL, REF_NODEREF,
3957                                    &type, &err);
3958         if (!lock) {
3959                 error("cannot lock ref '%s': %s", refname, err.buf);
3960                 strbuf_release(&err);
3961                 return -1;
3962         }
3963         if (!reflog_exists(refname)) {
3964                 unlock_ref(lock);
3965                 return 0;
3966         }
3967
3968         log_file = git_pathdup("logs/%s", refname);
3969         if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3970                 /*
3971                  * Even though holding $GIT_DIR/logs/$reflog.lock has
3972                  * no locking implications, we use the lock_file
3973                  * machinery here anyway because it does a lot of the
3974                  * work we need, including cleaning up if the program
3975                  * exits unexpectedly.
3976                  */
3977                 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3978                         struct strbuf err = STRBUF_INIT;
3979                         unable_to_lock_message(log_file, errno, &err);
3980                         error("%s", err.buf);
3981                         strbuf_release(&err);
3982                         goto failure;
3983                 }
3984                 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3985                 if (!cb.newlog) {
3986                         error("cannot fdopen %s (%s)",
3987                               get_lock_file_path(&reflog_lock), strerror(errno));
3988                         goto failure;
3989                 }
3990         }
3991
3992         (*prepare_fn)(refname, sha1, cb.policy_cb);
3993         for_each_reflog_ent(refname, expire_reflog_ent, &cb);
3994         (*cleanup_fn)(cb.policy_cb);
3995
3996         if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3997                 /*
3998                  * It doesn't make sense to adjust a reference pointed
3999                  * to by a symbolic ref based on expiring entries in
4000                  * the symbolic reference's reflog. Nor can we update
4001                  * a reference if there are no remaining reflog
4002                  * entries.
4003                  */
4004                 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
4005                         !(type & REF_ISSYMREF) &&
4006                         !is_null_sha1(cb.last_kept_sha1);
4007
4008                 if (close_lock_file(&reflog_lock)) {
4009                         status |= error("couldn't write %s: %s", log_file,
4010                                         strerror(errno));
4011                 } else if (update &&
4012                            (write_in_full(get_lock_file_fd(lock->lk),
4013                                 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
4014                             write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
4015                             close_ref(lock) < 0)) {
4016                         status |= error("couldn't write %s",
4017                                         get_lock_file_path(lock->lk));
4018                         rollback_lock_file(&reflog_lock);
4019                 } else if (commit_lock_file(&reflog_lock)) {
4020                         status |= error("unable to write reflog '%s' (%s)",
4021                                         log_file, strerror(errno));
4022                 } else if (update && commit_ref(lock)) {
4023                         status |= error("couldn't set %s", lock->ref_name);
4024                 }
4025         }
4026         free(log_file);
4027         unlock_ref(lock);
4028         return status;
4029
4030  failure:
4031         rollback_lock_file(&reflog_lock);
4032         free(log_file);
4033         unlock_ref(lock);
4034         return -1;
4035 }
4036
4037 struct ref_storage_be refs_be_files = {
4038         NULL,
4039         "files",
4040         files_ref_store_create,
4041         files_transaction_commit,
4042
4043         files_pack_refs,
4044         files_peel_ref,
4045         files_create_symref,
4046
4047         files_read_raw_ref,
4048         files_verify_refname_available
4049 };