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