(root)/
util-linux-2.39/
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 volatile 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  	close_stdout_atexit();
     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  			if (conflict_exit_code < 0 || conflict_exit_code > 255)
     216  				errx(EX_USAGE, _("exit code out of range (expected 0 to 255)"));
     217  			break;
     218  		case OPT_VERBOSE:
     219  			verbose = 1;
     220  			break;
     221  
     222  		case 'V':
     223  			print_version(EX_OK);
     224  		case 'h':
     225  			usage();
     226  		default:
     227  			errtryhelp(EX_USAGE);
     228  		}
     229  	}
     230  
     231  	if (no_fork && do_close)
     232  		errx(EX_USAGE,
     233  			_("the --no-fork and --close options are incompatible"));
     234  
     235  	if (argc > optind + 1) {
     236  		/* Run command */
     237  		if (!strcmp(argv[optind + 1], "-c") ||
     238  		    !strcmp(argv[optind + 1], "--command")) {
     239  			if (argc != optind + 3)
     240  				errx(EX_USAGE,
     241  				     _("%s requires exactly one command argument"),
     242  				     argv[optind + 1]);
     243  			cmd_argv = sh_c_argv;
     244  			cmd_argv[0] = getenv("SHELL");
     245  			if (!cmd_argv[0] || !*cmd_argv[0])
     246  				cmd_argv[0] = _PATH_BSHELL;
     247  			cmd_argv[1] = "-c";
     248  			cmd_argv[2] = argv[optind + 2];
     249  			cmd_argv[3] = NULL;
     250  		} else {
     251  			cmd_argv = &argv[optind + 1];
     252  		}
     253  
     254  		filename = argv[optind];
     255  		fd = open_file(filename, &open_flags);
     256  
     257  	} else if (optind < argc) {
     258  		/* Use provided file descriptor */
     259  		fd = strtos32_or_err(argv[optind], _("bad file descriptor"));
     260  	} else {
     261  		/* Bad options */
     262  		errx(EX_USAGE, _("requires file descriptor, file or directory"));
     263  	}
     264  
     265  	if (have_timeout) {
     266  		if (timeout.it_value.tv_sec == 0 &&
     267  		    timeout.it_value.tv_usec == 0) {
     268  			/* -w 0 is equivalent to -n; this has to be
     269  			 * special-cased because setting an itimer to zero
     270  			 * means disabled!
     271  			 */
     272  			have_timeout = 0;
     273  			block = LOCK_NB;
     274  		} else
     275  			if (setup_timer(&timer, &timeout, &timeout_handler))
     276  				err(EX_OSERR, _("cannot set up timer"));
     277  	}
     278  
     279  	if (verbose)
     280  		gettime_monotonic(&time_start);
     281  	while (flock(fd, type | block)) {
     282  		switch (errno) {
     283  		case EWOULDBLOCK:
     284  			/* -n option set and failed to lock. */
     285  			if (verbose)
     286  				warnx(_("failed to get lock"));
     287  			exit(conflict_exit_code);
     288  		case EINTR:
     289  			/* Signal received */
     290  			if (timeout_expired) {
     291  				/* -w option set and failed to lock. */
     292  				if (verbose)
     293  					warnx(_("timeout while waiting to get lock"));
     294  				exit(conflict_exit_code);
     295  			}
     296  			/* otherwise try again */
     297  			continue;
     298  		case EIO:
     299  		case EBADF:		/* since Linux 3.4 (commit 55725513) */
     300  			/* Probably NFSv4 where flock() is emulated by fcntl().
     301  			 * Let's try to reopen in read-write mode.
     302  			 */
     303  			if (!(open_flags & O_RDWR) &&
     304  			    type != LOCK_SH &&
     305  			    filename &&
     306  			    access(filename, R_OK | W_OK) == 0) {
     307  
     308  				close(fd);
     309  				open_flags = O_RDWR;
     310  				fd = open_file(filename, &open_flags);
     311  
     312  				if (open_flags & O_RDWR)
     313  					break;
     314  			}
     315  			/* fallthrough */
     316  		default:
     317  			/* Other errors */
     318  			if (filename)
     319  				warn("%s", filename);
     320  			else
     321  				warn("%d", fd);
     322  			exit((errno == ENOLCK
     323  			      || errno == ENOMEM) ? EX_OSERR : EX_DATAERR);
     324  		}
     325  	}
     326  
     327  	if (have_timeout)
     328  		cancel_timer(&timer);
     329  	if (verbose) {
     330  		struct timeval delta;
     331  
     332  		gettime_monotonic(&time_done);
     333  		timersub(&time_done, &time_start, &delta);
     334  		printf(_("%s: getting lock took %"PRId64".%06"PRId64" seconds\n"),
     335  		       program_invocation_short_name,
     336  		       (int64_t) delta.tv_sec,
     337  		       (int64_t) delta.tv_usec);
     338  	}
     339  	status = EX_OK;
     340  
     341  	if (cmd_argv) {
     342  		pid_t w, f;
     343  		/* Clear any inherited settings */
     344  		signal(SIGCHLD, SIG_DFL);
     345  		if (verbose)
     346  			printf(_("%s: executing %s\n"), program_invocation_short_name, cmd_argv[0]);
     347  
     348  		if (!no_fork) {
     349  			f = fork();
     350  			if (f < 0)
     351  				err(EX_OSERR, _("fork failed"));
     352  
     353  			/* child */
     354  			else if (f == 0) {
     355  				if (do_close)
     356  					close(fd);
     357  				run_program(cmd_argv);
     358  
     359  			/* parent */
     360  			} else {
     361  				do {
     362  					w = waitpid(f, &status, 0);
     363  					if (w == -1 && errno != EINTR)
     364  						break;
     365  				} while (w != f);
     366  
     367  				if (w == -1) {
     368  					status = EXIT_FAILURE;
     369  					warn(_("waitpid failed"));
     370  				} else if (WIFEXITED(status))
     371  					status = WEXITSTATUS(status);
     372  				else if (WIFSIGNALED(status))
     373  					status = WTERMSIG(status) + 128;
     374  				else
     375  					/* WTF? */
     376  					status = EX_OSERR;
     377  			}
     378  
     379  		} else
     380  			/* no-fork execution */
     381  			run_program(cmd_argv);
     382  	}
     383  
     384  	return status;
     385  }