sync distfile list
[got-portable.git] / lib / lockfile.c
blob2d85d99def0e84249e38b3f4724dd5e35e1a18a9
1 /*
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.
17 #include <sys/stat.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <string.h>
24 #include <stdio.h>
25 #include <time.h>
27 #include "got_error.h"
28 #include "got_path.h"
30 #include "got_lib_lockfile.h"
32 const struct got_error *
33 got_lockfile_lock(struct got_lockfile **lf, const char *path, int dir_fd)
35 const struct got_error *err = NULL;
36 int attempts = 5;
38 *lf = calloc(1, sizeof(**lf));
39 if (*lf == NULL)
40 return got_error_from_errno("calloc");
41 (*lf)->fd = -1;
43 (*lf)->locked_path = strdup(path);
44 if ((*lf)->locked_path == NULL) {
45 err = got_error_from_errno("strdup");
46 goto done;
49 if (asprintf(&(*lf)->path, "%s%s", path, GOT_LOCKFILE_SUFFIX) == -1) {
50 err = got_error_from_errno("asprintf");
51 goto done;
54 do {
55 if (dir_fd != -1) {
56 (*lf)->fd = openat(dir_fd, (*lf)->path,
57 O_RDONLY | O_CREAT | O_EXCL | O_EXLOCK | O_CLOEXEC,
58 GOT_DEFAULT_FILE_MODE);
59 } else {
60 (*lf)->fd = open((*lf)->path,
61 O_RDONLY | O_CREAT | O_EXCL | O_EXLOCK | O_CLOEXEC,
62 GOT_DEFAULT_FILE_MODE);
64 if ((*lf)->fd != -1)
65 break;
66 if (errno != EEXIST) {
67 err = got_error_from_errno2("open", (*lf)->path);
68 goto done;
70 sleep(1);
71 } while (--attempts > 0);
73 if ((*lf)->fd == -1)
74 err = got_error(GOT_ERR_LOCKFILE_TIMEOUT);
75 done:
76 if (err) {
77 got_lockfile_unlock(*lf, dir_fd);
78 *lf = NULL;
80 return err;
83 const struct got_error *
84 got_lockfile_unlock(struct got_lockfile *lf, int dir_fd)
86 const struct got_error *err = NULL;
88 if (dir_fd != -1) {
89 if (lf->path && lf->fd != -1 &&
90 unlinkat(dir_fd, lf->path, 0) != 0)
91 err = got_error_from_errno("unlinkat");
92 } else if (lf->path && lf->fd != -1 && unlink(lf->path) != 0)
93 err = got_error_from_errno("unlink");
94 if (lf->fd != -1 && close(lf->fd) == -1 && err == NULL)
95 err = got_error_from_errno("close");
96 free(lf->path);
97 free(lf->locked_path);
98 free(lf);
99 return err;