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