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