Raw
1 /*
2 * Copyright (c) 2005, Junio C Hamano
3 */
4
5 #define USE_THE_REPOSITORY_VARIABLE
6
7 #include "git-compat-util.h"
8 #include "abspath.h"
9 #include "gettext.h"
10 #include "lockfile.h"
11 #include "parse.h"
12 #include "repository.h"
13 #include "strbuf.h"
14 #include "wrapper.h"
15
16 /*
17 * path = absolute or relative path name
18 *
19 * Remove the last path name element from path (leaving the preceding
20 * "/", if any). If path is empty or the root directory ("/"), set
21 * path to the empty string.
22 */
23 static void trim_last_path_component(struct strbuf *path)
24 {
25 int i = path->len;
26
27 /* back up past trailing slashes, if any */
28 while (i && is_dir_sep(path->buf[i - 1]))
29 i--;
30
31 /*
32 * then go backwards until a slash, or the beginning of the
33 * string
34 */
35 while (i && !is_dir_sep(path->buf[i - 1]))
36 i--;
37
38 strbuf_setlen(path, i);
39 }
40
41
42 /* We allow "recursive" symbolic links. Only within reason, though */
43 #define MAXDEPTH 5
44
45 /*
46 * path contains a path that might be a symlink.
47 *
48 * If path is a symlink, attempt to overwrite it with a path to the
49 * real file or directory (which may or may not exist), following a
50 * chain of symlinks if necessary. Otherwise, leave path unmodified.
51 *
52 * This is a best-effort routine. If an error occurs, path will
53 * either be left unmodified or will name a different symlink in a
54 * symlink chain that started with the original path.
55 */
56 static void resolve_symlink(struct strbuf *path)
57 {
58 int depth = MAXDEPTH;
59 static struct strbuf link = STRBUF_INIT;
60
61 while (depth--) {
62 if (strbuf_readlink(&link, path->buf, path->len) < 0)
63 break;
64
65 if (is_absolute_path(link.buf))
66 /* absolute path simply replaces p */
67 strbuf_reset(path);
68 else
69 /*
70 * link is a relative path, so replace the
71 * last element of p with it.
72 */
73 trim_last_path_component(path);
74
75 strbuf_addbuf(path, &link);
76 }
77 strbuf_reset(&link);
78 }
79
80 /*
81 * Lock PID file functions - write PID to a foo~pid.lock file alongside
82 * the lock file for debugging stale locks. The PID file is registered
83 * as a tempfile so it gets cleaned up by signal/atexit handlers.
84 *
85 * Naming: For "foo.lock", the PID file is "foo~pid.lock". The tilde is
86 * forbidden in refnames and allowed in Windows filenames, guaranteeing
87 * no collision with the refs namespace.
88 */
89
90 /* Global config variable, initialized from core.lockfilePid */
91 int lockfile_pid_enabled;
92
93 /*
94 * Path generation helpers.
95 * Given base path "foo", generate:
96 * - lock path: "foo.lock"
97 * - pid path: "foo-pid.lock"
98 */
99 static void get_lock_path(struct strbuf *out, const char *path)
100 {
101 strbuf_addstr(out, path);
102 strbuf_addstr(out, LOCK_SUFFIX);
103 }
104
105 static void get_pid_path(struct strbuf *out, const char *path)
106 {
107 strbuf_addstr(out, path);
108 strbuf_addstr(out, LOCK_PID_INFIX);
109 strbuf_addstr(out, LOCK_SUFFIX);
110 }
111
112 static struct tempfile *create_lock_pid_file(const char *pid_path, int mode)
113 {
114 struct strbuf content = STRBUF_INIT;
115 struct tempfile *pid_tempfile = NULL;
116 int fd;
117
118 if (!lockfile_pid_enabled)
119 goto out;
120
121 fd = open(pid_path, O_WRONLY | O_CREAT | O_EXCL, mode);
122 if (fd < 0)
123 goto out;
124
125 strbuf_addf(&content, "pid %" PRIuMAX "\n", (uintmax_t)getpid());
126 if (write_in_full(fd, content.buf, content.len) < 0) {
127 warning_errno(_("could not write lock pid file '%s'"), pid_path);
128 close(fd);
129 unlink(pid_path);
130 goto out;
131 }
132
133 close(fd);
134 pid_tempfile = register_tempfile(pid_path);
135
136 out:
137 strbuf_release(&content);
138 return pid_tempfile;
139 }
140
141 static int read_lock_pid(const char *pid_path, uintmax_t *pid_out)
142 {
143 struct strbuf content = STRBUF_INIT;
144 const char *val;
145 int ret = -1;
146
147 if (strbuf_read_file(&content, pid_path, LOCK_PID_MAXLEN) <= 0)
148 goto out;
149
150 strbuf_rtrim(&content);
151
152 if (skip_prefix(content.buf, "pid ", &val)) {
153 char *endptr;
154 *pid_out = strtoumax(val, &endptr, 10);
155 if (*pid_out > 0 && !*endptr)
156 ret = 0;
157 }
158
159 if (ret)
160 warning(_("malformed lock pid file '%s'"), pid_path);
161
162 out:
163 strbuf_release(&content);
164 return ret;
165 }
166
167 /* Make sure errno contains a meaningful value on error */
168 static int lock_file(struct repository *r, struct lock_file *lk,
169 const char *path, int flags, int mode)
170 {
171 struct strbuf base_path = STRBUF_INIT;
172 struct strbuf lock_path = STRBUF_INIT;
173 struct strbuf pid_path = STRBUF_INIT;
174
175 strbuf_addstr(&base_path, path);
176 if (!(flags & LOCK_NO_DEREF))
177 resolve_symlink(&base_path);
178
179 get_lock_path(&lock_path, base_path.buf);
180 get_pid_path(&pid_path, base_path.buf);
181
182 lk->tempfile = repo_create_tempfile_mode(r, lock_path.buf, mode);
183 if (lk->tempfile)
184 lk->pid_tempfile = create_lock_pid_file(pid_path.buf, mode);
185
186 strbuf_release(&base_path);
187 strbuf_release(&lock_path);
188 strbuf_release(&pid_path);
189 return lk->tempfile ? lk->tempfile->fd : -1;
190 }
191
192 /*
193 * Constants defining the gaps between attempts to lock a file. The
194 * first backoff period is approximately INITIAL_BACKOFF_MS
195 * milliseconds. The longest backoff period is approximately
196 * (BACKOFF_MAX_MULTIPLIER * INITIAL_BACKOFF_MS) milliseconds.
197 */
198 #define INITIAL_BACKOFF_MS 1L
199 #define BACKOFF_MAX_MULTIPLIER 1000
200
201 /*
202 * Try locking path, retrying with quadratic backoff for at least
203 * timeout_ms milliseconds. If timeout_ms is 0, try locking the file
204 * exactly once. If timeout_ms is -1, try indefinitely.
205 */
206 static int lock_file_timeout(struct repository *r, struct lock_file *lk,
207 const char *path, int flags, long timeout_ms,
208 int mode)
209 {
210 int n = 1;
211 int multiplier = 1;
212 long remaining_ms = 0;
213 static int random_initialized = 0;
214
215 if (timeout_ms == 0)
216 return lock_file(r, lk, path, flags, mode);
217
218 if (!random_initialized) {
219 srand((unsigned int)getpid());
220 random_initialized = 1;
221 }
222
223 if (timeout_ms > 0)
224 remaining_ms = timeout_ms;
225
226 while (1) {
227 long backoff_ms, wait_ms;
228 int fd;
229
230 fd = lock_file(r, lk, path, flags, mode);
231
232 if (fd >= 0)
233 return fd; /* success */
234 else if (errno != EEXIST)
235 return -1; /* failure other than lock held */
236 else if (timeout_ms > 0 && remaining_ms <= 0)
237 return -1; /* failure due to timeout */
238
239 backoff_ms = multiplier * INITIAL_BACKOFF_MS;
240 /* back off for between 0.75*backoff_ms and 1.25*backoff_ms */
241 wait_ms = (750 + rand() % 500) * backoff_ms / 1000;
242 sleep_millisec(wait_ms);
243 remaining_ms -= wait_ms;
244
245 /* Recursion: (n+1)^2 = n^2 + 2n + 1 */
246 multiplier += 2*n + 1;
247 if (multiplier > BACKOFF_MAX_MULTIPLIER)
248 multiplier = BACKOFF_MAX_MULTIPLIER;
249 else
250 n++;
251 }
252 }
253
254 void unable_to_lock_message(const char *path, int err, struct strbuf *buf)
255 {
256 if (err == EEXIST) {
257 const char *abs_path = absolute_path(path);
258 struct strbuf lock_path = STRBUF_INIT;
259 struct strbuf pid_path = STRBUF_INIT;
260 uintmax_t pid;
261 int pid_status = 0; /* 0 = unknown, 1 = running, -1 = stale */
262
263 get_lock_path(&lock_path, abs_path);
264 get_pid_path(&pid_path, abs_path);
265
266 strbuf_addf(buf, _("Unable to create '%s': %s.\n\n"),
267 lock_path.buf, strerror(err));
268
269 /*
270 * Try to read PID file unconditionally - it may exist if
271 * core.lockfilePid was enabled.
272 */
273 if (!read_lock_pid(pid_path.buf, &pid)) {
274 if (kill((pid_t)pid, 0) == 0 || errno == EPERM)
275 pid_status = 1; /* running (or no permission to signal) */
276 else if (errno == ESRCH)
277 pid_status = -1; /* no such process - stale lock */
278 }
279
280 if (pid_status == 1)
281 strbuf_addf(buf, _("Lock may be held by process %" PRIuMAX "; "
282 "if no git process is running, the lock file "
283 "may be stale (PIDs can be reused)"),
284 pid);
285 else if (pid_status == -1)
286 strbuf_addf(buf, _("Lock was held by process %" PRIuMAX ", "
287 "which is no longer running; the lock file "
288 "appears to be stale"),
289 pid);
290 else
291 strbuf_addstr(buf, _("Another git process seems to be running in this repository, "
292 "or the lock file may be stale"));
293
294 strbuf_release(&lock_path);
295 strbuf_release(&pid_path);
296 } else {
297 strbuf_addf(buf, _("Unable to create '%s.lock': %s"),
298 absolute_path(path), strerror(err));
299 }
300 }
301
302 NORETURN void unable_to_lock_die(const char *path, int err)
303 {
304 struct strbuf buf = STRBUF_INIT;
305
306 unable_to_lock_message(path, err, &buf);
307 die("%s", buf.buf);
308 }
309
310 /* This should return a meaningful errno on failure */
311 int hold_lock_file_for_update_timeout_mode(struct lock_file *lk,
312 const char *path, int flags,
313 long timeout_ms, int mode)
314 {
315 return repo_hold_lock_file_for_update_timeout_mode(the_repository,
316 lk, path, flags,
317 timeout_ms, mode);
318 }
319
320 int repo_hold_lock_file_for_update_timeout_mode(struct repository *r,
321 struct lock_file *lk,
322 const char *path, int flags,
323 long timeout_ms, int mode)
324 {
325 int fd = lock_file_timeout(r, lk, path, flags, timeout_ms, mode);
326 if (fd < 0) {
327 if (flags & LOCK_DIE_ON_ERROR)
328 unable_to_lock_die(path, errno);
329 if (flags & LOCK_REPORT_ON_ERROR) {
330 struct strbuf buf = STRBUF_INIT;
331 unable_to_lock_message(path, errno, &buf);
332 error("%s", buf.buf);
333 strbuf_release(&buf);
334 }
335 }
336 return fd;
337 }
338
339 char *get_locked_file_path(struct lock_file *lk)
340 {
341 struct strbuf ret = STRBUF_INIT;
342
343 strbuf_addstr(&ret, get_tempfile_path(lk->tempfile));
344 if (ret.len <= LOCK_SUFFIX_LEN ||
345 strcmp(ret.buf + ret.len - LOCK_SUFFIX_LEN, LOCK_SUFFIX))
346 BUG("get_locked_file_path() called for malformed lock object");
347 /* remove ".lock": */
348 strbuf_setlen(&ret, ret.len - LOCK_SUFFIX_LEN);
349 return strbuf_detach(&ret, NULL);
350 }
351
352 int commit_lock_file(struct lock_file *lk)
353 {
354 char *result_path = get_locked_file_path(lk);
355
356 delete_tempfile(&lk->pid_tempfile);
357
358 if (commit_lock_file_to(lk, result_path)) {
359 int save_errno = errno;
360 free(result_path);
361 errno = save_errno;
362 return -1;
363 }
364 free(result_path);
365 return 0;
366 }
367
368 int rollback_lock_file(struct lock_file *lk)
369 {
370 delete_tempfile(&lk->pid_tempfile);
371 return delete_tempfile(&lk->tempfile);
372 }