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