chiark / gitweb /
Revert "fishdescriptor: for revert: attempt at setuptools"
[chiark-utils.git] / cprogs / with-lock-ex.c
1 /*
2  * File locker
3  *
4  * Usage:
5  *  with-lock-ex -<mode> [-t <secs>] <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  * If -t is specified, then with-lock-ex will wait for up to <secs>
17  * seconds to acquire the lock, and then fail or silently do nothing
18  * (depending on whether -f or -q is specified). You cannot specify
19  * a timeout for modes l or w.
20  *
21  * with-lock-ex will open and lock the lockfile for writing and
22  * then feed the remainder of its arguments to exec(2); when
23  * that process terminates the fd will be closed and the file
24  * unlocked automatically by the kernel.
25  *
26  * If invoked as with-lock, behaves like with-lock-ex -f (for backward
27  * compatibility with an earlier version).
28  *
29  * This file written by me, Ian Jackson, in 1993, 1994, 1995, 1996,
30  * 1998, 1999, 2016.
31  *
32  * Copyright 1993-2016 Ian Jackson in some jurisdictions
33  * Copyright 2017      Ian Jackson in all jurisdictions
34  * Copyright 2017      Genome Research Ltd
35  *
36  * (MIT licence:)
37  *
38  * Permission is hereby granted, free of charge, to any person obtaining a
39  * copy of this software and associated documentation files (the "Software"),
40  * to deal in the Software without restriction, including without limitation
41  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
42  * and/or sell copies of the Software, and to permit persons to whom the
43  * Software is furnished to do so, subject to the following conditions:
44  *
45  * The above copyright notice and this permission notice shall be included in
46  * all copies or substantial portions of the Software.
47  *
48  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
49  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
50  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
51  * SOFTWARE IN THE PUBLIC INTEREST, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR
52  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
53  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
54  * DEALINGS IN THE SOFTWARE.
55  */
56
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <unistd.h>
62 #include <string.h>
63 #include <sys/stat.h>
64 #include <limits.h>
65 #include <signal.h>
66 #include <sys/time.h>
67
68 static const char *cmd;
69
70 static void fail(const char *why) __attribute__((noreturn));
71
72 static void fail(const char *why) {
73   fprintf(stderr,"with-lock-ex %s: %s: %s\n",cmd,why,strerror(errno));
74   exit(255);
75 }
76
77 static void badusage(void) __attribute__((noreturn));
78
79 static void badusage(void) {
80     fputs("usage: with-lock-ex -w|-q|-f [-t <secs>] <lockfile> <command> <args>...\n"
81           "       with-lock-ex -l       <lockfile>\n"
82           "       with-lock-ex          <lockfile> <command> <args>...\n",
83           stderr);
84     exit(255);
85 }
86
87 static int mode;
88
89 /* This signal handler uses unsafe functions, so MUST NOT be callable
90  * during an unsafe function, as that is Undefined Behaviour
91  */
92 static void alrm_handler(int signum) {
93   if (mode=='q') {
94     exit(0);
95   } else {
96     fprintf(stderr,
97             "with-lock-ex %s: timer expired while trying to acquire lock\n",
98             cmd);
99     exit(255);
100   }
101 }
102
103 int main(int argc, char **argv) {
104   int fd, um, c, r;
105   struct stat stab, fstab;
106   long cloexec, secs=0;
107   struct flock fl;
108   char *endptr;
109   sigset_t sigs, oldsigs;
110   struct sigaction siga;
111   struct itimerval itv;
112
113   mode= 'x';
114   while ((c= getopt(argc,argv,"+wfqlt:")) != -1) {
115     switch(c) {
116     case 'l':
117     case 'w':
118     case 'f':
119     case 'q':
120       if (mode != 'x') badusage();
121       mode= c;
122       break;
123     case 't':
124       errno = 0;
125       secs = strtol(optarg, &endptr, 0);
126       if (*endptr || endptr==optarg || errno==ERANGE)
127         fail("parsing timeout value");
128       if (secs < 0) {
129         fprintf(stderr,"timeout value must be >=0\n");
130         exit(255);
131       }
132       break;
133     default:
134       badusage();
135     }
136   }
137
138   if (secs && (mode=='l' || mode=='w')) {
139     fputs("-t only allowed with -q or -f.\n", stderr);
140     exit(255);
141   }
142
143   argv += optind-1; argc -= optind-1;
144   if (argc < 2) badusage();
145
146   if (secs) {
147     if (sigemptyset(&sigs)) fail("Initialising signal set");
148     if (sigaddset(&sigs,SIGALRM)) fail("Adding SIGALRM to signal set");
149     if (sigprocmask(SIG_BLOCK,&sigs,&oldsigs)) fail("Blocking SIGALRM");
150     memset(&siga,0,sizeof(siga));
151     siga.sa_handler=alrm_handler;
152     if (sigaction(SIGALRM,&siga,NULL)) fail("Installing SIGALRM handler");
153     memset(&itv,0,sizeof(itv));
154     itv.it_value.tv_sec=secs;
155     if (setitimer(ITIMER_REAL,&itv,NULL)) fail("Setting timer");
156   }
157
158   cmd= argv[2];
159   um= umask(0777); if (um==-1) fail("find umask");
160   if (umask(um)==-1) fail("reset umask");
161
162   for (;;) {
163
164     int openmode = mode=='l' ? O_RDONLY : O_RDWR|O_CREAT;
165
166     fd= open(argv[1],openmode,0666&~(um|((um&0222)<<1)));
167     if (fd<0) fail(argv[1]);
168   
169     for (;;) {
170       fl.l_type= F_WRLCK;
171       fl.l_whence= SEEK_SET;
172       fl.l_start= 0;
173       fl.l_len= mode=='l' ? 0 : 1;
174       if (secs) sigprocmask(SIG_UNBLOCK,&sigs,NULL);
175       r = fcntl(fd,
176                 mode=='l' ? F_GETLK :
177                 mode=='w' || secs > 0 ? F_SETLKW :
178                 F_SETLK,
179                 &fl);
180       if (secs) sigprocmask(SIG_BLOCK,&sigs,NULL);
181       if (!r) {
182         break;
183       }
184       if (mode=='q' &&
185           (errno == EAGAIN || errno == EWOULDBLOCK || errno == EBUSY))
186         exit(0);
187       if (errno != EINTR) fail("could not acquire lock");
188     }
189     if (mode=='l') {
190       if (fl.l_pid) {
191         printf("%s %lu\n",
192                fl.l_type == F_WRLCK ? "write" :
193                fl.l_type == F_RDLCK ? "read" : "unknown",
194                (unsigned long)fl.l_pid);
195       } else {
196         printf("none\n");
197       }
198       if (ferror(stdout)) fail("print to stdout\n");
199       exit(0);
200     }
201
202     if (fstat(fd, &fstab)) fail("could not fstat lock fd");
203     if (stat(argv[1], &stab)) {
204       if (errno != ENOENT) fail("could not stat lockfile");
205     } else {
206       if (stab.st_dev == fstab.st_dev &&
207           stab.st_ino == fstab.st_ino) break;
208     }
209     close(fd);
210   }
211
212   if (secs) {
213     itv.it_value.tv_sec=0;
214     if (setitimer(ITIMER_REAL,&itv,NULL)) fail("Clearing timer");
215     sigprocmask(SIG_SETMASK,&oldsigs,NULL);
216     siga.sa_handler=SIG_DFL;
217     sigaction(SIGALRM,&siga,NULL);
218   }
219
220   cloexec= fcntl(fd, F_GETFD); if (cloexec==-1) fail("fcntl F_GETFD");
221   cloexec &= ~1;
222   if (fcntl(fd, F_SETFD, cloexec)==-1) fail("fcntl F_SETFD");
223
224   execvp(cmd,argv+2);
225   fail("unable to execute command");
226 }