xref: /freebsd/usr.bin/lockf/lockf.c (revision f5147e312f43a9050468de539aeafa072caa1a60)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (C) 1997 John D. Polstra.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY JOHN D. POLSTRA AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL JOHN D. POLSTRA OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include <sys/types.h>
32 #include <sys/wait.h>
33 
34 #include <err.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <signal.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <sysexits.h>
41 #include <unistd.h>
42 
43 static int acquire_lock(const char *name, int flags);
44 static void cleanup(void);
45 static void killed(int sig);
46 static void timeout(int sig);
47 static void usage(void);
48 static void wait_for_lock(const char *name);
49 
50 static const char *lockname;
51 static int lockfd = -1;
52 static int keep;
53 static volatile sig_atomic_t timed_out;
54 
55 /*
56  * Execute an arbitrary command while holding a file lock.
57  */
58 int
59 main(int argc, char **argv)
60 {
61 	int ch, flags, silent, status, waitsec;
62 	pid_t child;
63 
64 	silent = keep = 0;
65 	flags = O_CREAT;
66 	waitsec = -1;	/* Infinite. */
67 	while ((ch = getopt(argc, argv, "sknt:")) != -1) {
68 		switch (ch) {
69 		case 'k':
70 			keep = 1;
71 			break;
72 		case 'n':
73 			flags &= ~O_CREAT;
74 			break;
75 		case 's':
76 			silent = 1;
77 			break;
78 		case 't':
79 		{
80 			char *endptr;
81 			waitsec = strtol(optarg, &endptr, 0);
82 			if (*optarg == '\0' || *endptr != '\0' || waitsec < 0)
83 				errx(EX_USAGE,
84 				    "invalid timeout \"%s\"", optarg);
85 		}
86 			break;
87 		default:
88 			usage();
89 		}
90 	}
91 	if (argc - optind < 2)
92 		usage();
93 	lockname = argv[optind++];
94 	argc -= optind;
95 	argv += optind;
96 	if (waitsec > 0) {		/* Set up a timeout. */
97 		struct sigaction act;
98 
99 		act.sa_handler = timeout;
100 		sigemptyset(&act.sa_mask);
101 		act.sa_flags = 0;	/* Note that we do not set SA_RESTART. */
102 		sigaction(SIGALRM, &act, NULL);
103 		alarm(waitsec);
104 	}
105 	/*
106 	 * If the "-k" option is not given, then we must not block when
107 	 * acquiring the lock.  If we did, then the lock holder would
108 	 * unlink the file upon releasing the lock, and we would acquire
109 	 * a lock on a file with no directory entry.  Then another
110 	 * process could come along and acquire the same lock.  To avoid
111 	 * this problem, we separate out the actions of waiting for the
112 	 * lock to be available and of actually acquiring the lock.
113 	 *
114 	 * That approach produces behavior that is technically correct;
115 	 * however, it causes some performance & ordering problems for
116 	 * locks that have a lot of contention.  First, it is unfair in
117 	 * the sense that a released lock isn't necessarily granted to
118 	 * the process that has been waiting the longest.  A waiter may
119 	 * be starved out indefinitely.  Second, it creates a thundering
120 	 * herd situation each time the lock is released.
121 	 *
122 	 * When the "-k" option is used, the unlink race no longer
123 	 * exists.  In that case we can block while acquiring the lock,
124 	 * avoiding the separate step of waiting for the lock.  This
125 	 * yields fairness and improved performance.
126 	 */
127 	lockfd = acquire_lock(lockname, flags | O_NONBLOCK);
128 	while (lockfd == -1 && !timed_out && waitsec != 0) {
129 		if (keep)
130 			lockfd = acquire_lock(lockname, flags);
131 		else {
132 			wait_for_lock(lockname);
133 			lockfd = acquire_lock(lockname, flags | O_NONBLOCK);
134 		}
135 	}
136 	if (waitsec > 0)
137 		alarm(0);
138 	if (lockfd == -1) {		/* We failed to acquire the lock. */
139 		if (silent)
140 			exit(EX_TEMPFAIL);
141 		errx(EX_TEMPFAIL, "%s: already locked", lockname);
142 	}
143 	/* At this point, we own the lock. */
144 	if (atexit(cleanup) == -1)
145 		err(EX_OSERR, "atexit failed");
146 	if ((child = fork()) == -1)
147 		err(EX_OSERR, "cannot fork");
148 	if (child == 0) {	/* The child process. */
149 		close(lockfd);
150 		execvp(argv[0], argv);
151 		warn("%s", argv[0]);
152 		_exit(1);
153 	}
154 	/* This is the parent process. */
155 	signal(SIGINT, SIG_IGN);
156 	signal(SIGQUIT, SIG_IGN);
157 	signal(SIGTERM, killed);
158 	if (waitpid(child, &status, 0) == -1)
159 		err(EX_OSERR, "waitpid failed");
160 	return (WIFEXITED(status) ? WEXITSTATUS(status) : EX_SOFTWARE);
161 }
162 
163 /*
164  * Try to acquire a lock on the given file, creating the file if
165  * necessary.  The flags argument is O_NONBLOCK or 0, depending on
166  * whether we should wait for the lock.  Returns an open file descriptor
167  * on success, or -1 on failure.
168  */
169 static int
170 acquire_lock(const char *name, int flags)
171 {
172 	int fd;
173 
174 	if ((fd = open(name, O_RDONLY|O_EXLOCK|flags, 0666)) == -1) {
175 		if (errno == EAGAIN || errno == EINTR)
176 			return (-1);
177 		err(EX_CANTCREAT, "cannot open %s", name);
178 	}
179 	return (fd);
180 }
181 
182 /*
183  * Remove the lock file.
184  */
185 static void
186 cleanup(void)
187 {
188 
189 	if (keep)
190 		flock(lockfd, LOCK_UN);
191 	else
192 		unlink(lockname);
193 }
194 
195 /*
196  * Signal handler for SIGTERM.  Cleans up the lock file, then re-raises
197  * the signal.
198  */
199 static void
200 killed(int sig)
201 {
202 
203 	cleanup();
204 	signal(sig, SIG_DFL);
205 	if (kill(getpid(), sig) == -1)
206 		err(EX_OSERR, "kill failed");
207 }
208 
209 /*
210  * Signal handler for SIGALRM.
211  */
212 static void
213 timeout(int sig __unused)
214 {
215 
216 	timed_out = 1;
217 }
218 
219 static void
220 usage(void)
221 {
222 
223 	fprintf(stderr,
224 	    "usage: lockf [-kns] [-t seconds] file command [arguments]\n");
225 	exit(EX_USAGE);
226 }
227 
228 /*
229  * Wait until it might be possible to acquire a lock on the given file.
230  * If the file does not exist, return immediately without creating it.
231  */
232 static void
233 wait_for_lock(const char *name)
234 {
235 	int fd;
236 
237 	if ((fd = open(name, O_RDONLY|O_EXLOCK, 0666)) == -1) {
238 		if (errno == ENOENT || errno == EINTR)
239 			return;
240 		err(EX_CANTCREAT, "cannot open %s", name);
241 	}
242 	close(fd);
243 }
244