xref: /freebsd/usr.bin/lockf/lockf.c (revision e4967d4d48b0a7d873e4f778c0a6e560e09d4dc3)
11de7b4b8SPedro F. Giffuni /*-
24d846d26SWarner Losh  * SPDX-License-Identifier: BSD-2-Clause
31de7b4b8SPedro F. Giffuni  *
4c8929a49SJohn Polstra  * Copyright (C) 1997 John D. Polstra.  All rights reserved.
5c8929a49SJohn Polstra  *
6c8929a49SJohn Polstra  * Redistribution and use in source and binary forms, with or without
7c8929a49SJohn Polstra  * modification, are permitted provided that the following conditions
8c8929a49SJohn Polstra  * are met:
9c8929a49SJohn Polstra  * 1. Redistributions of source code must retain the above copyright
10c8929a49SJohn Polstra  *    notice, this list of conditions and the following disclaimer.
11c8929a49SJohn Polstra  * 2. Redistributions in binary form must reproduce the above copyright
12c8929a49SJohn Polstra  *    notice, this list of conditions and the following disclaimer in the
13c8929a49SJohn Polstra  *    documentation and/or other materials provided with the distribution.
14c8929a49SJohn Polstra  *
15c8929a49SJohn Polstra  * THIS SOFTWARE IS PROVIDED BY JOHN D. POLSTRA AND CONTRIBUTORS ``AS IS'' AND
16c8929a49SJohn Polstra  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17c8929a49SJohn Polstra  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18c8929a49SJohn Polstra  * ARE DISCLAIMED.  IN NO EVENT SHALL JOHN D. POLSTRA OR CONTRIBUTORS BE LIABLE
19c8929a49SJohn Polstra  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20c8929a49SJohn Polstra  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21c8929a49SJohn Polstra  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22c8929a49SJohn Polstra  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23c8929a49SJohn Polstra  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24c8929a49SJohn Polstra  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25c8929a49SJohn Polstra  * SUCH DAMAGE.
26c8929a49SJohn Polstra  */
27c8929a49SJohn Polstra 
28e026a48cSDavid E. O'Brien #include <sys/cdefs.h>
29c8929a49SJohn Polstra #include <sys/types.h>
30c8929a49SJohn Polstra #include <sys/wait.h>
31c8929a49SJohn Polstra 
3209a7fe0aSKyle Evans #include <assert.h>
33c8929a49SJohn Polstra #include <err.h>
34c8929a49SJohn Polstra #include <errno.h>
35c8929a49SJohn Polstra #include <fcntl.h>
3609a7fe0aSKyle Evans #include <limits.h>
37c8929a49SJohn Polstra #include <signal.h>
38c8929a49SJohn Polstra #include <stdio.h>
39c8929a49SJohn Polstra #include <stdlib.h>
4009a7fe0aSKyle Evans #include <string.h>
41ae06cb4dSJohn Polstra #include <sysexits.h>
42c8929a49SJohn Polstra #include <unistd.h>
43c8929a49SJohn Polstra 
4409a7fe0aSKyle Evans #define	FDLOCK_PREFIX	"/dev/fd/"
4509a7fe0aSKyle Evans 
4609a7fe0aSKyle Evans union lock_subject {
4709a7fe0aSKyle Evans 	long		 subj_fd;
4809a7fe0aSKyle Evans 	const char	*subj_name;
4909a7fe0aSKyle Evans };
5009a7fe0aSKyle Evans 
5109a7fe0aSKyle Evans static int acquire_lock(union lock_subject *subj, int flags, int silent);
52c8929a49SJohn Polstra static void cleanup(void);
53c8929a49SJohn Polstra static void killed(int sig);
54c8929a49SJohn Polstra static void timeout(int sig);
55a1b6427aSAlfonso Gregory static void usage(void) __dead2;
566a53f0a5SChristian S.J. Peron static void wait_for_lock(const char *name);
57c8929a49SJohn Polstra 
58c8929a49SJohn Polstra static const char *lockname;
59031469ebSChristian S.J. Peron static int lockfd = -1;
602f278eacSJohn Polstra static int keep;
6109a7fe0aSKyle Evans static int fdlock;
62c8929a49SJohn Polstra static volatile sig_atomic_t timed_out;
63c8929a49SJohn Polstra 
64c8929a49SJohn Polstra /*
6509a7fe0aSKyle Evans  * Check if fdlock is implied by the given `lockname`.  We'll write the fd that
6609a7fe0aSKyle Evans  * is represented by it out to ofd, and the caller is expected to do any
6709a7fe0aSKyle Evans  * necessary validation on it.
6809a7fe0aSKyle Evans  */
6909a7fe0aSKyle Evans static int
7009a7fe0aSKyle Evans fdlock_implied(const char *name, long *ofd)
7109a7fe0aSKyle Evans {
7209a7fe0aSKyle Evans 	char *endp;
7309a7fe0aSKyle Evans 	long fd;
7409a7fe0aSKyle Evans 
7509a7fe0aSKyle Evans 	if (strncmp(name, FDLOCK_PREFIX, sizeof(FDLOCK_PREFIX) - 1) != 0)
7609a7fe0aSKyle Evans 		return (0);
7709a7fe0aSKyle Evans 
7809a7fe0aSKyle Evans 	/* Skip past the prefix. */
7909a7fe0aSKyle Evans 	name += sizeof(FDLOCK_PREFIX) - 1;
8009a7fe0aSKyle Evans 	errno = 0;
8109a7fe0aSKyle Evans 	fd = strtol(name, &endp, 10);
8209a7fe0aSKyle Evans 	if (errno != 0 || *endp != '\0')
8309a7fe0aSKyle Evans 		return (0);
8409a7fe0aSKyle Evans 
8509a7fe0aSKyle Evans 	*ofd = fd;
8609a7fe0aSKyle Evans 	return (1);
8709a7fe0aSKyle Evans }
8809a7fe0aSKyle Evans 
8909a7fe0aSKyle Evans /*
90c8929a49SJohn Polstra  * Execute an arbitrary command while holding a file lock.
91c8929a49SJohn Polstra  */
92c8929a49SJohn Polstra int
93c8929a49SJohn Polstra main(int argc, char **argv)
94c8929a49SJohn Polstra {
95*e4967d4dSKyle Evans 	int ch, flags, silent, status;
96*e4967d4dSKyle Evans 	long long waitsec;
97c8929a49SJohn Polstra 	pid_t child;
9809a7fe0aSKyle Evans 	union lock_subject subj;
99c8929a49SJohn Polstra 
10045edbdccSChristian S.J. Peron 	silent = keep = 0;
101437bab48SColin Percival 	flags = O_CREAT | O_RDONLY;
102c8929a49SJohn Polstra 	waitsec = -1;	/* Infinite. */
10335095fd2SKyle Evans 	while ((ch = getopt(argc, argv, "knst:w")) != -1) {
104c8929a49SJohn Polstra 		switch (ch) {
1052f278eacSJohn Polstra 		case 'k':
1062f278eacSJohn Polstra 			keep = 1;
1072f278eacSJohn Polstra 			break;
108b5be420aSEitan Adler 		case 'n':
109b5be420aSEitan Adler 			flags &= ~O_CREAT;
110b5be420aSEitan Adler 			break;
111c8929a49SJohn Polstra 		case 's':
112c8929a49SJohn Polstra 			silent = 1;
113c8929a49SJohn Polstra 			break;
114c8929a49SJohn Polstra 		case 't':
115c8929a49SJohn Polstra 		{
116*e4967d4dSKyle Evans 			const char *errstr;
117*e4967d4dSKyle Evans 
118*e4967d4dSKyle Evans 			waitsec = strtonum(optarg, 0, UINT_MAX, &errstr);
119*e4967d4dSKyle Evans 			if (errstr != NULL)
12045edbdccSChristian S.J. Peron 				errx(EX_USAGE,
12145edbdccSChristian S.J. Peron 				    "invalid timeout \"%s\"", optarg);
122c8929a49SJohn Polstra 		}
123c8929a49SJohn Polstra 			break;
124437bab48SColin Percival 		case 'w':
125437bab48SColin Percival 			flags = (flags & ~O_RDONLY) | O_WRONLY;
126437bab48SColin Percival 			break;
127c8929a49SJohn Polstra 		default:
128c8929a49SJohn Polstra 			usage();
129c8929a49SJohn Polstra 		}
130c8929a49SJohn Polstra 	}
13109a7fe0aSKyle Evans 
132c8929a49SJohn Polstra 	argc -= optind;
133c8929a49SJohn Polstra 	argv += optind;
13409a7fe0aSKyle Evans 
13509a7fe0aSKyle Evans 	if (argc == 0)
13609a7fe0aSKyle Evans 		usage();
13709a7fe0aSKyle Evans 
13809a7fe0aSKyle Evans 	lockname = argv[0];
13909a7fe0aSKyle Evans 
14009a7fe0aSKyle Evans 	argc--;
14109a7fe0aSKyle Evans 	argv++;
14209a7fe0aSKyle Evans 
14309a7fe0aSKyle Evans 	/*
14409a7fe0aSKyle Evans 	 * If there aren't any arguments left, then we must be in fdlock mode.
14509a7fe0aSKyle Evans 	 */
14609a7fe0aSKyle Evans 	if (argc == 0 && *lockname != '/') {
14709a7fe0aSKyle Evans 		fdlock = 1;
14809a7fe0aSKyle Evans 		subj.subj_fd = -1;
14909a7fe0aSKyle Evans 	} else {
15009a7fe0aSKyle Evans 		fdlock = fdlock_implied(lockname, &subj.subj_fd);
15109a7fe0aSKyle Evans 		if (argc == 0 && !fdlock) {
15209a7fe0aSKyle Evans 			fprintf(stderr, "Expected fd, got '%s'\n", lockname);
15309a7fe0aSKyle Evans 			usage();
15409a7fe0aSKyle Evans 		}
15509a7fe0aSKyle Evans 	}
15609a7fe0aSKyle Evans 
15709a7fe0aSKyle Evans 	if (fdlock) {
15809a7fe0aSKyle Evans 		if (subj.subj_fd < 0) {
15909a7fe0aSKyle Evans 			char *endp;
16009a7fe0aSKyle Evans 
16109a7fe0aSKyle Evans 			errno = 0;
16209a7fe0aSKyle Evans 			subj.subj_fd = strtol(lockname, &endp, 10);
16309a7fe0aSKyle Evans 			if (errno != 0 || *endp != '\0') {
16409a7fe0aSKyle Evans 				fprintf(stderr, "Expected fd, got '%s'\n",
16509a7fe0aSKyle Evans 				    lockname);
16609a7fe0aSKyle Evans 				usage();
16709a7fe0aSKyle Evans 			}
16809a7fe0aSKyle Evans 		}
16909a7fe0aSKyle Evans 
17009a7fe0aSKyle Evans 		if (subj.subj_fd < 0 || subj.subj_fd > INT_MAX) {
17109a7fe0aSKyle Evans 			fprintf(stderr, "fd '%ld' out of range\n",
17209a7fe0aSKyle Evans 			    subj.subj_fd);
17309a7fe0aSKyle Evans 			usage();
17409a7fe0aSKyle Evans 		}
17509a7fe0aSKyle Evans 	} else {
17609a7fe0aSKyle Evans 		subj.subj_name = lockname;
17709a7fe0aSKyle Evans 	}
17809a7fe0aSKyle Evans 
179c8929a49SJohn Polstra 	if (waitsec > 0) {		/* Set up a timeout. */
180c8929a49SJohn Polstra 		struct sigaction act;
181c8929a49SJohn Polstra 
182c8929a49SJohn Polstra 		act.sa_handler = timeout;
183c8929a49SJohn Polstra 		sigemptyset(&act.sa_mask);
184c8929a49SJohn Polstra 		act.sa_flags = 0;	/* Note that we do not set SA_RESTART. */
185c8929a49SJohn Polstra 		sigaction(SIGALRM, &act, NULL);
186*e4967d4dSKyle Evans 		alarm((unsigned int)waitsec);
187c8929a49SJohn Polstra 	}
1886a53f0a5SChristian S.J. Peron 	/*
1896a53f0a5SChristian S.J. Peron 	 * If the "-k" option is not given, then we must not block when
1906a53f0a5SChristian S.J. Peron 	 * acquiring the lock.  If we did, then the lock holder would
1916a53f0a5SChristian S.J. Peron 	 * unlink the file upon releasing the lock, and we would acquire
1926a53f0a5SChristian S.J. Peron 	 * a lock on a file with no directory entry.  Then another
1936a53f0a5SChristian S.J. Peron 	 * process could come along and acquire the same lock.  To avoid
1946a53f0a5SChristian S.J. Peron 	 * this problem, we separate out the actions of waiting for the
1956a53f0a5SChristian S.J. Peron 	 * lock to be available and of actually acquiring the lock.
1966a53f0a5SChristian S.J. Peron 	 *
1976a53f0a5SChristian S.J. Peron 	 * That approach produces behavior that is technically correct;
1986a53f0a5SChristian S.J. Peron 	 * however, it causes some performance & ordering problems for
1996a53f0a5SChristian S.J. Peron 	 * locks that have a lot of contention.  First, it is unfair in
2006a53f0a5SChristian S.J. Peron 	 * the sense that a released lock isn't necessarily granted to
2016a53f0a5SChristian S.J. Peron 	 * the process that has been waiting the longest.  A waiter may
2026a53f0a5SChristian S.J. Peron 	 * be starved out indefinitely.  Second, it creates a thundering
2036a53f0a5SChristian S.J. Peron 	 * herd situation each time the lock is released.
2046a53f0a5SChristian S.J. Peron 	 *
2056a53f0a5SChristian S.J. Peron 	 * When the "-k" option is used, the unlink race no longer
2066a53f0a5SChristian S.J. Peron 	 * exists.  In that case we can block while acquiring the lock,
2076a53f0a5SChristian S.J. Peron 	 * avoiding the separate step of waiting for the lock.  This
2086a53f0a5SChristian S.J. Peron 	 * yields fairness and improved performance.
2096a53f0a5SChristian S.J. Peron 	 */
21009a7fe0aSKyle Evans 	lockfd = acquire_lock(&subj, flags | O_NONBLOCK, silent);
2116a53f0a5SChristian S.J. Peron 	while (lockfd == -1 && !timed_out && waitsec != 0) {
21209a7fe0aSKyle Evans 		if (keep || fdlock)
21309a7fe0aSKyle Evans 			lockfd = acquire_lock(&subj, flags, silent);
2146a53f0a5SChristian S.J. Peron 		else {
2156a53f0a5SChristian S.J. Peron 			wait_for_lock(lockname);
21609a7fe0aSKyle Evans 			lockfd = acquire_lock(&subj, flags | O_NONBLOCK,
2173041e695SKyle Evans 			    silent);
2186a53f0a5SChristian S.J. Peron 		}
2196a53f0a5SChristian S.J. Peron 	}
220c8929a49SJohn Polstra 	if (waitsec > 0)
221c8929a49SJohn Polstra 		alarm(0);
222c8929a49SJohn Polstra 	if (lockfd == -1) {		/* We failed to acquire the lock. */
223c8929a49SJohn Polstra 		if (silent)
224ae06cb4dSJohn Polstra 			exit(EX_TEMPFAIL);
225ae06cb4dSJohn Polstra 		errx(EX_TEMPFAIL, "%s: already locked", lockname);
226c8929a49SJohn Polstra 	}
22709a7fe0aSKyle Evans 
228c8929a49SJohn Polstra 	/* At this point, we own the lock. */
22909a7fe0aSKyle Evans 
23009a7fe0aSKyle Evans 	/* Nothing else to do for FD lock, just exit */
23109a7fe0aSKyle Evans 	if (argc == 0) {
23209a7fe0aSKyle Evans 		assert(fdlock);
23309a7fe0aSKyle Evans 		return 0;
23409a7fe0aSKyle Evans 	}
23509a7fe0aSKyle Evans 
236c8929a49SJohn Polstra 	if (atexit(cleanup) == -1)
237ae06cb4dSJohn Polstra 		err(EX_OSERR, "atexit failed");
238c8929a49SJohn Polstra 	if ((child = fork()) == -1)
239ae06cb4dSJohn Polstra 		err(EX_OSERR, "cannot fork");
240c8929a49SJohn Polstra 	if (child == 0) {	/* The child process. */
241c8929a49SJohn Polstra 		close(lockfd);
242c8929a49SJohn Polstra 		execvp(argv[0], argv);
243208f2fd1STim J. Robbins 		warn("%s", argv[0]);
244c8929a49SJohn Polstra 		_exit(1);
245c8929a49SJohn Polstra 	}
246c8929a49SJohn Polstra 	/* This is the parent process. */
247c8929a49SJohn Polstra 	signal(SIGINT, SIG_IGN);
248c8929a49SJohn Polstra 	signal(SIGQUIT, SIG_IGN);
249c8929a49SJohn Polstra 	signal(SIGTERM, killed);
25018425c19SAlexander Melkov 	fclose(stdin);
25118425c19SAlexander Melkov 	fclose(stdout);
25218425c19SAlexander Melkov 	fclose(stderr);
253c8929a49SJohn Polstra 	if (waitpid(child, &status, 0) == -1)
25418425c19SAlexander Melkov 		exit(EX_OSERR);
2557f15c32dSDavid Malone 	return (WIFEXITED(status) ? WEXITSTATUS(status) : EX_SOFTWARE);
256c8929a49SJohn Polstra }
257c8929a49SJohn Polstra 
258c8929a49SJohn Polstra /*
25909a7fe0aSKyle Evans  * Try to acquire a lock on the given file/fd, creating the file if
2606a53f0a5SChristian S.J. Peron  * necessary.  The flags argument is O_NONBLOCK or 0, depending on
2616a53f0a5SChristian S.J. Peron  * whether we should wait for the lock.  Returns an open file descriptor
2626a53f0a5SChristian S.J. Peron  * on success, or -1 on failure.
2636a53f0a5SChristian S.J. Peron  */
2646a53f0a5SChristian S.J. Peron static int
26509a7fe0aSKyle Evans acquire_lock(union lock_subject *subj, int flags, int silent)
2666a53f0a5SChristian S.J. Peron {
2676a53f0a5SChristian S.J. Peron 	int fd;
2686a53f0a5SChristian S.J. Peron 
26909a7fe0aSKyle Evans 	if (fdlock) {
27009a7fe0aSKyle Evans 		assert(subj->subj_fd >= 0 && subj->subj_fd <= INT_MAX);
27109a7fe0aSKyle Evans 		fd = (int)subj->subj_fd;
27209a7fe0aSKyle Evans 
27309a7fe0aSKyle Evans 		if (flock(fd, LOCK_EX | LOCK_NB) == -1) {
27409a7fe0aSKyle Evans 			if (errno == EAGAIN || errno == EINTR)
27509a7fe0aSKyle Evans 				return (-1);
27609a7fe0aSKyle Evans 			err(EX_CANTCREAT, "cannot lock fd %d", fd);
27709a7fe0aSKyle Evans 		}
27809a7fe0aSKyle Evans 	} else if ((fd = open(subj->subj_name, O_EXLOCK|flags, 0666)) == -1) {
2796a53f0a5SChristian S.J. Peron 		if (errno == EAGAIN || errno == EINTR)
2806a53f0a5SChristian S.J. Peron 			return (-1);
2813041e695SKyle Evans 		else if (errno == ENOENT && (flags & O_CREAT) == 0) {
2823041e695SKyle Evans 			if (!silent)
28309a7fe0aSKyle Evans 				warn("%s", subj->subj_name);
2843041e695SKyle Evans 			exit(EX_UNAVAILABLE);
2853041e695SKyle Evans 		}
28609a7fe0aSKyle Evans 		err(EX_CANTCREAT, "cannot open %s", subj->subj_name);
2876a53f0a5SChristian S.J. Peron 	}
2886a53f0a5SChristian S.J. Peron 	return (fd);
2896a53f0a5SChristian S.J. Peron }
2906a53f0a5SChristian S.J. Peron 
2916a53f0a5SChristian S.J. Peron /*
292c8929a49SJohn Polstra  * Remove the lock file.
293c8929a49SJohn Polstra  */
294c8929a49SJohn Polstra static void
295c8929a49SJohn Polstra cleanup(void)
296c8929a49SJohn Polstra {
297cc2a9f52SChristian S.J. Peron 
29809a7fe0aSKyle Evans 	if (keep || fdlock)
2992f278eacSJohn Polstra 		flock(lockfd, LOCK_UN);
3002f278eacSJohn Polstra 	else
301ae06cb4dSJohn Polstra 		unlink(lockname);
302c8929a49SJohn Polstra }
303c8929a49SJohn Polstra 
304c8929a49SJohn Polstra /*
305c8929a49SJohn Polstra  * Signal handler for SIGTERM.  Cleans up the lock file, then re-raises
306c8929a49SJohn Polstra  * the signal.
307c8929a49SJohn Polstra  */
308c8929a49SJohn Polstra static void
309c8929a49SJohn Polstra killed(int sig)
310c8929a49SJohn Polstra {
311cc2a9f52SChristian S.J. Peron 
312c8929a49SJohn Polstra 	cleanup();
313c8929a49SJohn Polstra 	signal(sig, SIG_DFL);
314c8929a49SJohn Polstra 	if (kill(getpid(), sig) == -1)
31518425c19SAlexander Melkov 		_Exit(EX_OSERR);
316c8929a49SJohn Polstra }
317c8929a49SJohn Polstra 
318c8929a49SJohn Polstra /*
319c8929a49SJohn Polstra  * Signal handler for SIGALRM.
320c8929a49SJohn Polstra  */
321c8929a49SJohn Polstra static void
3229ff5e898SDavid Malone timeout(int sig __unused)
323c8929a49SJohn Polstra {
324cc2a9f52SChristian S.J. Peron 
325c8929a49SJohn Polstra 	timed_out = 1;
326c8929a49SJohn Polstra }
327c8929a49SJohn Polstra 
328c8929a49SJohn Polstra static void
329c8929a49SJohn Polstra usage(void)
330c8929a49SJohn Polstra {
331cc2a9f52SChristian S.J. Peron 
3323ec665d4SPhilippe Charnier 	fprintf(stderr,
33309a7fe0aSKyle Evans 	    "usage: lockf [-knsw] [-t seconds] file command [arguments]\n"
33409a7fe0aSKyle Evans 	    "       lockf [-s] [-t seconds] fd\n");
3353ec665d4SPhilippe Charnier 	exit(EX_USAGE);
336c8929a49SJohn Polstra }
337c8929a49SJohn Polstra 
338c8929a49SJohn Polstra /*
339c8929a49SJohn Polstra  * Wait until it might be possible to acquire a lock on the given file.
3406a53f0a5SChristian S.J. Peron  * If the file does not exist, return immediately without creating it.
341c8929a49SJohn Polstra  */
3426a53f0a5SChristian S.J. Peron static void
3436a53f0a5SChristian S.J. Peron wait_for_lock(const char *name)
344c8929a49SJohn Polstra {
345c8929a49SJohn Polstra 	int fd;
346c8929a49SJohn Polstra 
3476a53f0a5SChristian S.J. Peron 	if ((fd = open(name, O_RDONLY|O_EXLOCK, 0666)) == -1) {
3486a53f0a5SChristian S.J. Peron 		if (errno == ENOENT || errno == EINTR)
3496a53f0a5SChristian S.J. Peron 			return;
350ae06cb4dSJohn Polstra 		err(EX_CANTCREAT, "cannot open %s", name);
351c8929a49SJohn Polstra 	}
3526a53f0a5SChristian S.J. Peron 	close(fd);
353c8929a49SJohn Polstra }
354