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