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