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