resolve_symlink(): take a strbuf parameter
[git/mjg.git] / lockfile.c
blob5f5bcfffbe25b6145f1683a989399f44880b3d5d
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 * The possible states of a lock_file object are as follows:
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:
36 * - the lockfile exists
37 * - active is set
38 * - filename holds the filename of the lockfile
39 * - fd holds a file descriptor open for writing to the lockfile
40 * - owner holds the PID of the process that locked the file
42 * - Locked, lockfile closed (after successful close_lock_file()).
43 * Same as the previous state, except that the lockfile is closed
44 * and fd is -1.
46 * - Unlocked (after commit_lock_file(), rollback_lock_file(), a
47 * failed attempt to lock, or a failed close_lock_file()). In this
48 * state:
49 * - active is unset
50 * - filename is empty (usually, though there are transitory
51 * states in which this condition doesn't hold). Client code should
52 * *not* rely on the filename being empty in this state.
53 * - fd is -1
54 * - the object is left registered in the lock_file_list, and
55 * on_list is set.
58 static struct lock_file *volatile lock_file_list;
60 static void remove_lock_file(void)
62 pid_t me = getpid();
64 while (lock_file_list) {
65 if (lock_file_list->owner == me)
66 rollback_lock_file(lock_file_list);
67 lock_file_list = lock_file_list->next;
71 static void remove_lock_file_on_signal(int signo)
73 remove_lock_file();
74 sigchain_pop(signo);
75 raise(signo);
79 * p = absolute or relative path name
81 * Return a pointer into p showing the beginning of the last path name
82 * element. If p is empty or the root directory ("/"), just return p.
84 static char *last_path_elm(char *p)
86 /* r starts pointing to null at the end of the string */
87 char *r = strchr(p, '\0');
89 if (r == p)
90 return p; /* just return empty string */
92 r--; /* back up to last non-null character */
94 /* back up past trailing slashes, if any */
95 while (r > p && *r == '/')
96 r--;
99 * then go backwards until I hit a slash, or the beginning of
100 * the string
102 while (r > p && *(r-1) != '/')
103 r--;
104 return r;
108 /* We allow "recursive" symbolic links. Only within reason, though */
109 #define MAXDEPTH 5
112 * path contains a path that might be a symlink.
114 * If path is a symlink, attempt to overwrite it with a path to the
115 * real file or directory (which may or may not exist), following a
116 * chain of symlinks if necessary. Otherwise, leave path unmodified.
118 * This is a best-effort routine. If an error occurs, path will
119 * either be left unmodified or will name a different symlink in a
120 * symlink chain that started with the original path.
122 static void resolve_symlink(struct strbuf *path)
124 int depth = MAXDEPTH;
125 static struct strbuf link = STRBUF_INIT;
127 while (depth--) {
128 if (strbuf_readlink(&link, path->buf, path->len) < 0)
129 break;
131 if (is_absolute_path(link.buf))
132 /* absolute path simply replaces p */
133 strbuf_reset(path);
134 else {
136 * link is a relative path, so replace the
137 * last element of p with it.
139 char *r = last_path_elm(path->buf);
140 strbuf_setlen(path, r - path->buf);
143 strbuf_addbuf(path, &link);
145 strbuf_reset(&link);
148 /* Make sure errno contains a meaningful value on error */
149 static int lock_file(struct lock_file *lk, const char *path, int flags)
151 size_t pathlen = strlen(path);
153 if (!lock_file_list) {
154 /* One-time initialization */
155 sigchain_push_common(remove_lock_file_on_signal);
156 atexit(remove_lock_file);
159 if (lk->active)
160 die("BUG: cannot lock_file(\"%s\") using active struct lock_file",
161 path);
162 if (!lk->on_list) {
163 /* Initialize *lk and add it to lock_file_list: */
164 lk->fd = -1;
165 lk->active = 0;
166 lk->owner = 0;
167 strbuf_init(&lk->filename, pathlen + LOCK_SUFFIX_LEN);
168 lk->next = lock_file_list;
169 lock_file_list = lk;
170 lk->on_list = 1;
171 } else if (lk->filename.len) {
172 /* This shouldn't happen, but better safe than sorry. */
173 die("BUG: lock_file(\"%s\") called with improperly-reset lock_file object",
174 path);
177 strbuf_add(&lk->filename, path, pathlen);
178 if (!(flags & LOCK_NODEREF))
179 resolve_symlink(&lk->filename);
180 strbuf_addstr(&lk->filename, LOCK_SUFFIX);
181 lk->fd = open(lk->filename.buf, O_RDWR | O_CREAT | O_EXCL, 0666);
182 if (lk->fd < 0) {
183 strbuf_reset(&lk->filename);
184 return -1;
186 lk->owner = getpid();
187 lk->active = 1;
188 if (adjust_shared_perm(lk->filename.buf)) {
189 int save_errno = errno;
190 error("cannot fix permission bits on %s", lk->filename.buf);
191 rollback_lock_file(lk);
192 errno = save_errno;
193 return -1;
195 return lk->fd;
198 void unable_to_lock_message(const char *path, int err, struct strbuf *buf)
200 if (err == EEXIST) {
201 strbuf_addf(buf, "Unable to create '%s.lock': %s.\n\n"
202 "If no other git process is currently running, this probably means a\n"
203 "git process crashed in this repository earlier. Make sure no other git\n"
204 "process is running and remove the file manually to continue.",
205 absolute_path(path), strerror(err));
206 } else
207 strbuf_addf(buf, "Unable to create '%s.lock': %s",
208 absolute_path(path), strerror(err));
211 int unable_to_lock_error(const char *path, int err)
213 struct strbuf buf = STRBUF_INIT;
215 unable_to_lock_message(path, err, &buf);
216 error("%s", buf.buf);
217 strbuf_release(&buf);
218 return -1;
221 NORETURN void unable_to_lock_die(const char *path, int err)
223 struct strbuf buf = STRBUF_INIT;
225 unable_to_lock_message(path, err, &buf);
226 die("%s", buf.buf);
229 /* This should return a meaningful errno on failure */
230 int hold_lock_file_for_update(struct lock_file *lk, const char *path, int flags)
232 int fd = lock_file(lk, path, flags);
233 if (fd < 0 && (flags & LOCK_DIE_ON_ERROR))
234 unable_to_lock_die(path, errno);
235 return fd;
238 int hold_lock_file_for_append(struct lock_file *lk, const char *path, int flags)
240 int fd, orig_fd;
242 fd = lock_file(lk, path, flags);
243 if (fd < 0) {
244 if (flags & LOCK_DIE_ON_ERROR)
245 unable_to_lock_die(path, errno);
246 return fd;
249 orig_fd = open(path, O_RDONLY);
250 if (orig_fd < 0) {
251 if (errno != ENOENT) {
252 if (flags & LOCK_DIE_ON_ERROR)
253 die("cannot open '%s' for copying", path);
254 rollback_lock_file(lk);
255 return error("cannot open '%s' for copying", path);
257 } else if (copy_fd(orig_fd, fd)) {
258 if (flags & LOCK_DIE_ON_ERROR)
259 exit(128);
260 rollback_lock_file(lk);
261 return -1;
263 return fd;
266 int close_lock_file(struct lock_file *lk)
268 int fd = lk->fd;
270 if (fd < 0)
271 return 0;
273 lk->fd = -1;
274 if (close(fd)) {
275 int save_errno = errno;
276 rollback_lock_file(lk);
277 errno = save_errno;
278 return -1;
280 return 0;
283 int reopen_lock_file(struct lock_file *lk)
285 if (0 <= lk->fd)
286 die(_("BUG: reopen a lockfile that is still open"));
287 if (!lk->active)
288 die(_("BUG: reopen a lockfile that has been committed"));
289 lk->fd = open(lk->filename.buf, O_WRONLY);
290 return lk->fd;
293 int commit_lock_file(struct lock_file *lk)
295 static struct strbuf result_file = STRBUF_INIT;
296 int err;
298 if (!lk->active)
299 die("BUG: attempt to commit unlocked object");
301 if (close_lock_file(lk))
302 return -1;
304 /* remove ".lock": */
305 strbuf_add(&result_file, lk->filename.buf,
306 lk->filename.len - LOCK_SUFFIX_LEN);
307 err = rename(lk->filename.buf, result_file.buf);
308 strbuf_reset(&result_file);
309 if (err) {
310 int save_errno = errno;
311 rollback_lock_file(lk);
312 errno = save_errno;
313 return -1;
316 lk->active = 0;
317 strbuf_reset(&lk->filename);
318 return 0;
321 int hold_locked_index(struct lock_file *lk, int die_on_error)
323 return hold_lock_file_for_update(lk, get_index_file(),
324 die_on_error
325 ? LOCK_DIE_ON_ERROR
326 : 0);
329 void rollback_lock_file(struct lock_file *lk)
331 if (!lk->active)
332 return;
334 if (!close_lock_file(lk)) {
335 unlink_or_warn(lk->filename.buf);
336 lk->active = 0;
337 strbuf_reset(&lk->filename);