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