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