Coverage Report

Created: 2026-03-21 06:46

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