2 * Copyright (c) 2019 Stefan Sperling <stsp@openbsd.org>
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.
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.
18 #include <sys/queue.h>
28 #include "got_error.h"
31 #include "got_lib_lockfile.h"
33 const struct got_error *
34 got_lockfile_lock(struct got_lockfile **lf, const char *path)
36 const struct got_error *err = NULL;
39 *lf = calloc(1, sizeof(**lf));
41 return got_error_from_errno("calloc");
44 (*lf)->locked_path = strdup(path);
45 if ((*lf)->locked_path == NULL) {
46 err = got_error_from_errno("strdup");
50 if (asprintf(&(*lf)->path, "%s%s", path, GOT_LOCKFILE_SUFFIX) == -1) {
51 err = got_error_from_errno("asprintf");
56 (*lf)->fd = open((*lf)->path,
57 O_RDONLY | O_CREAT | O_EXCL | O_EXLOCK,
58 GOT_DEFAULT_FILE_MODE);
61 if (errno != EEXIST) {
62 err = got_error_from_errno2("open", (*lf)->path);
66 } while (--attempts > 0);
69 err = got_error(GOT_ERR_LOCKFILE_TIMEOUT);
72 got_lockfile_unlock(*lf);
78 const struct got_error *
79 got_lockfile_unlock(struct got_lockfile *lf)
81 const struct got_error *err = NULL;
83 if (lf->path && lf->fd != -1 && unlink(lf->path) != 0)
84 err = got_error_from_errno("unlink");
85 if (lf->fd != -1 && close(lf->fd) != 0 && err == NULL)
86 err = got_error_from_errno("close");
88 free(lf->locked_path);