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