refs.con commit commit: allow associating auxiliary info on-demand (96c4f4a)
   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
 806/*
 807 * Read f, which is a packed-refs file, into dir.
 808 *
 809 * A comment line of the form "# pack-refs with: " may contain zero or
 810 * more traits. We interpret the traits as follows:
 811 *
 812 *   No traits:
 813 *
 814 *      Probably no references are peeled. But if the file contains a
 815 *      peeled value for a reference, we will use it.
 816 *
 817 *   peeled:
 818 *
 819 *      References under "refs/tags/", if they *can* be peeled, *are*
 820 *      peeled in this file. References outside of "refs/tags/" are
 821 *      probably not peeled even if they could have been, but if we find
 822 *      a peeled value for such a reference we will use it.
 823 *
 824 *   fully-peeled:
 825 *
 826 *      All references in the file that can be peeled are peeled.
 827 *      Inversely (and this is more important), any references in the
 828 *      file for which no peeled value is recorded is not peelable. This
 829 *      trait should typically be written alongside "peeled" for
 830 *      compatibility with older clients, but we do not require it
 831 *      (i.e., "peeled" is a no-op if "fully-peeled" is set).
 832 */
 833static void read_packed_refs(FILE *f, struct ref_dir *dir)
 834{
 835        struct ref_entry *last = NULL;
 836        char refline[PATH_MAX];
 837        enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
 838
 839        while (fgets(refline, sizeof(refline), f)) {
 840                unsigned char sha1[20];
 841                const char *refname;
 842                static const char header[] = "# pack-refs with:";
 843
 844                if (!strncmp(refline, header, sizeof(header)-1)) {
 845                        const char *traits = refline + sizeof(header) - 1;
 846                        if (strstr(traits, " fully-peeled "))
 847                                peeled = PEELED_FULLY;
 848                        else if (strstr(traits, " peeled "))
 849                                peeled = PEELED_TAGS;
 850                        /* perhaps other traits later as well */
 851                        continue;
 852                }
 853
 854                refname = parse_ref_line(refline, sha1);
 855                if (refname) {
 856                        last = create_ref_entry(refname, sha1, REF_ISPACKED, 1);
 857                        if (peeled == PEELED_FULLY ||
 858                            (peeled == PEELED_TAGS && !prefixcmp(refname, "refs/tags/")))
 859                                last->flag |= REF_KNOWS_PEELED;
 860                        add_ref(dir, last);
 861                        continue;
 862                }
 863                if (last &&
 864                    refline[0] == '^' &&
 865                    strlen(refline) == 42 &&
 866                    refline[41] == '\n' &&
 867                    !get_sha1_hex(refline + 1, sha1)) {
 868                        hashcpy(last->u.value.peeled, sha1);
 869                        /*
 870                         * Regardless of what the file header said,
 871                         * we definitely know the value of *this*
 872                         * reference:
 873                         */
 874                        last->flag |= REF_KNOWS_PEELED;
 875                }
 876        }
 877}
 878
 879static struct ref_dir *get_packed_refs(struct ref_cache *refs)
 880{
 881        if (!refs->packed) {
 882                const char *packed_refs_file;
 883                FILE *f;
 884
 885                refs->packed = create_dir_entry(refs, "", 0, 0);
 886                if (*refs->name)
 887                        packed_refs_file = git_path_submodule(refs->name, "packed-refs");
 888                else
 889                        packed_refs_file = git_path("packed-refs");
 890                f = fopen(packed_refs_file, "r");
 891                if (f) {
 892                        read_packed_refs(f, get_ref_dir(refs->packed));
 893                        fclose(f);
 894                }
 895        }
 896        return get_ref_dir(refs->packed);
 897}
 898
 899void add_packed_ref(const char *refname, const unsigned char *sha1)
 900{
 901        add_ref(get_packed_refs(get_ref_cache(NULL)),
 902                        create_ref_entry(refname, sha1, REF_ISPACKED, 1));
 903}
 904
 905/*
 906 * Read the loose references from the namespace dirname into dir
 907 * (without recursing).  dirname must end with '/'.  dir must be the
 908 * directory entry corresponding to dirname.
 909 */
 910static void read_loose_refs(const char *dirname, struct ref_dir *dir)
 911{
 912        struct ref_cache *refs = dir->ref_cache;
 913        DIR *d;
 914        const char *path;
 915        struct dirent *de;
 916        int dirnamelen = strlen(dirname);
 917        struct strbuf refname;
 918
 919        if (*refs->name)
 920                path = git_path_submodule(refs->name, "%s", dirname);
 921        else
 922                path = git_path("%s", dirname);
 923
 924        d = opendir(path);
 925        if (!d)
 926                return;
 927
 928        strbuf_init(&refname, dirnamelen + 257);
 929        strbuf_add(&refname, dirname, dirnamelen);
 930
 931        while ((de = readdir(d)) != NULL) {
 932                unsigned char sha1[20];
 933                struct stat st;
 934                int flag;
 935                const char *refdir;
 936
 937                if (de->d_name[0] == '.')
 938                        continue;
 939                if (has_extension(de->d_name, ".lock"))
 940                        continue;
 941                strbuf_addstr(&refname, de->d_name);
 942                refdir = *refs->name
 943                        ? git_path_submodule(refs->name, "%s", refname.buf)
 944                        : git_path("%s", refname.buf);
 945                if (stat(refdir, &st) < 0) {
 946                        ; /* silently ignore */
 947                } else if (S_ISDIR(st.st_mode)) {
 948                        strbuf_addch(&refname, '/');
 949                        add_entry_to_dir(dir,
 950                                         create_dir_entry(refs, refname.buf,
 951                                                          refname.len, 1));
 952                } else {
 953                        if (*refs->name) {
 954                                hashclr(sha1);
 955                                flag = 0;
 956                                if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
 957                                        hashclr(sha1);
 958                                        flag |= REF_ISBROKEN;
 959                                }
 960                        } else if (read_ref_full(refname.buf, sha1, 1, &flag)) {
 961                                hashclr(sha1);
 962                                flag |= REF_ISBROKEN;
 963                        }
 964                        add_entry_to_dir(dir,
 965                                         create_ref_entry(refname.buf, sha1, flag, 1));
 966                }
 967                strbuf_setlen(&refname, dirnamelen);
 968        }
 969        strbuf_release(&refname);
 970        closedir(d);
 971}
 972
 973static struct ref_dir *get_loose_refs(struct ref_cache *refs)
 974{
 975        if (!refs->loose) {
 976                /*
 977                 * Mark the top-level directory complete because we
 978                 * are about to read the only subdirectory that can
 979                 * hold references:
 980                 */
 981                refs->loose = create_dir_entry(refs, "", 0, 0);
 982                /*
 983                 * Create an incomplete entry for "refs/":
 984                 */
 985                add_entry_to_dir(get_ref_dir(refs->loose),
 986                                 create_dir_entry(refs, "refs/", 5, 1));
 987        }
 988        return get_ref_dir(refs->loose);
 989}
 990
 991/* We allow "recursive" symbolic refs. Only within reason, though */
 992#define MAXDEPTH 5
 993#define MAXREFLEN (1024)
 994
 995/*
 996 * Called by resolve_gitlink_ref_recursive() after it failed to read
 997 * from the loose refs in ref_cache refs. Find <refname> in the
 998 * packed-refs file for the submodule.
 999 */
1000static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1001                                      const char *refname, unsigned char *sha1)
1002{
1003        struct ref_entry *ref;
1004        struct ref_dir *dir = get_packed_refs(refs);
1005
1006        ref = find_ref(dir, refname);
1007        if (ref == NULL)
1008                return -1;
1009
1010        memcpy(sha1, ref->u.value.sha1, 20);
1011        return 0;
1012}
1013
1014static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1015                                         const char *refname, unsigned char *sha1,
1016                                         int recursion)
1017{
1018        int fd, len;
1019        char buffer[128], *p;
1020        char *path;
1021
1022        if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1023                return -1;
1024        path = *refs->name
1025                ? git_path_submodule(refs->name, "%s", refname)
1026                : git_path("%s", refname);
1027        fd = open(path, O_RDONLY);
1028        if (fd < 0)
1029                return resolve_gitlink_packed_ref(refs, refname, sha1);
1030
1031        len = read(fd, buffer, sizeof(buffer)-1);
1032        close(fd);
1033        if (len < 0)
1034                return -1;
1035        while (len && isspace(buffer[len-1]))
1036                len--;
1037        buffer[len] = 0;
1038
1039        /* Was it a detached head or an old-fashioned symlink? */
1040        if (!get_sha1_hex(buffer, sha1))
1041                return 0;
1042
1043        /* Symref? */
1044        if (strncmp(buffer, "ref:", 4))
1045                return -1;
1046        p = buffer + 4;
1047        while (isspace(*p))
1048                p++;
1049
1050        return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1051}
1052
1053int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1054{
1055        int len = strlen(path), retval;
1056        char *submodule;
1057        struct ref_cache *refs;
1058
1059        while (len && path[len-1] == '/')
1060                len--;
1061        if (!len)
1062                return -1;
1063        submodule = xstrndup(path, len);
1064        refs = get_ref_cache(submodule);
1065        free(submodule);
1066
1067        retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1068        return retval;
1069}
1070
1071/*
1072 * Try to read ref from the packed references.  On success, set sha1
1073 * and return 0; otherwise, return -1.
1074 */
1075static int get_packed_ref(const char *refname, unsigned char *sha1)
1076{
1077        struct ref_dir *packed = get_packed_refs(get_ref_cache(NULL));
1078        struct ref_entry *entry = find_ref(packed, refname);
1079        if (entry) {
1080                hashcpy(sha1, entry->u.value.sha1);
1081                return 0;
1082        }
1083        return -1;
1084}
1085
1086const char *resolve_ref_unsafe(const char *refname, unsigned char *sha1, int reading, int *flag)
1087{
1088        int depth = MAXDEPTH;
1089        ssize_t len;
1090        char buffer[256];
1091        static char refname_buffer[256];
1092
1093        if (flag)
1094                *flag = 0;
1095
1096        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1097                return NULL;
1098
1099        for (;;) {
1100                char path[PATH_MAX];
1101                struct stat st;
1102                char *buf;
1103                int fd;
1104
1105                if (--depth < 0)
1106                        return NULL;
1107
1108                git_snpath(path, sizeof(path), "%s", refname);
1109
1110                if (lstat(path, &st) < 0) {
1111                        if (errno != ENOENT)
1112                                return NULL;
1113                        /*
1114                         * The loose reference file does not exist;
1115                         * check for a packed reference.
1116                         */
1117                        if (!get_packed_ref(refname, sha1)) {
1118                                if (flag)
1119                                        *flag |= REF_ISPACKED;
1120                                return refname;
1121                        }
1122                        /* The reference is not a packed reference, either. */
1123                        if (reading) {
1124                                return NULL;
1125                        } else {
1126                                hashclr(sha1);
1127                                return refname;
1128                        }
1129                }
1130
1131                /* Follow "normalized" - ie "refs/.." symlinks by hand */
1132                if (S_ISLNK(st.st_mode)) {
1133                        len = readlink(path, buffer, sizeof(buffer)-1);
1134                        if (len < 0)
1135                                return NULL;
1136                        buffer[len] = 0;
1137                        if (!prefixcmp(buffer, "refs/") &&
1138                                        !check_refname_format(buffer, 0)) {
1139                                strcpy(refname_buffer, buffer);
1140                                refname = refname_buffer;
1141                                if (flag)
1142                                        *flag |= REF_ISSYMREF;
1143                                continue;
1144                        }
1145                }
1146
1147                /* Is it a directory? */
1148                if (S_ISDIR(st.st_mode)) {
1149                        errno = EISDIR;
1150                        return NULL;
1151                }
1152
1153                /*
1154                 * Anything else, just open it and try to use it as
1155                 * a ref
1156                 */
1157                fd = open(path, O_RDONLY);
1158                if (fd < 0)
1159                        return NULL;
1160                len = read_in_full(fd, buffer, sizeof(buffer)-1);
1161                close(fd);
1162                if (len < 0)
1163                        return NULL;
1164                while (len && isspace(buffer[len-1]))
1165                        len--;
1166                buffer[len] = '\0';
1167
1168                /*
1169                 * Is it a symbolic ref?
1170                 */
1171                if (prefixcmp(buffer, "ref:"))
1172                        break;
1173                if (flag)
1174                        *flag |= REF_ISSYMREF;
1175                buf = buffer + 4;
1176                while (isspace(*buf))
1177                        buf++;
1178                if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1179                        if (flag)
1180                                *flag |= REF_ISBROKEN;
1181                        return NULL;
1182                }
1183                refname = strcpy(refname_buffer, buf);
1184        }
1185        /* Please note that FETCH_HEAD has a second line containing other data. */
1186        if (get_sha1_hex(buffer, sha1) || (buffer[40] != '\0' && !isspace(buffer[40]))) {
1187                if (flag)
1188                        *flag |= REF_ISBROKEN;
1189                return NULL;
1190        }
1191        return refname;
1192}
1193
1194char *resolve_refdup(const char *ref, unsigned char *sha1, int reading, int *flag)
1195{
1196        const char *ret = resolve_ref_unsafe(ref, sha1, reading, flag);
1197        return ret ? xstrdup(ret) : NULL;
1198}
1199
1200/* The argument to filter_refs */
1201struct ref_filter {
1202        const char *pattern;
1203        each_ref_fn *fn;
1204        void *cb_data;
1205};
1206
1207int read_ref_full(const char *refname, unsigned char *sha1, int reading, int *flags)
1208{
1209        if (resolve_ref_unsafe(refname, sha1, reading, flags))
1210                return 0;
1211        return -1;
1212}
1213
1214int read_ref(const char *refname, unsigned char *sha1)
1215{
1216        return read_ref_full(refname, sha1, 1, NULL);
1217}
1218
1219int ref_exists(const char *refname)
1220{
1221        unsigned char sha1[20];
1222        return !!resolve_ref_unsafe(refname, sha1, 1, NULL);
1223}
1224
1225static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1226                       void *data)
1227{
1228        struct ref_filter *filter = (struct ref_filter *)data;
1229        if (fnmatch(filter->pattern, refname, 0))
1230                return 0;
1231        return filter->fn(refname, sha1, flags, filter->cb_data);
1232}
1233
1234int peel_ref(const char *refname, unsigned char *sha1)
1235{
1236        int flag;
1237        unsigned char base[20];
1238        struct object *o;
1239
1240        if (current_ref && (current_ref->name == refname
1241                || !strcmp(current_ref->name, refname))) {
1242                if (current_ref->flag & REF_KNOWS_PEELED) {
1243                        if (is_null_sha1(current_ref->u.value.peeled))
1244                            return -1;
1245                        hashcpy(sha1, current_ref->u.value.peeled);
1246                        return 0;
1247                }
1248                hashcpy(base, current_ref->u.value.sha1);
1249                goto fallback;
1250        }
1251
1252        if (read_ref_full(refname, base, 1, &flag))
1253                return -1;
1254
1255        if ((flag & REF_ISPACKED)) {
1256                struct ref_dir *dir = get_packed_refs(get_ref_cache(NULL));
1257                struct ref_entry *r = find_ref(dir, refname);
1258
1259                if (r != NULL && r->flag & REF_KNOWS_PEELED) {
1260                        hashcpy(sha1, r->u.value.peeled);
1261                        return 0;
1262                }
1263        }
1264
1265fallback:
1266        o = lookup_unknown_object(base);
1267        if (o->type == OBJ_NONE) {
1268                int type = sha1_object_info(base, NULL);
1269                if (type < 0)
1270                        return -1;
1271                o->type = type;
1272        }
1273
1274        if (o->type == OBJ_TAG) {
1275                o = deref_tag_noverify(o);
1276                if (o) {
1277                        hashcpy(sha1, o->sha1);
1278                        return 0;
1279                }
1280        }
1281        return -1;
1282}
1283
1284struct warn_if_dangling_data {
1285        FILE *fp;
1286        const char *refname;
1287        const char *msg_fmt;
1288};
1289
1290static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1291                                   int flags, void *cb_data)
1292{
1293        struct warn_if_dangling_data *d = cb_data;
1294        const char *resolves_to;
1295        unsigned char junk[20];
1296
1297        if (!(flags & REF_ISSYMREF))
1298                return 0;
1299
1300        resolves_to = resolve_ref_unsafe(refname, junk, 0, NULL);
1301        if (!resolves_to || strcmp(resolves_to, d->refname))
1302                return 0;
1303
1304        fprintf(d->fp, d->msg_fmt, refname);
1305        fputc('\n', d->fp);
1306        return 0;
1307}
1308
1309void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1310{
1311        struct warn_if_dangling_data data;
1312
1313        data.fp = fp;
1314        data.refname = refname;
1315        data.msg_fmt = msg_fmt;
1316        for_each_rawref(warn_if_dangling_symref, &data);
1317}
1318
1319static int do_for_each_ref(const char *submodule, const char *base, each_ref_fn fn,
1320                           int trim, int flags, void *cb_data)
1321{
1322        struct ref_cache *refs = get_ref_cache(submodule);
1323        struct ref_dir *packed_dir = get_packed_refs(refs);
1324        struct ref_dir *loose_dir = get_loose_refs(refs);
1325        int retval = 0;
1326
1327        if (base && *base) {
1328                packed_dir = find_containing_dir(packed_dir, base, 0);
1329                loose_dir = find_containing_dir(loose_dir, base, 0);
1330        }
1331
1332        if (packed_dir && loose_dir) {
1333                sort_ref_dir(packed_dir);
1334                sort_ref_dir(loose_dir);
1335                retval = do_for_each_ref_in_dirs(
1336                                packed_dir, loose_dir,
1337                                base, fn, trim, flags, cb_data);
1338        } else if (packed_dir) {
1339                sort_ref_dir(packed_dir);
1340                retval = do_for_each_ref_in_dir(
1341                                packed_dir, 0,
1342                                base, fn, trim, flags, cb_data);
1343        } else if (loose_dir) {
1344                sort_ref_dir(loose_dir);
1345                retval = do_for_each_ref_in_dir(
1346                                loose_dir, 0,
1347                                base, fn, trim, flags, cb_data);
1348        }
1349
1350        return retval;
1351}
1352
1353static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1354{
1355        unsigned char sha1[20];
1356        int flag;
1357
1358        if (submodule) {
1359                if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1360                        return fn("HEAD", sha1, 0, cb_data);
1361
1362                return 0;
1363        }
1364
1365        if (!read_ref_full("HEAD", sha1, 1, &flag))
1366                return fn("HEAD", sha1, flag, cb_data);
1367
1368        return 0;
1369}
1370
1371int head_ref(each_ref_fn fn, void *cb_data)
1372{
1373        return do_head_ref(NULL, fn, cb_data);
1374}
1375
1376int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1377{
1378        return do_head_ref(submodule, fn, cb_data);
1379}
1380
1381int for_each_ref(each_ref_fn fn, void *cb_data)
1382{
1383        return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
1384}
1385
1386int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1387{
1388        return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
1389}
1390
1391int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1392{
1393        return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
1394}
1395
1396int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1397                each_ref_fn fn, void *cb_data)
1398{
1399        return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
1400}
1401
1402int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1403{
1404        return for_each_ref_in("refs/tags/", fn, cb_data);
1405}
1406
1407int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1408{
1409        return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1410}
1411
1412int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1413{
1414        return for_each_ref_in("refs/heads/", fn, cb_data);
1415}
1416
1417int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1418{
1419        return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1420}
1421
1422int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1423{
1424        return for_each_ref_in("refs/remotes/", fn, cb_data);
1425}
1426
1427int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1428{
1429        return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
1430}
1431
1432int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1433{
1434        return do_for_each_ref(NULL, "refs/replace/", fn, 13, 0, cb_data);
1435}
1436
1437int head_ref_namespaced(each_ref_fn fn, void *cb_data)
1438{
1439        struct strbuf buf = STRBUF_INIT;
1440        int ret = 0;
1441        unsigned char sha1[20];
1442        int flag;
1443
1444        strbuf_addf(&buf, "%sHEAD", get_git_namespace());
1445        if (!read_ref_full(buf.buf, sha1, 1, &flag))
1446                ret = fn(buf.buf, sha1, flag, cb_data);
1447        strbuf_release(&buf);
1448
1449        return ret;
1450}
1451
1452int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1453{
1454        struct strbuf buf = STRBUF_INIT;
1455        int ret;
1456        strbuf_addf(&buf, "%srefs/", get_git_namespace());
1457        ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
1458        strbuf_release(&buf);
1459        return ret;
1460}
1461
1462int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
1463        const char *prefix, void *cb_data)
1464{
1465        struct strbuf real_pattern = STRBUF_INIT;
1466        struct ref_filter filter;
1467        int ret;
1468
1469        if (!prefix && prefixcmp(pattern, "refs/"))
1470                strbuf_addstr(&real_pattern, "refs/");
1471        else if (prefix)
1472                strbuf_addstr(&real_pattern, prefix);
1473        strbuf_addstr(&real_pattern, pattern);
1474
1475        if (!has_glob_specials(pattern)) {
1476                /* Append implied '/' '*' if not present. */
1477                if (real_pattern.buf[real_pattern.len - 1] != '/')
1478                        strbuf_addch(&real_pattern, '/');
1479                /* No need to check for '*', there is none. */
1480                strbuf_addch(&real_pattern, '*');
1481        }
1482
1483        filter.pattern = real_pattern.buf;
1484        filter.fn = fn;
1485        filter.cb_data = cb_data;
1486        ret = for_each_ref(filter_refs, &filter);
1487
1488        strbuf_release(&real_pattern);
1489        return ret;
1490}
1491
1492int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
1493{
1494        return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
1495}
1496
1497int for_each_rawref(each_ref_fn fn, void *cb_data)
1498{
1499        return do_for_each_ref(NULL, "", fn, 0,
1500                               DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1501}
1502
1503const char *prettify_refname(const char *name)
1504{
1505        return name + (
1506                !prefixcmp(name, "refs/heads/") ? 11 :
1507                !prefixcmp(name, "refs/tags/") ? 10 :
1508                !prefixcmp(name, "refs/remotes/") ? 13 :
1509                0);
1510}
1511
1512const char *ref_rev_parse_rules[] = {
1513        "%.*s",
1514        "refs/%.*s",
1515        "refs/tags/%.*s",
1516        "refs/heads/%.*s",
1517        "refs/remotes/%.*s",
1518        "refs/remotes/%.*s/HEAD",
1519        NULL
1520};
1521
1522int refname_match(const char *abbrev_name, const char *full_name, const char **rules)
1523{
1524        const char **p;
1525        const int abbrev_name_len = strlen(abbrev_name);
1526
1527        for (p = rules; *p; p++) {
1528                if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1529                        return 1;
1530                }
1531        }
1532
1533        return 0;
1534}
1535
1536static struct ref_lock *verify_lock(struct ref_lock *lock,
1537        const unsigned char *old_sha1, int mustexist)
1538{
1539        if (read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
1540                error("Can't verify ref %s", lock->ref_name);
1541                unlock_ref(lock);
1542                return NULL;
1543        }
1544        if (hashcmp(lock->old_sha1, old_sha1)) {
1545                error("Ref %s is at %s but expected %s", lock->ref_name,
1546                        sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1547                unlock_ref(lock);
1548                return NULL;
1549        }
1550        return lock;
1551}
1552
1553static int remove_empty_directories(const char *file)
1554{
1555        /* we want to create a file but there is a directory there;
1556         * if that is an empty directory (or a directory that contains
1557         * only empty directories), remove them.
1558         */
1559        struct strbuf path;
1560        int result;
1561
1562        strbuf_init(&path, 20);
1563        strbuf_addstr(&path, file);
1564
1565        result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
1566
1567        strbuf_release(&path);
1568
1569        return result;
1570}
1571
1572/*
1573 * *string and *len will only be substituted, and *string returned (for
1574 * later free()ing) if the string passed in is a magic short-hand form
1575 * to name a branch.
1576 */
1577static char *substitute_branch_name(const char **string, int *len)
1578{
1579        struct strbuf buf = STRBUF_INIT;
1580        int ret = interpret_branch_name(*string, &buf);
1581
1582        if (ret == *len) {
1583                size_t size;
1584                *string = strbuf_detach(&buf, &size);
1585                *len = size;
1586                return (char *)*string;
1587        }
1588
1589        return NULL;
1590}
1591
1592int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
1593{
1594        char *last_branch = substitute_branch_name(&str, &len);
1595        const char **p, *r;
1596        int refs_found = 0;
1597
1598        *ref = NULL;
1599        for (p = ref_rev_parse_rules; *p; p++) {
1600                char fullref[PATH_MAX];
1601                unsigned char sha1_from_ref[20];
1602                unsigned char *this_result;
1603                int flag;
1604
1605                this_result = refs_found ? sha1_from_ref : sha1;
1606                mksnpath(fullref, sizeof(fullref), *p, len, str);
1607                r = resolve_ref_unsafe(fullref, this_result, 1, &flag);
1608                if (r) {
1609                        if (!refs_found++)
1610                                *ref = xstrdup(r);
1611                        if (!warn_ambiguous_refs)
1612                                break;
1613                } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
1614                        warning("ignoring dangling symref %s.", fullref);
1615                } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
1616                        warning("ignoring broken ref %s.", fullref);
1617                }
1618        }
1619        free(last_branch);
1620        return refs_found;
1621}
1622
1623int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
1624{
1625        char *last_branch = substitute_branch_name(&str, &len);
1626        const char **p;
1627        int logs_found = 0;
1628
1629        *log = NULL;
1630        for (p = ref_rev_parse_rules; *p; p++) {
1631                struct stat st;
1632                unsigned char hash[20];
1633                char path[PATH_MAX];
1634                const char *ref, *it;
1635
1636                mksnpath(path, sizeof(path), *p, len, str);
1637                ref = resolve_ref_unsafe(path, hash, 1, NULL);
1638                if (!ref)
1639                        continue;
1640                if (!stat(git_path("logs/%s", path), &st) &&
1641                    S_ISREG(st.st_mode))
1642                        it = path;
1643                else if (strcmp(ref, path) &&
1644                         !stat(git_path("logs/%s", ref), &st) &&
1645                         S_ISREG(st.st_mode))
1646                        it = ref;
1647                else
1648                        continue;
1649                if (!logs_found++) {
1650                        *log = xstrdup(it);
1651                        hashcpy(sha1, hash);
1652                }
1653                if (!warn_ambiguous_refs)
1654                        break;
1655        }
1656        free(last_branch);
1657        return logs_found;
1658}
1659
1660static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1661                                            const unsigned char *old_sha1,
1662                                            int flags, int *type_p)
1663{
1664        char *ref_file;
1665        const char *orig_refname = refname;
1666        struct ref_lock *lock;
1667        int last_errno = 0;
1668        int type, lflags;
1669        int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1670        int missing = 0;
1671
1672        lock = xcalloc(1, sizeof(struct ref_lock));
1673        lock->lock_fd = -1;
1674
1675        refname = resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);
1676        if (!refname && errno == EISDIR) {
1677                /* we are trying to lock foo but we used to
1678                 * have foo/bar which now does not exist;
1679                 * it is normal for the empty directory 'foo'
1680                 * to remain.
1681                 */
1682                ref_file = git_path("%s", orig_refname);
1683                if (remove_empty_directories(ref_file)) {
1684                        last_errno = errno;
1685                        error("there are still refs under '%s'", orig_refname);
1686                        goto error_return;
1687                }
1688                refname = resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);
1689        }
1690        if (type_p)
1691            *type_p = type;
1692        if (!refname) {
1693                last_errno = errno;
1694                error("unable to resolve reference %s: %s",
1695                        orig_refname, strerror(errno));
1696                goto error_return;
1697        }
1698        missing = is_null_sha1(lock->old_sha1);
1699        /* When the ref did not exist and we are creating it,
1700         * make sure there is no existing ref that is packed
1701         * whose name begins with our refname, nor a ref whose
1702         * name is a proper prefix of our refname.
1703         */
1704        if (missing &&
1705             !is_refname_available(refname, NULL, get_packed_refs(get_ref_cache(NULL)))) {
1706                last_errno = ENOTDIR;
1707                goto error_return;
1708        }
1709
1710        lock->lk = xcalloc(1, sizeof(struct lock_file));
1711
1712        lflags = LOCK_DIE_ON_ERROR;
1713        if (flags & REF_NODEREF) {
1714                refname = orig_refname;
1715                lflags |= LOCK_NODEREF;
1716        }
1717        lock->ref_name = xstrdup(refname);
1718        lock->orig_ref_name = xstrdup(orig_refname);
1719        ref_file = git_path("%s", refname);
1720        if (missing)
1721                lock->force_write = 1;
1722        if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
1723                lock->force_write = 1;
1724
1725        if (safe_create_leading_directories(ref_file)) {
1726                last_errno = errno;
1727                error("unable to create directory for %s", ref_file);
1728                goto error_return;
1729        }
1730
1731        lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
1732        return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
1733
1734 error_return:
1735        unlock_ref(lock);
1736        errno = last_errno;
1737        return NULL;
1738}
1739
1740struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1)
1741{
1742        char refpath[PATH_MAX];
1743        if (check_refname_format(refname, 0))
1744                return NULL;
1745        strcpy(refpath, mkpath("refs/%s", refname));
1746        return lock_ref_sha1_basic(refpath, old_sha1, 0, NULL);
1747}
1748
1749struct ref_lock *lock_any_ref_for_update(const char *refname,
1750                                         const unsigned char *old_sha1, int flags)
1751{
1752        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1753                return NULL;
1754        return lock_ref_sha1_basic(refname, old_sha1, flags, NULL);
1755}
1756
1757struct repack_without_ref_sb {
1758        const char *refname;
1759        int fd;
1760};
1761
1762static int repack_without_ref_fn(const char *refname, const unsigned char *sha1,
1763                                 int flags, void *cb_data)
1764{
1765        struct repack_without_ref_sb *data = cb_data;
1766        char line[PATH_MAX + 100];
1767        int len;
1768
1769        if (!strcmp(data->refname, refname))
1770                return 0;
1771        len = snprintf(line, sizeof(line), "%s %s\n",
1772                       sha1_to_hex(sha1), refname);
1773        /* this should not happen but just being defensive */
1774        if (len > sizeof(line))
1775                die("too long a refname '%s'", refname);
1776        write_or_die(data->fd, line, len);
1777        return 0;
1778}
1779
1780static struct lock_file packlock;
1781
1782static int repack_without_ref(const char *refname)
1783{
1784        struct repack_without_ref_sb data;
1785        struct ref_cache *refs = get_ref_cache(NULL);
1786        struct ref_dir *packed = get_packed_refs(refs);
1787        if (find_ref(packed, refname) == NULL)
1788                return 0;
1789        data.refname = refname;
1790        data.fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
1791        if (data.fd < 0) {
1792                unable_to_lock_error(git_path("packed-refs"), errno);
1793                return error("cannot delete '%s' from packed refs", refname);
1794        }
1795        clear_packed_ref_cache(refs);
1796        packed = get_packed_refs(refs);
1797        do_for_each_ref_in_dir(packed, 0, "", repack_without_ref_fn, 0, 0, &data);
1798        return commit_lock_file(&packlock);
1799}
1800
1801int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
1802{
1803        struct ref_lock *lock;
1804        int err, i = 0, ret = 0, flag = 0;
1805
1806        lock = lock_ref_sha1_basic(refname, sha1, delopt, &flag);
1807        if (!lock)
1808                return 1;
1809        if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
1810                /* loose */
1811                i = strlen(lock->lk->filename) - 5; /* .lock */
1812                lock->lk->filename[i] = 0;
1813                err = unlink_or_warn(lock->lk->filename);
1814                if (err && errno != ENOENT)
1815                        ret = 1;
1816
1817                lock->lk->filename[i] = '.';
1818        }
1819        /* removing the loose one could have resurrected an earlier
1820         * packed one.  Also, if it was not loose we need to repack
1821         * without it.
1822         */
1823        ret |= repack_without_ref(lock->ref_name);
1824
1825        unlink_or_warn(git_path("logs/%s", lock->ref_name));
1826        invalidate_ref_cache(NULL);
1827        unlock_ref(lock);
1828        return ret;
1829}
1830
1831/*
1832 * People using contrib's git-new-workdir have .git/logs/refs ->
1833 * /some/other/path/.git/logs/refs, and that may live on another device.
1834 *
1835 * IOW, to avoid cross device rename errors, the temporary renamed log must
1836 * live into logs/refs.
1837 */
1838#define TMP_RENAMED_LOG  "logs/refs/.tmp-renamed-log"
1839
1840int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
1841{
1842        unsigned char sha1[20], orig_sha1[20];
1843        int flag = 0, logmoved = 0;
1844        struct ref_lock *lock;
1845        struct stat loginfo;
1846        int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
1847        const char *symref = NULL;
1848        struct ref_cache *refs = get_ref_cache(NULL);
1849
1850        if (log && S_ISLNK(loginfo.st_mode))
1851                return error("reflog for %s is a symlink", oldrefname);
1852
1853        symref = resolve_ref_unsafe(oldrefname, orig_sha1, 1, &flag);
1854        if (flag & REF_ISSYMREF)
1855                return error("refname %s is a symbolic ref, renaming it is not supported",
1856                        oldrefname);
1857        if (!symref)
1858                return error("refname %s not found", oldrefname);
1859
1860        if (!is_refname_available(newrefname, oldrefname, get_packed_refs(refs)))
1861                return 1;
1862
1863        if (!is_refname_available(newrefname, oldrefname, get_loose_refs(refs)))
1864                return 1;
1865
1866        if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
1867                return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
1868                        oldrefname, strerror(errno));
1869
1870        if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
1871                error("unable to delete old %s", oldrefname);
1872                goto rollback;
1873        }
1874
1875        if (!read_ref_full(newrefname, sha1, 1, &flag) &&
1876            delete_ref(newrefname, sha1, REF_NODEREF)) {
1877                if (errno==EISDIR) {
1878                        if (remove_empty_directories(git_path("%s", newrefname))) {
1879                                error("Directory not empty: %s", newrefname);
1880                                goto rollback;
1881                        }
1882                } else {
1883                        error("unable to delete existing %s", newrefname);
1884                        goto rollback;
1885                }
1886        }
1887
1888        if (log && safe_create_leading_directories(git_path("logs/%s", newrefname))) {
1889                error("unable to create directory for %s", newrefname);
1890                goto rollback;
1891        }
1892
1893 retry:
1894        if (log && rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
1895                if (errno==EISDIR || errno==ENOTDIR) {
1896                        /*
1897                         * rename(a, b) when b is an existing
1898                         * directory ought to result in ISDIR, but
1899                         * Solaris 5.8 gives ENOTDIR.  Sheesh.
1900                         */
1901                        if (remove_empty_directories(git_path("logs/%s", newrefname))) {
1902                                error("Directory not empty: logs/%s", newrefname);
1903                                goto rollback;
1904                        }
1905                        goto retry;
1906                } else {
1907                        error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
1908                                newrefname, strerror(errno));
1909                        goto rollback;
1910                }
1911        }
1912        logmoved = log;
1913
1914        lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL);
1915        if (!lock) {
1916                error("unable to lock %s for update", newrefname);
1917                goto rollback;
1918        }
1919        lock->force_write = 1;
1920        hashcpy(lock->old_sha1, orig_sha1);
1921        if (write_ref_sha1(lock, orig_sha1, logmsg)) {
1922                error("unable to write current sha1 into %s", newrefname);
1923                goto rollback;
1924        }
1925
1926        return 0;
1927
1928 rollback:
1929        lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL);
1930        if (!lock) {
1931                error("unable to lock %s for rollback", oldrefname);
1932                goto rollbacklog;
1933        }
1934
1935        lock->force_write = 1;
1936        flag = log_all_ref_updates;
1937        log_all_ref_updates = 0;
1938        if (write_ref_sha1(lock, orig_sha1, NULL))
1939                error("unable to write current sha1 into %s", oldrefname);
1940        log_all_ref_updates = flag;
1941
1942 rollbacklog:
1943        if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
1944                error("unable to restore logfile %s from %s: %s",
1945                        oldrefname, newrefname, strerror(errno));
1946        if (!logmoved && log &&
1947            rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
1948                error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
1949                        oldrefname, strerror(errno));
1950
1951        return 1;
1952}
1953
1954int close_ref(struct ref_lock *lock)
1955{
1956        if (close_lock_file(lock->lk))
1957                return -1;
1958        lock->lock_fd = -1;
1959        return 0;
1960}
1961
1962int commit_ref(struct ref_lock *lock)
1963{
1964        if (commit_lock_file(lock->lk))
1965                return -1;
1966        lock->lock_fd = -1;
1967        return 0;
1968}
1969
1970void unlock_ref(struct ref_lock *lock)
1971{
1972        /* Do not free lock->lk -- atexit() still looks at them */
1973        if (lock->lk)
1974                rollback_lock_file(lock->lk);
1975        free(lock->ref_name);
1976        free(lock->orig_ref_name);
1977        free(lock);
1978}
1979
1980/*
1981 * copy the reflog message msg to buf, which has been allocated sufficiently
1982 * large, while cleaning up the whitespaces.  Especially, convert LF to space,
1983 * because reflog file is one line per entry.
1984 */
1985static int copy_msg(char *buf, const char *msg)
1986{
1987        char *cp = buf;
1988        char c;
1989        int wasspace = 1;
1990
1991        *cp++ = '\t';
1992        while ((c = *msg++)) {
1993                if (wasspace && isspace(c))
1994                        continue;
1995                wasspace = isspace(c);
1996                if (wasspace)
1997                        c = ' ';
1998                *cp++ = c;
1999        }
2000        while (buf < cp && isspace(cp[-1]))
2001                cp--;
2002        *cp++ = '\n';
2003        return cp - buf;
2004}
2005
2006int log_ref_setup(const char *refname, char *logfile, int bufsize)
2007{
2008        int logfd, oflags = O_APPEND | O_WRONLY;
2009
2010        git_snpath(logfile, bufsize, "logs/%s", refname);
2011        if (log_all_ref_updates &&
2012            (!prefixcmp(refname, "refs/heads/") ||
2013             !prefixcmp(refname, "refs/remotes/") ||
2014             !prefixcmp(refname, "refs/notes/") ||
2015             !strcmp(refname, "HEAD"))) {
2016                if (safe_create_leading_directories(logfile) < 0)
2017                        return error("unable to create directory for %s",
2018                                     logfile);
2019                oflags |= O_CREAT;
2020        }
2021
2022        logfd = open(logfile, oflags, 0666);
2023        if (logfd < 0) {
2024                if (!(oflags & O_CREAT) && errno == ENOENT)
2025                        return 0;
2026
2027                if ((oflags & O_CREAT) && errno == EISDIR) {
2028                        if (remove_empty_directories(logfile)) {
2029                                return error("There are still logs under '%s'",
2030                                             logfile);
2031                        }
2032                        logfd = open(logfile, oflags, 0666);
2033                }
2034
2035                if (logfd < 0)
2036                        return error("Unable to append to %s: %s",
2037                                     logfile, strerror(errno));
2038        }
2039
2040        adjust_shared_perm(logfile);
2041        close(logfd);
2042        return 0;
2043}
2044
2045static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2046                         const unsigned char *new_sha1, const char *msg)
2047{
2048        int logfd, result, written, oflags = O_APPEND | O_WRONLY;
2049        unsigned maxlen, len;
2050        int msglen;
2051        char log_file[PATH_MAX];
2052        char *logrec;
2053        const char *committer;
2054
2055        if (log_all_ref_updates < 0)
2056                log_all_ref_updates = !is_bare_repository();
2057
2058        result = log_ref_setup(refname, log_file, sizeof(log_file));
2059        if (result)
2060                return result;
2061
2062        logfd = open(log_file, oflags);
2063        if (logfd < 0)
2064                return 0;
2065        msglen = msg ? strlen(msg) : 0;
2066        committer = git_committer_info(0);
2067        maxlen = strlen(committer) + msglen + 100;
2068        logrec = xmalloc(maxlen);
2069        len = sprintf(logrec, "%s %s %s\n",
2070                      sha1_to_hex(old_sha1),
2071                      sha1_to_hex(new_sha1),
2072                      committer);
2073        if (msglen)
2074                len += copy_msg(logrec + len - 1, msg) - 1;
2075        written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
2076        free(logrec);
2077        if (close(logfd) != 0 || written != len)
2078                return error("Unable to append to %s", log_file);
2079        return 0;
2080}
2081
2082static int is_branch(const char *refname)
2083{
2084        return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
2085}
2086
2087int write_ref_sha1(struct ref_lock *lock,
2088        const unsigned char *sha1, const char *logmsg)
2089{
2090        static char term = '\n';
2091        struct object *o;
2092
2093        if (!lock)
2094                return -1;
2095        if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
2096                unlock_ref(lock);
2097                return 0;
2098        }
2099        o = parse_object(sha1);
2100        if (!o) {
2101                error("Trying to write ref %s with nonexistent object %s",
2102                        lock->ref_name, sha1_to_hex(sha1));
2103                unlock_ref(lock);
2104                return -1;
2105        }
2106        if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2107                error("Trying to write non-commit object %s to branch %s",
2108                        sha1_to_hex(sha1), lock->ref_name);
2109                unlock_ref(lock);
2110                return -1;
2111        }
2112        if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
2113            write_in_full(lock->lock_fd, &term, 1) != 1
2114                || close_ref(lock) < 0) {
2115                error("Couldn't write %s", lock->lk->filename);
2116                unlock_ref(lock);
2117                return -1;
2118        }
2119        clear_loose_ref_cache(get_ref_cache(NULL));
2120        if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
2121            (strcmp(lock->ref_name, lock->orig_ref_name) &&
2122             log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
2123                unlock_ref(lock);
2124                return -1;
2125        }
2126        if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2127                /*
2128                 * Special hack: If a branch is updated directly and HEAD
2129                 * points to it (may happen on the remote side of a push
2130                 * for example) then logically the HEAD reflog should be
2131                 * updated too.
2132                 * A generic solution implies reverse symref information,
2133                 * but finding all symrefs pointing to the given branch
2134                 * would be rather costly for this rare event (the direct
2135                 * update of a branch) to be worth it.  So let's cheat and
2136                 * check with HEAD only which should cover 99% of all usage
2137                 * scenarios (even 100% of the default ones).
2138                 */
2139                unsigned char head_sha1[20];
2140                int head_flag;
2141                const char *head_ref;
2142                head_ref = resolve_ref_unsafe("HEAD", head_sha1, 1, &head_flag);
2143                if (head_ref && (head_flag & REF_ISSYMREF) &&
2144                    !strcmp(head_ref, lock->ref_name))
2145                        log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
2146        }
2147        if (commit_ref(lock)) {
2148                error("Couldn't set %s", lock->ref_name);
2149                unlock_ref(lock);
2150                return -1;
2151        }
2152        unlock_ref(lock);
2153        return 0;
2154}
2155
2156int create_symref(const char *ref_target, const char *refs_heads_master,
2157                  const char *logmsg)
2158{
2159        const char *lockpath;
2160        char ref[1000];
2161        int fd, len, written;
2162        char *git_HEAD = git_pathdup("%s", ref_target);
2163        unsigned char old_sha1[20], new_sha1[20];
2164
2165        if (logmsg && read_ref(ref_target, old_sha1))
2166                hashclr(old_sha1);
2167
2168        if (safe_create_leading_directories(git_HEAD) < 0)
2169                return error("unable to create directory for %s", git_HEAD);
2170
2171#ifndef NO_SYMLINK_HEAD
2172        if (prefer_symlink_refs) {
2173                unlink(git_HEAD);
2174                if (!symlink(refs_heads_master, git_HEAD))
2175                        goto done;
2176                fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2177        }
2178#endif
2179
2180        len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2181        if (sizeof(ref) <= len) {
2182                error("refname too long: %s", refs_heads_master);
2183                goto error_free_return;
2184        }
2185        lockpath = mkpath("%s.lock", git_HEAD);
2186        fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
2187        if (fd < 0) {
2188                error("Unable to open %s for writing", lockpath);
2189                goto error_free_return;
2190        }
2191        written = write_in_full(fd, ref, len);
2192        if (close(fd) != 0 || written != len) {
2193                error("Unable to write to %s", lockpath);
2194                goto error_unlink_return;
2195        }
2196        if (rename(lockpath, git_HEAD) < 0) {
2197                error("Unable to create %s", git_HEAD);
2198                goto error_unlink_return;
2199        }
2200        if (adjust_shared_perm(git_HEAD)) {
2201                error("Unable to fix permissions on %s", lockpath);
2202        error_unlink_return:
2203                unlink_or_warn(lockpath);
2204        error_free_return:
2205                free(git_HEAD);
2206                return -1;
2207        }
2208
2209#ifndef NO_SYMLINK_HEAD
2210        done:
2211#endif
2212        if (logmsg && !read_ref(refs_heads_master, new_sha1))
2213                log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
2214
2215        free(git_HEAD);
2216        return 0;
2217}
2218
2219static char *ref_msg(const char *line, const char *endp)
2220{
2221        const char *ep;
2222        line += 82;
2223        ep = memchr(line, '\n', endp - line);
2224        if (!ep)
2225                ep = endp;
2226        return xmemdupz(line, ep - line);
2227}
2228
2229int read_ref_at(const char *refname, unsigned long at_time, int cnt,
2230                unsigned char *sha1, char **msg,
2231                unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
2232{
2233        const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
2234        char *tz_c;
2235        int logfd, tz, reccnt = 0;
2236        struct stat st;
2237        unsigned long date;
2238        unsigned char logged_sha1[20];
2239        void *log_mapped;
2240        size_t mapsz;
2241
2242        logfile = git_path("logs/%s", refname);
2243        logfd = open(logfile, O_RDONLY, 0);
2244        if (logfd < 0)
2245                die_errno("Unable to read log '%s'", logfile);
2246        fstat(logfd, &st);
2247        if (!st.st_size)
2248                die("Log %s is empty.", logfile);
2249        mapsz = xsize_t(st.st_size);
2250        log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
2251        logdata = log_mapped;
2252        close(logfd);
2253
2254        lastrec = NULL;
2255        rec = logend = logdata + st.st_size;
2256        while (logdata < rec) {
2257                reccnt++;
2258                if (logdata < rec && *(rec-1) == '\n')
2259                        rec--;
2260                lastgt = NULL;
2261                while (logdata < rec && *(rec-1) != '\n') {
2262                        rec--;
2263                        if (*rec == '>')
2264                                lastgt = rec;
2265                }
2266                if (!lastgt)
2267                        die("Log %s is corrupt.", logfile);
2268                date = strtoul(lastgt + 1, &tz_c, 10);
2269                if (date <= at_time || cnt == 0) {
2270                        tz = strtoul(tz_c, NULL, 10);
2271                        if (msg)
2272                                *msg = ref_msg(rec, logend);
2273                        if (cutoff_time)
2274                                *cutoff_time = date;
2275                        if (cutoff_tz)
2276                                *cutoff_tz = tz;
2277                        if (cutoff_cnt)
2278                                *cutoff_cnt = reccnt - 1;
2279                        if (lastrec) {
2280                                if (get_sha1_hex(lastrec, logged_sha1))
2281                                        die("Log %s is corrupt.", logfile);
2282                                if (get_sha1_hex(rec + 41, sha1))
2283                                        die("Log %s is corrupt.", logfile);
2284                                if (hashcmp(logged_sha1, sha1)) {
2285                                        warning("Log %s has gap after %s.",
2286                                                logfile, show_date(date, tz, DATE_RFC2822));
2287                                }
2288                        }
2289                        else if (date == at_time) {
2290                                if (get_sha1_hex(rec + 41, sha1))
2291                                        die("Log %s is corrupt.", logfile);
2292                        }
2293                        else {
2294                                if (get_sha1_hex(rec + 41, logged_sha1))
2295                                        die("Log %s is corrupt.", logfile);
2296                                if (hashcmp(logged_sha1, sha1)) {
2297                                        warning("Log %s unexpectedly ended on %s.",
2298                                                logfile, show_date(date, tz, DATE_RFC2822));
2299                                }
2300                        }
2301                        munmap(log_mapped, mapsz);
2302                        return 0;
2303                }
2304                lastrec = rec;
2305                if (cnt > 0)
2306                        cnt--;
2307        }
2308
2309        rec = logdata;
2310        while (rec < logend && *rec != '>' && *rec != '\n')
2311                rec++;
2312        if (rec == logend || *rec == '\n')
2313                die("Log %s is corrupt.", logfile);
2314        date = strtoul(rec + 1, &tz_c, 10);
2315        tz = strtoul(tz_c, NULL, 10);
2316        if (get_sha1_hex(logdata, sha1))
2317                die("Log %s is corrupt.", logfile);
2318        if (is_null_sha1(sha1)) {
2319                if (get_sha1_hex(logdata + 41, sha1))
2320                        die("Log %s is corrupt.", logfile);
2321        }
2322        if (msg)
2323                *msg = ref_msg(logdata, logend);
2324        munmap(log_mapped, mapsz);
2325
2326        if (cutoff_time)
2327                *cutoff_time = date;
2328        if (cutoff_tz)
2329                *cutoff_tz = tz;
2330        if (cutoff_cnt)
2331                *cutoff_cnt = reccnt;
2332        return 1;
2333}
2334
2335int for_each_recent_reflog_ent(const char *refname, each_reflog_ent_fn fn, long ofs, void *cb_data)
2336{
2337        const char *logfile;
2338        FILE *logfp;
2339        struct strbuf sb = STRBUF_INIT;
2340        int ret = 0;
2341
2342        logfile = git_path("logs/%s", refname);
2343        logfp = fopen(logfile, "r");
2344        if (!logfp)
2345                return -1;
2346
2347        if (ofs) {
2348                struct stat statbuf;
2349                if (fstat(fileno(logfp), &statbuf) ||
2350                    statbuf.st_size < ofs ||
2351                    fseek(logfp, -ofs, SEEK_END) ||
2352                    strbuf_getwholeline(&sb, logfp, '\n')) {
2353                        fclose(logfp);
2354                        strbuf_release(&sb);
2355                        return -1;
2356                }
2357        }
2358
2359        while (!strbuf_getwholeline(&sb, logfp, '\n')) {
2360                unsigned char osha1[20], nsha1[20];
2361                char *email_end, *message;
2362                unsigned long timestamp;
2363                int tz;
2364
2365                /* old SP new SP name <email> SP time TAB msg LF */
2366                if (sb.len < 83 || sb.buf[sb.len - 1] != '\n' ||
2367                    get_sha1_hex(sb.buf, osha1) || sb.buf[40] != ' ' ||
2368                    get_sha1_hex(sb.buf + 41, nsha1) || sb.buf[81] != ' ' ||
2369                    !(email_end = strchr(sb.buf + 82, '>')) ||
2370                    email_end[1] != ' ' ||
2371                    !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2372                    !message || message[0] != ' ' ||
2373                    (message[1] != '+' && message[1] != '-') ||
2374                    !isdigit(message[2]) || !isdigit(message[3]) ||
2375                    !isdigit(message[4]) || !isdigit(message[5]))
2376                        continue; /* corrupt? */
2377                email_end[1] = '\0';
2378                tz = strtol(message + 1, NULL, 10);
2379                if (message[6] != '\t')
2380                        message += 6;
2381                else
2382                        message += 7;
2383                ret = fn(osha1, nsha1, sb.buf + 82, timestamp, tz, message,
2384                         cb_data);
2385                if (ret)
2386                        break;
2387        }
2388        fclose(logfp);
2389        strbuf_release(&sb);
2390        return ret;
2391}
2392
2393int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2394{
2395        return for_each_recent_reflog_ent(refname, fn, 0, cb_data);
2396}
2397
2398/*
2399 * Call fn for each reflog in the namespace indicated by name.  name
2400 * must be empty or end with '/'.  Name will be used as a scratch
2401 * space, but its contents will be restored before return.
2402 */
2403static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
2404{
2405        DIR *d = opendir(git_path("logs/%s", name->buf));
2406        int retval = 0;
2407        struct dirent *de;
2408        int oldlen = name->len;
2409
2410        if (!d)
2411                return name->len ? errno : 0;
2412
2413        while ((de = readdir(d)) != NULL) {
2414                struct stat st;
2415
2416                if (de->d_name[0] == '.')
2417                        continue;
2418                if (has_extension(de->d_name, ".lock"))
2419                        continue;
2420                strbuf_addstr(name, de->d_name);
2421                if (stat(git_path("logs/%s", name->buf), &st) < 0) {
2422                        ; /* silently ignore */
2423                } else {
2424                        if (S_ISDIR(st.st_mode)) {
2425                                strbuf_addch(name, '/');
2426                                retval = do_for_each_reflog(name, fn, cb_data);
2427                        } else {
2428                                unsigned char sha1[20];
2429                                if (read_ref_full(name->buf, sha1, 0, NULL))
2430                                        retval = error("bad ref for %s", name->buf);
2431                                else
2432                                        retval = fn(name->buf, sha1, 0, cb_data);
2433                        }
2434                        if (retval)
2435                                break;
2436                }
2437                strbuf_setlen(name, oldlen);
2438        }
2439        closedir(d);
2440        return retval;
2441}
2442
2443int for_each_reflog(each_ref_fn fn, void *cb_data)
2444{
2445        int retval;
2446        struct strbuf name;
2447        strbuf_init(&name, PATH_MAX);
2448        retval = do_for_each_reflog(&name, fn, cb_data);
2449        strbuf_release(&name);
2450        return retval;
2451}
2452
2453int update_ref(const char *action, const char *refname,
2454                const unsigned char *sha1, const unsigned char *oldval,
2455                int flags, enum action_on_err onerr)
2456{
2457        static struct ref_lock *lock;
2458        lock = lock_any_ref_for_update(refname, oldval, flags);
2459        if (!lock) {
2460                const char *str = "Cannot lock the ref '%s'.";
2461                switch (onerr) {
2462                case MSG_ON_ERR: error(str, refname); break;
2463                case DIE_ON_ERR: die(str, refname); break;
2464                case QUIET_ON_ERR: break;
2465                }
2466                return 1;
2467        }
2468        if (write_ref_sha1(lock, sha1, action) < 0) {
2469                const char *str = "Cannot update the ref '%s'.";
2470                switch (onerr) {
2471                case MSG_ON_ERR: error(str, refname); break;
2472                case DIE_ON_ERR: die(str, refname); break;
2473                case QUIET_ON_ERR: break;
2474                }
2475                return 1;
2476        }
2477        return 0;
2478}
2479
2480struct ref *find_ref_by_name(const struct ref *list, const char *name)
2481{
2482        for ( ; list; list = list->next)
2483                if (!strcmp(list->name, name))
2484                        return (struct ref *)list;
2485        return NULL;
2486}
2487
2488/*
2489 * generate a format suitable for scanf from a ref_rev_parse_rules
2490 * rule, that is replace the "%.*s" spec with a "%s" spec
2491 */
2492static void gen_scanf_fmt(char *scanf_fmt, const char *rule)
2493{
2494        char *spec;
2495
2496        spec = strstr(rule, "%.*s");
2497        if (!spec || strstr(spec + 4, "%.*s"))
2498                die("invalid rule in ref_rev_parse_rules: %s", rule);
2499
2500        /* copy all until spec */
2501        strncpy(scanf_fmt, rule, spec - rule);
2502        scanf_fmt[spec - rule] = '\0';
2503        /* copy new spec */
2504        strcat(scanf_fmt, "%s");
2505        /* copy remaining rule */
2506        strcat(scanf_fmt, spec + 4);
2507
2508        return;
2509}
2510
2511char *shorten_unambiguous_ref(const char *refname, int strict)
2512{
2513        int i;
2514        static char **scanf_fmts;
2515        static int nr_rules;
2516        char *short_name;
2517
2518        /* pre generate scanf formats from ref_rev_parse_rules[] */
2519        if (!nr_rules) {
2520                size_t total_len = 0;
2521
2522                /* the rule list is NULL terminated, count them first */
2523                for (; ref_rev_parse_rules[nr_rules]; nr_rules++)
2524                        /* no +1 because strlen("%s") < strlen("%.*s") */
2525                        total_len += strlen(ref_rev_parse_rules[nr_rules]);
2526
2527                scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
2528
2529                total_len = 0;
2530                for (i = 0; i < nr_rules; i++) {
2531                        scanf_fmts[i] = (char *)&scanf_fmts[nr_rules]
2532                                        + total_len;
2533                        gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);
2534                        total_len += strlen(ref_rev_parse_rules[i]);
2535                }
2536        }
2537
2538        /* bail out if there are no rules */
2539        if (!nr_rules)
2540                return xstrdup(refname);
2541
2542        /* buffer for scanf result, at most refname must fit */
2543        short_name = xstrdup(refname);
2544
2545        /* skip first rule, it will always match */
2546        for (i = nr_rules - 1; i > 0 ; --i) {
2547                int j;
2548                int rules_to_fail = i;
2549                int short_name_len;
2550
2551                if (1 != sscanf(refname, scanf_fmts[i], short_name))
2552                        continue;
2553
2554                short_name_len = strlen(short_name);
2555
2556                /*
2557                 * in strict mode, all (except the matched one) rules
2558                 * must fail to resolve to a valid non-ambiguous ref
2559                 */
2560                if (strict)
2561                        rules_to_fail = nr_rules;
2562
2563                /*
2564                 * check if the short name resolves to a valid ref,
2565                 * but use only rules prior to the matched one
2566                 */
2567                for (j = 0; j < rules_to_fail; j++) {
2568                        const char *rule = ref_rev_parse_rules[j];
2569                        char refname[PATH_MAX];
2570
2571                        /* skip matched rule */
2572                        if (i == j)
2573                                continue;
2574
2575                        /*
2576                         * the short name is ambiguous, if it resolves
2577                         * (with this previous rule) to a valid ref
2578                         * read_ref() returns 0 on success
2579                         */
2580                        mksnpath(refname, sizeof(refname),
2581                                 rule, short_name_len, short_name);
2582                        if (ref_exists(refname))
2583                                break;
2584                }
2585
2586                /*
2587                 * short name is non-ambiguous if all previous rules
2588                 * haven't resolved to a valid ref
2589                 */
2590                if (j == rules_to_fail)
2591                        return short_name;
2592        }
2593
2594        free(short_name);
2595        return xstrdup(refname);
2596}
2597
2598static struct string_list *hide_refs;
2599
2600int parse_hide_refs_config(const char *var, const char *value, const char *section)
2601{
2602        if (!strcmp("transfer.hiderefs", var) ||
2603            /* NEEDSWORK: use parse_config_key() once both are merged */
2604            (!prefixcmp(var, section) && var[strlen(section)] == '.' &&
2605             !strcmp(var + strlen(section), ".hiderefs"))) {
2606                char *ref;
2607                int len;
2608
2609                if (!value)
2610                        return config_error_nonbool(var);
2611                ref = xstrdup(value);
2612                len = strlen(ref);
2613                while (len && ref[len - 1] == '/')
2614                        ref[--len] = '\0';
2615                if (!hide_refs) {
2616                        hide_refs = xcalloc(1, sizeof(*hide_refs));
2617                        hide_refs->strdup_strings = 1;
2618                }
2619                string_list_append(hide_refs, ref);
2620        }
2621        return 0;
2622}
2623
2624int ref_is_hidden(const char *refname)
2625{
2626        struct string_list_item *item;
2627
2628        if (!hide_refs)
2629                return 0;
2630        for_each_string_list_item(item, hide_refs) {
2631                int len;
2632                if (prefixcmp(refname, item->string))
2633                        continue;
2634                len = strlen(item->string);
2635                if (!refname[len] || refname[len] == '/')
2636                        return 1;
2637        }
2638        return 0;
2639}