xref: /freebsd/usr.bin/lockf/lockf.c (revision 2008043f386721d58158e37e0d7e50df8095942d)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
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 #include <sys/types.h>
30 #include <sys/wait.h>
31 
32 #include <err.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <signal.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <sysexits.h>
39 #include <unistd.h>
40 
41 static int acquire_lock(const char *name, int flags);
42 static void cleanup(void);
43 static void killed(int sig);
44 static void timeout(int sig);
45 static void usage(void) __dead2;
46 static void wait_for_lock(const char *name);
47 
48 static const char *lockname;
49 static int lockfd = -1;
50 static int keep;
51 static volatile sig_atomic_t timed_out;
52 
53 /*
54  * Execute an arbitrary command while holding a file lock.
55  */
56 int
57 main(int argc, char **argv)
58 {
59 	int ch, flags, silent, status, waitsec;
60 	pid_t child;
61 
62 	silent = keep = 0;
63 	flags = O_CREAT | O_RDONLY;
64 	waitsec = -1;	/* Infinite. */
65 	while ((ch = getopt(argc, argv, "sknt:w")) != -1) {
66 		switch (ch) {
67 		case 'k':
68 			keep = 1;
69 			break;
70 		case 'n':
71 			flags &= ~O_CREAT;
72 			break;
73 		case 's':
74 			silent = 1;
75 			break;
76 		case 't':
77 		{
78 			char *endptr;
79 			waitsec = strtol(optarg, &endptr, 0);
80 			if (*optarg == '\0' || *endptr != '\0' || waitsec < 0)
81 				errx(EX_USAGE,
82 				    "invalid timeout \"%s\"", optarg);
83 		}
84 			break;
85 		case 'w':
86 			flags = (flags & ~O_RDONLY) | O_WRONLY;
87 			break;
88 		default:
89 			usage();
90 		}
91 	}
92 	if (argc - optind < 2)
93 		usage();
94 	lockname = argv[optind++];
95 	argc -= optind;
96 	argv += optind;
97 	if (waitsec > 0) {		/* Set up a timeout. */
98 		struct sigaction act;
99 
100 		act.sa_handler = timeout;
101 		sigemptyset(&act.sa_mask);
102 		act.sa_flags = 0;	/* Note that we do not set SA_RESTART. */
103 		sigaction(SIGALRM, &act, NULL);
104 		alarm(waitsec);
105 	}
106 	/*
107 	 * If the "-k" option is not given, then we must not block when
108 	 * acquiring the lock.  If we did, then the lock holder would
109 	 * unlink the file upon releasing the lock, and we would acquire
110 	 * a lock on a file with no directory entry.  Then another
111 	 * process could come along and acquire the same lock.  To avoid
112 	 * this problem, we separate out the actions of waiting for the
113 	 * lock to be available and of actually acquiring the lock.
114 	 *
115 	 * That approach produces behavior that is technically correct;
116 	 * however, it causes some performance & ordering problems for
117 	 * locks that have a lot of contention.  First, it is unfair in
118 	 * the sense that a released lock isn't necessarily granted to
119 	 * the process that has been waiting the longest.  A waiter may
120 	 * be starved out indefinitely.  Second, it creates a thundering
121 	 * herd situation each time the lock is released.
122 	 *
123 	 * When the "-k" option is used, the unlink race no longer
124 	 * exists.  In that case we can block while acquiring the lock,
125 	 * avoiding the separate step of waiting for the lock.  This
126 	 * yields fairness and improved performance.
127 	 */
128 	lockfd = acquire_lock(lockname, flags | O_NONBLOCK);
129 	while (lockfd == -1 && !timed_out && waitsec != 0) {
130 		if (keep)
131 			lockfd = acquire_lock(lockname, flags);
132 		else {
133 			wait_for_lock(lockname);
134 			lockfd = acquire_lock(lockname, flags | O_NONBLOCK);
135 		}
136 	}
137 	if (waitsec > 0)
138 		alarm(0);
139 	if (lockfd == -1) {		/* We failed to acquire the lock. */
140 		if (silent)
141 			exit(EX_TEMPFAIL);
142 		errx(EX_TEMPFAIL, "%s: already locked", lockname);
143 	}
144 	/* At this point, we own the lock. */
145 	if (atexit(cleanup) == -1)
146 		err(EX_OSERR, "atexit failed");
147 	if ((child = fork()) == -1)
148 		err(EX_OSERR, "cannot fork");
149 	if (child == 0) {	/* The child process. */
150 		close(lockfd);
151 		execvp(argv[0], argv);
152 		warn("%s", argv[0]);
153 		_exit(1);
154 	}
155 	/* This is the parent process. */
156 	signal(SIGINT, SIG_IGN);
157 	signal(SIGQUIT, SIG_IGN);
158 	signal(SIGTERM, killed);
159 	if (waitpid(child, &status, 0) == -1)
160 		err(EX_OSERR, "waitpid failed");
161 	return (WIFEXITED(status) ? WEXITSTATUS(status) : EX_SOFTWARE);
162 }
163 
164 /*
165  * Try to acquire a lock on the given file, creating the file if
166  * necessary.  The flags argument is O_NONBLOCK or 0, depending on
167  * whether we should wait for the lock.  Returns an open file descriptor
168  * on success, or -1 on failure.
169  */
170 static int
171 acquire_lock(const char *name, int flags)
172 {
173 	int fd;
174 
175 	if ((fd = open(name, O_EXLOCK|flags, 0666)) == -1) {
176 		if (errno == EAGAIN || errno == EINTR)
177 			return (-1);
178 		else if (errno == ENOENT && (flags & O_CREAT) == 0)
179 			err(EX_UNAVAILABLE, "%s", name);
180 		err(EX_CANTCREAT, "cannot open %s", name);
181 	}
182 	return (fd);
183 }
184 
185 /*
186  * Remove the lock file.
187  */
188 static void
189 cleanup(void)
190 {
191 
192 	if (keep)
193 		flock(lockfd, LOCK_UN);
194 	else
195 		unlink(lockname);
196 }
197 
198 /*
199  * Signal handler for SIGTERM.  Cleans up the lock file, then re-raises
200  * the signal.
201  */
202 static void
203 killed(int sig)
204 {
205 
206 	cleanup();
207 	signal(sig, SIG_DFL);
208 	if (kill(getpid(), sig) == -1)
209 		err(EX_OSERR, "kill failed");
210 }
211 
212 /*
213  * Signal handler for SIGALRM.
214  */
215 static void
216 timeout(int sig __unused)
217 {
218 
219 	timed_out = 1;
220 }
221 
222 static void
223 usage(void)
224 {
225 
226 	fprintf(stderr,
227 	    "usage: lockf [-kns] [-t seconds] file command [arguments]\n");
228 	exit(EX_USAGE);
229 }
230 
231 /*
232  * Wait until it might be possible to acquire a lock on the given file.
233  * If the file does not exist, return immediately without creating it.
234  */
235 static void
236 wait_for_lock(const char *name)
237 {
238 	int fd;
239 
240 	if ((fd = open(name, O_RDONLY|O_EXLOCK, 0666)) == -1) {
241 		if (errno == ENOENT || errno == EINTR)
242 			return;
243 		err(EX_CANTCREAT, "cannot open %s", name);
244 	}
245 	close(fd);
246 }
247