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"
30 #include "got_lib_lockfile.h"
31 #include "got_lib_path.h"
33 const struct got_error *
34 got_lockfile_lock(struct got_lockfile **lf, const char *path)
35 {
36 const struct got_error *err = NULL;
37 const int flags = O_RDONLY | O_CREAT | O_EXCL | O_EXLOCK;
38 int attempts = 5;
40 *lf = calloc(1, sizeof(**lf));
41 if (*lf == NULL)
42 return got_error_from_errno();
43 (*lf)->fd = -1;
45 (*lf)->locked_path = strdup(path);
46 if ((*lf)->locked_path == NULL) {
47 err = got_error_from_errno();
48 goto done;
49 }
51 if (asprintf(&(*lf)->path, "%s%s", path, GOT_LOCKFILE_SUFFIX) == -1) {
52 err = got_error_from_errno();
53 goto done;
54 }
56 do {
57 (*lf)->fd = open((*lf)->path, flags, GOT_DEFAULT_FILE_MODE);
58 if ((*lf)->fd != -1)
59 break;
60 if (errno != EEXIST) {
61 err = got_error_from_errno();
62 goto done;
63 }
64 sleep(1);
65 } while (--attempts > 0);
67 if ((*lf)->fd == -1)
68 err = got_error(GOT_ERR_LOCKFILE_TIMEOUT);
69 done:
70 if (err) {
71 got_lockfile_unlock(*lf);
72 *lf = NULL;
73 }
74 return err;
75 }
77 const struct got_error *
78 got_lockfile_unlock(struct got_lockfile *lf)
79 {
80 const struct got_error *err = NULL;
82 if (lf->path && lf->fd != -1 && unlink(lf->path) != 0)
83 err = got_error_from_errno();
84 if (lf->fd != -1 && close(lf->fd) != 0 && err == NULL)
85 err = got_error_from_errno();
86 free(lf->path);
87 free(lf->locked_path);
88 free(lf);
89 return err;
90 }