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