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