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