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