refs / files-backend.con commit packed_read_raw_ref(): new function, replacing `resolve_packed_ref()` (d13fa1a)
   1#include "../cache.h"
   2#include "../refs.h"
   3#include "refs-internal.h"
   4#include "ref-cache.h"
   5#include "../iterator.h"
   6#include "../dir-iterator.h"
   7#include "../lockfile.h"
   8#include "../object.h"
   9#include "../dir.h"
  10
  11struct ref_lock {
  12        char *ref_name;
  13        struct lock_file *lk;
  14        struct object_id old_oid;
  15};
  16
  17/*
  18 * Return true if refname, which has the specified oid and flags, can
  19 * be resolved to an object in the database. If the referred-to object
  20 * does not exist, emit a warning and return false.
  21 */
  22static int ref_resolves_to_object(const char *refname,
  23                                  const struct object_id *oid,
  24                                  unsigned int flags)
  25{
  26        if (flags & REF_ISBROKEN)
  27                return 0;
  28        if (!has_sha1_file(oid->hash)) {
  29                error("%s does not point to a valid object!", refname);
  30                return 0;
  31        }
  32        return 1;
  33}
  34
  35struct packed_ref_cache {
  36        struct ref_cache *cache;
  37
  38        /*
  39         * Count of references to the data structure in this instance,
  40         * including the pointer from files_ref_store::packed if any.
  41         * The data will not be freed as long as the reference count
  42         * is nonzero.
  43         */
  44        unsigned int referrers;
  45
  46        /* The metadata from when this packed-refs cache was read */
  47        struct stat_validity validity;
  48};
  49
  50/*
  51 * A container for `packed-refs`-related data. It is not (yet) a
  52 * `ref_store`.
  53 */
  54struct packed_ref_store {
  55        unsigned int store_flags;
  56
  57        /* The path of the "packed-refs" file: */
  58        char *path;
  59
  60        /*
  61         * A cache of the values read from the `packed-refs` file, if
  62         * it might still be current; otherwise, NULL.
  63         */
  64        struct packed_ref_cache *cache;
  65
  66        /*
  67         * Lock used for the "packed-refs" file. Note that this (and
  68         * thus the enclosing `packed_ref_store`) must not be freed.
  69         */
  70        struct lock_file lock;
  71};
  72
  73static struct packed_ref_store *packed_ref_store_create(
  74                const char *path, unsigned int store_flags)
  75{
  76        struct packed_ref_store *refs = xcalloc(1, sizeof(*refs));
  77
  78        refs->store_flags = store_flags;
  79        refs->path = xstrdup(path);
  80        return refs;
  81}
  82
  83/*
  84 * Die if refs is not the main ref store. caller is used in any
  85 * necessary error messages.
  86 */
  87static void packed_assert_main_repository(struct packed_ref_store *refs,
  88                                          const char *caller)
  89{
  90        if (refs->store_flags & REF_STORE_MAIN)
  91                return;
  92
  93        die("BUG: operation %s only allowed for main ref store", caller);
  94}
  95
  96/*
  97 * Future: need to be in "struct repository"
  98 * when doing a full libification.
  99 */
 100struct files_ref_store {
 101        struct ref_store base;
 102        unsigned int store_flags;
 103
 104        char *gitdir;
 105        char *gitcommondir;
 106
 107        struct ref_cache *loose;
 108
 109        struct packed_ref_store *packed_ref_store;
 110};
 111
 112/*
 113 * Increment the reference count of *packed_refs.
 114 */
 115static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
 116{
 117        packed_refs->referrers++;
 118}
 119
 120/*
 121 * Decrease the reference count of *packed_refs.  If it goes to zero,
 122 * free *packed_refs and return true; otherwise return false.
 123 */
 124static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
 125{
 126        if (!--packed_refs->referrers) {
 127                free_ref_cache(packed_refs->cache);
 128                stat_validity_clear(&packed_refs->validity);
 129                free(packed_refs);
 130                return 1;
 131        } else {
 132                return 0;
 133        }
 134}
 135
 136static void clear_packed_ref_cache(struct packed_ref_store *refs)
 137{
 138        if (refs->cache) {
 139                struct packed_ref_cache *cache = refs->cache;
 140
 141                if (is_lock_file_locked(&refs->lock))
 142                        die("BUG: packed-ref cache cleared while locked");
 143                refs->cache = NULL;
 144                release_packed_ref_cache(cache);
 145        }
 146}
 147
 148static void clear_loose_ref_cache(struct files_ref_store *refs)
 149{
 150        if (refs->loose) {
 151                free_ref_cache(refs->loose);
 152                refs->loose = NULL;
 153        }
 154}
 155
 156/*
 157 * Create a new submodule ref cache and add it to the internal
 158 * set of caches.
 159 */
 160static struct ref_store *files_ref_store_create(const char *gitdir,
 161                                                unsigned int flags)
 162{
 163        struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
 164        struct ref_store *ref_store = (struct ref_store *)refs;
 165        struct strbuf sb = STRBUF_INIT;
 166
 167        base_ref_store_init(ref_store, &refs_be_files);
 168        refs->store_flags = flags;
 169
 170        refs->gitdir = xstrdup(gitdir);
 171        get_common_dir_noenv(&sb, gitdir);
 172        refs->gitcommondir = strbuf_detach(&sb, NULL);
 173        strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
 174        refs->packed_ref_store = packed_ref_store_create(sb.buf, flags);
 175        strbuf_release(&sb);
 176
 177        return ref_store;
 178}
 179
 180/*
 181 * Die if refs is not the main ref store. caller is used in any
 182 * necessary error messages.
 183 */
 184static void files_assert_main_repository(struct files_ref_store *refs,
 185                                         const char *caller)
 186{
 187        if (refs->store_flags & REF_STORE_MAIN)
 188                return;
 189
 190        die("BUG: operation %s only allowed for main ref store", caller);
 191}
 192
 193/*
 194 * Downcast ref_store to files_ref_store. Die if ref_store is not a
 195 * files_ref_store. required_flags is compared with ref_store's
 196 * store_flags to ensure the ref_store has all required capabilities.
 197 * "caller" is used in any necessary error messages.
 198 */
 199static struct files_ref_store *files_downcast(struct ref_store *ref_store,
 200                                              unsigned int required_flags,
 201                                              const char *caller)
 202{
 203        struct files_ref_store *refs;
 204
 205        if (ref_store->be != &refs_be_files)
 206                die("BUG: ref_store is type \"%s\" not \"files\" in %s",
 207                    ref_store->be->name, caller);
 208
 209        refs = (struct files_ref_store *)ref_store;
 210
 211        if ((refs->store_flags & required_flags) != required_flags)
 212                die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
 213                    caller, required_flags, refs->store_flags);
 214
 215        return refs;
 216}
 217
 218/* The length of a peeled reference line in packed-refs, including EOL: */
 219#define PEELED_LINE_LENGTH 42
 220
 221/*
 222 * The packed-refs header line that we write out.  Perhaps other
 223 * traits will be added later.  The trailing space is required.
 224 */
 225static const char PACKED_REFS_HEADER[] =
 226        "# pack-refs with: peeled fully-peeled \n";
 227
 228/*
 229 * Parse one line from a packed-refs file.  Write the SHA1 to sha1.
 230 * Return a pointer to the refname within the line (null-terminated),
 231 * or NULL if there was a problem.
 232 */
 233static const char *parse_ref_line(struct strbuf *line, struct object_id *oid)
 234{
 235        const char *ref;
 236
 237        if (parse_oid_hex(line->buf, oid, &ref) < 0)
 238                return NULL;
 239        if (!isspace(*ref++))
 240                return NULL;
 241
 242        if (isspace(*ref))
 243                return NULL;
 244
 245        if (line->buf[line->len - 1] != '\n')
 246                return NULL;
 247        line->buf[--line->len] = 0;
 248
 249        return ref;
 250}
 251
 252/*
 253 * Read from `packed_refs_file` into a newly-allocated
 254 * `packed_ref_cache` and return it. The return value will already
 255 * have its reference count incremented.
 256 *
 257 * A comment line of the form "# pack-refs with: " may contain zero or
 258 * more traits. We interpret the traits as follows:
 259 *
 260 *   No traits:
 261 *
 262 *      Probably no references are peeled. But if the file contains a
 263 *      peeled value for a reference, we will use it.
 264 *
 265 *   peeled:
 266 *
 267 *      References under "refs/tags/", if they *can* be peeled, *are*
 268 *      peeled in this file. References outside of "refs/tags/" are
 269 *      probably not peeled even if they could have been, but if we find
 270 *      a peeled value for such a reference we will use it.
 271 *
 272 *   fully-peeled:
 273 *
 274 *      All references in the file that can be peeled are peeled.
 275 *      Inversely (and this is more important), any references in the
 276 *      file for which no peeled value is recorded is not peelable. This
 277 *      trait should typically be written alongside "peeled" for
 278 *      compatibility with older clients, but we do not require it
 279 *      (i.e., "peeled" is a no-op if "fully-peeled" is set).
 280 */
 281static struct packed_ref_cache *read_packed_refs(const char *packed_refs_file)
 282{
 283        FILE *f;
 284        struct packed_ref_cache *packed_refs = xcalloc(1, sizeof(*packed_refs));
 285        struct ref_entry *last = NULL;
 286        struct strbuf line = STRBUF_INIT;
 287        enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
 288        struct ref_dir *dir;
 289
 290        acquire_packed_ref_cache(packed_refs);
 291        packed_refs->cache = create_ref_cache(NULL, NULL);
 292        packed_refs->cache->root->flag &= ~REF_INCOMPLETE;
 293
 294        f = fopen(packed_refs_file, "r");
 295        if (!f) {
 296                if (errno == ENOENT) {
 297                        /*
 298                         * This is OK; it just means that no
 299                         * "packed-refs" file has been written yet,
 300                         * which is equivalent to it being empty.
 301                         */
 302                        return packed_refs;
 303                } else {
 304                        die_errno("couldn't read %s", packed_refs_file);
 305                }
 306        }
 307
 308        stat_validity_update(&packed_refs->validity, fileno(f));
 309
 310        dir = get_ref_dir(packed_refs->cache->root);
 311        while (strbuf_getwholeline(&line, f, '\n') != EOF) {
 312                struct object_id oid;
 313                const char *refname;
 314                const char *traits;
 315
 316                if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
 317                        if (strstr(traits, " fully-peeled "))
 318                                peeled = PEELED_FULLY;
 319                        else if (strstr(traits, " peeled "))
 320                                peeled = PEELED_TAGS;
 321                        /* perhaps other traits later as well */
 322                        continue;
 323                }
 324
 325                refname = parse_ref_line(&line, &oid);
 326                if (refname) {
 327                        int flag = REF_ISPACKED;
 328
 329                        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
 330                                if (!refname_is_safe(refname))
 331                                        die("packed refname is dangerous: %s", refname);
 332                                oidclr(&oid);
 333                                flag |= REF_BAD_NAME | REF_ISBROKEN;
 334                        }
 335                        last = create_ref_entry(refname, &oid, flag);
 336                        if (peeled == PEELED_FULLY ||
 337                            (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
 338                                last->flag |= REF_KNOWS_PEELED;
 339                        add_ref_entry(dir, last);
 340                        continue;
 341                }
 342                if (last &&
 343                    line.buf[0] == '^' &&
 344                    line.len == PEELED_LINE_LENGTH &&
 345                    line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
 346                    !get_oid_hex(line.buf + 1, &oid)) {
 347                        oidcpy(&last->u.value.peeled, &oid);
 348                        /*
 349                         * Regardless of what the file header said,
 350                         * we definitely know the value of *this*
 351                         * reference:
 352                         */
 353                        last->flag |= REF_KNOWS_PEELED;
 354                }
 355        }
 356
 357        fclose(f);
 358        strbuf_release(&line);
 359
 360        return packed_refs;
 361}
 362
 363static void files_reflog_path(struct files_ref_store *refs,
 364                              struct strbuf *sb,
 365                              const char *refname)
 366{
 367        if (!refname) {
 368                /*
 369                 * FIXME: of course this is wrong in multi worktree
 370                 * setting. To be fixed real soon.
 371                 */
 372                strbuf_addf(sb, "%s/logs", refs->gitcommondir);
 373                return;
 374        }
 375
 376        switch (ref_type(refname)) {
 377        case REF_TYPE_PER_WORKTREE:
 378        case REF_TYPE_PSEUDOREF:
 379                strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
 380                break;
 381        case REF_TYPE_NORMAL:
 382                strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
 383                break;
 384        default:
 385                die("BUG: unknown ref type %d of ref %s",
 386                    ref_type(refname), refname);
 387        }
 388}
 389
 390static void files_ref_path(struct files_ref_store *refs,
 391                           struct strbuf *sb,
 392                           const char *refname)
 393{
 394        switch (ref_type(refname)) {
 395        case REF_TYPE_PER_WORKTREE:
 396        case REF_TYPE_PSEUDOREF:
 397                strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
 398                break;
 399        case REF_TYPE_NORMAL:
 400                strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
 401                break;
 402        default:
 403                die("BUG: unknown ref type %d of ref %s",
 404                    ref_type(refname), refname);
 405        }
 406}
 407
 408/*
 409 * Check that the packed refs cache (if any) still reflects the
 410 * contents of the file. If not, clear the cache.
 411 */
 412static void validate_packed_ref_cache(struct packed_ref_store *refs)
 413{
 414        if (refs->cache &&
 415            !stat_validity_check(&refs->cache->validity, refs->path))
 416                clear_packed_ref_cache(refs);
 417}
 418
 419/*
 420 * Get the packed_ref_cache for the specified packed_ref_store,
 421 * creating and populating it if it hasn't been read before or if the
 422 * file has been changed (according to its `validity` field) since it
 423 * was last read. On the other hand, if we hold the lock, then assume
 424 * that the file hasn't been changed out from under us, so skip the
 425 * extra `stat()` call in `stat_validity_check()`.
 426 */
 427static struct packed_ref_cache *get_packed_ref_cache(struct packed_ref_store *refs)
 428{
 429        if (!is_lock_file_locked(&refs->lock))
 430                validate_packed_ref_cache(refs);
 431
 432        if (!refs->cache)
 433                refs->cache = read_packed_refs(refs->path);
 434
 435        return refs->cache;
 436}
 437
 438static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
 439{
 440        return get_ref_dir(packed_ref_cache->cache->root);
 441}
 442
 443static struct ref_dir *get_packed_refs(struct packed_ref_store *refs)
 444{
 445        return get_packed_ref_dir(get_packed_ref_cache(refs));
 446}
 447
 448/*
 449 * Add or overwrite a reference in the in-memory packed reference
 450 * cache. This may only be called while the packed-refs file is locked
 451 * (see lock_packed_refs()). To actually write the packed-refs file,
 452 * call commit_packed_refs().
 453 */
 454static void add_packed_ref(struct packed_ref_store *refs,
 455                           const char *refname, const struct object_id *oid)
 456{
 457        struct ref_dir *packed_refs;
 458        struct ref_entry *packed_entry;
 459
 460        if (!is_lock_file_locked(&refs->lock))
 461                die("BUG: packed refs not locked");
 462
 463        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
 464                die("Reference has invalid format: '%s'", refname);
 465
 466        packed_refs = get_packed_refs(refs);
 467        packed_entry = find_ref_entry(packed_refs, refname);
 468        if (packed_entry) {
 469                /* Overwrite the existing entry: */
 470                oidcpy(&packed_entry->u.value.oid, oid);
 471                packed_entry->flag = REF_ISPACKED;
 472                oidclr(&packed_entry->u.value.peeled);
 473        } else {
 474                packed_entry = create_ref_entry(refname, oid, REF_ISPACKED);
 475                add_ref_entry(packed_refs, packed_entry);
 476        }
 477}
 478
 479/*
 480 * Read the loose references from the namespace dirname into dir
 481 * (without recursing).  dirname must end with '/'.  dir must be the
 482 * directory entry corresponding to dirname.
 483 */
 484static void loose_fill_ref_dir(struct ref_store *ref_store,
 485                               struct ref_dir *dir, const char *dirname)
 486{
 487        struct files_ref_store *refs =
 488                files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
 489        DIR *d;
 490        struct dirent *de;
 491        int dirnamelen = strlen(dirname);
 492        struct strbuf refname;
 493        struct strbuf path = STRBUF_INIT;
 494        size_t path_baselen;
 495
 496        files_ref_path(refs, &path, dirname);
 497        path_baselen = path.len;
 498
 499        d = opendir(path.buf);
 500        if (!d) {
 501                strbuf_release(&path);
 502                return;
 503        }
 504
 505        strbuf_init(&refname, dirnamelen + 257);
 506        strbuf_add(&refname, dirname, dirnamelen);
 507
 508        while ((de = readdir(d)) != NULL) {
 509                struct object_id oid;
 510                struct stat st;
 511                int flag;
 512
 513                if (de->d_name[0] == '.')
 514                        continue;
 515                if (ends_with(de->d_name, ".lock"))
 516                        continue;
 517                strbuf_addstr(&refname, de->d_name);
 518                strbuf_addstr(&path, de->d_name);
 519                if (stat(path.buf, &st) < 0) {
 520                        ; /* silently ignore */
 521                } else if (S_ISDIR(st.st_mode)) {
 522                        strbuf_addch(&refname, '/');
 523                        add_entry_to_dir(dir,
 524                                         create_dir_entry(dir->cache, refname.buf,
 525                                                          refname.len, 1));
 526                } else {
 527                        if (!refs_resolve_ref_unsafe(&refs->base,
 528                                                     refname.buf,
 529                                                     RESOLVE_REF_READING,
 530                                                     oid.hash, &flag)) {
 531                                oidclr(&oid);
 532                                flag |= REF_ISBROKEN;
 533                        } else if (is_null_oid(&oid)) {
 534                                /*
 535                                 * It is so astronomically unlikely
 536                                 * that NULL_SHA1 is the SHA-1 of an
 537                                 * actual object that we consider its
 538                                 * appearance in a loose reference
 539                                 * file to be repo corruption
 540                                 * (probably due to a software bug).
 541                                 */
 542                                flag |= REF_ISBROKEN;
 543                        }
 544
 545                        if (check_refname_format(refname.buf,
 546                                                 REFNAME_ALLOW_ONELEVEL)) {
 547                                if (!refname_is_safe(refname.buf))
 548                                        die("loose refname is dangerous: %s", refname.buf);
 549                                oidclr(&oid);
 550                                flag |= REF_BAD_NAME | REF_ISBROKEN;
 551                        }
 552                        add_entry_to_dir(dir,
 553                                         create_ref_entry(refname.buf, &oid, flag));
 554                }
 555                strbuf_setlen(&refname, dirnamelen);
 556                strbuf_setlen(&path, path_baselen);
 557        }
 558        strbuf_release(&refname);
 559        strbuf_release(&path);
 560        closedir(d);
 561
 562        /*
 563         * Manually add refs/bisect, which, being per-worktree, might
 564         * not appear in the directory listing for refs/ in the main
 565         * repo.
 566         */
 567        if (!strcmp(dirname, "refs/")) {
 568                int pos = search_ref_dir(dir, "refs/bisect/", 12);
 569
 570                if (pos < 0) {
 571                        struct ref_entry *child_entry = create_dir_entry(
 572                                        dir->cache, "refs/bisect/", 12, 1);
 573                        add_entry_to_dir(dir, child_entry);
 574                }
 575        }
 576}
 577
 578static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
 579{
 580        if (!refs->loose) {
 581                /*
 582                 * Mark the top-level directory complete because we
 583                 * are about to read the only subdirectory that can
 584                 * hold references:
 585                 */
 586                refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
 587
 588                /* We're going to fill the top level ourselves: */
 589                refs->loose->root->flag &= ~REF_INCOMPLETE;
 590
 591                /*
 592                 * Add an incomplete entry for "refs/" (to be filled
 593                 * lazily):
 594                 */
 595                add_entry_to_dir(get_ref_dir(refs->loose->root),
 596                                 create_dir_entry(refs->loose, "refs/", 5, 1));
 597        }
 598        return refs->loose;
 599}
 600
 601/*
 602 * Return the ref_entry for the given refname from the packed
 603 * references.  If it does not exist, return NULL.
 604 */
 605static struct ref_entry *get_packed_ref(struct packed_ref_store *refs,
 606                                        const char *refname)
 607{
 608        return find_ref_entry(get_packed_refs(refs), refname);
 609}
 610
 611static int packed_read_raw_ref(struct packed_ref_store *refs,
 612                               const char *refname, unsigned char *sha1,
 613                               struct strbuf *referent, unsigned int *type)
 614{
 615        struct ref_entry *entry;
 616
 617        *type = 0;
 618
 619        entry = get_packed_ref(refs, refname);
 620        if (!entry) {
 621                errno = ENOENT;
 622                return -1;
 623        }
 624
 625        hashcpy(sha1, entry->u.value.oid.hash);
 626        *type = REF_ISPACKED;
 627        return 0;
 628}
 629
 630static int files_read_raw_ref(struct ref_store *ref_store,
 631                              const char *refname, unsigned char *sha1,
 632                              struct strbuf *referent, unsigned int *type)
 633{
 634        struct files_ref_store *refs =
 635                files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
 636        struct strbuf sb_contents = STRBUF_INIT;
 637        struct strbuf sb_path = STRBUF_INIT;
 638        const char *path;
 639        const char *buf;
 640        struct stat st;
 641        int fd;
 642        int ret = -1;
 643        int save_errno;
 644        int remaining_retries = 3;
 645
 646        *type = 0;
 647        strbuf_reset(&sb_path);
 648
 649        files_ref_path(refs, &sb_path, refname);
 650
 651        path = sb_path.buf;
 652
 653stat_ref:
 654        /*
 655         * We might have to loop back here to avoid a race
 656         * condition: first we lstat() the file, then we try
 657         * to read it as a link or as a file.  But if somebody
 658         * changes the type of the file (file <-> directory
 659         * <-> symlink) between the lstat() and reading, then
 660         * we don't want to report that as an error but rather
 661         * try again starting with the lstat().
 662         *
 663         * We'll keep a count of the retries, though, just to avoid
 664         * any confusing situation sending us into an infinite loop.
 665         */
 666
 667        if (remaining_retries-- <= 0)
 668                goto out;
 669
 670        if (lstat(path, &st) < 0) {
 671                if (errno != ENOENT)
 672                        goto out;
 673                if (packed_read_raw_ref(refs->packed_ref_store, refname,
 674                                        sha1, referent, type)) {
 675                        errno = ENOENT;
 676                        goto out;
 677                }
 678                ret = 0;
 679                goto out;
 680        }
 681
 682        /* Follow "normalized" - ie "refs/.." symlinks by hand */
 683        if (S_ISLNK(st.st_mode)) {
 684                strbuf_reset(&sb_contents);
 685                if (strbuf_readlink(&sb_contents, path, 0) < 0) {
 686                        if (errno == ENOENT || errno == EINVAL)
 687                                /* inconsistent with lstat; retry */
 688                                goto stat_ref;
 689                        else
 690                                goto out;
 691                }
 692                if (starts_with(sb_contents.buf, "refs/") &&
 693                    !check_refname_format(sb_contents.buf, 0)) {
 694                        strbuf_swap(&sb_contents, referent);
 695                        *type |= REF_ISSYMREF;
 696                        ret = 0;
 697                        goto out;
 698                }
 699                /*
 700                 * It doesn't look like a refname; fall through to just
 701                 * treating it like a non-symlink, and reading whatever it
 702                 * points to.
 703                 */
 704        }
 705
 706        /* Is it a directory? */
 707        if (S_ISDIR(st.st_mode)) {
 708                /*
 709                 * Even though there is a directory where the loose
 710                 * ref is supposed to be, there could still be a
 711                 * packed ref:
 712                 */
 713                if (packed_read_raw_ref(refs->packed_ref_store, refname,
 714                                        sha1, referent, type)) {
 715                        errno = EISDIR;
 716                        goto out;
 717                }
 718                ret = 0;
 719                goto out;
 720        }
 721
 722        /*
 723         * Anything else, just open it and try to use it as
 724         * a ref
 725         */
 726        fd = open(path, O_RDONLY);
 727        if (fd < 0) {
 728                if (errno == ENOENT && !S_ISLNK(st.st_mode))
 729                        /* inconsistent with lstat; retry */
 730                        goto stat_ref;
 731                else
 732                        goto out;
 733        }
 734        strbuf_reset(&sb_contents);
 735        if (strbuf_read(&sb_contents, fd, 256) < 0) {
 736                int save_errno = errno;
 737                close(fd);
 738                errno = save_errno;
 739                goto out;
 740        }
 741        close(fd);
 742        strbuf_rtrim(&sb_contents);
 743        buf = sb_contents.buf;
 744        if (starts_with(buf, "ref:")) {
 745                buf += 4;
 746                while (isspace(*buf))
 747                        buf++;
 748
 749                strbuf_reset(referent);
 750                strbuf_addstr(referent, buf);
 751                *type |= REF_ISSYMREF;
 752                ret = 0;
 753                goto out;
 754        }
 755
 756        /*
 757         * Please note that FETCH_HEAD has additional
 758         * data after the sha.
 759         */
 760        if (get_sha1_hex(buf, sha1) ||
 761            (buf[40] != '\0' && !isspace(buf[40]))) {
 762                *type |= REF_ISBROKEN;
 763                errno = EINVAL;
 764                goto out;
 765        }
 766
 767        ret = 0;
 768
 769out:
 770        save_errno = errno;
 771        strbuf_release(&sb_path);
 772        strbuf_release(&sb_contents);
 773        errno = save_errno;
 774        return ret;
 775}
 776
 777static void unlock_ref(struct ref_lock *lock)
 778{
 779        /* Do not free lock->lk -- atexit() still looks at them */
 780        if (lock->lk)
 781                rollback_lock_file(lock->lk);
 782        free(lock->ref_name);
 783        free(lock);
 784}
 785
 786/*
 787 * Lock refname, without following symrefs, and set *lock_p to point
 788 * at a newly-allocated lock object. Fill in lock->old_oid, referent,
 789 * and type similarly to read_raw_ref().
 790 *
 791 * The caller must verify that refname is a "safe" reference name (in
 792 * the sense of refname_is_safe()) before calling this function.
 793 *
 794 * If the reference doesn't already exist, verify that refname doesn't
 795 * have a D/F conflict with any existing references. extras and skip
 796 * are passed to refs_verify_refname_available() for this check.
 797 *
 798 * If mustexist is not set and the reference is not found or is
 799 * broken, lock the reference anyway but clear sha1.
 800 *
 801 * Return 0 on success. On failure, write an error message to err and
 802 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
 803 *
 804 * Implementation note: This function is basically
 805 *
 806 *     lock reference
 807 *     read_raw_ref()
 808 *
 809 * but it includes a lot more code to
 810 * - Deal with possible races with other processes
 811 * - Avoid calling refs_verify_refname_available() when it can be
 812 *   avoided, namely if we were successfully able to read the ref
 813 * - Generate informative error messages in the case of failure
 814 */
 815static int lock_raw_ref(struct files_ref_store *refs,
 816                        const char *refname, int mustexist,
 817                        const struct string_list *extras,
 818                        const struct string_list *skip,
 819                        struct ref_lock **lock_p,
 820                        struct strbuf *referent,
 821                        unsigned int *type,
 822                        struct strbuf *err)
 823{
 824        struct ref_lock *lock;
 825        struct strbuf ref_file = STRBUF_INIT;
 826        int attempts_remaining = 3;
 827        int ret = TRANSACTION_GENERIC_ERROR;
 828
 829        assert(err);
 830        files_assert_main_repository(refs, "lock_raw_ref");
 831
 832        *type = 0;
 833
 834        /* First lock the file so it can't change out from under us. */
 835
 836        *lock_p = lock = xcalloc(1, sizeof(*lock));
 837
 838        lock->ref_name = xstrdup(refname);
 839        files_ref_path(refs, &ref_file, refname);
 840
 841retry:
 842        switch (safe_create_leading_directories(ref_file.buf)) {
 843        case SCLD_OK:
 844                break; /* success */
 845        case SCLD_EXISTS:
 846                /*
 847                 * Suppose refname is "refs/foo/bar". We just failed
 848                 * to create the containing directory, "refs/foo",
 849                 * because there was a non-directory in the way. This
 850                 * indicates a D/F conflict, probably because of
 851                 * another reference such as "refs/foo". There is no
 852                 * reason to expect this error to be transitory.
 853                 */
 854                if (refs_verify_refname_available(&refs->base, refname,
 855                                                  extras, skip, err)) {
 856                        if (mustexist) {
 857                                /*
 858                                 * To the user the relevant error is
 859                                 * that the "mustexist" reference is
 860                                 * missing:
 861                                 */
 862                                strbuf_reset(err);
 863                                strbuf_addf(err, "unable to resolve reference '%s'",
 864                                            refname);
 865                        } else {
 866                                /*
 867                                 * The error message set by
 868                                 * refs_verify_refname_available() is
 869                                 * OK.
 870                                 */
 871                                ret = TRANSACTION_NAME_CONFLICT;
 872                        }
 873                } else {
 874                        /*
 875                         * The file that is in the way isn't a loose
 876                         * reference. Report it as a low-level
 877                         * failure.
 878                         */
 879                        strbuf_addf(err, "unable to create lock file %s.lock; "
 880                                    "non-directory in the way",
 881                                    ref_file.buf);
 882                }
 883                goto error_return;
 884        case SCLD_VANISHED:
 885                /* Maybe another process was tidying up. Try again. */
 886                if (--attempts_remaining > 0)
 887                        goto retry;
 888                /* fall through */
 889        default:
 890                strbuf_addf(err, "unable to create directory for %s",
 891                            ref_file.buf);
 892                goto error_return;
 893        }
 894
 895        if (!lock->lk)
 896                lock->lk = xcalloc(1, sizeof(struct lock_file));
 897
 898        if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
 899                if (errno == ENOENT && --attempts_remaining > 0) {
 900                        /*
 901                         * Maybe somebody just deleted one of the
 902                         * directories leading to ref_file.  Try
 903                         * again:
 904                         */
 905                        goto retry;
 906                } else {
 907                        unable_to_lock_message(ref_file.buf, errno, err);
 908                        goto error_return;
 909                }
 910        }
 911
 912        /*
 913         * Now we hold the lock and can read the reference without
 914         * fear that its value will change.
 915         */
 916
 917        if (files_read_raw_ref(&refs->base, refname,
 918                               lock->old_oid.hash, referent, type)) {
 919                if (errno == ENOENT) {
 920                        if (mustexist) {
 921                                /* Garden variety missing reference. */
 922                                strbuf_addf(err, "unable to resolve reference '%s'",
 923                                            refname);
 924                                goto error_return;
 925                        } else {
 926                                /*
 927                                 * Reference is missing, but that's OK. We
 928                                 * know that there is not a conflict with
 929                                 * another loose reference because
 930                                 * (supposing that we are trying to lock
 931                                 * reference "refs/foo/bar"):
 932                                 *
 933                                 * - We were successfully able to create
 934                                 *   the lockfile refs/foo/bar.lock, so we
 935                                 *   know there cannot be a loose reference
 936                                 *   named "refs/foo".
 937                                 *
 938                                 * - We got ENOENT and not EISDIR, so we
 939                                 *   know that there cannot be a loose
 940                                 *   reference named "refs/foo/bar/baz".
 941                                 */
 942                        }
 943                } else if (errno == EISDIR) {
 944                        /*
 945                         * There is a directory in the way. It might have
 946                         * contained references that have been deleted. If
 947                         * we don't require that the reference already
 948                         * exists, try to remove the directory so that it
 949                         * doesn't cause trouble when we want to rename the
 950                         * lockfile into place later.
 951                         */
 952                        if (mustexist) {
 953                                /* Garden variety missing reference. */
 954                                strbuf_addf(err, "unable to resolve reference '%s'",
 955                                            refname);
 956                                goto error_return;
 957                        } else if (remove_dir_recursively(&ref_file,
 958                                                          REMOVE_DIR_EMPTY_ONLY)) {
 959                                if (refs_verify_refname_available(
 960                                                    &refs->base, refname,
 961                                                    extras, skip, err)) {
 962                                        /*
 963                                         * The error message set by
 964                                         * verify_refname_available() is OK.
 965                                         */
 966                                        ret = TRANSACTION_NAME_CONFLICT;
 967                                        goto error_return;
 968                                } else {
 969                                        /*
 970                                         * We can't delete the directory,
 971                                         * but we also don't know of any
 972                                         * references that it should
 973                                         * contain.
 974                                         */
 975                                        strbuf_addf(err, "there is a non-empty directory '%s' "
 976                                                    "blocking reference '%s'",
 977                                                    ref_file.buf, refname);
 978                                        goto error_return;
 979                                }
 980                        }
 981                } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
 982                        strbuf_addf(err, "unable to resolve reference '%s': "
 983                                    "reference broken", refname);
 984                        goto error_return;
 985                } else {
 986                        strbuf_addf(err, "unable to resolve reference '%s': %s",
 987                                    refname, strerror(errno));
 988                        goto error_return;
 989                }
 990
 991                /*
 992                 * If the ref did not exist and we are creating it,
 993                 * make sure there is no existing ref that conflicts
 994                 * with refname:
 995                 */
 996                if (refs_verify_refname_available(
 997                                    &refs->base, refname,
 998                                    extras, skip, err))
 999                        goto error_return;
1000        }
1001
1002        ret = 0;
1003        goto out;
1004
1005error_return:
1006        unlock_ref(lock);
1007        *lock_p = NULL;
1008
1009out:
1010        strbuf_release(&ref_file);
1011        return ret;
1012}
1013
1014static int packed_peel_ref(struct packed_ref_store *refs,
1015                           const char *refname, unsigned char *sha1)
1016{
1017        struct ref_entry *r = get_packed_ref(refs, refname);
1018
1019        if (!r || peel_entry(r, 0))
1020                return -1;
1021
1022        hashcpy(sha1, r->u.value.peeled.hash);
1023        return 0;
1024}
1025
1026static int files_peel_ref(struct ref_store *ref_store,
1027                          const char *refname, unsigned char *sha1)
1028{
1029        struct files_ref_store *refs =
1030                files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
1031                               "peel_ref");
1032        int flag;
1033        unsigned char base[20];
1034
1035        if (current_ref_iter && current_ref_iter->refname == refname) {
1036                struct object_id peeled;
1037
1038                if (ref_iterator_peel(current_ref_iter, &peeled))
1039                        return -1;
1040                hashcpy(sha1, peeled.hash);
1041                return 0;
1042        }
1043
1044        if (refs_read_ref_full(ref_store, refname,
1045                               RESOLVE_REF_READING, base, &flag))
1046                return -1;
1047
1048        /*
1049         * If the reference is packed, read its ref_entry from the
1050         * cache in the hope that we already know its peeled value.
1051         * We only try this optimization on packed references because
1052         * (a) forcing the filling of the loose reference cache could
1053         * be expensive and (b) loose references anyway usually do not
1054         * have REF_KNOWS_PEELED.
1055         */
1056        if (flag & REF_ISPACKED &&
1057            !packed_peel_ref(refs->packed_ref_store, refname, sha1))
1058                return 0;
1059
1060        return peel_object(base, sha1);
1061}
1062
1063struct packed_ref_iterator {
1064        struct ref_iterator base;
1065
1066        struct packed_ref_cache *cache;
1067        struct ref_iterator *iter0;
1068        unsigned int flags;
1069};
1070
1071static int packed_ref_iterator_advance(struct ref_iterator *ref_iterator)
1072{
1073        struct packed_ref_iterator *iter =
1074                (struct packed_ref_iterator *)ref_iterator;
1075        int ok;
1076
1077        while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1078                if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1079                    ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1080                        continue;
1081
1082                if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1083                    !ref_resolves_to_object(iter->iter0->refname,
1084                                            iter->iter0->oid,
1085                                            iter->iter0->flags))
1086                        continue;
1087
1088                iter->base.refname = iter->iter0->refname;
1089                iter->base.oid = iter->iter0->oid;
1090                iter->base.flags = iter->iter0->flags;
1091                return ITER_OK;
1092        }
1093
1094        iter->iter0 = NULL;
1095        if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1096                ok = ITER_ERROR;
1097
1098        return ok;
1099}
1100
1101static int packed_ref_iterator_peel(struct ref_iterator *ref_iterator,
1102                                   struct object_id *peeled)
1103{
1104        struct packed_ref_iterator *iter =
1105                (struct packed_ref_iterator *)ref_iterator;
1106
1107        return ref_iterator_peel(iter->iter0, peeled);
1108}
1109
1110static int packed_ref_iterator_abort(struct ref_iterator *ref_iterator)
1111{
1112        struct packed_ref_iterator *iter =
1113                (struct packed_ref_iterator *)ref_iterator;
1114        int ok = ITER_DONE;
1115
1116        if (iter->iter0)
1117                ok = ref_iterator_abort(iter->iter0);
1118
1119        release_packed_ref_cache(iter->cache);
1120        base_ref_iterator_free(ref_iterator);
1121        return ok;
1122}
1123
1124static struct ref_iterator_vtable packed_ref_iterator_vtable = {
1125        packed_ref_iterator_advance,
1126        packed_ref_iterator_peel,
1127        packed_ref_iterator_abort
1128};
1129
1130static struct ref_iterator *packed_ref_iterator_begin(
1131                struct packed_ref_store *refs,
1132                const char *prefix, unsigned int flags)
1133{
1134        struct packed_ref_iterator *iter;
1135        struct ref_iterator *ref_iterator;
1136
1137        iter = xcalloc(1, sizeof(*iter));
1138        ref_iterator = &iter->base;
1139        base_ref_iterator_init(ref_iterator, &packed_ref_iterator_vtable);
1140
1141        /*
1142         * Note that get_packed_ref_cache() internally checks whether
1143         * the packed-ref cache is up to date with what is on disk,
1144         * and re-reads it if not.
1145         */
1146
1147        iter->cache = get_packed_ref_cache(refs);
1148        acquire_packed_ref_cache(iter->cache);
1149        iter->iter0 = cache_ref_iterator_begin(iter->cache->cache, prefix, 0);
1150
1151        iter->flags = flags;
1152
1153        return ref_iterator;
1154}
1155
1156struct files_ref_iterator {
1157        struct ref_iterator base;
1158
1159        struct ref_iterator *iter0;
1160        unsigned int flags;
1161};
1162
1163static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
1164{
1165        struct files_ref_iterator *iter =
1166                (struct files_ref_iterator *)ref_iterator;
1167        int ok;
1168
1169        while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1170                if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1171                    ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1172                        continue;
1173
1174                if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1175                    !ref_resolves_to_object(iter->iter0->refname,
1176                                            iter->iter0->oid,
1177                                            iter->iter0->flags))
1178                        continue;
1179
1180                iter->base.refname = iter->iter0->refname;
1181                iter->base.oid = iter->iter0->oid;
1182                iter->base.flags = iter->iter0->flags;
1183                return ITER_OK;
1184        }
1185
1186        iter->iter0 = NULL;
1187        if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1188                ok = ITER_ERROR;
1189
1190        return ok;
1191}
1192
1193static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1194                                   struct object_id *peeled)
1195{
1196        struct files_ref_iterator *iter =
1197                (struct files_ref_iterator *)ref_iterator;
1198
1199        return ref_iterator_peel(iter->iter0, peeled);
1200}
1201
1202static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1203{
1204        struct files_ref_iterator *iter =
1205                (struct files_ref_iterator *)ref_iterator;
1206        int ok = ITER_DONE;
1207
1208        if (iter->iter0)
1209                ok = ref_iterator_abort(iter->iter0);
1210
1211        base_ref_iterator_free(ref_iterator);
1212        return ok;
1213}
1214
1215static struct ref_iterator_vtable files_ref_iterator_vtable = {
1216        files_ref_iterator_advance,
1217        files_ref_iterator_peel,
1218        files_ref_iterator_abort
1219};
1220
1221static struct ref_iterator *files_ref_iterator_begin(
1222                struct ref_store *ref_store,
1223                const char *prefix, unsigned int flags)
1224{
1225        struct files_ref_store *refs;
1226        struct ref_iterator *loose_iter, *packed_iter;
1227        struct files_ref_iterator *iter;
1228        struct ref_iterator *ref_iterator;
1229        unsigned int required_flags = REF_STORE_READ;
1230
1231        if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
1232                required_flags |= REF_STORE_ODB;
1233
1234        refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
1235
1236        iter = xcalloc(1, sizeof(*iter));
1237        ref_iterator = &iter->base;
1238        base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1239
1240        /*
1241         * We must make sure that all loose refs are read before
1242         * accessing the packed-refs file; this avoids a race
1243         * condition if loose refs are migrated to the packed-refs
1244         * file by a simultaneous process, but our in-memory view is
1245         * from before the migration. We ensure this as follows:
1246         * First, we call start the loose refs iteration with its
1247         * `prime_ref` argument set to true. This causes the loose
1248         * references in the subtree to be pre-read into the cache.
1249         * (If they've already been read, that's OK; we only need to
1250         * guarantee that they're read before the packed refs, not
1251         * *how much* before.) After that, we call
1252         * packed_ref_iterator_begin(), which internally checks
1253         * whether the packed-ref cache is up to date with what is on
1254         * disk, and re-reads it if not.
1255         */
1256
1257        loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
1258                                              prefix, 1);
1259
1260        /*
1261         * The packed-refs file might contain broken references, for
1262         * example an old version of a reference that points at an
1263         * object that has since been garbage-collected. This is OK as
1264         * long as there is a corresponding loose reference that
1265         * overrides it, and we don't want to emit an error message in
1266         * this case. So ask the packed_ref_store for all of its
1267         * references, and (if needed) do our own check for broken
1268         * ones in files_ref_iterator_advance(), after we have merged
1269         * the packed and loose references.
1270         */
1271        packed_iter = packed_ref_iterator_begin(
1272                        refs->packed_ref_store, prefix,
1273                        DO_FOR_EACH_INCLUDE_BROKEN);
1274
1275        iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1276        iter->flags = flags;
1277
1278        return ref_iterator;
1279}
1280
1281/*
1282 * Verify that the reference locked by lock has the value old_sha1.
1283 * Fail if the reference doesn't exist and mustexist is set. Return 0
1284 * on success. On error, write an error message to err, set errno, and
1285 * return a negative value.
1286 */
1287static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
1288                       const unsigned char *old_sha1, int mustexist,
1289                       struct strbuf *err)
1290{
1291        assert(err);
1292
1293        if (refs_read_ref_full(ref_store, lock->ref_name,
1294                               mustexist ? RESOLVE_REF_READING : 0,
1295                               lock->old_oid.hash, NULL)) {
1296                if (old_sha1) {
1297                        int save_errno = errno;
1298                        strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
1299                        errno = save_errno;
1300                        return -1;
1301                } else {
1302                        oidclr(&lock->old_oid);
1303                        return 0;
1304                }
1305        }
1306        if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1307                strbuf_addf(err, "ref '%s' is at %s but expected %s",
1308                            lock->ref_name,
1309                            oid_to_hex(&lock->old_oid),
1310                            sha1_to_hex(old_sha1));
1311                errno = EBUSY;
1312                return -1;
1313        }
1314        return 0;
1315}
1316
1317static int remove_empty_directories(struct strbuf *path)
1318{
1319        /*
1320         * we want to create a file but there is a directory there;
1321         * if that is an empty directory (or a directory that contains
1322         * only empty directories), remove them.
1323         */
1324        return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1325}
1326
1327static int create_reflock(const char *path, void *cb)
1328{
1329        struct lock_file *lk = cb;
1330
1331        return hold_lock_file_for_update(lk, path, LOCK_NO_DEREF) < 0 ? -1 : 0;
1332}
1333
1334/*
1335 * Locks a ref returning the lock on success and NULL on failure.
1336 * On failure errno is set to something meaningful.
1337 */
1338static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1339                                            const char *refname,
1340                                            const unsigned char *old_sha1,
1341                                            const struct string_list *extras,
1342                                            const struct string_list *skip,
1343                                            unsigned int flags, int *type,
1344                                            struct strbuf *err)
1345{
1346        struct strbuf ref_file = STRBUF_INIT;
1347        struct ref_lock *lock;
1348        int last_errno = 0;
1349        int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1350        int resolve_flags = RESOLVE_REF_NO_RECURSE;
1351        int resolved;
1352
1353        files_assert_main_repository(refs, "lock_ref_sha1_basic");
1354        assert(err);
1355
1356        lock = xcalloc(1, sizeof(struct ref_lock));
1357
1358        if (mustexist)
1359                resolve_flags |= RESOLVE_REF_READING;
1360        if (flags & REF_DELETING)
1361                resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1362
1363        files_ref_path(refs, &ref_file, refname);
1364        resolved = !!refs_resolve_ref_unsafe(&refs->base,
1365                                             refname, resolve_flags,
1366                                             lock->old_oid.hash, type);
1367        if (!resolved && errno == EISDIR) {
1368                /*
1369                 * we are trying to lock foo but we used to
1370                 * have foo/bar which now does not exist;
1371                 * it is normal for the empty directory 'foo'
1372                 * to remain.
1373                 */
1374                if (remove_empty_directories(&ref_file)) {
1375                        last_errno = errno;
1376                        if (!refs_verify_refname_available(
1377                                            &refs->base,
1378                                            refname, extras, skip, err))
1379                                strbuf_addf(err, "there are still refs under '%s'",
1380                                            refname);
1381                        goto error_return;
1382                }
1383                resolved = !!refs_resolve_ref_unsafe(&refs->base,
1384                                                     refname, resolve_flags,
1385                                                     lock->old_oid.hash, type);
1386        }
1387        if (!resolved) {
1388                last_errno = errno;
1389                if (last_errno != ENOTDIR ||
1390                    !refs_verify_refname_available(&refs->base, refname,
1391                                                   extras, skip, err))
1392                        strbuf_addf(err, "unable to resolve reference '%s': %s",
1393                                    refname, strerror(last_errno));
1394
1395                goto error_return;
1396        }
1397
1398        /*
1399         * If the ref did not exist and we are creating it, make sure
1400         * there is no existing packed ref whose name begins with our
1401         * refname, nor a packed ref whose name is a proper prefix of
1402         * our refname.
1403         */
1404        if (is_null_oid(&lock->old_oid) &&
1405            refs_verify_refname_available(&refs->base, refname,
1406                                          extras, skip, err)) {
1407                last_errno = ENOTDIR;
1408                goto error_return;
1409        }
1410
1411        lock->lk = xcalloc(1, sizeof(struct lock_file));
1412
1413        lock->ref_name = xstrdup(refname);
1414
1415        if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
1416                last_errno = errno;
1417                unable_to_lock_message(ref_file.buf, errno, err);
1418                goto error_return;
1419        }
1420
1421        if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
1422                last_errno = errno;
1423                goto error_return;
1424        }
1425        goto out;
1426
1427 error_return:
1428        unlock_ref(lock);
1429        lock = NULL;
1430
1431 out:
1432        strbuf_release(&ref_file);
1433        errno = last_errno;
1434        return lock;
1435}
1436
1437/*
1438 * Write an entry to the packed-refs file for the specified refname.
1439 * If peeled is non-NULL, write it as the entry's peeled value.
1440 */
1441static void write_packed_entry(FILE *fh, const char *refname,
1442                               const unsigned char *sha1,
1443                               const unsigned char *peeled)
1444{
1445        fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1446        if (peeled)
1447                fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1448}
1449
1450/*
1451 * Lock the packed-refs file for writing. Flags is passed to
1452 * hold_lock_file_for_update(). Return 0 on success. On errors, set
1453 * errno appropriately and return a nonzero value.
1454 */
1455static int lock_packed_refs(struct packed_ref_store *refs, int flags)
1456{
1457        static int timeout_configured = 0;
1458        static int timeout_value = 1000;
1459        struct packed_ref_cache *packed_ref_cache;
1460
1461        packed_assert_main_repository(refs, "lock_packed_refs");
1462
1463        if (!timeout_configured) {
1464                git_config_get_int("core.packedrefstimeout", &timeout_value);
1465                timeout_configured = 1;
1466        }
1467
1468        if (hold_lock_file_for_update_timeout(
1469                            &refs->lock,
1470                            refs->path,
1471                            flags, timeout_value) < 0)
1472                return -1;
1473
1474        /*
1475         * Now that we hold the `packed-refs` lock, make sure that our
1476         * cache matches the current version of the file. Normally
1477         * `get_packed_ref_cache()` does that for us, but that
1478         * function assumes that when the file is locked, any existing
1479         * cache is still valid. We've just locked the file, but it
1480         * might have changed the moment *before* we locked it.
1481         */
1482        validate_packed_ref_cache(refs);
1483
1484        packed_ref_cache = get_packed_ref_cache(refs);
1485        /* Increment the reference count to prevent it from being freed: */
1486        acquire_packed_ref_cache(packed_ref_cache);
1487        return 0;
1488}
1489
1490/*
1491 * Write the current version of the packed refs cache from memory to
1492 * disk. The packed-refs file must already be locked for writing (see
1493 * lock_packed_refs()). Return zero on success. On errors, set errno
1494 * and return a nonzero value
1495 */
1496static int commit_packed_refs(struct packed_ref_store *refs)
1497{
1498        struct packed_ref_cache *packed_ref_cache =
1499                get_packed_ref_cache(refs);
1500        int ok, error = 0;
1501        int save_errno = 0;
1502        FILE *out;
1503        struct ref_iterator *iter;
1504
1505        packed_assert_main_repository(refs, "commit_packed_refs");
1506
1507        if (!is_lock_file_locked(&refs->lock))
1508                die("BUG: packed-refs not locked");
1509
1510        out = fdopen_lock_file(&refs->lock, "w");
1511        if (!out)
1512                die_errno("unable to fdopen packed-refs descriptor");
1513
1514        fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1515
1516        iter = cache_ref_iterator_begin(packed_ref_cache->cache, NULL, 0);
1517        while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1518                struct object_id peeled;
1519                int peel_error = ref_iterator_peel(iter, &peeled);
1520
1521                write_packed_entry(out, iter->refname, iter->oid->hash,
1522                                   peel_error ? NULL : peeled.hash);
1523        }
1524
1525        if (ok != ITER_DONE)
1526                die("error while iterating over references");
1527
1528        if (commit_lock_file(&refs->lock)) {
1529                save_errno = errno;
1530                error = -1;
1531        }
1532        release_packed_ref_cache(packed_ref_cache);
1533        errno = save_errno;
1534        return error;
1535}
1536
1537/*
1538 * Rollback the lockfile for the packed-refs file, and discard the
1539 * in-memory packed reference cache.  (The packed-refs file will be
1540 * read anew if it is needed again after this function is called.)
1541 */
1542static void rollback_packed_refs(struct packed_ref_store *refs)
1543{
1544        struct packed_ref_cache *packed_ref_cache = get_packed_ref_cache(refs);
1545
1546        packed_assert_main_repository(refs, "rollback_packed_refs");
1547
1548        if (!is_lock_file_locked(&refs->lock))
1549                die("BUG: packed-refs not locked");
1550        rollback_lock_file(&refs->lock);
1551        release_packed_ref_cache(packed_ref_cache);
1552        clear_packed_ref_cache(refs);
1553}
1554
1555struct ref_to_prune {
1556        struct ref_to_prune *next;
1557        unsigned char sha1[20];
1558        char name[FLEX_ARRAY];
1559};
1560
1561enum {
1562        REMOVE_EMPTY_PARENTS_REF = 0x01,
1563        REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1564};
1565
1566/*
1567 * Remove empty parent directories associated with the specified
1568 * reference and/or its reflog, but spare [logs/]refs/ and immediate
1569 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1570 * REMOVE_EMPTY_PARENTS_REFLOG.
1571 */
1572static void try_remove_empty_parents(struct files_ref_store *refs,
1573                                     const char *refname,
1574                                     unsigned int flags)
1575{
1576        struct strbuf buf = STRBUF_INIT;
1577        struct strbuf sb = STRBUF_INIT;
1578        char *p, *q;
1579        int i;
1580
1581        strbuf_addstr(&buf, refname);
1582        p = buf.buf;
1583        for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1584                while (*p && *p != '/')
1585                        p++;
1586                /* tolerate duplicate slashes; see check_refname_format() */
1587                while (*p == '/')
1588                        p++;
1589        }
1590        q = buf.buf + buf.len;
1591        while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1592                while (q > p && *q != '/')
1593                        q--;
1594                while (q > p && *(q-1) == '/')
1595                        q--;
1596                if (q == p)
1597                        break;
1598                strbuf_setlen(&buf, q - buf.buf);
1599
1600                strbuf_reset(&sb);
1601                files_ref_path(refs, &sb, buf.buf);
1602                if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1603                        flags &= ~REMOVE_EMPTY_PARENTS_REF;
1604
1605                strbuf_reset(&sb);
1606                files_reflog_path(refs, &sb, buf.buf);
1607                if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1608                        flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1609        }
1610        strbuf_release(&buf);
1611        strbuf_release(&sb);
1612}
1613
1614/* make sure nobody touched the ref, and unlink */
1615static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1616{
1617        struct ref_transaction *transaction;
1618        struct strbuf err = STRBUF_INIT;
1619
1620        if (check_refname_format(r->name, 0))
1621                return;
1622
1623        transaction = ref_store_transaction_begin(&refs->base, &err);
1624        if (!transaction ||
1625            ref_transaction_delete(transaction, r->name, r->sha1,
1626                                   REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1627            ref_transaction_commit(transaction, &err)) {
1628                ref_transaction_free(transaction);
1629                error("%s", err.buf);
1630                strbuf_release(&err);
1631                return;
1632        }
1633        ref_transaction_free(transaction);
1634        strbuf_release(&err);
1635}
1636
1637static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1638{
1639        while (r) {
1640                prune_ref(refs, r);
1641                r = r->next;
1642        }
1643}
1644
1645/*
1646 * Return true if the specified reference should be packed.
1647 */
1648static int should_pack_ref(const char *refname,
1649                           const struct object_id *oid, unsigned int ref_flags,
1650                           unsigned int pack_flags)
1651{
1652        /* Do not pack per-worktree refs: */
1653        if (ref_type(refname) != REF_TYPE_NORMAL)
1654                return 0;
1655
1656        /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1657        if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1658                return 0;
1659
1660        /* Do not pack symbolic refs: */
1661        if (ref_flags & REF_ISSYMREF)
1662                return 0;
1663
1664        /* Do not pack broken refs: */
1665        if (!ref_resolves_to_object(refname, oid, ref_flags))
1666                return 0;
1667
1668        return 1;
1669}
1670
1671static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1672{
1673        struct files_ref_store *refs =
1674                files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1675                               "pack_refs");
1676        struct ref_iterator *iter;
1677        int ok;
1678        struct ref_to_prune *refs_to_prune = NULL;
1679
1680        lock_packed_refs(refs->packed_ref_store, LOCK_DIE_ON_ERROR);
1681
1682        iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1683        while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1684                /*
1685                 * If the loose reference can be packed, add an entry
1686                 * in the packed ref cache. If the reference should be
1687                 * pruned, also add it to refs_to_prune.
1688                 */
1689                if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1690                                     flags))
1691                        continue;
1692
1693                /*
1694                 * Create an entry in the packed-refs cache equivalent
1695                 * to the one from the loose ref cache, except that
1696                 * we don't copy the peeled status, because we want it
1697                 * to be re-peeled.
1698                 */
1699                add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);
1700
1701                /* Schedule the loose reference for pruning if requested. */
1702                if ((flags & PACK_REFS_PRUNE)) {
1703                        struct ref_to_prune *n;
1704                        FLEX_ALLOC_STR(n, name, iter->refname);
1705                        hashcpy(n->sha1, iter->oid->hash);
1706                        n->next = refs_to_prune;
1707                        refs_to_prune = n;
1708                }
1709        }
1710        if (ok != ITER_DONE)
1711                die("error while iterating over references");
1712
1713        if (commit_packed_refs(refs->packed_ref_store))
1714                die_errno("unable to overwrite old ref-pack file");
1715
1716        prune_refs(refs, refs_to_prune);
1717        return 0;
1718}
1719
1720/*
1721 * Rewrite the packed-refs file, omitting any refs listed in
1722 * 'refnames'. On error, leave packed-refs unchanged, write an error
1723 * message to 'err', and return a nonzero value.
1724 *
1725 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
1726 */
1727static int repack_without_refs(struct packed_ref_store *refs,
1728                               struct string_list *refnames, struct strbuf *err)
1729{
1730        struct ref_dir *packed;
1731        struct string_list_item *refname;
1732        int ret, needs_repacking = 0, removed = 0;
1733
1734        packed_assert_main_repository(refs, "repack_without_refs");
1735        assert(err);
1736
1737        /* Look for a packed ref */
1738        for_each_string_list_item(refname, refnames) {
1739                if (get_packed_ref(refs, refname->string)) {
1740                        needs_repacking = 1;
1741                        break;
1742                }
1743        }
1744
1745        /* Avoid locking if we have nothing to do */
1746        if (!needs_repacking)
1747                return 0; /* no refname exists in packed refs */
1748
1749        if (lock_packed_refs(refs, 0)) {
1750                unable_to_lock_message(refs->path, errno, err);
1751                return -1;
1752        }
1753        packed = get_packed_refs(refs);
1754
1755        /* Remove refnames from the cache */
1756        for_each_string_list_item(refname, refnames)
1757                if (remove_entry_from_dir(packed, refname->string) != -1)
1758                        removed = 1;
1759        if (!removed) {
1760                /*
1761                 * All packed entries disappeared while we were
1762                 * acquiring the lock.
1763                 */
1764                rollback_packed_refs(refs);
1765                return 0;
1766        }
1767
1768        /* Write what remains */
1769        ret = commit_packed_refs(refs);
1770        if (ret)
1771                strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
1772                            strerror(errno));
1773        return ret;
1774}
1775
1776static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1777                             struct string_list *refnames, unsigned int flags)
1778{
1779        struct files_ref_store *refs =
1780                files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1781        struct strbuf err = STRBUF_INIT;
1782        int i, result = 0;
1783
1784        if (!refnames->nr)
1785                return 0;
1786
1787        result = repack_without_refs(refs->packed_ref_store, refnames, &err);
1788        if (result) {
1789                /*
1790                 * If we failed to rewrite the packed-refs file, then
1791                 * it is unsafe to try to remove loose refs, because
1792                 * doing so might expose an obsolete packed value for
1793                 * a reference that might even point at an object that
1794                 * has been garbage collected.
1795                 */
1796                if (refnames->nr == 1)
1797                        error(_("could not delete reference %s: %s"),
1798                              refnames->items[0].string, err.buf);
1799                else
1800                        error(_("could not delete references: %s"), err.buf);
1801
1802                goto out;
1803        }
1804
1805        for (i = 0; i < refnames->nr; i++) {
1806                const char *refname = refnames->items[i].string;
1807
1808                if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1809                        result |= error(_("could not remove reference %s"), refname);
1810        }
1811
1812out:
1813        strbuf_release(&err);
1814        return result;
1815}
1816
1817/*
1818 * People using contrib's git-new-workdir have .git/logs/refs ->
1819 * /some/other/path/.git/logs/refs, and that may live on another device.
1820 *
1821 * IOW, to avoid cross device rename errors, the temporary renamed log must
1822 * live into logs/refs.
1823 */
1824#define TMP_RENAMED_LOG  "refs/.tmp-renamed-log"
1825
1826struct rename_cb {
1827        const char *tmp_renamed_log;
1828        int true_errno;
1829};
1830
1831static int rename_tmp_log_callback(const char *path, void *cb_data)
1832{
1833        struct rename_cb *cb = cb_data;
1834
1835        if (rename(cb->tmp_renamed_log, path)) {
1836                /*
1837                 * rename(a, b) when b is an existing directory ought
1838                 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1839                 * Sheesh. Record the true errno for error reporting,
1840                 * but report EISDIR to raceproof_create_file() so
1841                 * that it knows to retry.
1842                 */
1843                cb->true_errno = errno;
1844                if (errno == ENOTDIR)
1845                        errno = EISDIR;
1846                return -1;
1847        } else {
1848                return 0;
1849        }
1850}
1851
1852static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1853{
1854        struct strbuf path = STRBUF_INIT;
1855        struct strbuf tmp = STRBUF_INIT;
1856        struct rename_cb cb;
1857        int ret;
1858
1859        files_reflog_path(refs, &path, newrefname);
1860        files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1861        cb.tmp_renamed_log = tmp.buf;
1862        ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1863        if (ret) {
1864                if (errno == EISDIR)
1865                        error("directory not empty: %s", path.buf);
1866                else
1867                        error("unable to move logfile %s to %s: %s",
1868                              tmp.buf, path.buf,
1869                              strerror(cb.true_errno));
1870        }
1871
1872        strbuf_release(&path);
1873        strbuf_release(&tmp);
1874        return ret;
1875}
1876
1877static int write_ref_to_lockfile(struct ref_lock *lock,
1878                                 const struct object_id *oid, struct strbuf *err);
1879static int commit_ref_update(struct files_ref_store *refs,
1880                             struct ref_lock *lock,
1881                             const struct object_id *oid, const char *logmsg,
1882                             struct strbuf *err);
1883
1884static int files_rename_ref(struct ref_store *ref_store,
1885                            const char *oldrefname, const char *newrefname,
1886                            const char *logmsg)
1887{
1888        struct files_ref_store *refs =
1889                files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1890        struct object_id oid, orig_oid;
1891        int flag = 0, logmoved = 0;
1892        struct ref_lock *lock;
1893        struct stat loginfo;
1894        struct strbuf sb_oldref = STRBUF_INIT;
1895        struct strbuf sb_newref = STRBUF_INIT;
1896        struct strbuf tmp_renamed_log = STRBUF_INIT;
1897        int log, ret;
1898        struct strbuf err = STRBUF_INIT;
1899
1900        files_reflog_path(refs, &sb_oldref, oldrefname);
1901        files_reflog_path(refs, &sb_newref, newrefname);
1902        files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1903
1904        log = !lstat(sb_oldref.buf, &loginfo);
1905        if (log && S_ISLNK(loginfo.st_mode)) {
1906                ret = error("reflog for %s is a symlink", oldrefname);
1907                goto out;
1908        }
1909
1910        if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1911                                     RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1912                                orig_oid.hash, &flag)) {
1913                ret = error("refname %s not found", oldrefname);
1914                goto out;
1915        }
1916
1917        if (flag & REF_ISSYMREF) {
1918                ret = error("refname %s is a symbolic ref, renaming it is not supported",
1919                            oldrefname);
1920                goto out;
1921        }
1922        if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1923                ret = 1;
1924                goto out;
1925        }
1926
1927        if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1928                ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1929                            oldrefname, strerror(errno));
1930                goto out;
1931        }
1932
1933        if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1934                            orig_oid.hash, REF_NODEREF)) {
1935                error("unable to delete old %s", oldrefname);
1936                goto rollback;
1937        }
1938
1939        /*
1940         * Since we are doing a shallow lookup, oid is not the
1941         * correct value to pass to delete_ref as old_oid. But that
1942         * doesn't matter, because an old_oid check wouldn't add to
1943         * the safety anyway; we want to delete the reference whatever
1944         * its current value.
1945         */
1946        if (!refs_read_ref_full(&refs->base, newrefname,
1947                                RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1948                                oid.hash, NULL) &&
1949            refs_delete_ref(&refs->base, NULL, newrefname,
1950                            NULL, REF_NODEREF)) {
1951                if (errno == EISDIR) {
1952                        struct strbuf path = STRBUF_INIT;
1953                        int result;
1954
1955                        files_ref_path(refs, &path, newrefname);
1956                        result = remove_empty_directories(&path);
1957                        strbuf_release(&path);
1958
1959                        if (result) {
1960                                error("Directory not empty: %s", newrefname);
1961                                goto rollback;
1962                        }
1963                } else {
1964                        error("unable to delete existing %s", newrefname);
1965                        goto rollback;
1966                }
1967        }
1968
1969        if (log && rename_tmp_log(refs, newrefname))
1970                goto rollback;
1971
1972        logmoved = log;
1973
1974        lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1975                                   REF_NODEREF, NULL, &err);
1976        if (!lock) {
1977                error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1978                strbuf_release(&err);
1979                goto rollback;
1980        }
1981        oidcpy(&lock->old_oid, &orig_oid);
1982
1983        if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1984            commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1985                error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1986                strbuf_release(&err);
1987                goto rollback;
1988        }
1989
1990        ret = 0;
1991        goto out;
1992
1993 rollback:
1994        lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1995                                   REF_NODEREF, NULL, &err);
1996        if (!lock) {
1997                error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1998                strbuf_release(&err);
1999                goto rollbacklog;
2000        }
2001
2002        flag = log_all_ref_updates;
2003        log_all_ref_updates = LOG_REFS_NONE;
2004        if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
2005            commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
2006                error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
2007                strbuf_release(&err);
2008        }
2009        log_all_ref_updates = flag;
2010
2011 rollbacklog:
2012        if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
2013                error("unable to restore logfile %s from %s: %s",
2014                        oldrefname, newrefname, strerror(errno));
2015        if (!logmoved && log &&
2016            rename(tmp_renamed_log.buf, sb_oldref.buf))
2017                error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
2018                        oldrefname, strerror(errno));
2019        ret = 1;
2020 out:
2021        strbuf_release(&sb_newref);
2022        strbuf_release(&sb_oldref);
2023        strbuf_release(&tmp_renamed_log);
2024
2025        return ret;
2026}
2027
2028static int close_ref(struct ref_lock *lock)
2029{
2030        if (close_lock_file(lock->lk))
2031                return -1;
2032        return 0;
2033}
2034
2035static int commit_ref(struct ref_lock *lock)
2036{
2037        char *path = get_locked_file_path(lock->lk);
2038        struct stat st;
2039
2040        if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
2041                /*
2042                 * There is a directory at the path we want to rename
2043                 * the lockfile to. Hopefully it is empty; try to
2044                 * delete it.
2045                 */
2046                size_t len = strlen(path);
2047                struct strbuf sb_path = STRBUF_INIT;
2048
2049                strbuf_attach(&sb_path, path, len, len);
2050
2051                /*
2052                 * If this fails, commit_lock_file() will also fail
2053                 * and will report the problem.
2054                 */
2055                remove_empty_directories(&sb_path);
2056                strbuf_release(&sb_path);
2057        } else {
2058                free(path);
2059        }
2060
2061        if (commit_lock_file(lock->lk))
2062                return -1;
2063        return 0;
2064}
2065
2066static int open_or_create_logfile(const char *path, void *cb)
2067{
2068        int *fd = cb;
2069
2070        *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
2071        return (*fd < 0) ? -1 : 0;
2072}
2073
2074/*
2075 * Create a reflog for a ref. If force_create = 0, only create the
2076 * reflog for certain refs (those for which should_autocreate_reflog
2077 * returns non-zero). Otherwise, create it regardless of the reference
2078 * name. If the logfile already existed or was created, return 0 and
2079 * set *logfd to the file descriptor opened for appending to the file.
2080 * If no logfile exists and we decided not to create one, return 0 and
2081 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
2082 * return -1.
2083 */
2084static int log_ref_setup(struct files_ref_store *refs,
2085                         const char *refname, int force_create,
2086                         int *logfd, struct strbuf *err)
2087{
2088        struct strbuf logfile_sb = STRBUF_INIT;
2089        char *logfile;
2090
2091        files_reflog_path(refs, &logfile_sb, refname);
2092        logfile = strbuf_detach(&logfile_sb, NULL);
2093
2094        if (force_create || should_autocreate_reflog(refname)) {
2095                if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
2096                        if (errno == ENOENT)
2097                                strbuf_addf(err, "unable to create directory for '%s': "
2098                                            "%s", logfile, strerror(errno));
2099                        else if (errno == EISDIR)
2100                                strbuf_addf(err, "there are still logs under '%s'",
2101                                            logfile);
2102                        else
2103                                strbuf_addf(err, "unable to append to '%s': %s",
2104                                            logfile, strerror(errno));
2105
2106                        goto error;
2107                }
2108        } else {
2109                *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
2110                if (*logfd < 0) {
2111                        if (errno == ENOENT || errno == EISDIR) {
2112                                /*
2113                                 * The logfile doesn't already exist,
2114                                 * but that is not an error; it only
2115                                 * means that we won't write log
2116                                 * entries to it.
2117                                 */
2118                                ;
2119                        } else {
2120                                strbuf_addf(err, "unable to append to '%s': %s",
2121                                            logfile, strerror(errno));
2122                                goto error;
2123                        }
2124                }
2125        }
2126
2127        if (*logfd >= 0)
2128                adjust_shared_perm(logfile);
2129
2130        free(logfile);
2131        return 0;
2132
2133error:
2134        free(logfile);
2135        return -1;
2136}
2137
2138static int files_create_reflog(struct ref_store *ref_store,
2139                               const char *refname, int force_create,
2140                               struct strbuf *err)
2141{
2142        struct files_ref_store *refs =
2143                files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
2144        int fd;
2145
2146        if (log_ref_setup(refs, refname, force_create, &fd, err))
2147                return -1;
2148
2149        if (fd >= 0)
2150                close(fd);
2151
2152        return 0;
2153}
2154
2155static int log_ref_write_fd(int fd, const struct object_id *old_oid,
2156                            const struct object_id *new_oid,
2157                            const char *committer, const char *msg)
2158{
2159        int msglen, written;
2160        unsigned maxlen, len;
2161        char *logrec;
2162
2163        msglen = msg ? strlen(msg) : 0;
2164        maxlen = strlen(committer) + msglen + 100;
2165        logrec = xmalloc(maxlen);
2166        len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2167                        oid_to_hex(old_oid),
2168                        oid_to_hex(new_oid),
2169                        committer);
2170        if (msglen)
2171                len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2172
2173        written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2174        free(logrec);
2175        if (written != len)
2176                return -1;
2177
2178        return 0;
2179}
2180
2181static int files_log_ref_write(struct files_ref_store *refs,
2182                               const char *refname, const struct object_id *old_oid,
2183                               const struct object_id *new_oid, const char *msg,
2184                               int flags, struct strbuf *err)
2185{
2186        int logfd, result;
2187
2188        if (log_all_ref_updates == LOG_REFS_UNSET)
2189                log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
2190
2191        result = log_ref_setup(refs, refname,
2192                               flags & REF_FORCE_CREATE_REFLOG,
2193                               &logfd, err);
2194
2195        if (result)
2196                return result;
2197
2198        if (logfd < 0)
2199                return 0;
2200        result = log_ref_write_fd(logfd, old_oid, new_oid,
2201                                  git_committer_info(0), msg);
2202        if (result) {
2203                struct strbuf sb = STRBUF_INIT;
2204                int save_errno = errno;
2205
2206                files_reflog_path(refs, &sb, refname);
2207                strbuf_addf(err, "unable to append to '%s': %s",
2208                            sb.buf, strerror(save_errno));
2209                strbuf_release(&sb);
2210                close(logfd);
2211                return -1;
2212        }
2213        if (close(logfd)) {
2214                struct strbuf sb = STRBUF_INIT;
2215                int save_errno = errno;
2216
2217                files_reflog_path(refs, &sb, refname);
2218                strbuf_addf(err, "unable to append to '%s': %s",
2219                            sb.buf, strerror(save_errno));
2220                strbuf_release(&sb);
2221                return -1;
2222        }
2223        return 0;
2224}
2225
2226/*
2227 * Write sha1 into the open lockfile, then close the lockfile. On
2228 * errors, rollback the lockfile, fill in *err and
2229 * return -1.
2230 */
2231static int write_ref_to_lockfile(struct ref_lock *lock,
2232                                 const struct object_id *oid, struct strbuf *err)
2233{
2234        static char term = '\n';
2235        struct object *o;
2236        int fd;
2237
2238        o = parse_object(oid);
2239        if (!o) {
2240                strbuf_addf(err,
2241                            "trying to write ref '%s' with nonexistent object %s",
2242                            lock->ref_name, oid_to_hex(oid));
2243                unlock_ref(lock);
2244                return -1;
2245        }
2246        if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2247                strbuf_addf(err,
2248                            "trying to write non-commit object %s to branch '%s'",
2249                            oid_to_hex(oid), lock->ref_name);
2250                unlock_ref(lock);
2251                return -1;
2252        }
2253        fd = get_lock_file_fd(lock->lk);
2254        if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2255            write_in_full(fd, &term, 1) != 1 ||
2256            close_ref(lock) < 0) {
2257                strbuf_addf(err,
2258                            "couldn't write '%s'", get_lock_file_path(lock->lk));
2259                unlock_ref(lock);
2260                return -1;
2261        }
2262        return 0;
2263}
2264
2265/*
2266 * Commit a change to a loose reference that has already been written
2267 * to the loose reference lockfile. Also update the reflogs if
2268 * necessary, using the specified lockmsg (which can be NULL).
2269 */
2270static int commit_ref_update(struct files_ref_store *refs,
2271                             struct ref_lock *lock,
2272                             const struct object_id *oid, const char *logmsg,
2273                             struct strbuf *err)
2274{
2275        files_assert_main_repository(refs, "commit_ref_update");
2276
2277        clear_loose_ref_cache(refs);
2278        if (files_log_ref_write(refs, lock->ref_name,
2279                                &lock->old_oid, oid,
2280                                logmsg, 0, err)) {
2281                char *old_msg = strbuf_detach(err, NULL);
2282                strbuf_addf(err, "cannot update the ref '%s': %s",
2283                            lock->ref_name, old_msg);
2284                free(old_msg);
2285                unlock_ref(lock);
2286                return -1;
2287        }
2288
2289        if (strcmp(lock->ref_name, "HEAD") != 0) {
2290                /*
2291                 * Special hack: If a branch is updated directly and HEAD
2292                 * points to it (may happen on the remote side of a push
2293                 * for example) then logically the HEAD reflog should be
2294                 * updated too.
2295                 * A generic solution implies reverse symref information,
2296                 * but finding all symrefs pointing to the given branch
2297                 * would be rather costly for this rare event (the direct
2298                 * update of a branch) to be worth it.  So let's cheat and
2299                 * check with HEAD only which should cover 99% of all usage
2300                 * scenarios (even 100% of the default ones).
2301                 */
2302                struct object_id head_oid;
2303                int head_flag;
2304                const char *head_ref;
2305
2306                head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2307                                                   RESOLVE_REF_READING,
2308                                                   head_oid.hash, &head_flag);
2309                if (head_ref && (head_flag & REF_ISSYMREF) &&
2310                    !strcmp(head_ref, lock->ref_name)) {
2311                        struct strbuf log_err = STRBUF_INIT;
2312                        if (files_log_ref_write(refs, "HEAD",
2313                                                &lock->old_oid, oid,
2314                                                logmsg, 0, &log_err)) {
2315                                error("%s", log_err.buf);
2316                                strbuf_release(&log_err);
2317                        }
2318                }
2319        }
2320
2321        if (commit_ref(lock)) {
2322                strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2323                unlock_ref(lock);
2324                return -1;
2325        }
2326
2327        unlock_ref(lock);
2328        return 0;
2329}
2330
2331static int create_ref_symlink(struct ref_lock *lock, const char *target)
2332{
2333        int ret = -1;
2334#ifndef NO_SYMLINK_HEAD
2335        char *ref_path = get_locked_file_path(lock->lk);
2336        unlink(ref_path);
2337        ret = symlink(target, ref_path);
2338        free(ref_path);
2339
2340        if (ret)
2341                fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2342#endif
2343        return ret;
2344}
2345
2346static void update_symref_reflog(struct files_ref_store *refs,
2347                                 struct ref_lock *lock, const char *refname,
2348                                 const char *target, const char *logmsg)
2349{
2350        struct strbuf err = STRBUF_INIT;
2351        struct object_id new_oid;
2352        if (logmsg &&
2353            !refs_read_ref_full(&refs->base, target,
2354                                RESOLVE_REF_READING, new_oid.hash, NULL) &&
2355            files_log_ref_write(refs, refname, &lock->old_oid,
2356                                &new_oid, logmsg, 0, &err)) {
2357                error("%s", err.buf);
2358                strbuf_release(&err);
2359        }
2360}
2361
2362static int create_symref_locked(struct files_ref_store *refs,
2363                                struct ref_lock *lock, const char *refname,
2364                                const char *target, const char *logmsg)
2365{
2366        if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2367                update_symref_reflog(refs, lock, refname, target, logmsg);
2368                return 0;
2369        }
2370
2371        if (!fdopen_lock_file(lock->lk, "w"))
2372                return error("unable to fdopen %s: %s",
2373                             lock->lk->tempfile.filename.buf, strerror(errno));
2374
2375        update_symref_reflog(refs, lock, refname, target, logmsg);
2376
2377        /* no error check; commit_ref will check ferror */
2378        fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2379        if (commit_ref(lock) < 0)
2380                return error("unable to write symref for %s: %s", refname,
2381                             strerror(errno));
2382        return 0;
2383}
2384
2385static int files_create_symref(struct ref_store *ref_store,
2386                               const char *refname, const char *target,
2387                               const char *logmsg)
2388{
2389        struct files_ref_store *refs =
2390                files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
2391        struct strbuf err = STRBUF_INIT;
2392        struct ref_lock *lock;
2393        int ret;
2394
2395        lock = lock_ref_sha1_basic(refs, refname, NULL,
2396                                   NULL, NULL, REF_NODEREF, NULL,
2397                                   &err);
2398        if (!lock) {
2399                error("%s", err.buf);
2400                strbuf_release(&err);
2401                return -1;
2402        }
2403
2404        ret = create_symref_locked(refs, lock, refname, target, logmsg);
2405        unlock_ref(lock);
2406        return ret;
2407}
2408
2409static int files_reflog_exists(struct ref_store *ref_store,
2410                               const char *refname)
2411{
2412        struct files_ref_store *refs =
2413                files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
2414        struct strbuf sb = STRBUF_INIT;
2415        struct stat st;
2416        int ret;
2417
2418        files_reflog_path(refs, &sb, refname);
2419        ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2420        strbuf_release(&sb);
2421        return ret;
2422}
2423
2424static int files_delete_reflog(struct ref_store *ref_store,
2425                               const char *refname)
2426{
2427        struct files_ref_store *refs =
2428                files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
2429        struct strbuf sb = STRBUF_INIT;
2430        int ret;
2431
2432        files_reflog_path(refs, &sb, refname);
2433        ret = remove_path(sb.buf);
2434        strbuf_release(&sb);
2435        return ret;
2436}
2437
2438static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2439{
2440        struct object_id ooid, noid;
2441        char *email_end, *message;
2442        timestamp_t timestamp;
2443        int tz;
2444        const char *p = sb->buf;
2445
2446        /* old SP new SP name <email> SP time TAB msg LF */
2447        if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2448            parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
2449            parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
2450            !(email_end = strchr(p, '>')) ||
2451            email_end[1] != ' ' ||
2452            !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
2453            !message || message[0] != ' ' ||
2454            (message[1] != '+' && message[1] != '-') ||
2455            !isdigit(message[2]) || !isdigit(message[3]) ||
2456            !isdigit(message[4]) || !isdigit(message[5]))
2457                return 0; /* corrupt? */
2458        email_end[1] = '\0';
2459        tz = strtol(message + 1, NULL, 10);
2460        if (message[6] != '\t')
2461                message += 6;
2462        else
2463                message += 7;
2464        return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
2465}
2466
2467static char *find_beginning_of_line(char *bob, char *scan)
2468{
2469        while (bob < scan && *(--scan) != '\n')
2470                ; /* keep scanning backwards */
2471        /*
2472         * Return either beginning of the buffer, or LF at the end of
2473         * the previous line.
2474         */
2475        return scan;
2476}
2477
2478static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2479                                             const char *refname,
2480                                             each_reflog_ent_fn fn,
2481                                             void *cb_data)
2482{
2483        struct files_ref_store *refs =
2484                files_downcast(ref_store, REF_STORE_READ,
2485                               "for_each_reflog_ent_reverse");
2486        struct strbuf sb = STRBUF_INIT;
2487        FILE *logfp;
2488        long pos;
2489        int ret = 0, at_tail = 1;
2490
2491        files_reflog_path(refs, &sb, refname);
2492        logfp = fopen(sb.buf, "r");
2493        strbuf_release(&sb);
2494        if (!logfp)
2495                return -1;
2496
2497        /* Jump to the end */
2498        if (fseek(logfp, 0, SEEK_END) < 0)
2499                ret = error("cannot seek back reflog for %s: %s",
2500                            refname, strerror(errno));
2501        pos = ftell(logfp);
2502        while (!ret && 0 < pos) {
2503                int cnt;
2504                size_t nread;
2505                char buf[BUFSIZ];
2506                char *endp, *scanp;
2507
2508                /* Fill next block from the end */
2509                cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2510                if (fseek(logfp, pos - cnt, SEEK_SET)) {
2511                        ret = error("cannot seek back reflog for %s: %s",
2512                                    refname, strerror(errno));
2513                        break;
2514                }
2515                nread = fread(buf, cnt, 1, logfp);
2516                if (nread != 1) {
2517                        ret = error("cannot read %d bytes from reflog for %s: %s",
2518                                    cnt, refname, strerror(errno));
2519                        break;
2520                }
2521                pos -= cnt;
2522
2523                scanp = endp = buf + cnt;
2524                if (at_tail && scanp[-1] == '\n')
2525                        /* Looking at the final LF at the end of the file */
2526                        scanp--;
2527                at_tail = 0;
2528
2529                while (buf < scanp) {
2530                        /*
2531                         * terminating LF of the previous line, or the beginning
2532                         * of the buffer.
2533                         */
2534                        char *bp;
2535
2536                        bp = find_beginning_of_line(buf, scanp);
2537
2538                        if (*bp == '\n') {
2539                                /*
2540                                 * The newline is the end of the previous line,
2541                                 * so we know we have complete line starting
2542                                 * at (bp + 1). Prefix it onto any prior data
2543                                 * we collected for the line and process it.
2544                                 */
2545                                strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2546                                scanp = bp;
2547                                endp = bp + 1;
2548                                ret = show_one_reflog_ent(&sb, fn, cb_data);
2549                                strbuf_reset(&sb);
2550                                if (ret)
2551                                        break;
2552                        } else if (!pos) {
2553                                /*
2554                                 * We are at the start of the buffer, and the
2555                                 * start of the file; there is no previous
2556                                 * line, and we have everything for this one.
2557                                 * Process it, and we can end the loop.
2558                                 */
2559                                strbuf_splice(&sb, 0, 0, buf, endp - buf);
2560                                ret = show_one_reflog_ent(&sb, fn, cb_data);
2561                                strbuf_reset(&sb);
2562                                break;
2563                        }
2564
2565                        if (bp == buf) {
2566                                /*
2567                                 * We are at the start of the buffer, and there
2568                                 * is more file to read backwards. Which means
2569                                 * we are in the middle of a line. Note that we
2570                                 * may get here even if *bp was a newline; that
2571                                 * just means we are at the exact end of the
2572                                 * previous line, rather than some spot in the
2573                                 * middle.
2574                                 *
2575                                 * Save away what we have to be combined with
2576                                 * the data from the next read.
2577                                 */
2578                                strbuf_splice(&sb, 0, 0, buf, endp - buf);
2579                                break;
2580                        }
2581                }
2582
2583        }
2584        if (!ret && sb.len)
2585                die("BUG: reverse reflog parser had leftover data");
2586
2587        fclose(logfp);
2588        strbuf_release(&sb);
2589        return ret;
2590}
2591
2592static int files_for_each_reflog_ent(struct ref_store *ref_store,
2593                                     const char *refname,
2594                                     each_reflog_ent_fn fn, void *cb_data)
2595{
2596        struct files_ref_store *refs =
2597                files_downcast(ref_store, REF_STORE_READ,
2598                               "for_each_reflog_ent");
2599        FILE *logfp;
2600        struct strbuf sb = STRBUF_INIT;
2601        int ret = 0;
2602
2603        files_reflog_path(refs, &sb, refname);
2604        logfp = fopen(sb.buf, "r");
2605        strbuf_release(&sb);
2606        if (!logfp)
2607                return -1;
2608
2609        while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2610                ret = show_one_reflog_ent(&sb, fn, cb_data);
2611        fclose(logfp);
2612        strbuf_release(&sb);
2613        return ret;
2614}
2615
2616struct files_reflog_iterator {
2617        struct ref_iterator base;
2618
2619        struct ref_store *ref_store;
2620        struct dir_iterator *dir_iterator;
2621        struct object_id oid;
2622};
2623
2624static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2625{
2626        struct files_reflog_iterator *iter =
2627                (struct files_reflog_iterator *)ref_iterator;
2628        struct dir_iterator *diter = iter->dir_iterator;
2629        int ok;
2630
2631        while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2632                int flags;
2633
2634                if (!S_ISREG(diter->st.st_mode))
2635                        continue;
2636                if (diter->basename[0] == '.')
2637                        continue;
2638                if (ends_with(diter->basename, ".lock"))
2639                        continue;
2640
2641                if (refs_read_ref_full(iter->ref_store,
2642                                       diter->relative_path, 0,
2643                                       iter->oid.hash, &flags)) {
2644                        error("bad ref for %s", diter->path.buf);
2645                        continue;
2646                }
2647
2648                iter->base.refname = diter->relative_path;
2649                iter->base.oid = &iter->oid;
2650                iter->base.flags = flags;
2651                return ITER_OK;
2652        }
2653
2654        iter->dir_iterator = NULL;
2655        if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2656                ok = ITER_ERROR;
2657        return ok;
2658}
2659
2660static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2661                                   struct object_id *peeled)
2662{
2663        die("BUG: ref_iterator_peel() called for reflog_iterator");
2664}
2665
2666static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2667{
2668        struct files_reflog_iterator *iter =
2669                (struct files_reflog_iterator *)ref_iterator;
2670        int ok = ITER_DONE;
2671
2672        if (iter->dir_iterator)
2673                ok = dir_iterator_abort(iter->dir_iterator);
2674
2675        base_ref_iterator_free(ref_iterator);
2676        return ok;
2677}
2678
2679static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2680        files_reflog_iterator_advance,
2681        files_reflog_iterator_peel,
2682        files_reflog_iterator_abort
2683};
2684
2685static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2686{
2687        struct files_ref_store *refs =
2688                files_downcast(ref_store, REF_STORE_READ,
2689                               "reflog_iterator_begin");
2690        struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2691        struct ref_iterator *ref_iterator = &iter->base;
2692        struct strbuf sb = STRBUF_INIT;
2693
2694        base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2695        files_reflog_path(refs, &sb, NULL);
2696        iter->dir_iterator = dir_iterator_begin(sb.buf);
2697        iter->ref_store = ref_store;
2698        strbuf_release(&sb);
2699        return ref_iterator;
2700}
2701
2702/*
2703 * If update is a direct update of head_ref (the reference pointed to
2704 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2705 */
2706static int split_head_update(struct ref_update *update,
2707                             struct ref_transaction *transaction,
2708                             const char *head_ref,
2709                             struct string_list *affected_refnames,
2710                             struct strbuf *err)
2711{
2712        struct string_list_item *item;
2713        struct ref_update *new_update;
2714
2715        if ((update->flags & REF_LOG_ONLY) ||
2716            (update->flags & REF_ISPRUNING) ||
2717            (update->flags & REF_UPDATE_VIA_HEAD))
2718                return 0;
2719
2720        if (strcmp(update->refname, head_ref))
2721                return 0;
2722
2723        /*
2724         * First make sure that HEAD is not already in the
2725         * transaction. This insertion is O(N) in the transaction
2726         * size, but it happens at most once per transaction.
2727         */
2728        item = string_list_insert(affected_refnames, "HEAD");
2729        if (item->util) {
2730                /* An entry already existed */
2731                strbuf_addf(err,
2732                            "multiple updates for 'HEAD' (including one "
2733                            "via its referent '%s') are not allowed",
2734                            update->refname);
2735                return TRANSACTION_NAME_CONFLICT;
2736        }
2737
2738        new_update = ref_transaction_add_update(
2739                        transaction, "HEAD",
2740                        update->flags | REF_LOG_ONLY | REF_NODEREF,
2741                        update->new_oid.hash, update->old_oid.hash,
2742                        update->msg);
2743
2744        item->util = new_update;
2745
2746        return 0;
2747}
2748
2749/*
2750 * update is for a symref that points at referent and doesn't have
2751 * REF_NODEREF set. Split it into two updates:
2752 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2753 * - A new, separate update for the referent reference
2754 * Note that the new update will itself be subject to splitting when
2755 * the iteration gets to it.
2756 */
2757static int split_symref_update(struct files_ref_store *refs,
2758                               struct ref_update *update,
2759                               const char *referent,
2760                               struct ref_transaction *transaction,
2761                               struct string_list *affected_refnames,
2762                               struct strbuf *err)
2763{
2764        struct string_list_item *item;
2765        struct ref_update *new_update;
2766        unsigned int new_flags;
2767
2768        /*
2769         * First make sure that referent is not already in the
2770         * transaction. This insertion is O(N) in the transaction
2771         * size, but it happens at most once per symref in a
2772         * transaction.
2773         */
2774        item = string_list_insert(affected_refnames, referent);
2775        if (item->util) {
2776                /* An entry already existed */
2777                strbuf_addf(err,
2778                            "multiple updates for '%s' (including one "
2779                            "via symref '%s') are not allowed",
2780                            referent, update->refname);
2781                return TRANSACTION_NAME_CONFLICT;
2782        }
2783
2784        new_flags = update->flags;
2785        if (!strcmp(update->refname, "HEAD")) {
2786                /*
2787                 * Record that the new update came via HEAD, so that
2788                 * when we process it, split_head_update() doesn't try
2789                 * to add another reflog update for HEAD. Note that
2790                 * this bit will be propagated if the new_update
2791                 * itself needs to be split.
2792                 */
2793                new_flags |= REF_UPDATE_VIA_HEAD;
2794        }
2795
2796        new_update = ref_transaction_add_update(
2797                        transaction, referent, new_flags,
2798                        update->new_oid.hash, update->old_oid.hash,
2799                        update->msg);
2800
2801        new_update->parent_update = update;
2802
2803        /*
2804         * Change the symbolic ref update to log only. Also, it
2805         * doesn't need to check its old SHA-1 value, as that will be
2806         * done when new_update is processed.
2807         */
2808        update->flags |= REF_LOG_ONLY | REF_NODEREF;
2809        update->flags &= ~REF_HAVE_OLD;
2810
2811        item->util = new_update;
2812
2813        return 0;
2814}
2815
2816/*
2817 * Return the refname under which update was originally requested.
2818 */
2819static const char *original_update_refname(struct ref_update *update)
2820{
2821        while (update->parent_update)
2822                update = update->parent_update;
2823
2824        return update->refname;
2825}
2826
2827/*
2828 * Check whether the REF_HAVE_OLD and old_oid values stored in update
2829 * are consistent with oid, which is the reference's current value. If
2830 * everything is OK, return 0; otherwise, write an error message to
2831 * err and return -1.
2832 */
2833static int check_old_oid(struct ref_update *update, struct object_id *oid,
2834                         struct strbuf *err)
2835{
2836        if (!(update->flags & REF_HAVE_OLD) ||
2837                   !oidcmp(oid, &update->old_oid))
2838                return 0;
2839
2840        if (is_null_oid(&update->old_oid))
2841                strbuf_addf(err, "cannot lock ref '%s': "
2842                            "reference already exists",
2843                            original_update_refname(update));
2844        else if (is_null_oid(oid))
2845                strbuf_addf(err, "cannot lock ref '%s': "
2846                            "reference is missing but expected %s",
2847                            original_update_refname(update),
2848                            oid_to_hex(&update->old_oid));
2849        else
2850                strbuf_addf(err, "cannot lock ref '%s': "
2851                            "is at %s but expected %s",
2852                            original_update_refname(update),
2853                            oid_to_hex(oid),
2854                            oid_to_hex(&update->old_oid));
2855
2856        return -1;
2857}
2858
2859/*
2860 * Prepare for carrying out update:
2861 * - Lock the reference referred to by update.
2862 * - Read the reference under lock.
2863 * - Check that its old SHA-1 value (if specified) is correct, and in
2864 *   any case record it in update->lock->old_oid for later use when
2865 *   writing the reflog.
2866 * - If it is a symref update without REF_NODEREF, split it up into a
2867 *   REF_LOG_ONLY update of the symref and add a separate update for
2868 *   the referent to transaction.
2869 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2870 *   update of HEAD.
2871 */
2872static int lock_ref_for_update(struct files_ref_store *refs,
2873                               struct ref_update *update,
2874                               struct ref_transaction *transaction,
2875                               const char *head_ref,
2876                               struct string_list *affected_refnames,
2877                               struct strbuf *err)
2878{
2879        struct strbuf referent = STRBUF_INIT;
2880        int mustexist = (update->flags & REF_HAVE_OLD) &&
2881                !is_null_oid(&update->old_oid);
2882        int ret;
2883        struct ref_lock *lock;
2884
2885        files_assert_main_repository(refs, "lock_ref_for_update");
2886
2887        if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2888                update->flags |= REF_DELETING;
2889
2890        if (head_ref) {
2891                ret = split_head_update(update, transaction, head_ref,
2892                                        affected_refnames, err);
2893                if (ret)
2894                        return ret;
2895        }
2896
2897        ret = lock_raw_ref(refs, update->refname, mustexist,
2898                           affected_refnames, NULL,
2899                           &lock, &referent,
2900                           &update->type, err);
2901        if (ret) {
2902                char *reason;
2903
2904                reason = strbuf_detach(err, NULL);
2905                strbuf_addf(err, "cannot lock ref '%s': %s",
2906                            original_update_refname(update), reason);
2907                free(reason);
2908                return ret;
2909        }
2910
2911        update->backend_data = lock;
2912
2913        if (update->type & REF_ISSYMREF) {
2914                if (update->flags & REF_NODEREF) {
2915                        /*
2916                         * We won't be reading the referent as part of
2917                         * the transaction, so we have to read it here
2918                         * to record and possibly check old_sha1:
2919                         */
2920                        if (refs_read_ref_full(&refs->base,
2921                                               referent.buf, 0,
2922                                               lock->old_oid.hash, NULL)) {
2923                                if (update->flags & REF_HAVE_OLD) {
2924                                        strbuf_addf(err, "cannot lock ref '%s': "
2925                                                    "error reading reference",
2926                                                    original_update_refname(update));
2927                                        return -1;
2928                                }
2929                        } else if (check_old_oid(update, &lock->old_oid, err)) {
2930                                return TRANSACTION_GENERIC_ERROR;
2931                        }
2932                } else {
2933                        /*
2934                         * Create a new update for the reference this
2935                         * symref is pointing at. Also, we will record
2936                         * and verify old_sha1 for this update as part
2937                         * of processing the split-off update, so we
2938                         * don't have to do it here.
2939                         */
2940                        ret = split_symref_update(refs, update,
2941                                                  referent.buf, transaction,
2942                                                  affected_refnames, err);
2943                        if (ret)
2944                                return ret;
2945                }
2946        } else {
2947                struct ref_update *parent_update;
2948
2949                if (check_old_oid(update, &lock->old_oid, err))
2950                        return TRANSACTION_GENERIC_ERROR;
2951
2952                /*
2953                 * If this update is happening indirectly because of a
2954                 * symref update, record the old SHA-1 in the parent
2955                 * update:
2956                 */
2957                for (parent_update = update->parent_update;
2958                     parent_update;
2959                     parent_update = parent_update->parent_update) {
2960                        struct ref_lock *parent_lock = parent_update->backend_data;
2961                        oidcpy(&parent_lock->old_oid, &lock->old_oid);
2962                }
2963        }
2964
2965        if ((update->flags & REF_HAVE_NEW) &&
2966            !(update->flags & REF_DELETING) &&
2967            !(update->flags & REF_LOG_ONLY)) {
2968                if (!(update->type & REF_ISSYMREF) &&
2969                    !oidcmp(&lock->old_oid, &update->new_oid)) {
2970                        /*
2971                         * The reference already has the desired
2972                         * value, so we don't need to write it.
2973                         */
2974                } else if (write_ref_to_lockfile(lock, &update->new_oid,
2975                                                 err)) {
2976                        char *write_err = strbuf_detach(err, NULL);
2977
2978                        /*
2979                         * The lock was freed upon failure of
2980                         * write_ref_to_lockfile():
2981                         */
2982                        update->backend_data = NULL;
2983                        strbuf_addf(err,
2984                                    "cannot update ref '%s': %s",
2985                                    update->refname, write_err);
2986                        free(write_err);
2987                        return TRANSACTION_GENERIC_ERROR;
2988                } else {
2989                        update->flags |= REF_NEEDS_COMMIT;
2990                }
2991        }
2992        if (!(update->flags & REF_NEEDS_COMMIT)) {
2993                /*
2994                 * We didn't call write_ref_to_lockfile(), so
2995                 * the lockfile is still open. Close it to
2996                 * free up the file descriptor:
2997                 */
2998                if (close_ref(lock)) {
2999                        strbuf_addf(err, "couldn't close '%s.lock'",
3000                                    update->refname);
3001                        return TRANSACTION_GENERIC_ERROR;
3002                }
3003        }
3004        return 0;
3005}
3006
3007/*
3008 * Unlock any references in `transaction` that are still locked, and
3009 * mark the transaction closed.
3010 */
3011static void files_transaction_cleanup(struct ref_transaction *transaction)
3012{
3013        size_t i;
3014
3015        for (i = 0; i < transaction->nr; i++) {
3016                struct ref_update *update = transaction->updates[i];
3017                struct ref_lock *lock = update->backend_data;
3018
3019                if (lock) {
3020                        unlock_ref(lock);
3021                        update->backend_data = NULL;
3022                }
3023        }
3024
3025        transaction->state = REF_TRANSACTION_CLOSED;
3026}
3027
3028static int files_transaction_prepare(struct ref_store *ref_store,
3029                                     struct ref_transaction *transaction,
3030                                     struct strbuf *err)
3031{
3032        struct files_ref_store *refs =
3033                files_downcast(ref_store, REF_STORE_WRITE,
3034                               "ref_transaction_prepare");
3035        size_t i;
3036        int ret = 0;
3037        struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3038        char *head_ref = NULL;
3039        int head_type;
3040        struct object_id head_oid;
3041
3042        assert(err);
3043
3044        if (!transaction->nr)
3045                goto cleanup;
3046
3047        /*
3048         * Fail if a refname appears more than once in the
3049         * transaction. (If we end up splitting up any updates using
3050         * split_symref_update() or split_head_update(), those
3051         * functions will check that the new updates don't have the
3052         * same refname as any existing ones.)
3053         */
3054        for (i = 0; i < transaction->nr; i++) {
3055                struct ref_update *update = transaction->updates[i];
3056                struct string_list_item *item =
3057                        string_list_append(&affected_refnames, update->refname);
3058
3059                /*
3060                 * We store a pointer to update in item->util, but at
3061                 * the moment we never use the value of this field
3062                 * except to check whether it is non-NULL.
3063                 */
3064                item->util = update;
3065        }
3066        string_list_sort(&affected_refnames);
3067        if (ref_update_reject_duplicates(&affected_refnames, err)) {
3068                ret = TRANSACTION_GENERIC_ERROR;
3069                goto cleanup;
3070        }
3071
3072        /*
3073         * Special hack: If a branch is updated directly and HEAD
3074         * points to it (may happen on the remote side of a push
3075         * for example) then logically the HEAD reflog should be
3076         * updated too.
3077         *
3078         * A generic solution would require reverse symref lookups,
3079         * but finding all symrefs pointing to a given branch would be
3080         * rather costly for this rare event (the direct update of a
3081         * branch) to be worth it. So let's cheat and check with HEAD
3082         * only, which should cover 99% of all usage scenarios (even
3083         * 100% of the default ones).
3084         *
3085         * So if HEAD is a symbolic reference, then record the name of
3086         * the reference that it points to. If we see an update of
3087         * head_ref within the transaction, then split_head_update()
3088         * arranges for the reflog of HEAD to be updated, too.
3089         */
3090        head_ref = refs_resolve_refdup(ref_store, "HEAD",
3091                                       RESOLVE_REF_NO_RECURSE,
3092                                       head_oid.hash, &head_type);
3093
3094        if (head_ref && !(head_type & REF_ISSYMREF)) {
3095                free(head_ref);
3096                head_ref = NULL;
3097        }
3098
3099        /*
3100         * Acquire all locks, verify old values if provided, check
3101         * that new values are valid, and write new values to the
3102         * lockfiles, ready to be activated. Only keep one lockfile
3103         * open at a time to avoid running out of file descriptors.
3104         * Note that lock_ref_for_update() might append more updates
3105         * to the transaction.
3106         */
3107        for (i = 0; i < transaction->nr; i++) {
3108                struct ref_update *update = transaction->updates[i];
3109
3110                ret = lock_ref_for_update(refs, update, transaction,
3111                                          head_ref, &affected_refnames, err);
3112                if (ret)
3113                        break;
3114        }
3115
3116cleanup:
3117        free(head_ref);
3118        string_list_clear(&affected_refnames, 0);
3119
3120        if (ret)
3121                files_transaction_cleanup(transaction);
3122        else
3123                transaction->state = REF_TRANSACTION_PREPARED;
3124
3125        return ret;
3126}
3127
3128static int files_transaction_finish(struct ref_store *ref_store,
3129                                    struct ref_transaction *transaction,
3130                                    struct strbuf *err)
3131{
3132        struct files_ref_store *refs =
3133                files_downcast(ref_store, 0, "ref_transaction_finish");
3134        size_t i;
3135        int ret = 0;
3136        struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3137        struct string_list_item *ref_to_delete;
3138        struct strbuf sb = STRBUF_INIT;
3139
3140        assert(err);
3141
3142        if (!transaction->nr) {
3143                transaction->state = REF_TRANSACTION_CLOSED;
3144                return 0;
3145        }
3146
3147        /* Perform updates first so live commits remain referenced */
3148        for (i = 0; i < transaction->nr; i++) {
3149                struct ref_update *update = transaction->updates[i];
3150                struct ref_lock *lock = update->backend_data;
3151
3152                if (update->flags & REF_NEEDS_COMMIT ||
3153                    update->flags & REF_LOG_ONLY) {
3154                        if (files_log_ref_write(refs,
3155                                                lock->ref_name,
3156                                                &lock->old_oid,
3157                                                &update->new_oid,
3158                                                update->msg, update->flags,
3159                                                err)) {
3160                                char *old_msg = strbuf_detach(err, NULL);
3161
3162                                strbuf_addf(err, "cannot update the ref '%s': %s",
3163                                            lock->ref_name, old_msg);
3164                                free(old_msg);
3165                                unlock_ref(lock);
3166                                update->backend_data = NULL;
3167                                ret = TRANSACTION_GENERIC_ERROR;
3168                                goto cleanup;
3169                        }
3170                }
3171                if (update->flags & REF_NEEDS_COMMIT) {
3172                        clear_loose_ref_cache(refs);
3173                        if (commit_ref(lock)) {
3174                                strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
3175                                unlock_ref(lock);
3176                                update->backend_data = NULL;
3177                                ret = TRANSACTION_GENERIC_ERROR;
3178                                goto cleanup;
3179                        }
3180                }
3181        }
3182        /* Perform deletes now that updates are safely completed */
3183        for (i = 0; i < transaction->nr; i++) {
3184                struct ref_update *update = transaction->updates[i];
3185                struct ref_lock *lock = update->backend_data;
3186
3187                if (update->flags & REF_DELETING &&
3188                    !(update->flags & REF_LOG_ONLY)) {
3189                        if (!(update->type & REF_ISPACKED) ||
3190                            update->type & REF_ISSYMREF) {
3191                                /* It is a loose reference. */
3192                                strbuf_reset(&sb);
3193                                files_ref_path(refs, &sb, lock->ref_name);
3194                                if (unlink_or_msg(sb.buf, err)) {
3195                                        ret = TRANSACTION_GENERIC_ERROR;
3196                                        goto cleanup;
3197                                }
3198                                update->flags |= REF_DELETED_LOOSE;
3199                        }
3200
3201                        if (!(update->flags & REF_ISPRUNING))
3202                                string_list_append(&refs_to_delete,
3203                                                   lock->ref_name);
3204                }
3205        }
3206
3207        if (repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {
3208                ret = TRANSACTION_GENERIC_ERROR;
3209                goto cleanup;
3210        }
3211
3212        /* Delete the reflogs of any references that were deleted: */
3213        for_each_string_list_item(ref_to_delete, &refs_to_delete) {
3214                strbuf_reset(&sb);
3215                files_reflog_path(refs, &sb, ref_to_delete->string);
3216                if (!unlink_or_warn(sb.buf))
3217                        try_remove_empty_parents(refs, ref_to_delete->string,
3218                                                 REMOVE_EMPTY_PARENTS_REFLOG);
3219        }
3220
3221        clear_loose_ref_cache(refs);
3222
3223cleanup:
3224        files_transaction_cleanup(transaction);
3225
3226        for (i = 0; i < transaction->nr; i++) {
3227                struct ref_update *update = transaction->updates[i];
3228
3229                if (update->flags & REF_DELETED_LOOSE) {
3230                        /*
3231                         * The loose reference was deleted. Delete any
3232                         * empty parent directories. (Note that this
3233                         * can only work because we have already
3234                         * removed the lockfile.)
3235                         */
3236                        try_remove_empty_parents(refs, update->refname,
3237                                                 REMOVE_EMPTY_PARENTS_REF);
3238                }
3239        }
3240
3241        strbuf_release(&sb);
3242        string_list_clear(&refs_to_delete, 0);
3243        return ret;
3244}
3245
3246static int files_transaction_abort(struct ref_store *ref_store,
3247                                   struct ref_transaction *transaction,
3248                                   struct strbuf *err)
3249{
3250        files_transaction_cleanup(transaction);
3251        return 0;
3252}
3253
3254static int ref_present(const char *refname,
3255                       const struct object_id *oid, int flags, void *cb_data)
3256{
3257        struct string_list *affected_refnames = cb_data;
3258
3259        return string_list_has_string(affected_refnames, refname);
3260}
3261
3262static int files_initial_transaction_commit(struct ref_store *ref_store,
3263                                            struct ref_transaction *transaction,
3264                                            struct strbuf *err)
3265{
3266        struct files_ref_store *refs =
3267                files_downcast(ref_store, REF_STORE_WRITE,
3268                               "initial_ref_transaction_commit");
3269        size_t i;
3270        int ret = 0;
3271        struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3272
3273        assert(err);
3274
3275        if (transaction->state != REF_TRANSACTION_OPEN)
3276                die("BUG: commit called for transaction that is not open");
3277
3278        /* Fail if a refname appears more than once in the transaction: */
3279        for (i = 0; i < transaction->nr; i++)
3280                string_list_append(&affected_refnames,
3281                                   transaction->updates[i]->refname);
3282        string_list_sort(&affected_refnames);
3283        if (ref_update_reject_duplicates(&affected_refnames, err)) {
3284                ret = TRANSACTION_GENERIC_ERROR;
3285                goto cleanup;
3286        }
3287
3288        /*
3289         * It's really undefined to call this function in an active
3290         * repository or when there are existing references: we are
3291         * only locking and changing packed-refs, so (1) any
3292         * simultaneous processes might try to change a reference at
3293         * the same time we do, and (2) any existing loose versions of
3294         * the references that we are setting would have precedence
3295         * over our values. But some remote helpers create the remote
3296         * "HEAD" and "master" branches before calling this function,
3297         * so here we really only check that none of the references
3298         * that we are creating already exists.
3299         */
3300        if (refs_for_each_rawref(&refs->base, ref_present,
3301                                 &affected_refnames))
3302                die("BUG: initial ref transaction called with existing refs");
3303
3304        for (i = 0; i < transaction->nr; i++) {
3305                struct ref_update *update = transaction->updates[i];
3306
3307                if ((update->flags & REF_HAVE_OLD) &&
3308                    !is_null_oid(&update->old_oid))
3309                        die("BUG: initial ref transaction with old_sha1 set");
3310                if (refs_verify_refname_available(&refs->base, update->refname,
3311                                                  &affected_refnames, NULL,
3312                                                  err)) {
3313                        ret = TRANSACTION_NAME_CONFLICT;
3314                        goto cleanup;
3315                }
3316        }
3317
3318        if (lock_packed_refs(refs->packed_ref_store, 0)) {
3319                strbuf_addf(err, "unable to lock packed-refs file: %s",
3320                            strerror(errno));
3321                ret = TRANSACTION_GENERIC_ERROR;
3322                goto cleanup;
3323        }
3324
3325        for (i = 0; i < transaction->nr; i++) {
3326                struct ref_update *update = transaction->updates[i];
3327
3328                if ((update->flags & REF_HAVE_NEW) &&
3329                    !is_null_oid(&update->new_oid))
3330                        add_packed_ref(refs->packed_ref_store, update->refname,
3331                                       &update->new_oid);
3332        }
3333
3334        if (commit_packed_refs(refs->packed_ref_store)) {
3335                strbuf_addf(err, "unable to commit packed-refs file: %s",
3336                            strerror(errno));
3337                ret = TRANSACTION_GENERIC_ERROR;
3338                goto cleanup;
3339        }
3340
3341cleanup:
3342        transaction->state = REF_TRANSACTION_CLOSED;
3343        string_list_clear(&affected_refnames, 0);
3344        return ret;
3345}
3346
3347struct expire_reflog_cb {
3348        unsigned int flags;
3349        reflog_expiry_should_prune_fn *should_prune_fn;
3350        void *policy_cb;
3351        FILE *newlog;
3352        struct object_id last_kept_oid;
3353};
3354
3355static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
3356                             const char *email, timestamp_t timestamp, int tz,
3357                             const char *message, void *cb_data)
3358{
3359        struct expire_reflog_cb *cb = cb_data;
3360        struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3361
3362        if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3363                ooid = &cb->last_kept_oid;
3364
3365        if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
3366                                   message, policy_cb)) {
3367                if (!cb->newlog)
3368                        printf("would prune %s", message);
3369                else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3370                        printf("prune %s", message);
3371        } else {
3372                if (cb->newlog) {
3373                        fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
3374                                oid_to_hex(ooid), oid_to_hex(noid),
3375                                email, timestamp, tz, message);
3376                        oidcpy(&cb->last_kept_oid, noid);
3377                }
3378                if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3379                        printf("keep %s", message);
3380        }
3381        return 0;
3382}
3383
3384static int files_reflog_expire(struct ref_store *ref_store,
3385                               const char *refname, const unsigned char *sha1,
3386                               unsigned int flags,
3387                               reflog_expiry_prepare_fn prepare_fn,
3388                               reflog_expiry_should_prune_fn should_prune_fn,
3389                               reflog_expiry_cleanup_fn cleanup_fn,
3390                               void *policy_cb_data)
3391{
3392        struct files_ref_store *refs =
3393                files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
3394        static struct lock_file reflog_lock;
3395        struct expire_reflog_cb cb;
3396        struct ref_lock *lock;
3397        struct strbuf log_file_sb = STRBUF_INIT;
3398        char *log_file;
3399        int status = 0;
3400        int type;
3401        struct strbuf err = STRBUF_INIT;
3402        struct object_id oid;
3403
3404        memset(&cb, 0, sizeof(cb));
3405        cb.flags = flags;
3406        cb.policy_cb = policy_cb_data;
3407        cb.should_prune_fn = should_prune_fn;
3408
3409        /*
3410         * The reflog file is locked by holding the lock on the
3411         * reference itself, plus we might need to update the
3412         * reference if --updateref was specified:
3413         */
3414        lock = lock_ref_sha1_basic(refs, refname, sha1,
3415                                   NULL, NULL, REF_NODEREF,
3416                                   &type, &err);
3417        if (!lock) {
3418                error("cannot lock ref '%s': %s", refname, err.buf);
3419                strbuf_release(&err);
3420                return -1;
3421        }
3422        if (!refs_reflog_exists(ref_store, refname)) {
3423                unlock_ref(lock);
3424                return 0;
3425        }
3426
3427        files_reflog_path(refs, &log_file_sb, refname);
3428        log_file = strbuf_detach(&log_file_sb, NULL);
3429        if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3430                /*
3431                 * Even though holding $GIT_DIR/logs/$reflog.lock has
3432                 * no locking implications, we use the lock_file
3433                 * machinery here anyway because it does a lot of the
3434                 * work we need, including cleaning up if the program
3435                 * exits unexpectedly.
3436                 */
3437                if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3438                        struct strbuf err = STRBUF_INIT;
3439                        unable_to_lock_message(log_file, errno, &err);
3440                        error("%s", err.buf);
3441                        strbuf_release(&err);
3442                        goto failure;
3443                }
3444                cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3445                if (!cb.newlog) {
3446                        error("cannot fdopen %s (%s)",
3447                              get_lock_file_path(&reflog_lock), strerror(errno));
3448                        goto failure;
3449                }
3450        }
3451
3452        hashcpy(oid.hash, sha1);
3453
3454        (*prepare_fn)(refname, &oid, cb.policy_cb);
3455        refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3456        (*cleanup_fn)(cb.policy_cb);
3457
3458        if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3459                /*
3460                 * It doesn't make sense to adjust a reference pointed
3461                 * to by a symbolic ref based on expiring entries in
3462                 * the symbolic reference's reflog. Nor can we update
3463                 * a reference if there are no remaining reflog
3464                 * entries.
3465                 */
3466                int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3467                        !(type & REF_ISSYMREF) &&
3468                        !is_null_oid(&cb.last_kept_oid);
3469
3470                if (close_lock_file(&reflog_lock)) {
3471                        status |= error("couldn't write %s: %s", log_file,
3472                                        strerror(errno));
3473                } else if (update &&
3474                           (write_in_full(get_lock_file_fd(lock->lk),
3475                                oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
3476                            write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3477                            close_ref(lock) < 0)) {
3478                        status |= error("couldn't write %s",
3479                                        get_lock_file_path(lock->lk));
3480                        rollback_lock_file(&reflog_lock);
3481                } else if (commit_lock_file(&reflog_lock)) {
3482                        status |= error("unable to write reflog '%s' (%s)",
3483                                        log_file, strerror(errno));
3484                } else if (update && commit_ref(lock)) {
3485                        status |= error("couldn't set %s", lock->ref_name);
3486                }
3487        }
3488        free(log_file);
3489        unlock_ref(lock);
3490        return status;
3491
3492 failure:
3493        rollback_lock_file(&reflog_lock);
3494        free(log_file);
3495        unlock_ref(lock);
3496        return -1;
3497}
3498
3499static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3500{
3501        struct files_ref_store *refs =
3502                files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3503        struct strbuf sb = STRBUF_INIT;
3504
3505        /*
3506         * Create .git/refs/{heads,tags}
3507         */
3508        files_ref_path(refs, &sb, "refs/heads");
3509        safe_create_dir(sb.buf, 1);
3510
3511        strbuf_reset(&sb);
3512        files_ref_path(refs, &sb, "refs/tags");
3513        safe_create_dir(sb.buf, 1);
3514
3515        strbuf_release(&sb);
3516        return 0;
3517}
3518
3519struct ref_storage_be refs_be_files = {
3520        NULL,
3521        "files",
3522        files_ref_store_create,
3523        files_init_db,
3524        files_transaction_prepare,
3525        files_transaction_finish,
3526        files_transaction_abort,
3527        files_initial_transaction_commit,
3528
3529        files_pack_refs,
3530        files_peel_ref,
3531        files_create_symref,
3532        files_delete_refs,
3533        files_rename_ref,
3534
3535        files_ref_iterator_begin,
3536        files_read_raw_ref,
3537
3538        files_reflog_iterator_begin,
3539        files_for_each_reflog_ent,
3540        files_for_each_reflog_ent_reverse,
3541        files_reflog_exists,
3542        files_create_reflog,
3543        files_delete_reflog,
3544        files_reflog_expire
3545};