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