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