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