Coverage Report

Created: 2024-09-08 06:23

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