xref: /openbmc/openbmc/poky/meta/recipes-core/util-linux/util-linux/fcntl-lock.c (revision 03514f1996efa799e50da744818ba331c2e893b6)
1 // From https://github.com/magnumripper/fcntl-lock
2 // SPDX-License-Identifier: MIT
3 /* ----------------------------------------------------------------------- *
4  *
5  *   Copyright 2003-2005 H. Peter Anvin - All Rights Reserved
6  *   Copyright 2015 magnum (fcntl version)
7  *
8  *   Permission is hereby granted, free of charge, to any person
9  *   obtaining a copy of this software and associated documentation
10  *   files (the "Software"), to deal in the Software without
11  *   restriction, including without limitation the rights to use,
12  *   copy, modify, merge, publish, distribute, sublicense, and/or
13  *   sell copies of the Software, and to permit persons to whom
14  *   the Software is furnished to do so, subject to the following
15  *   conditions:
16  *
17  *   The above copyright notice and this permission notice shall
18  *   be included in all copies or substantial portions of the Software.
19  *
20  *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
22  *   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  *   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
24  *   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
25  *   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26  *   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
27  *   OTHER DEALINGS IN THE SOFTWARE.
28  *
29  * ----------------------------------------------------------------------- */
30 
31 #include <errno.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <fcntl.h>
35 #include <unistd.h>
36 #include <getopt.h>
37 #include <signal.h>
38 #include <ctype.h>
39 #include <string.h>
40 #include <paths.h>
41 #include <sysexits.h>
42 #include <sys/types.h>
43 #include <sys/file.h>
44 #include <sys/time.h>
45 #include <sys/wait.h>
46 
47 #define PACKAGE_STRING "magnum"
48 #define _(x) (x)
49 
50 static const struct option long_options[] = {
51   { "shared",       0, NULL, 's' },
52   { "exclusive",    0, NULL, 'x' },
53   { "unlock",       0, NULL, 'u' },
54   { "nonblocking",  0, NULL, 'n' },
55   { "nb",           0, NULL, 'n' },
56   { "timeout",      1, NULL, 'w' },
57   { "wait",         1, NULL, 'w' },
58   { "close",        0, NULL, 'o' },
59   { "help",         0, NULL, 'h' },
60   { "version",      0, NULL, 'V' },
61   { 0, 0, 0, 0 }
62 };
63 
64 const char *program;
65 
usage(int ex)66 static void usage(int ex)
67 {
68   fputs("fcntl-lock (" PACKAGE_STRING ")\n", stderr);
69   fprintf(stderr,
70 	_("Usage: %1$s [-sxun][-w #] fd#\n"
71 	  "       %1$s [-sxon][-w #] file [-c] command...\n"
72 	  "       %1$s [-sxon][-w #] directory [-c] command...\n"
73 	  "  -s  --shared     Get a shared lock\n"
74 	  "  -x  --exclusive  Get an exclusive lock\n"
75 	  "  -u  --unlock     Remove a lock\n"
76 	  "  -n  --nonblock   Fail rather than wait\n"
77 	  "  -w  --timeout    Wait for a limited amount of time\n"
78 	  "  -o  --close      Close file descriptor before running command\n"
79 	  "  -c  --command    Run a single command string through the shell\n"
80 	  "  -h  --help       Display this text\n"
81 	  "  -V  --version    Display version\n"),
82 	  program);
83   exit(ex);
84 }
85 
86 
87 static sig_atomic_t timeout_expired = 0;
88 
timeout_handler(int sig)89 static void timeout_handler(int sig)
90 {
91   (void)sig;
92 
93   timeout_expired = 1;
94 }
95 
96 
strtotimeval(const char * str,struct timeval * tv)97 static char * strtotimeval(const char *str, struct timeval *tv)
98 {
99   char *s;
100   long fs;			/* Fractional seconds */
101   int i;
102 
103   tv->tv_sec = strtol(str, &s, 10);
104   fs = 0;
105 
106   if ( *s == '.' ) {
107     s++;
108 
109     for ( i = 0 ; i < 6 ; i++ ) {
110       if ( !isdigit(*s) )
111 	break;
112 
113       fs *= 10;
114       fs += *s++ - '0';
115     }
116 
117     for ( ; i < 6; i++ )
118       fs *= 10;
119 
120     while ( isdigit(*s) )
121       s++;
122   }
123 
124   tv->tv_usec = fs;
125   return s;
126 }
127 
main(int argc,char * argv[])128 int main(int argc, char *argv[])
129 {
130   struct itimerval timeout, old_timer;
131   int have_timeout = 0;
132   int type = F_WRLCK;
133   int block = F_SETLKW;
134   int fd = -1;
135   int opt, ix;
136   int do_close = 0;
137   int err;
138   int status;
139   char *eon;
140   char **cmd_argv = NULL, *sh_c_argv[4];
141   struct flock lock;
142   const char *filename = NULL;
143   struct sigaction sa, old_sa;
144 
145   program = argv[0];
146 
147   if ( argc < 2 )
148     usage(EX_USAGE);
149 
150   memset(&timeout, 0, sizeof timeout);
151 
152   optopt = 0;
153   while ( (opt = getopt_long(argc, argv, "+sexnouw:hV?", long_options, &ix)) != EOF ) {
154     switch(opt) {
155     case 's':
156       type = F_RDLCK;
157       break;
158     case 'e':
159     case 'x':
160       type = F_WRLCK;
161       break;
162     case 'u':
163       type = F_UNLCK;
164       break;
165     case 'o':
166       do_close = 1;
167       break;
168     case 'n':
169       block = F_SETLK;
170       break;
171     case 'w':
172       have_timeout = 1;
173       eon = strtotimeval(optarg, &timeout.it_value);
174       if ( *eon )
175 	usage(EX_USAGE);
176       break;
177     case 'V':
178       printf("fcntl-lock (%s)\n", PACKAGE_STRING);
179       exit(0);
180     default:
181       /* optopt will be set if this was an unrecognized option, i.e. *not* 'h' or '?' */
182       usage(optopt ? EX_USAGE : 0);
183       break;
184     }
185   }
186 
187   if ( argc > optind+1 ) {
188     /* Run command */
189 
190     if ( !strcmp(argv[optind+1], "-c") ||
191 	 !strcmp(argv[optind+1], "--command") ) {
192 
193       if ( argc != optind+3 ) {
194 	fprintf(stderr, _("%s: %s requires exactly one command argument\n"),
195 		program, argv[optind+1]);
196 	exit(EX_USAGE);
197       }
198 
199       cmd_argv = sh_c_argv;
200 
201       cmd_argv[0] = getenv("SHELL");
202       if ( !cmd_argv[0] || !*cmd_argv[0] )
203 	cmd_argv[0] = _PATH_BSHELL;
204 
205       cmd_argv[1] = "-c";
206       cmd_argv[2] = argv[optind+2];
207       cmd_argv[3] = 0;
208     } else {
209       cmd_argv = &argv[optind+1];
210     }
211 
212     filename = argv[optind];
213     fd = open(filename, O_RDWR|O_NOCTTY|O_CREAT, 0666);
214     /* Linux doesn't like O_CREAT on a directory, even though it should be a
215        no-op */
216     if (fd < 0 && errno == EISDIR)
217         fd = open(filename, O_RDONLY|O_NOCTTY);
218 
219     if ( fd < 0 ) {
220       err = errno;
221       fprintf(stderr, _("%s: cannot open lock file %s: %s\n"),
222 	      program, argv[optind], strerror(err));
223       exit((err == ENOMEM||err == EMFILE||err == ENFILE) ? EX_OSERR :
224 	   (err == EROFS||err == ENOSPC) ? EX_CANTCREAT :
225 	   EX_NOINPUT);
226     }
227 
228   } else if (optind < argc) {
229     /* Use provided file descriptor */
230 
231     fd = (int)strtol(argv[optind], &eon, 10);
232     if ( *eon || !argv[optind] ) {
233       fprintf(stderr, _("%s: bad number: %s\n"), program, argv[optind]);
234       exit(EX_USAGE);
235     }
236 
237   } else {
238     /* Bad options */
239 
240     fprintf(stderr, _("%s: requires file descriptor, file or directory\n"),
241 		program);
242     exit(EX_USAGE);
243   }
244 
245 
246   if ( have_timeout ) {
247     if ( timeout.it_value.tv_sec == 0 &&
248 	 timeout.it_value.tv_usec == 0 ) {
249       /* -w 0 is equivalent to -n; this has to be special-cased
250 	 because setting an itimer to zero means disabled! */
251 
252       have_timeout = 0;
253       block = F_SETLK;
254     } else {
255       memset(&sa, 0, sizeof sa);
256 
257       sa.sa_handler = timeout_handler;
258       sa.sa_flags   = SA_RESETHAND;
259       sigaction(SIGALRM, &sa, &old_sa);
260 
261       setitimer(ITIMER_REAL, &timeout, &old_timer);
262     }
263   }
264 
265   memset(&lock, 0, sizeof(lock));
266   lock.l_type = type;
267   while ( fcntl(fd, block, &lock) ) {
268     switch( (err = errno) ) {
269     case EAGAIN:		/* -n option set and failed to lock */
270     case EACCES:		/* -n option set and failed to lock */
271       exit(1);
272     case EINTR:			/* Signal received */
273       if ( timeout_expired )
274 	exit(1);		/* -w option set and failed to lock */
275       continue;			/* otherwise try again */
276     default:			/* Other errors */
277       if ( filename )
278 	fprintf(stderr, "%s: %s: %s\n", program, filename, strerror(err));
279       else
280 	fprintf(stderr, "%s: %d: %s\n", program, fd, strerror(err));
281       exit((err == ENOLCK||err == ENOMEM) ? EX_OSERR : EX_DATAERR);
282     }
283   }
284 
285   if ( have_timeout ) {
286     setitimer(ITIMER_REAL, &old_timer, NULL); /* Cancel itimer */
287     sigaction(SIGALRM, &old_sa, NULL); /* Cancel signal handler */
288   }
289 
290   status = 0;
291 
292   if ( cmd_argv ) {
293     pid_t w, f;
294 
295     /* Clear any inherited settings */
296     signal(SIGCHLD, SIG_DFL);
297     f = fork();
298 
299     if ( f < 0 ) {
300       err = errno;
301       fprintf(stderr, _("%s: fork failed: %s\n"), program, strerror(err));
302       exit(EX_OSERR);
303     } else if ( f == 0 ) {
304       if ( do_close )
305 	close(fd);
306       err = errno;
307       execvp(cmd_argv[0], cmd_argv);
308       /* execvp() failed */
309       fprintf(stderr, "%s: %s: %s\n", program, cmd_argv[0], strerror(err));
310       _exit((err == ENOMEM) ? EX_OSERR: EX_UNAVAILABLE);
311     } else {
312       do {
313 	w = waitpid(f, &status, 0);
314 	if (w == -1 && errno != EINTR)
315 	  break;
316       } while ( w != f );
317 
318       if (w == -1) {
319 	err = errno;
320 	status = EXIT_FAILURE;
321 	fprintf(stderr, "%s: waitpid failed: %s\n", program, strerror(err));
322       } else if ( WIFEXITED(status) )
323 	status = WEXITSTATUS(status);
324       else if ( WIFSIGNALED(status) )
325 	status = WTERMSIG(status) + 128;
326       else
327 	status = EX_OSERR;	/* WTF? */
328     }
329   }
330 
331   return status;
332 }
333