chiark / gitweb /
with-lock-ex: Convert to MIT
[chiark-utils.git] / cprogs / with-lock-ex.c
1 /*
2  * File locker
3  *
4  * Usage:
5  *  with-lock-ex -<mode> <lockfile> <command> <args>...
6  *  with-lock-ex -l      <lockfile>
7  *
8  * modes are
9  *  w    wait for the lock
10  *  f    fail if the lock cannot be acquired
11  *  q    silently do nothing if the lock cannot be acquired
12  *  l    show who is waiting (print "none" or "read <pid>"
13  *         or "write <pid>"; lockfile opened for reading;
14  *         no command may be specified)
15  *
16  * with-lock-ex will open and lock the lockfile for writing and
17  * then feed the remainder of its arguments to exec(2); when
18  * that process terminates the fd will be closed and the file
19  * unlocked automatically by the kernel.
20  *
21  * If invoked as with-lock, behaves like with-lock-ex -f (for backward
22  * compatibility with an earlier version).
23  *
24  * This file written by me, Ian Jackson, in 1993, 1994, 1995, 1996,
25  * 1998, 1999, 2016.
26  *
27  * Copyright 1993-2016 Ian Jackson in some jurisdictions
28  * Copyright 2017      Ian Jackson in all jurisdictions
29  *
30  * (MIT licence:)
31  *
32  * Permission is hereby granted, free of charge, to any person obtaining a
33  * copy of this software and associated documentation files (the "Software"),
34  * to deal in the Software without restriction, including without limitation
35  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
36  * and/or sell copies of the Software, and to permit persons to whom the
37  * Software is furnished to do so, subject to the following conditions:
38  *
39  * The above copyright notice and this permission notice shall be included in
40  * all copies or substantial portions of the Software.
41  *
42  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
45  * SOFTWARE IN THE PUBLIC INTEREST, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR
46  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
47  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
48  * DEALINGS IN THE SOFTWARE.
49  */
50
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <unistd.h>
56 #include <string.h>
57 #include <sys/stat.h>
58
59 static const char *cmd;
60
61 static void fail(const char *why) __attribute__((noreturn));
62
63 static void fail(const char *why) {
64   fprintf(stderr,"with-lock-ex %s: %s: %s\n",cmd,why,strerror(errno));
65   exit(255);
66 }
67
68 int main(int argc, char **argv) {
69   int fd, mode, um;
70   struct stat stab, fstab;
71   long cloexec;
72   struct flock fl;
73   const char *p;
74
75   if (argc >= 3 && !strcmp((p= strrchr(argv[0],'/')) ? ++p : argv[0], "with-lock")) {
76     mode= 'f';
77   } else if (argc < 3 || argv[1][0] != '-' || argv[1][2] ||
78              ((mode= argv[1][1]) != 'w' && mode != 'q' && mode != 'f'
79               && mode != 'l') ||
80              (mode != 'l' && argc < 4) ||
81              (mode == 'l' && argc != 3)) {
82     fputs("usage: with-lock-ex -w|-q|-f <lockfile> <command> <args>...\n"
83           "       with-lock-ex -l       <lockfile>\n"
84           "       with-lock             <lockfile> <command> <args>...\n",
85           stderr);
86     exit(255);
87   } else {
88     argv++; argc--;
89   }
90   cmd= argv[2];
91   um= umask(0777); if (um==-1) fail("find umask");
92   if (umask(um)==-1) fail("reset umask");
93
94   for (;;) {
95
96     int openmode = mode=='l' ? O_RDONLY : O_RDWR|O_CREAT;
97
98     fd= open(argv[1],openmode,0666&~(um|((um&0222)<<1)));
99     if (fd<0) fail(argv[1]);
100   
101     for (;;) {
102       fl.l_type= F_WRLCK;
103       fl.l_whence= SEEK_SET;
104       fl.l_start= 0;
105       fl.l_len= mode=='l' ? 0 : 1;
106       if (fcntl(fd,
107                 mode=='l' ? F_GETLK :
108                 mode=='w' ? F_SETLKW :
109                 F_SETLK,
110                 &fl) != -1) break;
111       if (mode=='q' &&
112           (errno == EAGAIN || errno == EWOULDBLOCK || errno == EBUSY))
113         exit(0);
114       if (errno != EINTR) fail("could not acquire lock");
115     }
116     if (mode=='l') {
117       if (fl.l_pid) {
118         printf("%s %lu\n",
119                fl.l_type == F_WRLCK ? "write" :
120                fl.l_type == F_RDLCK ? "read" : "unknown",
121                (unsigned long)fl.l_pid);
122       } else {
123         printf("none\n");
124       }
125       if (ferror(stdout)) fail("print to stdout\n");
126       exit(0);
127     }
128
129     if (fstat(fd, &fstab)) fail("could not fstat lock fd");
130     if (stat(argv[1], &stab)) {
131       if (errno != ENOENT) fail("could not stat lockfile");
132     } else {
133       if (stab.st_dev == fstab.st_dev &&
134           stab.st_ino == fstab.st_ino) break;
135     }
136     close(fd);
137   }
138
139   cloexec= fcntl(fd, F_GETFD); if (cloexec==-1) fail("fcntl F_GETFD");
140   cloexec &= ~1;
141   if (fcntl(fd, F_SETFD, cloexec)==-1) fail("fcntl F_SETFD");
142
143   execvp(cmd,argv+2);
144   fail("unable to execute command");
145 }