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