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