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/types.h> 29 #include <sys/wait.h> 30 31 #include <assert.h> 32 #include <err.h> 33 #include <errno.h> 34 #include <fcntl.h> 35 #include <limits.h> 36 #include <signal.h> 37 #include <stdatomic.h> 38 #include <stdbool.h> 39 #include <stdio.h> 40 #include <stdlib.h> 41 #include <string.h> 42 #include <sysexits.h> 43 #include <unistd.h> 44 45 #define FDLOCK_PREFIX "/dev/fd/" 46 47 union lock_subject { 48 long subj_fd; 49 const char *subj_name; 50 }; 51 52 static int acquire_lock(union lock_subject *subj, int flags, int silent); 53 static void cleanup(void); 54 static void killed(int sig); 55 static void sigchld(int sig); 56 static void timeout(int sig); 57 static void usage(void) __dead2; 58 static void wait_for_lock(const char *name); 59 60 static const char *lockname; 61 _Static_assert(sizeof(sig_atomic_t) >= sizeof(pid_t), 62 "PIDs cannot be managed safely from a signal handler on this platform."); 63 static sig_atomic_t child = -1; 64 static int lockfd = -1; 65 static bool keep; 66 static bool fdlock; 67 static int status; 68 static bool termchild; 69 static sig_atomic_t timed_out; 70 71 /* 72 * Check if fdlock is implied by the given `lockname`. We'll write the fd that 73 * is represented by it out to ofd, and the caller is expected to do any 74 * necessary validation on it. 75 */ 76 static bool 77 fdlock_implied(const char *name, long *ofd) 78 { 79 char *endp; 80 long fd; 81 82 if (strncmp(name, FDLOCK_PREFIX, sizeof(FDLOCK_PREFIX) - 1) != 0) 83 return (false); 84 85 /* Skip past the prefix. */ 86 name += sizeof(FDLOCK_PREFIX) - 1; 87 errno = 0; 88 fd = strtol(name, &endp, 10); 89 if (errno != 0 || *endp != '\0') 90 return (false); 91 92 *ofd = fd; 93 return (true); 94 } 95 96 /* 97 * Execute an arbitrary command while holding a file lock. 98 */ 99 int 100 main(int argc, char **argv) 101 { 102 struct sigaction sa_chld = { 103 .sa_handler = sigchld, 104 .sa_flags = SA_NOCLDSTOP, 105 }, sa_prev; 106 sigset_t mask, omask; 107 long long waitsec; 108 const char *errstr; 109 union lock_subject subj; 110 int ch, flags; 111 bool silent, writepid; 112 113 silent = writepid = false; 114 flags = O_CREAT | O_RDONLY; 115 waitsec = -1; /* Infinite. */ 116 while ((ch = getopt(argc, argv, "knpsTt:w")) != -1) { 117 switch (ch) { 118 case 'k': 119 keep = true; 120 break; 121 case 'n': 122 flags &= ~O_CREAT; 123 break; 124 case 's': 125 silent = true; 126 break; 127 case 'T': 128 termchild = true; 129 break; 130 case 't': 131 waitsec = strtonum(optarg, 0, UINT_MAX, &errstr); 132 if (errstr != NULL) 133 errx(EX_USAGE, 134 "invalid timeout \"%s\"", optarg); 135 break; 136 case 'p': 137 writepid = true; 138 flags |= O_TRUNC; 139 /* FALLTHROUGH */ 140 case 'w': 141 flags = (flags & ~O_RDONLY) | O_WRONLY; 142 break; 143 default: 144 usage(); 145 } 146 } 147 148 argc -= optind; 149 argv += optind; 150 151 if (argc == 0) 152 usage(); 153 154 lockname = argv[0]; 155 156 argc--; 157 argv++; 158 159 /* 160 * If there aren't any arguments left, then we must be in fdlock mode. 161 */ 162 if (argc == 0 && *lockname != '/') { 163 fdlock = true; 164 subj.subj_fd = -1; 165 } else { 166 fdlock = fdlock_implied(lockname, &subj.subj_fd); 167 if (argc == 0 && !fdlock) { 168 fprintf(stderr, "Expected fd, got '%s'\n", lockname); 169 usage(); 170 } 171 } 172 173 if (fdlock) { 174 if (subj.subj_fd < 0) { 175 char *endp; 176 177 errno = 0; 178 subj.subj_fd = strtol(lockname, &endp, 10); 179 if (errno != 0 || *endp != '\0') { 180 fprintf(stderr, "Expected fd, got '%s'\n", 181 lockname); 182 usage(); 183 } 184 } 185 186 if (subj.subj_fd < 0 || subj.subj_fd > INT_MAX) { 187 fprintf(stderr, "fd '%ld' out of range\n", 188 subj.subj_fd); 189 usage(); 190 } 191 } else { 192 subj.subj_name = lockname; 193 } 194 195 if (waitsec > 0) { /* Set up a timeout. */ 196 struct sigaction act; 197 198 act.sa_handler = timeout; 199 sigemptyset(&act.sa_mask); 200 act.sa_flags = 0; /* Note that we do not set SA_RESTART. */ 201 sigaction(SIGALRM, &act, NULL); 202 alarm((unsigned int)waitsec); 203 } 204 /* 205 * If the "-k" option is not given, then we must not block when 206 * acquiring the lock. If we did, then the lock holder would 207 * unlink the file upon releasing the lock, and we would acquire 208 * a lock on a file with no directory entry. Then another 209 * process could come along and acquire the same lock. To avoid 210 * this problem, we separate out the actions of waiting for the 211 * lock to be available and of actually acquiring the lock. 212 * 213 * That approach produces behavior that is technically correct; 214 * however, it causes some performance & ordering problems for 215 * locks that have a lot of contention. First, it is unfair in 216 * the sense that a released lock isn't necessarily granted to 217 * the process that has been waiting the longest. A waiter may 218 * be starved out indefinitely. Second, it creates a thundering 219 * herd situation each time the lock is released. 220 * 221 * When the "-k" option is used, the unlink race no longer 222 * exists. In that case we can block while acquiring the lock, 223 * avoiding the separate step of waiting for the lock. This 224 * yields fairness and improved performance. 225 */ 226 lockfd = acquire_lock(&subj, flags | O_NONBLOCK, silent); 227 while (lockfd == -1 && !timed_out && waitsec != 0) { 228 if (keep || fdlock) { 229 lockfd = acquire_lock(&subj, flags, silent); 230 } else { 231 wait_for_lock(lockname); 232 lockfd = acquire_lock(&subj, flags | O_NONBLOCK, 233 silent); 234 } 235 236 /* timed_out */ 237 atomic_signal_fence(memory_order_acquire); 238 } 239 if (waitsec > 0) 240 alarm(0); 241 if (lockfd == -1) { /* We failed to acquire the lock. */ 242 if (silent) 243 exit(EX_TEMPFAIL); 244 errx(EX_TEMPFAIL, "%s: already locked", lockname); 245 } 246 247 /* At this point, we own the lock. */ 248 249 /* Nothing else to do for FD lock, just exit */ 250 if (argc == 0) { 251 assert(fdlock); 252 return 0; 253 } 254 255 if (atexit(cleanup) == -1) 256 err(EX_OSERR, "atexit failed"); 257 258 /* 259 * Block SIGTERM while SIGCHLD is being processed, so that we can safely 260 * waitpid(2) for the child without a concurrent termination observing 261 * an invalid pid (i.e., waited-on). If our setup between here and the 262 * sigsuspend loop gets any more complicated, we should rewrite it to 263 * just use a pipe to signal the child onto execvp(). 264 * 265 * We're blocking SIGCHLD and SIGTERM here so that we don't do any 266 * cleanup before we're ready to (after the pid is written out). 267 */ 268 sigemptyset(&mask); 269 sigaddset(&mask, SIGCHLD); 270 sigaddset(&mask, SIGTERM); 271 (void)sigprocmask(SIG_BLOCK, &mask, &omask); 272 273 memcpy(&sa_chld.sa_mask, &omask, sizeof(omask)); 274 sigaddset(&sa_chld.sa_mask, SIGTERM); 275 (void)sigaction(SIGCHLD, &sa_chld, &sa_prev); 276 277 if ((child = fork()) == -1) 278 err(EX_OSERR, "cannot fork"); 279 if (child == 0) { /* The child process. */ 280 (void)sigprocmask(SIG_SETMASK, &omask, NULL); 281 close(lockfd); 282 execvp(argv[0], argv); 283 warn("%s", argv[0]); 284 _exit(1); 285 } 286 /* This is the parent process. */ 287 signal(SIGINT, SIG_IGN); 288 signal(SIGQUIT, SIG_IGN); 289 signal(SIGTERM, killed); 290 291 fclose(stdin); 292 fclose(stdout); 293 fclose(stderr); 294 295 /* Write out the pid before we sleep on it. */ 296 if (writepid) 297 (void)dprintf(lockfd, "%d\n", (int)child); 298 299 /* Just in case they were blocked on entry. */ 300 sigdelset(&omask, SIGCHLD); 301 sigdelset(&omask, SIGTERM); 302 while (child >= 0) { 303 (void)sigsuspend(&omask); 304 /* child */ 305 atomic_signal_fence(memory_order_acquire); 306 } 307 308 return (WIFEXITED(status) ? WEXITSTATUS(status) : EX_SOFTWARE); 309 } 310 311 /* 312 * Try to acquire a lock on the given file/fd, creating the file if 313 * necessary. The flags argument is O_NONBLOCK or 0, depending on 314 * whether we should wait for the lock. Returns an open file descriptor 315 * on success, or -1 on failure. 316 */ 317 static int 318 acquire_lock(union lock_subject *subj, int flags, int silent) 319 { 320 int fd; 321 322 if (fdlock) { 323 assert(subj->subj_fd >= 0 && subj->subj_fd <= INT_MAX); 324 fd = (int)subj->subj_fd; 325 326 if (flock(fd, LOCK_EX | LOCK_NB) == -1) { 327 if (errno == EAGAIN || errno == EINTR) 328 return (-1); 329 err(EX_CANTCREAT, "cannot lock fd %d", fd); 330 } 331 } else if ((fd = open(subj->subj_name, O_EXLOCK|flags, 0666)) == -1) { 332 if (errno == EAGAIN || errno == EINTR) 333 return (-1); 334 else if (errno == ENOENT && (flags & O_CREAT) == 0) { 335 if (!silent) 336 warn("%s", subj->subj_name); 337 exit(EX_UNAVAILABLE); 338 } 339 err(EX_CANTCREAT, "cannot open %s", subj->subj_name); 340 } 341 return (fd); 342 } 343 344 /* 345 * Remove the lock file. 346 */ 347 static void 348 cleanup(void) 349 { 350 351 if (keep || fdlock) 352 flock(lockfd, LOCK_UN); 353 else 354 unlink(lockname); 355 } 356 357 /* 358 * Signal handler for SIGTERM. Cleans up the lock file, then re-raises 359 * the signal. 360 */ 361 static void 362 killed(int sig) 363 { 364 365 if (termchild && child >= 0) 366 kill(child, sig); 367 cleanup(); 368 signal(sig, SIG_DFL); 369 if (raise(sig) == -1) 370 _Exit(EX_OSERR); 371 } 372 373 /* 374 * Signal handler for SIGCHLD. Simply waits for the child and ensures that we 375 * don't end up in a sticky situation if we receive a SIGTERM around the same 376 * time. 377 */ 378 static void 379 sigchld(int sig __unused) 380 { 381 int ostatus; 382 383 while (waitpid(child, &ostatus, 0) != child) { 384 if (errno != EINTR) 385 _exit(EX_OSERR); 386 } 387 388 status = ostatus; 389 child = -1; 390 atomic_signal_fence(memory_order_release); 391 } 392 393 /* 394 * Signal handler for SIGALRM. 395 */ 396 static void 397 timeout(int sig __unused) 398 { 399 400 timed_out = 1; 401 atomic_signal_fence(memory_order_release); 402 } 403 404 static void 405 usage(void) 406 { 407 408 fprintf(stderr, 409 "usage: lockf [-knsw] [-t seconds] file command [arguments]\n" 410 " lockf [-s] [-t seconds] fd\n"); 411 exit(EX_USAGE); 412 } 413 414 /* 415 * Wait until it might be possible to acquire a lock on the given file. 416 * If the file does not exist, return immediately without creating it. 417 */ 418 static void 419 wait_for_lock(const char *name) 420 { 421 int fd; 422 423 if ((fd = open(name, O_RDONLY|O_EXLOCK, 0666)) == -1) { 424 if (errno == ENOENT || errno == EINTR) 425 return; 426 err(EX_CANTCREAT, "cannot open %s", name); 427 } 428 close(fd); 429 } 430