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