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 "got_compat.h"
19 #include <sys/stat.h>
20 #include <sys/queue.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <string.h>
27 #include <stdio.h>
28 #include <time.h>
30 #include "got_error.h"
31 #include "got_path.h"
33 #include "got_lib_lockfile.h"
35 const struct got_error *
36 got_lockfile_lock(struct got_lockfile **lf, const char *path, int dir_fd)
37 {
38 const struct got_error *err = NULL;
39 int attempts = 5;
41 *lf = calloc(1, sizeof(**lf));
42 if (*lf == NULL)
43 return got_error_from_errno("calloc");
44 (*lf)->fd = -1;
46 (*lf)->locked_path = strdup(path);
47 if ((*lf)->locked_path == NULL) {
48 err = got_error_from_errno("strdup");
49 goto done;
50 }
52 if (asprintf(&(*lf)->path, "%s%s", path, GOT_LOCKFILE_SUFFIX) == -1) {
53 err = got_error_from_errno("asprintf");
54 goto done;
55 }
57 do {
58 if (dir_fd != -1) {
59 (*lf)->fd = openat(dir_fd, (*lf)->path,
60 O_RDWR | O_CREAT | O_EXCL | O_EXLOCK | O_CLOEXEC,
61 GOT_DEFAULT_FILE_MODE);
62 } else {
63 (*lf)->fd = open((*lf)->path,
64 O_RDWR | O_CREAT | O_EXCL | O_EXLOCK | O_CLOEXEC,
65 GOT_DEFAULT_FILE_MODE);
66 }
67 if ((*lf)->fd != -1)
68 break;
69 if (errno != EEXIST) {
70 err = got_error_from_errno2("open", (*lf)->path);
71 goto done;
72 }
73 sleep(1);
74 } while (--attempts > 0);
76 if ((*lf)->fd == -1) {
77 err = got_error_fmt(GOT_ERR_LOCKFILE_TIMEOUT,
78 "%s", (*lf)->path);
79 }
80 done:
81 if (err) {
82 got_lockfile_unlock(*lf, dir_fd);
83 *lf = NULL;
84 }
85 return err;
86 }
88 const struct got_error *
89 got_lockfile_unlock(struct got_lockfile *lf, int dir_fd)
90 {
91 const struct got_error *err = NULL;
93 if (dir_fd != -1) {
94 if (lf->path && lf->fd != -1 &&
95 unlinkat(dir_fd, lf->path, 0) != 0)
96 err = got_error_from_errno("unlinkat");
97 } else if (lf->path && lf->fd != -1 && unlink(lf->path) != 0)
98 err = got_error_from_errno("unlink");
99 if (lf->fd != -1 && close(lf->fd) == -1 && err == NULL)
100 err = got_error_from_errno("close");
101 free(lf->path);
102 free(lf->locked_path);
103 free(lf);
104 return err;