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