Blob


1 /*
2 * Copyright (c) 2019 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/stat.h>
18 #include <sys/queue.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <stdio.h>
26 #include <time.h>
28 #include "got_error.h"
29 #include "got_path.h"
31 #include "got_lib_lockfile.h"
33 const struct got_error *
34 got_lockfile_lock(struct got_lockfile **lf, const char *path, int dir_fd)
35 {
36 const struct got_error *err = NULL;
37 int attempts = 5;
39 *lf = calloc(1, sizeof(**lf));
40 if (*lf == NULL)
41 return got_error_from_errno("calloc");
42 (*lf)->fd = -1;
44 (*lf)->locked_path = strdup(path);
45 if ((*lf)->locked_path == NULL) {
46 err = got_error_from_errno("strdup");
47 goto done;
48 }
50 if (asprintf(&(*lf)->path, "%s%s", path, GOT_LOCKFILE_SUFFIX) == -1) {
51 err = got_error_from_errno("asprintf");
52 goto done;
53 }
55 do {
56 if (dir_fd != -1) {
57 (*lf)->fd = openat(dir_fd, (*lf)->path,
58 O_RDONLY | O_CREAT | O_EXCL | O_EXLOCK | O_CLOEXEC,
59 GOT_DEFAULT_FILE_MODE);
60 } else {
61 (*lf)->fd = open((*lf)->path,
62 O_RDONLY | O_CREAT | O_EXCL | O_EXLOCK | O_CLOEXEC,
63 GOT_DEFAULT_FILE_MODE);
64 }
65 if ((*lf)->fd != -1)
66 break;
67 if (errno != EEXIST) {
68 err = got_error_from_errno2("open", (*lf)->path);
69 goto done;
70 }
71 sleep(1);
72 } while (--attempts > 0);
74 if ((*lf)->fd == -1)
75 err = got_error(GOT_ERR_LOCKFILE_TIMEOUT);
76 done:
77 if (err) {
78 got_lockfile_unlock(*lf, dir_fd);
79 *lf = NULL;
80 }
81 return err;
82 }
84 const struct got_error *
85 got_lockfile_unlock(struct got_lockfile *lf, int dir_fd)
86 {
87 const struct got_error *err = NULL;
89 if (dir_fd != -1) {
90 if (lf->path && lf->fd != -1 &&
91 unlinkat(dir_fd, lf->path, 0) != 0)
92 err = got_error_from_errno("unlinkat");
93 } else if (lf->path && lf->fd != -1 && unlink(lf->path) != 0)
94 err = got_error_from_errno("unlink");
95 if (lf->fd != -1 && close(lf->fd) == -1 && err == NULL)
96 err = got_error_from_errno("close");
97 free(lf->path);
98 free(lf->locked_path);
99 free(lf);
100 return err;