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