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