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