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