refs.con commit free_ref_entry(): do not trigger reading of loose refs (27b5587)
   1#include "cache.h"
   2#include "refs.h"
   3#include "object.h"
   4#include "tag.h"
   5#include "dir.h"
   6
   7/*
   8 * Make sure "ref" is something reasonable to have under ".git/refs/";
   9 * We do not like it if:
  10 *
  11 * - any path component of it begins with ".", or
  12 * - it has double dots "..", or
  13 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
  14 * - it ends with a "/".
  15 * - it ends with ".lock"
  16 * - it contains a "\" (backslash)
  17 */
  18
  19/* Return true iff ch is not allowed in reference names. */
  20static inline int bad_ref_char(int ch)
  21{
  22        if (((unsigned) ch) <= ' ' || ch == 0x7f ||
  23            ch == '~' || ch == '^' || ch == ':' || ch == '\\')
  24                return 1;
  25        /* 2.13 Pattern Matching Notation */
  26        if (ch == '*' || ch == '?' || ch == '[') /* Unsupported */
  27                return 1;
  28        return 0;
  29}
  30
  31/*
  32 * Try to read one refname component from the front of refname.  Return
  33 * the length of the component found, or -1 if the component is not
  34 * legal.
  35 */
  36static int check_refname_component(const char *refname, int flags)
  37{
  38        const char *cp;
  39        char last = '\0';
  40
  41        for (cp = refname; ; cp++) {
  42                char ch = *cp;
  43                if (ch == '\0' || ch == '/')
  44                        break;
  45                if (bad_ref_char(ch))
  46                        return -1; /* Illegal character in refname. */
  47                if (last == '.' && ch == '.')
  48                        return -1; /* Refname contains "..". */
  49                if (last == '@' && ch == '{')
  50                        return -1; /* Refname contains "@{". */
  51                last = ch;
  52        }
  53        if (cp == refname)
  54                return 0; /* Component has zero length. */
  55        if (refname[0] == '.') {
  56                if (!(flags & REFNAME_DOT_COMPONENT))
  57                        return -1; /* Component starts with '.'. */
  58                /*
  59                 * Even if leading dots are allowed, don't allow "."
  60                 * as a component (".." is prevented by a rule above).
  61                 */
  62                if (refname[1] == '\0')
  63                        return -1; /* Component equals ".". */
  64        }
  65        if (cp - refname >= 5 && !memcmp(cp - 5, ".lock", 5))
  66                return -1; /* Refname ends with ".lock". */
  67        return cp - refname;
  68}
  69
  70int check_refname_format(const char *refname, int flags)
  71{
  72        int component_len, component_count = 0;
  73
  74        while (1) {
  75                /* We are at the start of a path component. */
  76                component_len = check_refname_component(refname, flags);
  77                if (component_len <= 0) {
  78                        if ((flags & REFNAME_REFSPEC_PATTERN) &&
  79                                        refname[0] == '*' &&
  80                                        (refname[1] == '\0' || refname[1] == '/')) {
  81                                /* Accept one wildcard as a full refname component. */
  82                                flags &= ~REFNAME_REFSPEC_PATTERN;
  83                                component_len = 1;
  84                        } else {
  85                                return -1;
  86                        }
  87                }
  88                component_count++;
  89                if (refname[component_len] == '\0')
  90                        break;
  91                /* Skip to next component. */
  92                refname += component_len + 1;
  93        }
  94
  95        if (refname[component_len - 1] == '.')
  96                return -1; /* Refname ends with '.'. */
  97        if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
  98                return -1; /* Refname has only one component. */
  99        return 0;
 100}
 101
 102struct ref_entry;
 103
 104/*
 105 * Information used (along with the information in ref_entry) to
 106 * describe a single cached reference.  This data structure only
 107 * occurs embedded in a union in struct ref_entry, and only when
 108 * (ref_entry->flag & REF_DIR) is zero.
 109 */
 110struct ref_value {
 111        unsigned char sha1[20];
 112        unsigned char peeled[20];
 113};
 114
 115struct ref_cache;
 116
 117/*
 118 * Information used (along with the information in ref_entry) to
 119 * describe a level in the hierarchy of references.  This data
 120 * structure only occurs embedded in a union in struct ref_entry, and
 121 * only when (ref_entry.flag & REF_DIR) is set.  In that case,
 122 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
 123 * in the directory have already been read:
 124 *
 125 *     (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
 126 *         or packed references, already read.
 127 *
 128 *     (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
 129 *         references that hasn't been read yet (nor has any of its
 130 *         subdirectories).
 131 *
 132 * Entries within a directory are stored within a growable array of
 133 * pointers to ref_entries (entries, nr, alloc).  Entries 0 <= i <
 134 * sorted are sorted by their component name in strcmp() order and the
 135 * remaining entries are unsorted.
 136 *
 137 * Loose references are read lazily, one directory at a time.  When a
 138 * directory of loose references is read, then all of the references
 139 * in that directory are stored, and REF_INCOMPLETE stubs are created
 140 * for any subdirectories, but the subdirectories themselves are not
 141 * read.  The reading is triggered by get_ref_dir().
 142 */
 143struct ref_dir {
 144        int nr, alloc;
 145
 146        /*
 147         * Entries with index 0 <= i < sorted are sorted by name.  New
 148         * entries are appended to the list unsorted, and are sorted
 149         * only when required; thus we avoid the need to sort the list
 150         * after the addition of every reference.
 151         */
 152        int sorted;
 153
 154        /* A pointer to the ref_cache that contains this ref_dir. */
 155        struct ref_cache *ref_cache;
 156
 157        struct ref_entry **entries;
 158};
 159
 160/* ISSYMREF=0x01, ISPACKED=0x02, and ISBROKEN=0x04 are public interfaces */
 161#define REF_KNOWS_PEELED 0x08
 162
 163/* ref_entry represents a directory of references */
 164#define REF_DIR 0x10
 165
 166/*
 167 * Entry has not yet been read from disk (used only for REF_DIR
 168 * entries representing loose references)
 169 */
 170#define REF_INCOMPLETE 0x20
 171
 172/*
 173 * A ref_entry represents either a reference or a "subdirectory" of
 174 * references.
 175 *
 176 * Each directory in the reference namespace is represented by a
 177 * ref_entry with (flags & REF_DIR) set and containing a subdir member
 178 * that holds the entries in that directory that have been read so
 179 * far.  If (flags & REF_INCOMPLETE) is set, then the directory and
 180 * its subdirectories haven't been read yet.  REF_INCOMPLETE is only
 181 * used for loose reference directories.
 182 *
 183 * References are represented by a ref_entry with (flags & REF_DIR)
 184 * unset and a value member that describes the reference's value.  The
 185 * flag member is at the ref_entry level, but it is also needed to
 186 * interpret the contents of the value field (in other words, a
 187 * ref_value object is not very much use without the enclosing
 188 * ref_entry).
 189 *
 190 * Reference names cannot end with slash and directories' names are
 191 * always stored with a trailing slash (except for the top-level
 192 * directory, which is always denoted by "").  This has two nice
 193 * consequences: (1) when the entries in each subdir are sorted
 194 * lexicographically by name (as they usually are), the references in
 195 * a whole tree can be generated in lexicographic order by traversing
 196 * the tree in left-to-right, depth-first order; (2) the names of
 197 * references and subdirectories cannot conflict, and therefore the
 198 * presence of an empty subdirectory does not block the creation of a
 199 * similarly-named reference.  (The fact that reference names with the
 200 * same leading components can conflict *with each other* is a
 201 * separate issue that is regulated by is_refname_available().)
 202 *
 203 * Please note that the name field contains the fully-qualified
 204 * reference (or subdirectory) name.  Space could be saved by only
 205 * storing the relative names.  But that would require the full names
 206 * to be generated on the fly when iterating in do_for_each_ref(), and
 207 * would break callback functions, who have always been able to assume
 208 * that the name strings that they are passed will not be freed during
 209 * the iteration.
 210 */
 211struct ref_entry {
 212        unsigned char flag; /* ISSYMREF? ISPACKED? */
 213        union {
 214                struct ref_value value; /* if not (flags&REF_DIR) */
 215                struct ref_dir subdir; /* if (flags&REF_DIR) */
 216        } u;
 217        /*
 218         * The full name of the reference (e.g., "refs/heads/master")
 219         * or the full name of the directory with a trailing slash
 220         * (e.g., "refs/heads/"):
 221         */
 222        char name[FLEX_ARRAY];
 223};
 224
 225static void read_loose_refs(const char *dirname, struct ref_dir *dir);
 226
 227static struct ref_dir *get_ref_dir(struct ref_entry *entry)
 228{
 229        struct ref_dir *dir;
 230        assert(entry->flag & REF_DIR);
 231        dir = &entry->u.subdir;
 232        if (entry->flag & REF_INCOMPLETE) {
 233                read_loose_refs(entry->name, dir);
 234                entry->flag &= ~REF_INCOMPLETE;
 235        }
 236        return dir;
 237}
 238
 239static struct ref_entry *create_ref_entry(const char *refname,
 240                                          const unsigned char *sha1, int flag,
 241                                          int check_name)
 242{
 243        int len;
 244        struct ref_entry *ref;
 245
 246        if (check_name &&
 247            check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT))
 248                die("Reference has invalid format: '%s'", refname);
 249        len = strlen(refname) + 1;
 250        ref = xmalloc(sizeof(struct ref_entry) + len);
 251        hashcpy(ref->u.value.sha1, sha1);
 252        hashclr(ref->u.value.peeled);
 253        memcpy(ref->name, refname, len);
 254        ref->flag = flag;
 255        return ref;
 256}
 257
 258static void clear_ref_dir(struct ref_dir *dir);
 259
 260static void free_ref_entry(struct ref_entry *entry)
 261{
 262        if (entry->flag & REF_DIR) {
 263                /*
 264                 * Do not use get_ref_dir() here, as that might
 265                 * trigger the reading of loose refs.
 266                 */
 267                clear_ref_dir(&entry->u.subdir);
 268        }
 269        free(entry);
 270}
 271
 272/*
 273 * Add a ref_entry to the end of dir (unsorted).  Entry is always
 274 * stored directly in dir; no recursion into subdirectories is
 275 * done.
 276 */
 277static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
 278{
 279        ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
 280        dir->entries[dir->nr++] = entry;
 281}
 282
 283/*
 284 * Clear and free all entries in dir, recursively.
 285 */
 286static void clear_ref_dir(struct ref_dir *dir)
 287{
 288        int i;
 289        for (i = 0; i < dir->nr; i++)
 290                free_ref_entry(dir->entries[i]);
 291        free(dir->entries);
 292        dir->sorted = dir->nr = dir->alloc = 0;
 293        dir->entries = NULL;
 294}
 295
 296/*
 297 * Create a struct ref_entry object for the specified dirname.
 298 * dirname is the name of the directory with a trailing slash (e.g.,
 299 * "refs/heads/") or "" for the top-level directory.
 300 */
 301static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
 302                                          const char *dirname, int incomplete)
 303{
 304        struct ref_entry *direntry;
 305        int len = strlen(dirname);
 306        direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
 307        memcpy(direntry->name, dirname, len + 1);
 308        direntry->u.subdir.ref_cache = ref_cache;
 309        direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
 310        return direntry;
 311}
 312
 313static int ref_entry_cmp(const void *a, const void *b)
 314{
 315        struct ref_entry *one = *(struct ref_entry **)a;
 316        struct ref_entry *two = *(struct ref_entry **)b;
 317        return strcmp(one->name, two->name);
 318}
 319
 320static void sort_ref_dir(struct ref_dir *dir);
 321
 322/*
 323 * Return the entry with the given refname from the ref_dir
 324 * (non-recursively), sorting dir if necessary.  Return NULL if no
 325 * such entry is found.  dir must already be complete.
 326 */
 327static struct ref_entry *search_ref_dir(struct ref_dir *dir, const char *refname)
 328{
 329        struct ref_entry *e, **r;
 330        int len;
 331
 332        if (refname == NULL || !dir->nr)
 333                return NULL;
 334
 335        sort_ref_dir(dir);
 336
 337        len = strlen(refname) + 1;
 338        e = xmalloc(sizeof(struct ref_entry) + len);
 339        memcpy(e->name, refname, len);
 340
 341        r = bsearch(&e, dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
 342
 343        free(e);
 344
 345        if (r == NULL)
 346                return NULL;
 347
 348        return *r;
 349}
 350
 351/*
 352 * Search for a directory entry directly within dir (without
 353 * recursing).  Sort dir if necessary.  subdirname must be a directory
 354 * name (i.e., end in '/').  If mkdir is set, then create the
 355 * directory if it is missing; otherwise, return NULL if the desired
 356 * directory cannot be found.  dir must already be complete.
 357 */
 358static struct ref_dir *search_for_subdir(struct ref_dir *dir,
 359                                         const char *subdirname, int mkdir)
 360{
 361        struct ref_entry *entry = search_ref_dir(dir, subdirname);
 362        if (!entry) {
 363                if (!mkdir)
 364                        return NULL;
 365                /*
 366                 * Since dir is complete, the absence of a subdir
 367                 * means that the subdir really doesn't exist;
 368                 * therefore, create an empty record for it but mark
 369                 * the record complete.
 370                 */
 371                entry = create_dir_entry(dir->ref_cache, subdirname, 0);
 372                add_entry_to_dir(dir, entry);
 373        }
 374        return get_ref_dir(entry);
 375}
 376
 377/*
 378 * If refname is a reference name, find the ref_dir within the dir
 379 * tree that should hold refname.  If refname is a directory name
 380 * (i.e., ends in '/'), then return that ref_dir itself.  dir must
 381 * represent the top-level directory and must already be complete.
 382 * Sort ref_dirs and recurse into subdirectories as necessary.  If
 383 * mkdir is set, then create any missing directories; otherwise,
 384 * return NULL if the desired directory cannot be found.
 385 */
 386static struct ref_dir *find_containing_dir(struct ref_dir *dir,
 387                                           const char *refname, int mkdir)
 388{
 389        struct strbuf dirname;
 390        const char *slash;
 391        strbuf_init(&dirname, PATH_MAX);
 392        for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
 393                struct ref_dir *subdir;
 394                strbuf_add(&dirname,
 395                           refname + dirname.len,
 396                           (slash + 1) - (refname + dirname.len));
 397                subdir = search_for_subdir(dir, dirname.buf, mkdir);
 398                if (!subdir) {
 399                        dir = NULL;
 400                        break;
 401                }
 402                dir = subdir;
 403        }
 404
 405        strbuf_release(&dirname);
 406        return dir;
 407}
 408
 409/*
 410 * Find the value entry with the given name in dir, sorting ref_dirs
 411 * and recursing into subdirectories as necessary.  If the name is not
 412 * found or it corresponds to a directory entry, return NULL.
 413 */
 414static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
 415{
 416        struct ref_entry *entry;
 417        dir = find_containing_dir(dir, refname, 0);
 418        if (!dir)
 419                return NULL;
 420        entry = search_ref_dir(dir, refname);
 421        return (entry && !(entry->flag & REF_DIR)) ? entry : NULL;
 422}
 423
 424/*
 425 * Add a ref_entry to the ref_dir (unsorted), recursing into
 426 * subdirectories as necessary.  dir must represent the top-level
 427 * directory.  Return 0 on success.
 428 */
 429static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
 430{
 431        dir = find_containing_dir(dir, ref->name, 1);
 432        if (!dir)
 433                return -1;
 434        add_entry_to_dir(dir, ref);
 435        return 0;
 436}
 437
 438/*
 439 * Emit a warning and return true iff ref1 and ref2 have the same name
 440 * and the same sha1.  Die if they have the same name but different
 441 * sha1s.
 442 */
 443static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
 444{
 445        if (strcmp(ref1->name, ref2->name))
 446                return 0;
 447
 448        /* Duplicate name; make sure that they don't conflict: */
 449
 450        if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
 451                /* This is impossible by construction */
 452                die("Reference directory conflict: %s", ref1->name);
 453
 454        if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
 455                die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
 456
 457        warning("Duplicated ref: %s", ref1->name);
 458        return 1;
 459}
 460
 461/*
 462 * Sort the entries in dir non-recursively (if they are not already
 463 * sorted) and remove any duplicate entries.
 464 */
 465static void sort_ref_dir(struct ref_dir *dir)
 466{
 467        int i, j;
 468        struct ref_entry *last = NULL;
 469
 470        /*
 471         * This check also prevents passing a zero-length array to qsort(),
 472         * which is a problem on some platforms.
 473         */
 474        if (dir->sorted == dir->nr)
 475                return;
 476
 477        qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
 478
 479        /* Remove any duplicates: */
 480        for (i = 0, j = 0; j < dir->nr; j++) {
 481                struct ref_entry *entry = dir->entries[j];
 482                if (last && is_dup_ref(last, entry))
 483                        free_ref_entry(entry);
 484                else
 485                        last = dir->entries[i++] = entry;
 486        }
 487        dir->sorted = dir->nr = i;
 488}
 489
 490#define DO_FOR_EACH_INCLUDE_BROKEN 01
 491
 492static struct ref_entry *current_ref;
 493
 494static int do_one_ref(const char *base, each_ref_fn fn, int trim,
 495                      int flags, void *cb_data, struct ref_entry *entry)
 496{
 497        int retval;
 498        if (prefixcmp(entry->name, base))
 499                return 0;
 500
 501        if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
 502                if (entry->flag & REF_ISBROKEN)
 503                        return 0; /* ignore broken refs e.g. dangling symref */
 504                if (!has_sha1_file(entry->u.value.sha1)) {
 505                        error("%s does not point to a valid object!", entry->name);
 506                        return 0;
 507                }
 508        }
 509        current_ref = entry;
 510        retval = fn(entry->name + trim, entry->u.value.sha1, entry->flag, cb_data);
 511        current_ref = NULL;
 512        return retval;
 513}
 514
 515/*
 516 * Call fn for each reference in dir that has index in the range
 517 * offset <= index < dir->nr.  Recurse into subdirectories that are in
 518 * that index range, sorting them before iterating.  This function
 519 * does not sort dir itself; it should be sorted beforehand.
 520 */
 521static int do_for_each_ref_in_dir(struct ref_dir *dir, int offset,
 522                                  const char *base,
 523                                  each_ref_fn fn, int trim, int flags, void *cb_data)
 524{
 525        int i;
 526        assert(dir->sorted == dir->nr);
 527        for (i = offset; i < dir->nr; i++) {
 528                struct ref_entry *entry = dir->entries[i];
 529                int retval;
 530                if (entry->flag & REF_DIR) {
 531                        struct ref_dir *subdir = get_ref_dir(entry);
 532                        sort_ref_dir(subdir);
 533                        retval = do_for_each_ref_in_dir(subdir, 0,
 534                                                        base, fn, trim, flags, cb_data);
 535                } else {
 536                        retval = do_one_ref(base, fn, trim, flags, cb_data, entry);
 537                }
 538                if (retval)
 539                        return retval;
 540        }
 541        return 0;
 542}
 543
 544/*
 545 * Call fn for each reference in the union of dir1 and dir2, in order
 546 * by refname.  Recurse into subdirectories.  If a value entry appears
 547 * in both dir1 and dir2, then only process the version that is in
 548 * dir2.  The input dirs must already be sorted, but subdirs will be
 549 * sorted as needed.
 550 */
 551static int do_for_each_ref_in_dirs(struct ref_dir *dir1,
 552                                   struct ref_dir *dir2,
 553                                   const char *base, each_ref_fn fn, int trim,
 554                                   int flags, void *cb_data)
 555{
 556        int retval;
 557        int i1 = 0, i2 = 0;
 558
 559        assert(dir1->sorted == dir1->nr);
 560        assert(dir2->sorted == dir2->nr);
 561        while (1) {
 562                struct ref_entry *e1, *e2;
 563                int cmp;
 564                if (i1 == dir1->nr) {
 565                        return do_for_each_ref_in_dir(dir2, i2,
 566                                                      base, fn, trim, flags, cb_data);
 567                }
 568                if (i2 == dir2->nr) {
 569                        return do_for_each_ref_in_dir(dir1, i1,
 570                                                      base, fn, trim, flags, cb_data);
 571                }
 572                e1 = dir1->entries[i1];
 573                e2 = dir2->entries[i2];
 574                cmp = strcmp(e1->name, e2->name);
 575                if (cmp == 0) {
 576                        if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
 577                                /* Both are directories; descend them in parallel. */
 578                                struct ref_dir *subdir1 = get_ref_dir(e1);
 579                                struct ref_dir *subdir2 = get_ref_dir(e2);
 580                                sort_ref_dir(subdir1);
 581                                sort_ref_dir(subdir2);
 582                                retval = do_for_each_ref_in_dirs(
 583                                                subdir1, subdir2,
 584                                                base, fn, trim, flags, cb_data);
 585                                i1++;
 586                                i2++;
 587                        } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
 588                                /* Both are references; ignore the one from dir1. */
 589                                retval = do_one_ref(base, fn, trim, flags, cb_data, e2);
 590                                i1++;
 591                                i2++;
 592                        } else {
 593                                die("conflict between reference and directory: %s",
 594                                    e1->name);
 595                        }
 596                } else {
 597                        struct ref_entry *e;
 598                        if (cmp < 0) {
 599                                e = e1;
 600                                i1++;
 601                        } else {
 602                                e = e2;
 603                                i2++;
 604                        }
 605                        if (e->flag & REF_DIR) {
 606                                struct ref_dir *subdir = get_ref_dir(e);
 607                                sort_ref_dir(subdir);
 608                                retval = do_for_each_ref_in_dir(
 609                                                subdir, 0,
 610                                                base, fn, trim, flags, cb_data);
 611                        } else {
 612                                retval = do_one_ref(base, fn, trim, flags, cb_data, e);
 613                        }
 614                }
 615                if (retval)
 616                        return retval;
 617        }
 618        if (i1 < dir1->nr)
 619                return do_for_each_ref_in_dir(dir1, i1,
 620                                              base, fn, trim, flags, cb_data);
 621        if (i2 < dir2->nr)
 622                return do_for_each_ref_in_dir(dir2, i2,
 623                                              base, fn, trim, flags, cb_data);
 624        return 0;
 625}
 626
 627/*
 628 * Return true iff refname1 and refname2 conflict with each other.
 629 * Two reference names conflict if one of them exactly matches the
 630 * leading components of the other; e.g., "foo/bar" conflicts with
 631 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
 632 * "foo/barbados".
 633 */
 634static int names_conflict(const char *refname1, const char *refname2)
 635{
 636        for (; *refname1 && *refname1 == *refname2; refname1++, refname2++)
 637                ;
 638        return (*refname1 == '\0' && *refname2 == '/')
 639                || (*refname1 == '/' && *refname2 == '\0');
 640}
 641
 642struct name_conflict_cb {
 643        const char *refname;
 644        const char *oldrefname;
 645        const char *conflicting_refname;
 646};
 647
 648static int name_conflict_fn(const char *existingrefname, const unsigned char *sha1,
 649                            int flags, void *cb_data)
 650{
 651        struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data;
 652        if (data->oldrefname && !strcmp(data->oldrefname, existingrefname))
 653                return 0;
 654        if (names_conflict(data->refname, existingrefname)) {
 655                data->conflicting_refname = existingrefname;
 656                return 1;
 657        }
 658        return 0;
 659}
 660
 661/*
 662 * Return true iff a reference named refname could be created without
 663 * conflicting with the name of an existing reference in array.  If
 664 * oldrefname is non-NULL, ignore potential conflicts with oldrefname
 665 * (e.g., because oldrefname is scheduled for deletion in the same
 666 * operation).
 667 */
 668static int is_refname_available(const char *refname, const char *oldrefname,
 669                                struct ref_dir *dir)
 670{
 671        struct name_conflict_cb data;
 672        data.refname = refname;
 673        data.oldrefname = oldrefname;
 674        data.conflicting_refname = NULL;
 675
 676        sort_ref_dir(dir);
 677        if (do_for_each_ref_in_dir(dir, 0, "", name_conflict_fn,
 678                                   0, DO_FOR_EACH_INCLUDE_BROKEN,
 679                                   &data)) {
 680                error("'%s' exists; cannot create '%s'",
 681                      data.conflicting_refname, refname);
 682                return 0;
 683        }
 684        return 1;
 685}
 686
 687/*
 688 * Future: need to be in "struct repository"
 689 * when doing a full libification.
 690 */
 691static struct ref_cache {
 692        struct ref_cache *next;
 693        struct ref_entry *loose;
 694        struct ref_entry *packed;
 695        /* The submodule name, or "" for the main repo. */
 696        char name[FLEX_ARRAY];
 697} *ref_cache;
 698
 699static void clear_packed_ref_cache(struct ref_cache *refs)
 700{
 701        if (refs->packed) {
 702                free_ref_entry(refs->packed);
 703                refs->packed = NULL;
 704        }
 705}
 706
 707static void clear_loose_ref_cache(struct ref_cache *refs)
 708{
 709        if (refs->loose) {
 710                free_ref_entry(refs->loose);
 711                refs->loose = NULL;
 712        }
 713}
 714
 715static struct ref_cache *create_ref_cache(const char *submodule)
 716{
 717        int len;
 718        struct ref_cache *refs;
 719        if (!submodule)
 720                submodule = "";
 721        len = strlen(submodule) + 1;
 722        refs = xcalloc(1, sizeof(struct ref_cache) + len);
 723        memcpy(refs->name, submodule, len);
 724        return refs;
 725}
 726
 727/*
 728 * Return a pointer to a ref_cache for the specified submodule. For
 729 * the main repository, use submodule==NULL. The returned structure
 730 * will be allocated and initialized but not necessarily populated; it
 731 * should not be freed.
 732 */
 733static struct ref_cache *get_ref_cache(const char *submodule)
 734{
 735        struct ref_cache *refs = ref_cache;
 736        if (!submodule)
 737                submodule = "";
 738        while (refs) {
 739                if (!strcmp(submodule, refs->name))
 740                        return refs;
 741                refs = refs->next;
 742        }
 743
 744        refs = create_ref_cache(submodule);
 745        refs->next = ref_cache;
 746        ref_cache = refs;
 747        return refs;
 748}
 749
 750void invalidate_ref_cache(const char *submodule)
 751{
 752        struct ref_cache *refs = get_ref_cache(submodule);
 753        clear_packed_ref_cache(refs);
 754        clear_loose_ref_cache(refs);
 755}
 756
 757/*
 758 * Parse one line from a packed-refs file.  Write the SHA1 to sha1.
 759 * Return a pointer to the refname within the line (null-terminated),
 760 * or NULL if there was a problem.
 761 */
 762static const char *parse_ref_line(char *line, unsigned char *sha1)
 763{
 764        /*
 765         * 42: the answer to everything.
 766         *
 767         * In this case, it happens to be the answer to
 768         *  40 (length of sha1 hex representation)
 769         *  +1 (space in between hex and name)
 770         *  +1 (newline at the end of the line)
 771         */
 772        int len = strlen(line) - 42;
 773
 774        if (len <= 0)
 775                return NULL;
 776        if (get_sha1_hex(line, sha1) < 0)
 777                return NULL;
 778        if (!isspace(line[40]))
 779                return NULL;
 780        line += 41;
 781        if (isspace(*line))
 782                return NULL;
 783        if (line[len] != '\n')
 784                return NULL;
 785        line[len] = 0;
 786
 787        return line;
 788}
 789
 790static void read_packed_refs(FILE *f, struct ref_dir *dir)
 791{
 792        struct ref_entry *last = NULL;
 793        char refline[PATH_MAX];
 794        int flag = REF_ISPACKED;
 795
 796        while (fgets(refline, sizeof(refline), f)) {
 797                unsigned char sha1[20];
 798                const char *refname;
 799                static const char header[] = "# pack-refs with:";
 800
 801                if (!strncmp(refline, header, sizeof(header)-1)) {
 802                        const char *traits = refline + sizeof(header) - 1;
 803                        if (strstr(traits, " peeled "))
 804                                flag |= REF_KNOWS_PEELED;
 805                        /* perhaps other traits later as well */
 806                        continue;
 807                }
 808
 809                refname = parse_ref_line(refline, sha1);
 810                if (refname) {
 811                        last = create_ref_entry(refname, sha1, flag, 1);
 812                        add_ref(dir, last);
 813                        continue;
 814                }
 815                if (last &&
 816                    refline[0] == '^' &&
 817                    strlen(refline) == 42 &&
 818                    refline[41] == '\n' &&
 819                    !get_sha1_hex(refline + 1, sha1))
 820                        hashcpy(last->u.value.peeled, sha1);
 821        }
 822}
 823
 824static struct ref_dir *get_packed_refs(struct ref_cache *refs)
 825{
 826        if (!refs->packed) {
 827                const char *packed_refs_file;
 828                FILE *f;
 829
 830                refs->packed = create_dir_entry(refs, "", 0);
 831                if (*refs->name)
 832                        packed_refs_file = git_path_submodule(refs->name, "packed-refs");
 833                else
 834                        packed_refs_file = git_path("packed-refs");
 835                f = fopen(packed_refs_file, "r");
 836                if (f) {
 837                        read_packed_refs(f, get_ref_dir(refs->packed));
 838                        fclose(f);
 839                }
 840        }
 841        return get_ref_dir(refs->packed);
 842}
 843
 844void add_packed_ref(const char *refname, const unsigned char *sha1)
 845{
 846        add_ref(get_packed_refs(get_ref_cache(NULL)),
 847                        create_ref_entry(refname, sha1, REF_ISPACKED, 1));
 848}
 849
 850/*
 851 * Read the loose references from the namespace dirname into dir
 852 * (without recursing).  dirname must end with '/'.  dir must be the
 853 * directory entry corresponding to dirname.
 854 */
 855static void read_loose_refs(const char *dirname, struct ref_dir *dir)
 856{
 857        struct ref_cache *refs = dir->ref_cache;
 858        DIR *d;
 859        const char *path;
 860        struct dirent *de;
 861        int dirnamelen = strlen(dirname);
 862        struct strbuf refname;
 863
 864        if (*refs->name)
 865                path = git_path_submodule(refs->name, "%s", dirname);
 866        else
 867                path = git_path("%s", dirname);
 868
 869        d = opendir(path);
 870        if (!d)
 871                return;
 872
 873        strbuf_init(&refname, dirnamelen + 257);
 874        strbuf_add(&refname, dirname, dirnamelen);
 875
 876        while ((de = readdir(d)) != NULL) {
 877                unsigned char sha1[20];
 878                struct stat st;
 879                int flag;
 880                const char *refdir;
 881
 882                if (de->d_name[0] == '.')
 883                        continue;
 884                if (has_extension(de->d_name, ".lock"))
 885                        continue;
 886                strbuf_addstr(&refname, de->d_name);
 887                refdir = *refs->name
 888                        ? git_path_submodule(refs->name, "%s", refname.buf)
 889                        : git_path("%s", refname.buf);
 890                if (stat(refdir, &st) < 0) {
 891                        ; /* silently ignore */
 892                } else if (S_ISDIR(st.st_mode)) {
 893                        strbuf_addch(&refname, '/');
 894                        add_entry_to_dir(dir,
 895                                         create_dir_entry(refs, refname.buf, 1));
 896                } else {
 897                        if (*refs->name) {
 898                                hashclr(sha1);
 899                                flag = 0;
 900                                if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
 901                                        hashclr(sha1);
 902                                        flag |= REF_ISBROKEN;
 903                                }
 904                        } else if (read_ref_full(refname.buf, sha1, 1, &flag)) {
 905                                hashclr(sha1);
 906                                flag |= REF_ISBROKEN;
 907                        }
 908                        add_entry_to_dir(dir,
 909                                         create_ref_entry(refname.buf, sha1, flag, 1));
 910                }
 911                strbuf_setlen(&refname, dirnamelen);
 912        }
 913        strbuf_release(&refname);
 914        closedir(d);
 915}
 916
 917static struct ref_dir *get_loose_refs(struct ref_cache *refs)
 918{
 919        if (!refs->loose) {
 920                /*
 921                 * Mark the top-level directory complete because we
 922                 * are about to read the only subdirectory that can
 923                 * hold references:
 924                 */
 925                refs->loose = create_dir_entry(refs, "", 0);
 926                /*
 927                 * Create an incomplete entry for "refs/":
 928                 */
 929                add_entry_to_dir(get_ref_dir(refs->loose),
 930                                 create_dir_entry(refs, "refs/", 1));
 931        }
 932        return get_ref_dir(refs->loose);
 933}
 934
 935/* We allow "recursive" symbolic refs. Only within reason, though */
 936#define MAXDEPTH 5
 937#define MAXREFLEN (1024)
 938
 939/*
 940 * Called by resolve_gitlink_ref_recursive() after it failed to read
 941 * from the loose refs in ref_cache refs. Find <refname> in the
 942 * packed-refs file for the submodule.
 943 */
 944static int resolve_gitlink_packed_ref(struct ref_cache *refs,
 945                                      const char *refname, unsigned char *sha1)
 946{
 947        struct ref_entry *ref;
 948        struct ref_dir *dir = get_packed_refs(refs);
 949
 950        ref = find_ref(dir, refname);
 951        if (ref == NULL)
 952                return -1;
 953
 954        memcpy(sha1, ref->u.value.sha1, 20);
 955        return 0;
 956}
 957
 958static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
 959                                         const char *refname, unsigned char *sha1,
 960                                         int recursion)
 961{
 962        int fd, len;
 963        char buffer[128], *p;
 964        char *path;
 965
 966        if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
 967                return -1;
 968        path = *refs->name
 969                ? git_path_submodule(refs->name, "%s", refname)
 970                : git_path("%s", refname);
 971        fd = open(path, O_RDONLY);
 972        if (fd < 0)
 973                return resolve_gitlink_packed_ref(refs, refname, sha1);
 974
 975        len = read(fd, buffer, sizeof(buffer)-1);
 976        close(fd);
 977        if (len < 0)
 978                return -1;
 979        while (len && isspace(buffer[len-1]))
 980                len--;
 981        buffer[len] = 0;
 982
 983        /* Was it a detached head or an old-fashioned symlink? */
 984        if (!get_sha1_hex(buffer, sha1))
 985                return 0;
 986
 987        /* Symref? */
 988        if (strncmp(buffer, "ref:", 4))
 989                return -1;
 990        p = buffer + 4;
 991        while (isspace(*p))
 992                p++;
 993
 994        return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
 995}
 996
 997int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
 998{
 999        int len = strlen(path), retval;
1000        char *submodule;
1001        struct ref_cache *refs;
1002
1003        while (len && path[len-1] == '/')
1004                len--;
1005        if (!len)
1006                return -1;
1007        submodule = xstrndup(path, len);
1008        refs = get_ref_cache(submodule);
1009        free(submodule);
1010
1011        retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1012        return retval;
1013}
1014
1015/*
1016 * Try to read ref from the packed references.  On success, set sha1
1017 * and return 0; otherwise, return -1.
1018 */
1019static int get_packed_ref(const char *refname, unsigned char *sha1)
1020{
1021        struct ref_dir *packed = get_packed_refs(get_ref_cache(NULL));
1022        struct ref_entry *entry = find_ref(packed, refname);
1023        if (entry) {
1024                hashcpy(sha1, entry->u.value.sha1);
1025                return 0;
1026        }
1027        return -1;
1028}
1029
1030const char *resolve_ref_unsafe(const char *refname, unsigned char *sha1, int reading, int *flag)
1031{
1032        int depth = MAXDEPTH;
1033        ssize_t len;
1034        char buffer[256];
1035        static char refname_buffer[256];
1036
1037        if (flag)
1038                *flag = 0;
1039
1040        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1041                return NULL;
1042
1043        for (;;) {
1044                char path[PATH_MAX];
1045                struct stat st;
1046                char *buf;
1047                int fd;
1048
1049                if (--depth < 0)
1050                        return NULL;
1051
1052                git_snpath(path, sizeof(path), "%s", refname);
1053
1054                if (lstat(path, &st) < 0) {
1055                        if (errno != ENOENT)
1056                                return NULL;
1057                        /*
1058                         * The loose reference file does not exist;
1059                         * check for a packed reference.
1060                         */
1061                        if (!get_packed_ref(refname, sha1)) {
1062                                if (flag)
1063                                        *flag |= REF_ISPACKED;
1064                                return refname;
1065                        }
1066                        /* The reference is not a packed reference, either. */
1067                        if (reading) {
1068                                return NULL;
1069                        } else {
1070                                hashclr(sha1);
1071                                return refname;
1072                        }
1073                }
1074
1075                /* Follow "normalized" - ie "refs/.." symlinks by hand */
1076                if (S_ISLNK(st.st_mode)) {
1077                        len = readlink(path, buffer, sizeof(buffer)-1);
1078                        if (len < 0)
1079                                return NULL;
1080                        buffer[len] = 0;
1081                        if (!prefixcmp(buffer, "refs/") &&
1082                                        !check_refname_format(buffer, 0)) {
1083                                strcpy(refname_buffer, buffer);
1084                                refname = refname_buffer;
1085                                if (flag)
1086                                        *flag |= REF_ISSYMREF;
1087                                continue;
1088                        }
1089                }
1090
1091                /* Is it a directory? */
1092                if (S_ISDIR(st.st_mode)) {
1093                        errno = EISDIR;
1094                        return NULL;
1095                }
1096
1097                /*
1098                 * Anything else, just open it and try to use it as
1099                 * a ref
1100                 */
1101                fd = open(path, O_RDONLY);
1102                if (fd < 0)
1103                        return NULL;
1104                len = read_in_full(fd, buffer, sizeof(buffer)-1);
1105                close(fd);
1106                if (len < 0)
1107                        return NULL;
1108                while (len && isspace(buffer[len-1]))
1109                        len--;
1110                buffer[len] = '\0';
1111
1112                /*
1113                 * Is it a symbolic ref?
1114                 */
1115                if (prefixcmp(buffer, "ref:"))
1116                        break;
1117                if (flag)
1118                        *flag |= REF_ISSYMREF;
1119                buf = buffer + 4;
1120                while (isspace(*buf))
1121                        buf++;
1122                if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1123                        if (flag)
1124                                *flag |= REF_ISBROKEN;
1125                        return NULL;
1126                }
1127                refname = strcpy(refname_buffer, buf);
1128        }
1129        /* Please note that FETCH_HEAD has a second line containing other data. */
1130        if (get_sha1_hex(buffer, sha1) || (buffer[40] != '\0' && !isspace(buffer[40]))) {
1131                if (flag)
1132                        *flag |= REF_ISBROKEN;
1133                return NULL;
1134        }
1135        return refname;
1136}
1137
1138char *resolve_refdup(const char *ref, unsigned char *sha1, int reading, int *flag)
1139{
1140        const char *ret = resolve_ref_unsafe(ref, sha1, reading, flag);
1141        return ret ? xstrdup(ret) : NULL;
1142}
1143
1144/* The argument to filter_refs */
1145struct ref_filter {
1146        const char *pattern;
1147        each_ref_fn *fn;
1148        void *cb_data;
1149};
1150
1151int read_ref_full(const char *refname, unsigned char *sha1, int reading, int *flags)
1152{
1153        if (resolve_ref_unsafe(refname, sha1, reading, flags))
1154                return 0;
1155        return -1;
1156}
1157
1158int read_ref(const char *refname, unsigned char *sha1)
1159{
1160        return read_ref_full(refname, sha1, 1, NULL);
1161}
1162
1163int ref_exists(const char *refname)
1164{
1165        unsigned char sha1[20];
1166        return !!resolve_ref_unsafe(refname, sha1, 1, NULL);
1167}
1168
1169static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1170                       void *data)
1171{
1172        struct ref_filter *filter = (struct ref_filter *)data;
1173        if (fnmatch(filter->pattern, refname, 0))
1174                return 0;
1175        return filter->fn(refname, sha1, flags, filter->cb_data);
1176}
1177
1178int peel_ref(const char *refname, unsigned char *sha1)
1179{
1180        int flag;
1181        unsigned char base[20];
1182        struct object *o;
1183
1184        if (current_ref && (current_ref->name == refname
1185                || !strcmp(current_ref->name, refname))) {
1186                if (current_ref->flag & REF_KNOWS_PEELED) {
1187                        hashcpy(sha1, current_ref->u.value.peeled);
1188                        return 0;
1189                }
1190                hashcpy(base, current_ref->u.value.sha1);
1191                goto fallback;
1192        }
1193
1194        if (read_ref_full(refname, base, 1, &flag))
1195                return -1;
1196
1197        if ((flag & REF_ISPACKED)) {
1198                struct ref_dir *dir = get_packed_refs(get_ref_cache(NULL));
1199                struct ref_entry *r = find_ref(dir, refname);
1200
1201                if (r != NULL && r->flag & REF_KNOWS_PEELED) {
1202                        hashcpy(sha1, r->u.value.peeled);
1203                        return 0;
1204                }
1205        }
1206
1207fallback:
1208        o = parse_object(base);
1209        if (o && o->type == OBJ_TAG) {
1210                o = deref_tag(o, refname, 0);
1211                if (o) {
1212                        hashcpy(sha1, o->sha1);
1213                        return 0;
1214                }
1215        }
1216        return -1;
1217}
1218
1219struct warn_if_dangling_data {
1220        FILE *fp;
1221        const char *refname;
1222        const char *msg_fmt;
1223};
1224
1225static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1226                                   int flags, void *cb_data)
1227{
1228        struct warn_if_dangling_data *d = cb_data;
1229        const char *resolves_to;
1230        unsigned char junk[20];
1231
1232        if (!(flags & REF_ISSYMREF))
1233                return 0;
1234
1235        resolves_to = resolve_ref_unsafe(refname, junk, 0, NULL);
1236        if (!resolves_to || strcmp(resolves_to, d->refname))
1237                return 0;
1238
1239        fprintf(d->fp, d->msg_fmt, refname);
1240        return 0;
1241}
1242
1243void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1244{
1245        struct warn_if_dangling_data data;
1246
1247        data.fp = fp;
1248        data.refname = refname;
1249        data.msg_fmt = msg_fmt;
1250        for_each_rawref(warn_if_dangling_symref, &data);
1251}
1252
1253static int do_for_each_ref(const char *submodule, const char *base, each_ref_fn fn,
1254                           int trim, int flags, void *cb_data)
1255{
1256        struct ref_cache *refs = get_ref_cache(submodule);
1257        struct ref_dir *packed_dir = get_packed_refs(refs);
1258        struct ref_dir *loose_dir = get_loose_refs(refs);
1259        int retval = 0;
1260
1261        if (base && *base) {
1262                packed_dir = find_containing_dir(packed_dir, base, 0);
1263                loose_dir = find_containing_dir(loose_dir, base, 0);
1264        }
1265
1266        if (packed_dir && loose_dir) {
1267                sort_ref_dir(packed_dir);
1268                sort_ref_dir(loose_dir);
1269                retval = do_for_each_ref_in_dirs(
1270                                packed_dir, loose_dir,
1271                                base, fn, trim, flags, cb_data);
1272        } else if (packed_dir) {
1273                sort_ref_dir(packed_dir);
1274                retval = do_for_each_ref_in_dir(
1275                                packed_dir, 0,
1276                                base, fn, trim, flags, cb_data);
1277        } else if (loose_dir) {
1278                sort_ref_dir(loose_dir);
1279                retval = do_for_each_ref_in_dir(
1280                                loose_dir, 0,
1281                                base, fn, trim, flags, cb_data);
1282        }
1283
1284        return retval;
1285}
1286
1287static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1288{
1289        unsigned char sha1[20];
1290        int flag;
1291
1292        if (submodule) {
1293                if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1294                        return fn("HEAD", sha1, 0, cb_data);
1295
1296                return 0;
1297        }
1298
1299        if (!read_ref_full("HEAD", sha1, 1, &flag))
1300                return fn("HEAD", sha1, flag, cb_data);
1301
1302        return 0;
1303}
1304
1305int head_ref(each_ref_fn fn, void *cb_data)
1306{
1307        return do_head_ref(NULL, fn, cb_data);
1308}
1309
1310int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1311{
1312        return do_head_ref(submodule, fn, cb_data);
1313}
1314
1315int for_each_ref(each_ref_fn fn, void *cb_data)
1316{
1317        return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
1318}
1319
1320int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1321{
1322        return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
1323}
1324
1325int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1326{
1327        return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
1328}
1329
1330int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1331                each_ref_fn fn, void *cb_data)
1332{
1333        return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
1334}
1335
1336int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1337{
1338        return for_each_ref_in("refs/tags/", fn, cb_data);
1339}
1340
1341int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1342{
1343        return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1344}
1345
1346int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1347{
1348        return for_each_ref_in("refs/heads/", fn, cb_data);
1349}
1350
1351int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1352{
1353        return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1354}
1355
1356int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1357{
1358        return for_each_ref_in("refs/remotes/", fn, cb_data);
1359}
1360
1361int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1362{
1363        return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
1364}
1365
1366int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1367{
1368        return do_for_each_ref(NULL, "refs/replace/", fn, 13, 0, cb_data);
1369}
1370
1371int head_ref_namespaced(each_ref_fn fn, void *cb_data)
1372{
1373        struct strbuf buf = STRBUF_INIT;
1374        int ret = 0;
1375        unsigned char sha1[20];
1376        int flag;
1377
1378        strbuf_addf(&buf, "%sHEAD", get_git_namespace());
1379        if (!read_ref_full(buf.buf, sha1, 1, &flag))
1380                ret = fn(buf.buf, sha1, flag, cb_data);
1381        strbuf_release(&buf);
1382
1383        return ret;
1384}
1385
1386int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1387{
1388        struct strbuf buf = STRBUF_INIT;
1389        int ret;
1390        strbuf_addf(&buf, "%srefs/", get_git_namespace());
1391        ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
1392        strbuf_release(&buf);
1393        return ret;
1394}
1395
1396int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
1397        const char *prefix, void *cb_data)
1398{
1399        struct strbuf real_pattern = STRBUF_INIT;
1400        struct ref_filter filter;
1401        int ret;
1402
1403        if (!prefix && prefixcmp(pattern, "refs/"))
1404                strbuf_addstr(&real_pattern, "refs/");
1405        else if (prefix)
1406                strbuf_addstr(&real_pattern, prefix);
1407        strbuf_addstr(&real_pattern, pattern);
1408
1409        if (!has_glob_specials(pattern)) {
1410                /* Append implied '/' '*' if not present. */
1411                if (real_pattern.buf[real_pattern.len - 1] != '/')
1412                        strbuf_addch(&real_pattern, '/');
1413                /* No need to check for '*', there is none. */
1414                strbuf_addch(&real_pattern, '*');
1415        }
1416
1417        filter.pattern = real_pattern.buf;
1418        filter.fn = fn;
1419        filter.cb_data = cb_data;
1420        ret = for_each_ref(filter_refs, &filter);
1421
1422        strbuf_release(&real_pattern);
1423        return ret;
1424}
1425
1426int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
1427{
1428        return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
1429}
1430
1431int for_each_rawref(each_ref_fn fn, void *cb_data)
1432{
1433        return do_for_each_ref(NULL, "", fn, 0,
1434                               DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1435}
1436
1437const char *prettify_refname(const char *name)
1438{
1439        return name + (
1440                !prefixcmp(name, "refs/heads/") ? 11 :
1441                !prefixcmp(name, "refs/tags/") ? 10 :
1442                !prefixcmp(name, "refs/remotes/") ? 13 :
1443                0);
1444}
1445
1446const char *ref_rev_parse_rules[] = {
1447        "%.*s",
1448        "refs/%.*s",
1449        "refs/tags/%.*s",
1450        "refs/heads/%.*s",
1451        "refs/remotes/%.*s",
1452        "refs/remotes/%.*s/HEAD",
1453        NULL
1454};
1455
1456int refname_match(const char *abbrev_name, const char *full_name, const char **rules)
1457{
1458        const char **p;
1459        const int abbrev_name_len = strlen(abbrev_name);
1460
1461        for (p = rules; *p; p++) {
1462                if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1463                        return 1;
1464                }
1465        }
1466
1467        return 0;
1468}
1469
1470static struct ref_lock *verify_lock(struct ref_lock *lock,
1471        const unsigned char *old_sha1, int mustexist)
1472{
1473        if (read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
1474                error("Can't verify ref %s", lock->ref_name);
1475                unlock_ref(lock);
1476                return NULL;
1477        }
1478        if (hashcmp(lock->old_sha1, old_sha1)) {
1479                error("Ref %s is at %s but expected %s", lock->ref_name,
1480                        sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1481                unlock_ref(lock);
1482                return NULL;
1483        }
1484        return lock;
1485}
1486
1487static int remove_empty_directories(const char *file)
1488{
1489        /* we want to create a file but there is a directory there;
1490         * if that is an empty directory (or a directory that contains
1491         * only empty directories), remove them.
1492         */
1493        struct strbuf path;
1494        int result;
1495
1496        strbuf_init(&path, 20);
1497        strbuf_addstr(&path, file);
1498
1499        result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
1500
1501        strbuf_release(&path);
1502
1503        return result;
1504}
1505
1506/*
1507 * *string and *len will only be substituted, and *string returned (for
1508 * later free()ing) if the string passed in is a magic short-hand form
1509 * to name a branch.
1510 */
1511static char *substitute_branch_name(const char **string, int *len)
1512{
1513        struct strbuf buf = STRBUF_INIT;
1514        int ret = interpret_branch_name(*string, &buf);
1515
1516        if (ret == *len) {
1517                size_t size;
1518                *string = strbuf_detach(&buf, &size);
1519                *len = size;
1520                return (char *)*string;
1521        }
1522
1523        return NULL;
1524}
1525
1526int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
1527{
1528        char *last_branch = substitute_branch_name(&str, &len);
1529        const char **p, *r;
1530        int refs_found = 0;
1531
1532        *ref = NULL;
1533        for (p = ref_rev_parse_rules; *p; p++) {
1534                char fullref[PATH_MAX];
1535                unsigned char sha1_from_ref[20];
1536                unsigned char *this_result;
1537                int flag;
1538
1539                this_result = refs_found ? sha1_from_ref : sha1;
1540                mksnpath(fullref, sizeof(fullref), *p, len, str);
1541                r = resolve_ref_unsafe(fullref, this_result, 1, &flag);
1542                if (r) {
1543                        if (!refs_found++)
1544                                *ref = xstrdup(r);
1545                        if (!warn_ambiguous_refs)
1546                                break;
1547                } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
1548                        warning("ignoring dangling symref %s.", fullref);
1549                } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
1550                        warning("ignoring broken ref %s.", fullref);
1551                }
1552        }
1553        free(last_branch);
1554        return refs_found;
1555}
1556
1557int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
1558{
1559        char *last_branch = substitute_branch_name(&str, &len);
1560        const char **p;
1561        int logs_found = 0;
1562
1563        *log = NULL;
1564        for (p = ref_rev_parse_rules; *p; p++) {
1565                struct stat st;
1566                unsigned char hash[20];
1567                char path[PATH_MAX];
1568                const char *ref, *it;
1569
1570                mksnpath(path, sizeof(path), *p, len, str);
1571                ref = resolve_ref_unsafe(path, hash, 1, NULL);
1572                if (!ref)
1573                        continue;
1574                if (!stat(git_path("logs/%s", path), &st) &&
1575                    S_ISREG(st.st_mode))
1576                        it = path;
1577                else if (strcmp(ref, path) &&
1578                         !stat(git_path("logs/%s", ref), &st) &&
1579                         S_ISREG(st.st_mode))
1580                        it = ref;
1581                else
1582                        continue;
1583                if (!logs_found++) {
1584                        *log = xstrdup(it);
1585                        hashcpy(sha1, hash);
1586                }
1587                if (!warn_ambiguous_refs)
1588                        break;
1589        }
1590        free(last_branch);
1591        return logs_found;
1592}
1593
1594static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1595                                            const unsigned char *old_sha1,
1596                                            int flags, int *type_p)
1597{
1598        char *ref_file;
1599        const char *orig_refname = refname;
1600        struct ref_lock *lock;
1601        int last_errno = 0;
1602        int type, lflags;
1603        int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1604        int missing = 0;
1605
1606        lock = xcalloc(1, sizeof(struct ref_lock));
1607        lock->lock_fd = -1;
1608
1609        refname = resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);
1610        if (!refname && errno == EISDIR) {
1611                /* we are trying to lock foo but we used to
1612                 * have foo/bar which now does not exist;
1613                 * it is normal for the empty directory 'foo'
1614                 * to remain.
1615                 */
1616                ref_file = git_path("%s", orig_refname);
1617                if (remove_empty_directories(ref_file)) {
1618                        last_errno = errno;
1619                        error("there are still refs under '%s'", orig_refname);
1620                        goto error_return;
1621                }
1622                refname = resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);
1623        }
1624        if (type_p)
1625            *type_p = type;
1626        if (!refname) {
1627                last_errno = errno;
1628                error("unable to resolve reference %s: %s",
1629                        orig_refname, strerror(errno));
1630                goto error_return;
1631        }
1632        missing = is_null_sha1(lock->old_sha1);
1633        /* When the ref did not exist and we are creating it,
1634         * make sure there is no existing ref that is packed
1635         * whose name begins with our refname, nor a ref whose
1636         * name is a proper prefix of our refname.
1637         */
1638        if (missing &&
1639             !is_refname_available(refname, NULL, get_packed_refs(get_ref_cache(NULL)))) {
1640                last_errno = ENOTDIR;
1641                goto error_return;
1642        }
1643
1644        lock->lk = xcalloc(1, sizeof(struct lock_file));
1645
1646        lflags = LOCK_DIE_ON_ERROR;
1647        if (flags & REF_NODEREF) {
1648                refname = orig_refname;
1649                lflags |= LOCK_NODEREF;
1650        }
1651        lock->ref_name = xstrdup(refname);
1652        lock->orig_ref_name = xstrdup(orig_refname);
1653        ref_file = git_path("%s", refname);
1654        if (missing)
1655                lock->force_write = 1;
1656        if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
1657                lock->force_write = 1;
1658
1659        if (safe_create_leading_directories(ref_file)) {
1660                last_errno = errno;
1661                error("unable to create directory for %s", ref_file);
1662                goto error_return;
1663        }
1664
1665        lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
1666        return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
1667
1668 error_return:
1669        unlock_ref(lock);
1670        errno = last_errno;
1671        return NULL;
1672}
1673
1674struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1)
1675{
1676        char refpath[PATH_MAX];
1677        if (check_refname_format(refname, 0))
1678                return NULL;
1679        strcpy(refpath, mkpath("refs/%s", refname));
1680        return lock_ref_sha1_basic(refpath, old_sha1, 0, NULL);
1681}
1682
1683struct ref_lock *lock_any_ref_for_update(const char *refname,
1684                                         const unsigned char *old_sha1, int flags)
1685{
1686        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1687                return NULL;
1688        return lock_ref_sha1_basic(refname, old_sha1, flags, NULL);
1689}
1690
1691struct repack_without_ref_sb {
1692        const char *refname;
1693        int fd;
1694};
1695
1696static int repack_without_ref_fn(const char *refname, const unsigned char *sha1,
1697                                 int flags, void *cb_data)
1698{
1699        struct repack_without_ref_sb *data = cb_data;
1700        char line[PATH_MAX + 100];
1701        int len;
1702
1703        if (!strcmp(data->refname, refname))
1704                return 0;
1705        len = snprintf(line, sizeof(line), "%s %s\n",
1706                       sha1_to_hex(sha1), refname);
1707        /* this should not happen but just being defensive */
1708        if (len > sizeof(line))
1709                die("too long a refname '%s'", refname);
1710        write_or_die(data->fd, line, len);
1711        return 0;
1712}
1713
1714static struct lock_file packlock;
1715
1716static int repack_without_ref(const char *refname)
1717{
1718        struct repack_without_ref_sb data;
1719        struct ref_dir *packed = get_packed_refs(get_ref_cache(NULL));
1720        if (find_ref(packed, refname) == NULL)
1721                return 0;
1722        data.refname = refname;
1723        data.fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
1724        if (data.fd < 0) {
1725                unable_to_lock_error(git_path("packed-refs"), errno);
1726                return error("cannot delete '%s' from packed refs", refname);
1727        }
1728        do_for_each_ref_in_dir(packed, 0, "", repack_without_ref_fn, 0, 0, &data);
1729        return commit_lock_file(&packlock);
1730}
1731
1732int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
1733{
1734        struct ref_lock *lock;
1735        int err, i = 0, ret = 0, flag = 0;
1736
1737        lock = lock_ref_sha1_basic(refname, sha1, 0, &flag);
1738        if (!lock)
1739                return 1;
1740        if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
1741                /* loose */
1742                const char *path;
1743
1744                if (!(delopt & REF_NODEREF)) {
1745                        i = strlen(lock->lk->filename) - 5; /* .lock */
1746                        lock->lk->filename[i] = 0;
1747                        path = lock->lk->filename;
1748                } else {
1749                        path = git_path("%s", refname);
1750                }
1751                err = unlink_or_warn(path);
1752                if (err && errno != ENOENT)
1753                        ret = 1;
1754
1755                if (!(delopt & REF_NODEREF))
1756                        lock->lk->filename[i] = '.';
1757        }
1758        /* removing the loose one could have resurrected an earlier
1759         * packed one.  Also, if it was not loose we need to repack
1760         * without it.
1761         */
1762        ret |= repack_without_ref(refname);
1763
1764        unlink_or_warn(git_path("logs/%s", lock->ref_name));
1765        invalidate_ref_cache(NULL);
1766        unlock_ref(lock);
1767        return ret;
1768}
1769
1770/*
1771 * People using contrib's git-new-workdir have .git/logs/refs ->
1772 * /some/other/path/.git/logs/refs, and that may live on another device.
1773 *
1774 * IOW, to avoid cross device rename errors, the temporary renamed log must
1775 * live into logs/refs.
1776 */
1777#define TMP_RENAMED_LOG  "logs/refs/.tmp-renamed-log"
1778
1779int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
1780{
1781        unsigned char sha1[20], orig_sha1[20];
1782        int flag = 0, logmoved = 0;
1783        struct ref_lock *lock;
1784        struct stat loginfo;
1785        int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
1786        const char *symref = NULL;
1787        struct ref_cache *refs = get_ref_cache(NULL);
1788
1789        if (log && S_ISLNK(loginfo.st_mode))
1790                return error("reflog for %s is a symlink", oldrefname);
1791
1792        symref = resolve_ref_unsafe(oldrefname, orig_sha1, 1, &flag);
1793        if (flag & REF_ISSYMREF)
1794                return error("refname %s is a symbolic ref, renaming it is not supported",
1795                        oldrefname);
1796        if (!symref)
1797                return error("refname %s not found", oldrefname);
1798
1799        if (!is_refname_available(newrefname, oldrefname, get_packed_refs(refs)))
1800                return 1;
1801
1802        if (!is_refname_available(newrefname, oldrefname, get_loose_refs(refs)))
1803                return 1;
1804
1805        if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
1806                return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
1807                        oldrefname, strerror(errno));
1808
1809        if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
1810                error("unable to delete old %s", oldrefname);
1811                goto rollback;
1812        }
1813
1814        if (!read_ref_full(newrefname, sha1, 1, &flag) &&
1815            delete_ref(newrefname, sha1, REF_NODEREF)) {
1816                if (errno==EISDIR) {
1817                        if (remove_empty_directories(git_path("%s", newrefname))) {
1818                                error("Directory not empty: %s", newrefname);
1819                                goto rollback;
1820                        }
1821                } else {
1822                        error("unable to delete existing %s", newrefname);
1823                        goto rollback;
1824                }
1825        }
1826
1827        if (log && safe_create_leading_directories(git_path("logs/%s", newrefname))) {
1828                error("unable to create directory for %s", newrefname);
1829                goto rollback;
1830        }
1831
1832 retry:
1833        if (log && rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
1834                if (errno==EISDIR || errno==ENOTDIR) {
1835                        /*
1836                         * rename(a, b) when b is an existing
1837                         * directory ought to result in ISDIR, but
1838                         * Solaris 5.8 gives ENOTDIR.  Sheesh.
1839                         */
1840                        if (remove_empty_directories(git_path("logs/%s", newrefname))) {
1841                                error("Directory not empty: logs/%s", newrefname);
1842                                goto rollback;
1843                        }
1844                        goto retry;
1845                } else {
1846                        error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
1847                                newrefname, strerror(errno));
1848                        goto rollback;
1849                }
1850        }
1851        logmoved = log;
1852
1853        lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL);
1854        if (!lock) {
1855                error("unable to lock %s for update", newrefname);
1856                goto rollback;
1857        }
1858        lock->force_write = 1;
1859        hashcpy(lock->old_sha1, orig_sha1);
1860        if (write_ref_sha1(lock, orig_sha1, logmsg)) {
1861                error("unable to write current sha1 into %s", newrefname);
1862                goto rollback;
1863        }
1864
1865        return 0;
1866
1867 rollback:
1868        lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL);
1869        if (!lock) {
1870                error("unable to lock %s for rollback", oldrefname);
1871                goto rollbacklog;
1872        }
1873
1874        lock->force_write = 1;
1875        flag = log_all_ref_updates;
1876        log_all_ref_updates = 0;
1877        if (write_ref_sha1(lock, orig_sha1, NULL))
1878                error("unable to write current sha1 into %s", oldrefname);
1879        log_all_ref_updates = flag;
1880
1881 rollbacklog:
1882        if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
1883                error("unable to restore logfile %s from %s: %s",
1884                        oldrefname, newrefname, strerror(errno));
1885        if (!logmoved && log &&
1886            rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
1887                error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
1888                        oldrefname, strerror(errno));
1889
1890        return 1;
1891}
1892
1893int close_ref(struct ref_lock *lock)
1894{
1895        if (close_lock_file(lock->lk))
1896                return -1;
1897        lock->lock_fd = -1;
1898        return 0;
1899}
1900
1901int commit_ref(struct ref_lock *lock)
1902{
1903        if (commit_lock_file(lock->lk))
1904                return -1;
1905        lock->lock_fd = -1;
1906        return 0;
1907}
1908
1909void unlock_ref(struct ref_lock *lock)
1910{
1911        /* Do not free lock->lk -- atexit() still looks at them */
1912        if (lock->lk)
1913                rollback_lock_file(lock->lk);
1914        free(lock->ref_name);
1915        free(lock->orig_ref_name);
1916        free(lock);
1917}
1918
1919/*
1920 * copy the reflog message msg to buf, which has been allocated sufficiently
1921 * large, while cleaning up the whitespaces.  Especially, convert LF to space,
1922 * because reflog file is one line per entry.
1923 */
1924static int copy_msg(char *buf, const char *msg)
1925{
1926        char *cp = buf;
1927        char c;
1928        int wasspace = 1;
1929
1930        *cp++ = '\t';
1931        while ((c = *msg++)) {
1932                if (wasspace && isspace(c))
1933                        continue;
1934                wasspace = isspace(c);
1935                if (wasspace)
1936                        c = ' ';
1937                *cp++ = c;
1938        }
1939        while (buf < cp && isspace(cp[-1]))
1940                cp--;
1941        *cp++ = '\n';
1942        return cp - buf;
1943}
1944
1945int log_ref_setup(const char *refname, char *logfile, int bufsize)
1946{
1947        int logfd, oflags = O_APPEND | O_WRONLY;
1948
1949        git_snpath(logfile, bufsize, "logs/%s", refname);
1950        if (log_all_ref_updates &&
1951            (!prefixcmp(refname, "refs/heads/") ||
1952             !prefixcmp(refname, "refs/remotes/") ||
1953             !prefixcmp(refname, "refs/notes/") ||
1954             !strcmp(refname, "HEAD"))) {
1955                if (safe_create_leading_directories(logfile) < 0)
1956                        return error("unable to create directory for %s",
1957                                     logfile);
1958                oflags |= O_CREAT;
1959        }
1960
1961        logfd = open(logfile, oflags, 0666);
1962        if (logfd < 0) {
1963                if (!(oflags & O_CREAT) && errno == ENOENT)
1964                        return 0;
1965
1966                if ((oflags & O_CREAT) && errno == EISDIR) {
1967                        if (remove_empty_directories(logfile)) {
1968                                return error("There are still logs under '%s'",
1969                                             logfile);
1970                        }
1971                        logfd = open(logfile, oflags, 0666);
1972                }
1973
1974                if (logfd < 0)
1975                        return error("Unable to append to %s: %s",
1976                                     logfile, strerror(errno));
1977        }
1978
1979        adjust_shared_perm(logfile);
1980        close(logfd);
1981        return 0;
1982}
1983
1984static int log_ref_write(const char *refname, const unsigned char *old_sha1,
1985                         const unsigned char *new_sha1, const char *msg)
1986{
1987        int logfd, result, written, oflags = O_APPEND | O_WRONLY;
1988        unsigned maxlen, len;
1989        int msglen;
1990        char log_file[PATH_MAX];
1991        char *logrec;
1992        const char *committer;
1993
1994        if (log_all_ref_updates < 0)
1995                log_all_ref_updates = !is_bare_repository();
1996
1997        result = log_ref_setup(refname, log_file, sizeof(log_file));
1998        if (result)
1999                return result;
2000
2001        logfd = open(log_file, oflags);
2002        if (logfd < 0)
2003                return 0;
2004        msglen = msg ? strlen(msg) : 0;
2005        committer = git_committer_info(0);
2006        maxlen = strlen(committer) + msglen + 100;
2007        logrec = xmalloc(maxlen);
2008        len = sprintf(logrec, "%s %s %s\n",
2009                      sha1_to_hex(old_sha1),
2010                      sha1_to_hex(new_sha1),
2011                      committer);
2012        if (msglen)
2013                len += copy_msg(logrec + len - 1, msg) - 1;
2014        written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
2015        free(logrec);
2016        if (close(logfd) != 0 || written != len)
2017                return error("Unable to append to %s", log_file);
2018        return 0;
2019}
2020
2021static int is_branch(const char *refname)
2022{
2023        return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
2024}
2025
2026int write_ref_sha1(struct ref_lock *lock,
2027        const unsigned char *sha1, const char *logmsg)
2028{
2029        static char term = '\n';
2030        struct object *o;
2031
2032        if (!lock)
2033                return -1;
2034        if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
2035                unlock_ref(lock);
2036                return 0;
2037        }
2038        o = parse_object(sha1);
2039        if (!o) {
2040                error("Trying to write ref %s with nonexistent object %s",
2041                        lock->ref_name, sha1_to_hex(sha1));
2042                unlock_ref(lock);
2043                return -1;
2044        }
2045        if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2046                error("Trying to write non-commit object %s to branch %s",
2047                        sha1_to_hex(sha1), lock->ref_name);
2048                unlock_ref(lock);
2049                return -1;
2050        }
2051        if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
2052            write_in_full(lock->lock_fd, &term, 1) != 1
2053                || close_ref(lock) < 0) {
2054                error("Couldn't write %s", lock->lk->filename);
2055                unlock_ref(lock);
2056                return -1;
2057        }
2058        clear_loose_ref_cache(get_ref_cache(NULL));
2059        if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
2060            (strcmp(lock->ref_name, lock->orig_ref_name) &&
2061             log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
2062                unlock_ref(lock);
2063                return -1;
2064        }
2065        if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2066                /*
2067                 * Special hack: If a branch is updated directly and HEAD
2068                 * points to it (may happen on the remote side of a push
2069                 * for example) then logically the HEAD reflog should be
2070                 * updated too.
2071                 * A generic solution implies reverse symref information,
2072                 * but finding all symrefs pointing to the given branch
2073                 * would be rather costly for this rare event (the direct
2074                 * update of a branch) to be worth it.  So let's cheat and
2075                 * check with HEAD only which should cover 99% of all usage
2076                 * scenarios (even 100% of the default ones).
2077                 */
2078                unsigned char head_sha1[20];
2079                int head_flag;
2080                const char *head_ref;
2081                head_ref = resolve_ref_unsafe("HEAD", head_sha1, 1, &head_flag);
2082                if (head_ref && (head_flag & REF_ISSYMREF) &&
2083                    !strcmp(head_ref, lock->ref_name))
2084                        log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
2085        }
2086        if (commit_ref(lock)) {
2087                error("Couldn't set %s", lock->ref_name);
2088                unlock_ref(lock);
2089                return -1;
2090        }
2091        unlock_ref(lock);
2092        return 0;
2093}
2094
2095int create_symref(const char *ref_target, const char *refs_heads_master,
2096                  const char *logmsg)
2097{
2098        const char *lockpath;
2099        char ref[1000];
2100        int fd, len, written;
2101        char *git_HEAD = git_pathdup("%s", ref_target);
2102        unsigned char old_sha1[20], new_sha1[20];
2103
2104        if (logmsg && read_ref(ref_target, old_sha1))
2105                hashclr(old_sha1);
2106
2107        if (safe_create_leading_directories(git_HEAD) < 0)
2108                return error("unable to create directory for %s", git_HEAD);
2109
2110#ifndef NO_SYMLINK_HEAD
2111        if (prefer_symlink_refs) {
2112                unlink(git_HEAD);
2113                if (!symlink(refs_heads_master, git_HEAD))
2114                        goto done;
2115                fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2116        }
2117#endif
2118
2119        len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2120        if (sizeof(ref) <= len) {
2121                error("refname too long: %s", refs_heads_master);
2122                goto error_free_return;
2123        }
2124        lockpath = mkpath("%s.lock", git_HEAD);
2125        fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
2126        if (fd < 0) {
2127                error("Unable to open %s for writing", lockpath);
2128                goto error_free_return;
2129        }
2130        written = write_in_full(fd, ref, len);
2131        if (close(fd) != 0 || written != len) {
2132                error("Unable to write to %s", lockpath);
2133                goto error_unlink_return;
2134        }
2135        if (rename(lockpath, git_HEAD) < 0) {
2136                error("Unable to create %s", git_HEAD);
2137                goto error_unlink_return;
2138        }
2139        if (adjust_shared_perm(git_HEAD)) {
2140                error("Unable to fix permissions on %s", lockpath);
2141        error_unlink_return:
2142                unlink_or_warn(lockpath);
2143        error_free_return:
2144                free(git_HEAD);
2145                return -1;
2146        }
2147
2148#ifndef NO_SYMLINK_HEAD
2149        done:
2150#endif
2151        if (logmsg && !read_ref(refs_heads_master, new_sha1))
2152                log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
2153
2154        free(git_HEAD);
2155        return 0;
2156}
2157
2158static char *ref_msg(const char *line, const char *endp)
2159{
2160        const char *ep;
2161        line += 82;
2162        ep = memchr(line, '\n', endp - line);
2163        if (!ep)
2164                ep = endp;
2165        return xmemdupz(line, ep - line);
2166}
2167
2168int read_ref_at(const char *refname, unsigned long at_time, int cnt,
2169                unsigned char *sha1, char **msg,
2170                unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
2171{
2172        const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
2173        char *tz_c;
2174        int logfd, tz, reccnt = 0;
2175        struct stat st;
2176        unsigned long date;
2177        unsigned char logged_sha1[20];
2178        void *log_mapped;
2179        size_t mapsz;
2180
2181        logfile = git_path("logs/%s", refname);
2182        logfd = open(logfile, O_RDONLY, 0);
2183        if (logfd < 0)
2184                die_errno("Unable to read log '%s'", logfile);
2185        fstat(logfd, &st);
2186        if (!st.st_size)
2187                die("Log %s is empty.", logfile);
2188        mapsz = xsize_t(st.st_size);
2189        log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
2190        logdata = log_mapped;
2191        close(logfd);
2192
2193        lastrec = NULL;
2194        rec = logend = logdata + st.st_size;
2195        while (logdata < rec) {
2196                reccnt++;
2197                if (logdata < rec && *(rec-1) == '\n')
2198                        rec--;
2199                lastgt = NULL;
2200                while (logdata < rec && *(rec-1) != '\n') {
2201                        rec--;
2202                        if (*rec == '>')
2203                                lastgt = rec;
2204                }
2205                if (!lastgt)
2206                        die("Log %s is corrupt.", logfile);
2207                date = strtoul(lastgt + 1, &tz_c, 10);
2208                if (date <= at_time || cnt == 0) {
2209                        tz = strtoul(tz_c, NULL, 10);
2210                        if (msg)
2211                                *msg = ref_msg(rec, logend);
2212                        if (cutoff_time)
2213                                *cutoff_time = date;
2214                        if (cutoff_tz)
2215                                *cutoff_tz = tz;
2216                        if (cutoff_cnt)
2217                                *cutoff_cnt = reccnt - 1;
2218                        if (lastrec) {
2219                                if (get_sha1_hex(lastrec, logged_sha1))
2220                                        die("Log %s is corrupt.", logfile);
2221                                if (get_sha1_hex(rec + 41, sha1))
2222                                        die("Log %s is corrupt.", logfile);
2223                                if (hashcmp(logged_sha1, sha1)) {
2224                                        warning("Log %s has gap after %s.",
2225                                                logfile, show_date(date, tz, DATE_RFC2822));
2226                                }
2227                        }
2228                        else if (date == at_time) {
2229                                if (get_sha1_hex(rec + 41, sha1))
2230                                        die("Log %s is corrupt.", logfile);
2231                        }
2232                        else {
2233                                if (get_sha1_hex(rec + 41, logged_sha1))
2234                                        die("Log %s is corrupt.", logfile);
2235                                if (hashcmp(logged_sha1, sha1)) {
2236                                        warning("Log %s unexpectedly ended on %s.",
2237                                                logfile, show_date(date, tz, DATE_RFC2822));
2238                                }
2239                        }
2240                        munmap(log_mapped, mapsz);
2241                        return 0;
2242                }
2243                lastrec = rec;
2244                if (cnt > 0)
2245                        cnt--;
2246        }
2247
2248        rec = logdata;
2249        while (rec < logend && *rec != '>' && *rec != '\n')
2250                rec++;
2251        if (rec == logend || *rec == '\n')
2252                die("Log %s is corrupt.", logfile);
2253        date = strtoul(rec + 1, &tz_c, 10);
2254        tz = strtoul(tz_c, NULL, 10);
2255        if (get_sha1_hex(logdata, sha1))
2256                die("Log %s is corrupt.", logfile);
2257        if (is_null_sha1(sha1)) {
2258                if (get_sha1_hex(logdata + 41, sha1))
2259                        die("Log %s is corrupt.", logfile);
2260        }
2261        if (msg)
2262                *msg = ref_msg(logdata, logend);
2263        munmap(log_mapped, mapsz);
2264
2265        if (cutoff_time)
2266                *cutoff_time = date;
2267        if (cutoff_tz)
2268                *cutoff_tz = tz;
2269        if (cutoff_cnt)
2270                *cutoff_cnt = reccnt;
2271        return 1;
2272}
2273
2274int for_each_recent_reflog_ent(const char *refname, each_reflog_ent_fn fn, long ofs, void *cb_data)
2275{
2276        const char *logfile;
2277        FILE *logfp;
2278        struct strbuf sb = STRBUF_INIT;
2279        int ret = 0;
2280
2281        logfile = git_path("logs/%s", refname);
2282        logfp = fopen(logfile, "r");
2283        if (!logfp)
2284                return -1;
2285
2286        if (ofs) {
2287                struct stat statbuf;
2288                if (fstat(fileno(logfp), &statbuf) ||
2289                    statbuf.st_size < ofs ||
2290                    fseek(logfp, -ofs, SEEK_END) ||
2291                    strbuf_getwholeline(&sb, logfp, '\n')) {
2292                        fclose(logfp);
2293                        strbuf_release(&sb);
2294                        return -1;
2295                }
2296        }
2297
2298        while (!strbuf_getwholeline(&sb, logfp, '\n')) {
2299                unsigned char osha1[20], nsha1[20];
2300                char *email_end, *message;
2301                unsigned long timestamp;
2302                int tz;
2303
2304                /* old SP new SP name <email> SP time TAB msg LF */
2305                if (sb.len < 83 || sb.buf[sb.len - 1] != '\n' ||
2306                    get_sha1_hex(sb.buf, osha1) || sb.buf[40] != ' ' ||
2307                    get_sha1_hex(sb.buf + 41, nsha1) || sb.buf[81] != ' ' ||
2308                    !(email_end = strchr(sb.buf + 82, '>')) ||
2309                    email_end[1] != ' ' ||
2310                    !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2311                    !message || message[0] != ' ' ||
2312                    (message[1] != '+' && message[1] != '-') ||
2313                    !isdigit(message[2]) || !isdigit(message[3]) ||
2314                    !isdigit(message[4]) || !isdigit(message[5]))
2315                        continue; /* corrupt? */
2316                email_end[1] = '\0';
2317                tz = strtol(message + 1, NULL, 10);
2318                if (message[6] != '\t')
2319                        message += 6;
2320                else
2321                        message += 7;
2322                ret = fn(osha1, nsha1, sb.buf + 82, timestamp, tz, message,
2323                         cb_data);
2324                if (ret)
2325                        break;
2326        }
2327        fclose(logfp);
2328        strbuf_release(&sb);
2329        return ret;
2330}
2331
2332int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2333{
2334        return for_each_recent_reflog_ent(refname, fn, 0, cb_data);
2335}
2336
2337/*
2338 * Call fn for each reflog in the namespace indicated by name.  name
2339 * must be empty or end with '/'.  Name will be used as a scratch
2340 * space, but its contents will be restored before return.
2341 */
2342static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
2343{
2344        DIR *d = opendir(git_path("logs/%s", name->buf));
2345        int retval = 0;
2346        struct dirent *de;
2347        int oldlen = name->len;
2348
2349        if (!d)
2350                return name->len ? errno : 0;
2351
2352        while ((de = readdir(d)) != NULL) {
2353                struct stat st;
2354
2355                if (de->d_name[0] == '.')
2356                        continue;
2357                if (has_extension(de->d_name, ".lock"))
2358                        continue;
2359                strbuf_addstr(name, de->d_name);
2360                if (stat(git_path("logs/%s", name->buf), &st) < 0) {
2361                        ; /* silently ignore */
2362                } else {
2363                        if (S_ISDIR(st.st_mode)) {
2364                                strbuf_addch(name, '/');
2365                                retval = do_for_each_reflog(name, fn, cb_data);
2366                        } else {
2367                                unsigned char sha1[20];
2368                                if (read_ref_full(name->buf, sha1, 0, NULL))
2369                                        retval = error("bad ref for %s", name->buf);
2370                                else
2371                                        retval = fn(name->buf, sha1, 0, cb_data);
2372                        }
2373                        if (retval)
2374                                break;
2375                }
2376                strbuf_setlen(name, oldlen);
2377        }
2378        closedir(d);
2379        return retval;
2380}
2381
2382int for_each_reflog(each_ref_fn fn, void *cb_data)
2383{
2384        int retval;
2385        struct strbuf name;
2386        strbuf_init(&name, PATH_MAX);
2387        retval = do_for_each_reflog(&name, fn, cb_data);
2388        strbuf_release(&name);
2389        return retval;
2390}
2391
2392int update_ref(const char *action, const char *refname,
2393                const unsigned char *sha1, const unsigned char *oldval,
2394                int flags, enum action_on_err onerr)
2395{
2396        static struct ref_lock *lock;
2397        lock = lock_any_ref_for_update(refname, oldval, flags);
2398        if (!lock) {
2399                const char *str = "Cannot lock the ref '%s'.";
2400                switch (onerr) {
2401                case MSG_ON_ERR: error(str, refname); break;
2402                case DIE_ON_ERR: die(str, refname); break;
2403                case QUIET_ON_ERR: break;
2404                }
2405                return 1;
2406        }
2407        if (write_ref_sha1(lock, sha1, action) < 0) {
2408                const char *str = "Cannot update the ref '%s'.";
2409                switch (onerr) {
2410                case MSG_ON_ERR: error(str, refname); break;
2411                case DIE_ON_ERR: die(str, refname); break;
2412                case QUIET_ON_ERR: break;
2413                }
2414                return 1;
2415        }
2416        return 0;
2417}
2418
2419struct ref *find_ref_by_name(const struct ref *list, const char *name)
2420{
2421        for ( ; list; list = list->next)
2422                if (!strcmp(list->name, name))
2423                        return (struct ref *)list;
2424        return NULL;
2425}
2426
2427/*
2428 * generate a format suitable for scanf from a ref_rev_parse_rules
2429 * rule, that is replace the "%.*s" spec with a "%s" spec
2430 */
2431static void gen_scanf_fmt(char *scanf_fmt, const char *rule)
2432{
2433        char *spec;
2434
2435        spec = strstr(rule, "%.*s");
2436        if (!spec || strstr(spec + 4, "%.*s"))
2437                die("invalid rule in ref_rev_parse_rules: %s", rule);
2438
2439        /* copy all until spec */
2440        strncpy(scanf_fmt, rule, spec - rule);
2441        scanf_fmt[spec - rule] = '\0';
2442        /* copy new spec */
2443        strcat(scanf_fmt, "%s");
2444        /* copy remaining rule */
2445        strcat(scanf_fmt, spec + 4);
2446
2447        return;
2448}
2449
2450char *shorten_unambiguous_ref(const char *refname, int strict)
2451{
2452        int i;
2453        static char **scanf_fmts;
2454        static int nr_rules;
2455        char *short_name;
2456
2457        /* pre generate scanf formats from ref_rev_parse_rules[] */
2458        if (!nr_rules) {
2459                size_t total_len = 0;
2460
2461                /* the rule list is NULL terminated, count them first */
2462                for (; ref_rev_parse_rules[nr_rules]; nr_rules++)
2463                        /* no +1 because strlen("%s") < strlen("%.*s") */
2464                        total_len += strlen(ref_rev_parse_rules[nr_rules]);
2465
2466                scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
2467
2468                total_len = 0;
2469                for (i = 0; i < nr_rules; i++) {
2470                        scanf_fmts[i] = (char *)&scanf_fmts[nr_rules]
2471                                        + total_len;
2472                        gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);
2473                        total_len += strlen(ref_rev_parse_rules[i]);
2474                }
2475        }
2476
2477        /* bail out if there are no rules */
2478        if (!nr_rules)
2479                return xstrdup(refname);
2480
2481        /* buffer for scanf result, at most refname must fit */
2482        short_name = xstrdup(refname);
2483
2484        /* skip first rule, it will always match */
2485        for (i = nr_rules - 1; i > 0 ; --i) {
2486                int j;
2487                int rules_to_fail = i;
2488                int short_name_len;
2489
2490                if (1 != sscanf(refname, scanf_fmts[i], short_name))
2491                        continue;
2492
2493                short_name_len = strlen(short_name);
2494
2495                /*
2496                 * in strict mode, all (except the matched one) rules
2497                 * must fail to resolve to a valid non-ambiguous ref
2498                 */
2499                if (strict)
2500                        rules_to_fail = nr_rules;
2501
2502                /*
2503                 * check if the short name resolves to a valid ref,
2504                 * but use only rules prior to the matched one
2505                 */
2506                for (j = 0; j < rules_to_fail; j++) {
2507                        const char *rule = ref_rev_parse_rules[j];
2508                        char refname[PATH_MAX];
2509
2510                        /* skip matched rule */
2511                        if (i == j)
2512                                continue;
2513
2514                        /*
2515                         * the short name is ambiguous, if it resolves
2516                         * (with this previous rule) to a valid ref
2517                         * read_ref() returns 0 on success
2518                         */
2519                        mksnpath(refname, sizeof(refname),
2520                                 rule, short_name_len, short_name);
2521                        if (ref_exists(refname))
2522                                break;
2523                }
2524
2525                /*
2526                 * short name is non-ambiguous if all previous rules
2527                 * haven't resolved to a valid ref
2528                 */
2529                if (j == rules_to_fail)
2530                        return short_name;
2531        }
2532
2533        free(short_name);
2534        return xstrdup(refname);
2535}