commit_lock_file(): rollback lock file on failure to rename
[git/mjg.git] / lockfile.c
blob728ce497654127ce7245f34c894b3ef8db92fa74
1 /*
2 * Copyright (c) 2005, Junio C Hamano
3 */
4 #include "cache.h"
5 #include "sigchain.h"
7 /*
8 * File write-locks as used by Git.
10 * For an overview of how to use the lockfile API, please see
12 * Documentation/technical/api-lockfile.txt
14 * This module keeps track of all locked files in lock_file_list for
15 * use at cleanup. This list and the lock_file objects that comprise
16 * it must be kept in self-consistent states at all time, because the
17 * program can be interrupted any time by a signal, in which case the
18 * signal handler will walk through the list attempting to clean up
19 * any open lock files.
21 * A lockfile is owned by the process that created it. The lock_file
22 * object has an "owner" field that records its owner. This field is
23 * used to prevent a forked process from closing a lockfile created by
24 * its parent.
26 * A lock_file object can be in several states:
28 * - Uninitialized. In this state the object's on_list field must be
29 * zero but the rest of its contents need not be initialized. As
30 * soon as the object is used in any way, it is irrevocably
31 * registered in the lock_file_list, and on_list is set.
33 * - Locked, lockfile open (after hold_lock_file_for_update(),
34 * hold_lock_file_for_append(), or reopen_lock_file()). In this
35 * state, the lockfile exists, filename holds the filename of the
36 * lockfile, fd holds a file descriptor open for writing to the
37 * lockfile, and owner holds the PID of the process that locked the
38 * file.
40 * - Locked, lockfile closed (after successful close_lock_file()).
41 * Same as the previous state, except that the lockfile is closed
42 * and fd is -1.
44 * - Unlocked (after commit_lock_file(), rollback_lock_file(), a
45 * failed attempt to lock, or a failed close_lock_file()). In this
46 * state, filename[0] == '\0' and fd is -1. The object is left
47 * registered in the lock_file_list, and on_list is set.
50 static struct lock_file *lock_file_list;
52 static void remove_lock_file(void)
54 pid_t me = getpid();
56 while (lock_file_list) {
57 if (lock_file_list->owner == me)
58 rollback_lock_file(lock_file_list);
59 lock_file_list = lock_file_list->next;
63 static void remove_lock_file_on_signal(int signo)
65 remove_lock_file();
66 sigchain_pop(signo);
67 raise(signo);
71 * p = absolute or relative path name
73 * Return a pointer into p showing the beginning of the last path name
74 * element. If p is empty or the root directory ("/"), just return p.
76 static char *last_path_elm(char *p)
78 /* r starts pointing to null at the end of the string */
79 char *r = strchr(p, '\0');
81 if (r == p)
82 return p; /* just return empty string */
84 r--; /* back up to last non-null character */
86 /* back up past trailing slashes, if any */
87 while (r > p && *r == '/')
88 r--;
91 * then go backwards until I hit a slash, or the beginning of
92 * the string
94 while (r > p && *(r-1) != '/')
95 r--;
96 return r;
100 /* We allow "recursive" symbolic links. Only within reason, though */
101 #define MAXDEPTH 5
104 * p = path that may be a symlink
105 * s = full size of p
107 * If p is a symlink, attempt to overwrite p with a path to the real
108 * file or directory (which may or may not exist), following a chain of
109 * symlinks if necessary. Otherwise, leave p unmodified.
111 * This is a best-effort routine. If an error occurs, p will either be
112 * left unmodified or will name a different symlink in a symlink chain
113 * that started with p's initial contents.
115 * Always returns p.
118 static char *resolve_symlink(char *p, size_t s)
120 int depth = MAXDEPTH;
122 while (depth--) {
123 char link[PATH_MAX];
124 int link_len = readlink(p, link, sizeof(link));
125 if (link_len < 0) {
126 /* not a symlink anymore */
127 return p;
129 else if (link_len < sizeof(link))
130 /* readlink() never null-terminates */
131 link[link_len] = '\0';
132 else {
133 warning("%s: symlink too long", p);
134 return p;
137 if (is_absolute_path(link)) {
138 /* absolute path simply replaces p */
139 if (link_len < s)
140 strcpy(p, link);
141 else {
142 warning("%s: symlink too long", p);
143 return p;
145 } else {
147 * link is a relative path, so I must replace the
148 * last element of p with it.
150 char *r = (char *)last_path_elm(p);
151 if (r - p + link_len < s)
152 strcpy(r, link);
153 else {
154 warning("%s: symlink too long", p);
155 return p;
159 return p;
162 /* Make sure errno contains a meaningful value on error */
163 static int lock_file(struct lock_file *lk, const char *path, int flags)
166 * subtract LOCK_SUFFIX_LEN from size to make sure there's
167 * room for adding ".lock" for the lock file name:
169 static const size_t max_path_len = sizeof(lk->filename) -
170 LOCK_SUFFIX_LEN;
172 if (!lock_file_list) {
173 /* One-time initialization */
174 sigchain_push_common(remove_lock_file_on_signal);
175 atexit(remove_lock_file);
178 if (!lk->on_list) {
179 /* Initialize *lk and add it to lock_file_list: */
180 lk->fd = -1;
181 lk->owner = 0;
182 lk->filename[0] = 0;
183 lk->next = lock_file_list;
184 lock_file_list = lk;
185 lk->on_list = 1;
188 if (strlen(path) >= max_path_len) {
189 errno = ENAMETOOLONG;
190 return -1;
192 strcpy(lk->filename, path);
193 if (!(flags & LOCK_NODEREF))
194 resolve_symlink(lk->filename, max_path_len);
195 strcat(lk->filename, LOCK_SUFFIX);
196 lk->fd = open(lk->filename, O_RDWR | O_CREAT | O_EXCL, 0666);
197 if (lk->fd < 0) {
198 lk->filename[0] = 0;
199 return -1;
201 lk->owner = getpid();
202 if (adjust_shared_perm(lk->filename)) {
203 int save_errno = errno;
204 error("cannot fix permission bits on %s", lk->filename);
205 rollback_lock_file(lk);
206 errno = save_errno;
207 return -1;
209 return lk->fd;
212 void unable_to_lock_message(const char *path, int err, struct strbuf *buf)
214 if (err == EEXIST) {
215 strbuf_addf(buf, "Unable to create '%s.lock': %s.\n\n"
216 "If no other git process is currently running, this probably means a\n"
217 "git process crashed in this repository earlier. Make sure no other git\n"
218 "process is running and remove the file manually to continue.",
219 absolute_path(path), strerror(err));
220 } else
221 strbuf_addf(buf, "Unable to create '%s.lock': %s",
222 absolute_path(path), strerror(err));
225 int unable_to_lock_error(const char *path, int err)
227 struct strbuf buf = STRBUF_INIT;
229 unable_to_lock_message(path, err, &buf);
230 error("%s", buf.buf);
231 strbuf_release(&buf);
232 return -1;
235 NORETURN void unable_to_lock_die(const char *path, int err)
237 struct strbuf buf = STRBUF_INIT;
239 unable_to_lock_message(path, err, &buf);
240 die("%s", buf.buf);
243 /* This should return a meaningful errno on failure */
244 int hold_lock_file_for_update(struct lock_file *lk, const char *path, int flags)
246 int fd = lock_file(lk, path, flags);
247 if (fd < 0 && (flags & LOCK_DIE_ON_ERROR))
248 unable_to_lock_die(path, errno);
249 return fd;
252 int hold_lock_file_for_append(struct lock_file *lk, const char *path, int flags)
254 int fd, orig_fd;
256 fd = lock_file(lk, path, flags);
257 if (fd < 0) {
258 if (flags & LOCK_DIE_ON_ERROR)
259 unable_to_lock_die(path, errno);
260 return fd;
263 orig_fd = open(path, O_RDONLY);
264 if (orig_fd < 0) {
265 if (errno != ENOENT) {
266 if (flags & LOCK_DIE_ON_ERROR)
267 die("cannot open '%s' for copying", path);
268 rollback_lock_file(lk);
269 return error("cannot open '%s' for copying", path);
271 } else if (copy_fd(orig_fd, fd)) {
272 if (flags & LOCK_DIE_ON_ERROR)
273 exit(128);
274 rollback_lock_file(lk);
275 return -1;
277 return fd;
280 int close_lock_file(struct lock_file *lk)
282 int fd = lk->fd;
284 if (fd < 0)
285 return 0;
287 lk->fd = -1;
288 if (close(fd)) {
289 int save_errno = errno;
290 rollback_lock_file(lk);
291 errno = save_errno;
292 return -1;
294 return 0;
297 int reopen_lock_file(struct lock_file *lk)
299 if (0 <= lk->fd)
300 die(_("BUG: reopen a lockfile that is still open"));
301 if (!lk->filename[0])
302 die(_("BUG: reopen a lockfile that has been committed"));
303 lk->fd = open(lk->filename, O_WRONLY);
304 return lk->fd;
307 int commit_lock_file(struct lock_file *lk)
309 char result_file[PATH_MAX];
311 if (!lk->filename[0])
312 die("BUG: attempt to commit unlocked object");
314 if (close_lock_file(lk))
315 return -1;
317 strcpy(result_file, lk->filename);
318 /* remove ".lock": */
319 result_file[strlen(result_file) - LOCK_SUFFIX_LEN] = 0;
321 if (rename(lk->filename, result_file)) {
322 int save_errno = errno;
323 rollback_lock_file(lk);
324 errno = save_errno;
325 return -1;
328 lk->filename[0] = 0;
329 return 0;
332 int hold_locked_index(struct lock_file *lk, int die_on_error)
334 return hold_lock_file_for_update(lk, get_index_file(),
335 die_on_error
336 ? LOCK_DIE_ON_ERROR
337 : 0);
340 void rollback_lock_file(struct lock_file *lk)
342 if (!lk->filename[0])
343 return;
345 if (!close_lock_file(lk)) {
346 unlink_or_warn(lk->filename);
347 lk->filename[0] = 0;