commit_lock_file(): use a strbuf to manage temporary space
[git/git.git] / lockfile.c
CommitLineData
021b6e45
JH
1/*
2 * Copyright (c) 2005, Junio C Hamano
3 */
021b6e45 4#include "cache.h"
4a16d072 5#include "sigchain.h"
021b6e45 6
0a06f148
MH
7/*
8 * File write-locks as used by Git.
9 *
10 * For an overview of how to use the lockfile API, please see
11 *
12 * Documentation/technical/api-lockfile.txt
13 *
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.
20 *
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.
25 *
707103fd 26 * The possible states of a lock_file object are as follows:
0a06f148
MH
27 *
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.
32 *
33 * - Locked, lockfile open (after hold_lock_file_for_update(),
34 * hold_lock_file_for_append(), or reopen_lock_file()). In this
707103fd
MH
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
0a06f148 41 *
8e86c155
MH
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.
0a06f148 45 *
8e86c155 46 * - Unlocked (after commit_lock_file(), rollback_lock_file(), a
707103fd
MH
47 * failed attempt to lock, or a failed close_lock_file()). In this
48 * state:
49 * - active is unset
50 * - filename[0] == '\0' (usually, though there are transitory states
51 * in which this condition doesn't hold). Client code should *not*
52 * rely on this fact!
53 * - fd is -1
54 * - the object is left registered in the lock_file_list, and
55 * on_list is set.
0a06f148
MH
56 */
57
2091c506 58static struct lock_file *volatile lock_file_list;
021b6e45
JH
59
60static void remove_lock_file(void)
61{
5e635e39
JH
62 pid_t me = getpid();
63
021b6e45 64 while (lock_file_list) {
a1754bcc
MH
65 if (lock_file_list->owner == me)
66 rollback_lock_file(lock_file_list);
021b6e45
JH
67 lock_file_list = lock_file_list->next;
68 }
69}
70
71static void remove_lock_file_on_signal(int signo)
72{
73 remove_lock_file();
4a16d072 74 sigchain_pop(signo);
021b6e45
JH
75 raise(signo);
76}
77
5d5a7a67
BS
78/*
79 * p = absolute or relative path name
80 *
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.
83 */
84static char *last_path_elm(char *p)
85{
86 /* r starts pointing to null at the end of the string */
87 char *r = strchr(p, '\0');
88
89 if (r == p)
90 return p; /* just return empty string */
91
92 r--; /* back up to last non-null character */
93
94 /* back up past trailing slashes, if any */
95 while (r > p && *r == '/')
96 r--;
97
98 /*
99 * then go backwards until I hit a slash, or the beginning of
100 * the string
101 */
102 while (r > p && *(r-1) != '/')
103 r--;
104 return r;
105}
106
107
108/* We allow "recursive" symbolic links. Only within reason, though */
109#define MAXDEPTH 5
110
111/*
112 * p = path that may be a symlink
113 * s = full size of p
114 *
115 * If p is a symlink, attempt to overwrite p with a path to the real
116 * file or directory (which may or may not exist), following a chain of
117 * symlinks if necessary. Otherwise, leave p unmodified.
118 *
119 * This is a best-effort routine. If an error occurs, p will either be
120 * left unmodified or will name a different symlink in a symlink chain
121 * that started with p's initial contents.
122 *
123 * Always returns p.
124 */
125
126static char *resolve_symlink(char *p, size_t s)
127{
128 int depth = MAXDEPTH;
129
130 while (depth--) {
131 char link[PATH_MAX];
132 int link_len = readlink(p, link, sizeof(link));
133 if (link_len < 0) {
134 /* not a symlink anymore */
135 return p;
136 }
137 else if (link_len < sizeof(link))
138 /* readlink() never null-terminates */
139 link[link_len] = '\0';
140 else {
141 warning("%s: symlink too long", p);
142 return p;
143 }
144
ecf4831d 145 if (is_absolute_path(link)) {
5d5a7a67
BS
146 /* absolute path simply replaces p */
147 if (link_len < s)
148 strcpy(p, link);
149 else {
150 warning("%s: symlink too long", p);
151 return p;
152 }
153 } else {
154 /*
155 * link is a relative path, so I must replace the
156 * last element of p with it.
157 */
4b25d091 158 char *r = (char *)last_path_elm(p);
5d5a7a67
BS
159 if (r - p + link_len < s)
160 strcpy(r, link);
161 else {
162 warning("%s: symlink too long", p);
163 return p;
164 }
165 }
166 }
167 return p;
168}
169
447ff1bf 170/* Make sure errno contains a meaningful value on error */
acd3b9ec 171static int lock_file(struct lock_file *lk, const char *path, int flags)
021b6e45 172{
5d5a7a67 173 /*
7108ad23
MH
174 * subtract LOCK_SUFFIX_LEN from size to make sure there's
175 * room for adding ".lock" for the lock file name:
5d5a7a67 176 */
7108ad23
MH
177 static const size_t max_path_len = sizeof(lk->filename) -
178 LOCK_SUFFIX_LEN;
2fbd4f92 179
04e57d4d
MH
180 if (!lock_file_list) {
181 /* One-time initialization */
182 sigchain_push_common(remove_lock_file_on_signal);
183 atexit(remove_lock_file);
184 }
185
707103fd
MH
186 if (lk->active)
187 die("BUG: cannot lock_file(\"%s\") using active struct lock_file",
188 path);
04e57d4d
MH
189 if (!lk->on_list) {
190 /* Initialize *lk and add it to lock_file_list: */
191 lk->fd = -1;
707103fd 192 lk->active = 0;
04e57d4d
MH
193 lk->owner = 0;
194 lk->filename[0] = 0;
195 lk->next = lock_file_list;
196 lock_file_list = lk;
197 lk->on_list = 1;
198 }
199
447ff1bf
RS
200 if (strlen(path) >= max_path_len) {
201 errno = ENAMETOOLONG;
2fbd4f92 202 return -1;
447ff1bf 203 }
2fbd4f92 204 strcpy(lk->filename, path);
acd3b9ec 205 if (!(flags & LOCK_NODEREF))
2fbd4f92 206 resolve_symlink(lk->filename, max_path_len);
7108ad23 207 strcat(lk->filename, LOCK_SUFFIX);
4723ee99 208 lk->fd = open(lk->filename, O_RDWR | O_CREAT | O_EXCL, 0666);
e31e949b 209 if (lk->fd < 0) {
1084b845 210 lk->filename[0] = 0;
e31e949b
MH
211 return -1;
212 }
213 lk->owner = getpid();
707103fd 214 lk->active = 1;
e31e949b
MH
215 if (adjust_shared_perm(lk->filename)) {
216 int save_errno = errno;
217 error("cannot fix permission bits on %s", lk->filename);
218 rollback_lock_file(lk);
219 errno = save_errno;
220 return -1;
221 }
4723ee99 222 return lk->fd;
021b6e45
JH
223}
224
6af926e8 225void unable_to_lock_message(const char *path, int err, struct strbuf *buf)
e43a6fd3 226{
bdfd739d 227 if (err == EEXIST) {
6af926e8 228 strbuf_addf(buf, "Unable to create '%s.lock': %s.\n\n"
e43a6fd3
MM
229 "If no other git process is currently running, this probably means a\n"
230 "git process crashed in this repository earlier. Make sure no other git\n"
231 "process is running and remove the file manually to continue.",
e2a57aac 232 absolute_path(path), strerror(err));
1b018fd9 233 } else
6af926e8 234 strbuf_addf(buf, "Unable to create '%s.lock': %s",
e2a57aac 235 absolute_path(path), strerror(err));
1b018fd9
MV
236}
237
238int unable_to_lock_error(const char *path, int err)
239{
6af926e8
RS
240 struct strbuf buf = STRBUF_INIT;
241
242 unable_to_lock_message(path, err, &buf);
243 error("%s", buf.buf);
244 strbuf_release(&buf);
1b018fd9
MV
245 return -1;
246}
247
e197c218 248NORETURN void unable_to_lock_die(const char *path, int err)
1b018fd9 249{
6af926e8
RS
250 struct strbuf buf = STRBUF_INIT;
251
252 unable_to_lock_message(path, err, &buf);
253 die("%s", buf.buf);
e43a6fd3
MM
254}
255
447ff1bf 256/* This should return a meaningful errno on failure */
acd3b9ec 257int hold_lock_file_for_update(struct lock_file *lk, const char *path, int flags)
40aaae88 258{
acd3b9ec
JH
259 int fd = lock_file(lk, path, flags);
260 if (fd < 0 && (flags & LOCK_DIE_ON_ERROR))
e197c218 261 unable_to_lock_die(path, errno);
40aaae88
JH
262 return fd;
263}
264
acd3b9ec 265int hold_lock_file_for_append(struct lock_file *lk, const char *path, int flags)
ea3cd5c7
DB
266{
267 int fd, orig_fd;
268
acd3b9ec 269 fd = lock_file(lk, path, flags);
ea3cd5c7 270 if (fd < 0) {
acd3b9ec 271 if (flags & LOCK_DIE_ON_ERROR)
e197c218 272 unable_to_lock_die(path, errno);
ea3cd5c7
DB
273 return fd;
274 }
275
276 orig_fd = open(path, O_RDONLY);
277 if (orig_fd < 0) {
278 if (errno != ENOENT) {
acd3b9ec 279 if (flags & LOCK_DIE_ON_ERROR)
ea3cd5c7 280 die("cannot open '%s' for copying", path);
ebb8e380 281 rollback_lock_file(lk);
ea3cd5c7
DB
282 return error("cannot open '%s' for copying", path);
283 }
284 } else if (copy_fd(orig_fd, fd)) {
acd3b9ec 285 if (flags & LOCK_DIE_ON_ERROR)
ea3cd5c7 286 exit(128);
ebb8e380 287 rollback_lock_file(lk);
ea3cd5c7
DB
288 return -1;
289 }
290 return fd;
291}
292
d6cf61bf
BC
293int close_lock_file(struct lock_file *lk)
294{
295 int fd = lk->fd;
419f0c0f
MH
296
297 if (fd < 0)
298 return 0;
299
d6cf61bf 300 lk->fd = -1;
8e86c155
MH
301 if (close(fd)) {
302 int save_errno = errno;
303 rollback_lock_file(lk);
304 errno = save_errno;
305 return -1;
306 }
307 return 0;
d6cf61bf
BC
308}
309
93dcaea2
JH
310int reopen_lock_file(struct lock_file *lk)
311{
312 if (0 <= lk->fd)
313 die(_("BUG: reopen a lockfile that is still open"));
707103fd 314 if (!lk->active)
93dcaea2
JH
315 die(_("BUG: reopen a lockfile that has been committed"));
316 lk->fd = open(lk->filename, O_WRONLY);
317 return lk->fd;
318}
319
021b6e45
JH
320int commit_lock_file(struct lock_file *lk)
321{
3e88e8fc
MH
322 static struct strbuf result_file = STRBUF_INIT;
323 int err;
4f4713df 324
707103fd 325 if (!lk->active)
8a1c7533
MH
326 die("BUG: attempt to commit unlocked object");
327
419f0c0f 328 if (close_lock_file(lk))
d6cf61bf 329 return -1;
4f4713df 330
4f4713df 331 /* remove ".lock": */
3e88e8fc
MH
332 strbuf_add(&result_file, lk->filename,
333 strlen(lk->filename) - LOCK_SUFFIX_LEN);
334 err = rename(lk->filename, result_file.buf);
335 strbuf_reset(&result_file);
336 if (err) {
1b1648f4
MH
337 int save_errno = errno;
338 rollback_lock_file(lk);
339 errno = save_errno;
d6cf61bf 340 return -1;
1b1648f4
MH
341 }
342
707103fd 343 lk->active = 0;
021b6e45 344 lk->filename[0] = 0;
d6cf61bf 345 return 0;
021b6e45
JH
346}
347
30ca07a2
JH
348int hold_locked_index(struct lock_file *lk, int die_on_error)
349{
acd3b9ec
JH
350 return hold_lock_file_for_update(lk, get_index_file(),
351 die_on_error
352 ? LOCK_DIE_ON_ERROR
353 : 0);
30ca07a2
JH
354}
355
021b6e45
JH
356void rollback_lock_file(struct lock_file *lk)
357{
707103fd 358 if (!lk->active)
9085f8e2
MH
359 return;
360
8e86c155
MH
361 if (!close_lock_file(lk)) {
362 unlink_or_warn(lk->filename);
707103fd 363 lk->active = 0;
8e86c155
MH
364 lk->filename[0] = 0;
365 }
021b6e45 366}