]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/flock.c
57153c8d9af0a2d3884410aca5fe47955f696a03
[thirdparty/util-linux.git] / sys-utils / flock.c
1 /* Copyright 2003-2005 H. Peter Anvin - All Rights Reserved
2 *
3 * Permission is hereby granted, free of charge, to any person
4 * obtaining a copy of this software and associated documentation
5 * files (the "Software"), to deal in the Software without
6 * restriction, including without limitation the rights to use,
7 * copy, modify, merge, publish, distribute, sublicense, and/or
8 * sell copies of the Software, and to permit persons to whom
9 * the Software is furnished to do so, subject to the following
10 * conditions:
11 *
12 * The above copyright notice and this permission notice shall
13 * be included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 * OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25 #include <ctype.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <getopt.h>
29 #include <paths.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sysexits.h>
35 #include <sys/file.h>
36 #include <sys/stat.h>
37 #include <sys/time.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #include <unistd.h>
41
42 #include "c.h"
43 #include "nls.h"
44 #include "strutils.h"
45 #include "closestream.h"
46 #include "monotonic.h"
47 #include "timer.h"
48
49 static void __attribute__((__noreturn__)) usage(void)
50 {
51 fputs(USAGE_HEADER, stdout);
52 printf(
53 _(" %1$s [options] <file>|<directory> <command> [<argument>...]\n"
54 " %1$s [options] <file>|<directory> -c <command>\n"
55 " %1$s [options] <file descriptor number>\n"),
56 program_invocation_short_name);
57
58 fputs(USAGE_SEPARATOR, stdout);
59 fputs(_("Manage file locks from shell scripts.\n"), stdout);
60
61 fputs(USAGE_OPTIONS, stdout);
62 fputs(_( " -s, --shared get a shared lock\n"), stdout);
63 fputs(_( " -x, --exclusive get an exclusive lock (default)\n"), stdout);
64 fputs(_( " -u, --unlock remove a lock\n"), stdout);
65 fputs(_( " -n, --nonblock fail rather than wait\n"), stdout);
66 fputs(_( " -w, --timeout <secs> wait for a limited amount of time\n"), stdout);
67 fputs(_( " -E, --conflict-exit-code <number> exit code after conflict or timeout\n"), stdout);
68 fputs(_( " -o, --close close file descriptor before running command\n"), stdout);
69 fputs(_( " -c, --command <command> run a single command string through the shell\n"), stdout);
70 fputs(_( " -F, --no-fork execute command without forking\n"), stdout);
71 fputs(_( " --verbose increase verbosity\n"), stdout);
72 fputs(USAGE_SEPARATOR, stdout);
73 printf(USAGE_HELP_OPTIONS(26));
74 printf(USAGE_MAN_TAIL("flock(1)"));
75 exit(EXIT_SUCCESS);
76 }
77
78 static sig_atomic_t timeout_expired = 0;
79
80 static void timeout_handler(int sig __attribute__((__unused__)),
81 siginfo_t *info,
82 void *context __attribute__((__unused__)))
83 {
84 #ifdef HAVE_TIMER_CREATE
85 if (info->si_code == SI_TIMER)
86 #endif
87 timeout_expired = 1;
88 }
89
90 static int open_file(const char *filename, int *flags)
91 {
92
93 int fd;
94 int fl = *flags == 0 ? O_RDONLY : *flags;
95
96 errno = 0;
97 fl |= O_NOCTTY | O_CREAT;
98 fd = open(filename, fl, 0666);
99
100 /* Linux doesn't like O_CREAT on a directory, even though it
101 * should be a no-op; POSIX doesn't allow O_RDWR or O_WRONLY
102 */
103 if (fd < 0 && errno == EISDIR) {
104 fl = O_RDONLY | O_NOCTTY;
105 fd = open(filename, fl);
106 }
107 if (fd < 0) {
108 warn(_("cannot open lock file %s"), filename);
109 if (errno == ENOMEM || errno == EMFILE || errno == ENFILE)
110 exit(EX_OSERR);
111 if (errno == EROFS || errno == ENOSPC)
112 exit(EX_CANTCREAT);
113 exit(EX_NOINPUT);
114 }
115 *flags = fl;
116 return fd;
117 }
118
119 static void __attribute__((__noreturn__)) run_program(char **cmd_argv)
120 {
121 execvp(cmd_argv[0], cmd_argv);
122
123 warn(_("failed to execute %s"), cmd_argv[0]);
124 _exit((errno == ENOMEM) ? EX_OSERR : EX_UNAVAILABLE);
125 }
126
127 int main(int argc, char *argv[])
128 {
129 struct ul_timer timer;
130 struct itimerval timeout;
131 int have_timeout = 0;
132 int type = LOCK_EX;
133 int block = 0;
134 int open_flags = 0;
135 int fd = -1;
136 int opt, ix;
137 int do_close = 0;
138 int no_fork = 0;
139 int status;
140 int verbose = 0;
141 struct timeval time_start, time_done;
142 /*
143 * The default exit code for lock conflict or timeout
144 * is specified in man flock.1
145 */
146 int conflict_exit_code = 1;
147 char **cmd_argv = NULL, *sh_c_argv[4];
148 const char *filename = NULL;
149 enum {
150 OPT_VERBOSE = CHAR_MAX + 1
151 };
152 static const struct option long_options[] = {
153 {"shared", no_argument, NULL, 's'},
154 {"exclusive", no_argument, NULL, 'x'},
155 {"unlock", no_argument, NULL, 'u'},
156 {"nonblocking", no_argument, NULL, 'n'},
157 {"nb", no_argument, NULL, 'n'},
158 {"timeout", required_argument, NULL, 'w'},
159 {"wait", required_argument, NULL, 'w'},
160 {"conflict-exit-code", required_argument, NULL, 'E'},
161 {"close", no_argument, NULL, 'o'},
162 {"no-fork", no_argument, NULL, 'F'},
163 {"verbose", no_argument, NULL, OPT_VERBOSE},
164 {"help", no_argument, NULL, 'h'},
165 {"version", no_argument, NULL, 'V'},
166 {NULL, 0, NULL, 0}
167 };
168
169 setlocale(LC_ALL, "");
170 bindtextdomain(PACKAGE, LOCALEDIR);
171 textdomain(PACKAGE);
172 atexit(close_stdout);
173
174 strutils_set_exitcode(EX_USAGE);
175
176 if (argc < 2) {
177 warnx(_("not enough arguments"));
178 errtryhelp(EX_USAGE);
179 }
180
181 memset(&timeout, 0, sizeof timeout);
182
183 optopt = 0;
184 while ((opt =
185 getopt_long(argc, argv, "+sexnoFuw:E:hV?", long_options,
186 &ix)) != EOF) {
187 switch (opt) {
188 case 's':
189 type = LOCK_SH;
190 break;
191 case 'e':
192 case 'x':
193 type = LOCK_EX;
194 break;
195 case 'u':
196 type = LOCK_UN;
197 break;
198 case 'o':
199 do_close = 1;
200 break;
201 case 'F':
202 no_fork = 1;
203 break;
204 case 'n':
205 block = LOCK_NB;
206 break;
207 case 'w':
208 have_timeout = 1;
209 strtotimeval_or_err(optarg, &timeout.it_value,
210 _("invalid timeout value"));
211 break;
212 case 'E':
213 conflict_exit_code = strtos32_or_err(optarg,
214 _("invalid exit code"));
215 break;
216 case OPT_VERBOSE:
217 verbose = 1;
218 break;
219 case 'V':
220 printf(UTIL_LINUX_VERSION);
221 exit(EX_OK);
222 case 'h':
223 usage();
224 default:
225 errtryhelp(EX_USAGE);
226 }
227 }
228
229 if (no_fork && do_close)
230 errx(EX_USAGE,
231 _("the --no-fork and --close options are incompatible"));
232
233 if (argc > optind + 1) {
234 /* Run command */
235 if (!strcmp(argv[optind + 1], "-c") ||
236 !strcmp(argv[optind + 1], "--command")) {
237 if (argc != optind + 3)
238 errx(EX_USAGE,
239 _("%s requires exactly one command argument"),
240 argv[optind + 1]);
241 cmd_argv = sh_c_argv;
242 cmd_argv[0] = getenv("SHELL");
243 if (!cmd_argv[0] || !*cmd_argv[0])
244 cmd_argv[0] = _PATH_BSHELL;
245 cmd_argv[1] = "-c";
246 cmd_argv[2] = argv[optind + 2];
247 cmd_argv[3] = NULL;
248 } else {
249 cmd_argv = &argv[optind + 1];
250 }
251
252 filename = argv[optind];
253 fd = open_file(filename, &open_flags);
254
255 } else if (optind < argc) {
256 /* Use provided file descriptor */
257 fd = strtos32_or_err(argv[optind], _("bad file descriptor"));
258 } else {
259 /* Bad options */
260 errx(EX_USAGE, _("requires file descriptor, file or directory"));
261 }
262
263 if (have_timeout) {
264 if (timeout.it_value.tv_sec == 0 &&
265 timeout.it_value.tv_usec == 0) {
266 /* -w 0 is equivalent to -n; this has to be
267 * special-cased because setting an itimer to zero
268 * means disabled!
269 */
270 have_timeout = 0;
271 block = LOCK_NB;
272 } else
273 if (setup_timer(&timer, &timeout, &timeout_handler))
274 err(EX_OSERR, _("cannot set up timer"));
275 }
276
277 if (verbose)
278 gettime_monotonic(&time_start);
279 while (flock(fd, type | block)) {
280 switch (errno) {
281 case EWOULDBLOCK:
282 /* -n option set and failed to lock. */
283 if (verbose)
284 warnx(_("failed to get lock"));
285 exit(conflict_exit_code);
286 case EINTR:
287 /* Signal received */
288 if (timeout_expired) {
289 /* -w option set and failed to lock. */
290 if (verbose)
291 warnx(_("timeout while waiting to get lock"));
292 exit(conflict_exit_code);
293 }
294 /* otherwise try again */
295 continue;
296 case EIO:
297 case EBADF: /* since Linux 3.4 (commit 55725513) */
298 /* Probably NFSv4 where flock() is emulated by fcntl().
299 * Let's try to reopen in read-write mode.
300 */
301 if (!(open_flags & O_RDWR) &&
302 type != LOCK_SH &&
303 filename &&
304 access(filename, R_OK | W_OK) == 0) {
305
306 close(fd);
307 open_flags = O_RDWR;
308 fd = open_file(filename, &open_flags);
309
310 if (open_flags & O_RDWR)
311 break;
312 }
313 /* fallthrough */
314 default:
315 /* Other errors */
316 if (filename)
317 warn("%s", filename);
318 else
319 warn("%d", fd);
320 exit((errno == ENOLCK
321 || errno == ENOMEM) ? EX_OSERR : EX_DATAERR);
322 }
323 }
324
325 if (have_timeout)
326 cancel_timer(&timer);
327 if (verbose) {
328 struct timeval delta;
329
330 gettime_monotonic(&time_done);
331 timersub(&time_done, &time_start, &delta);
332 printf(_("%s: getting lock took %ld.%06ld seconds\n"),
333 program_invocation_short_name, delta.tv_sec,
334 delta.tv_usec);
335 }
336 status = EX_OK;
337
338 if (cmd_argv) {
339 pid_t w, f;
340 /* Clear any inherited settings */
341 signal(SIGCHLD, SIG_DFL);
342 if (verbose)
343 printf(_("%s: executing %s\n"), program_invocation_short_name, cmd_argv[0]);
344
345 if (!no_fork) {
346 f = fork();
347 if (f < 0)
348 err(EX_OSERR, _("fork failed"));
349
350 /* child */
351 else if (f == 0) {
352 if (do_close)
353 close(fd);
354 run_program(cmd_argv);
355
356 /* parent */
357 } else {
358 do {
359 w = waitpid(f, &status, 0);
360 if (w == -1 && errno != EINTR)
361 break;
362 } while (w != f);
363
364 if (w == -1) {
365 status = EXIT_FAILURE;
366 warn(_("waitpid failed"));
367 } else if (WIFEXITED(status))
368 status = WEXITSTATUS(status);
369 else if (WIFSIGNALED(status))
370 status = WTERMSIG(status) + 128;
371 else
372 /* WTF? */
373 status = EX_OSERR;
374 }
375
376 } else
377 /* no-fork execution */
378 run_program(cmd_argv);
379 }
380
381 return status;
382 }