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