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