1 /* f_setlk -- locking part of fcntl
2 Copyright (C) 2014-2022 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
18
19 #include <sys/types.h>
20 #include <sys/file.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23 #include <errno.h>
24
25 /* XXX
26 We need new RPCs to support POSIX.1 fcntl file locking!!
27 For the time being we support the whole-file case only,
28 with all kinds of WRONG WRONG WRONG semantics,
29 by using flock. This is definitely the Wrong Thing,
30 but it might be better than nothing (?). */
31 int
__f_setlk(int fd,int type,int whence,__off64_t start,__off64_t len,int wait)32 __f_setlk (int fd, int type, int whence, __off64_t start, __off64_t len, int wait)
33 {
34 int cmd = 0;
35
36 switch (type)
37 {
38 case F_RDLCK: cmd = LOCK_SH; break;
39 case F_WRLCK: cmd = LOCK_EX; break;
40 case F_UNLCK: cmd = LOCK_UN; break;
41 default:
42 errno = EINVAL;
43 return -1;
44 }
45
46 if (cmd != LOCK_UN && wait == 0)
47 cmd |= LOCK_NB;
48
49 if (whence == SEEK_CUR)
50 {
51 /* In case the target position is 0, we can support it below. */
52 __off64_t cur = __lseek64 (fd, 0, SEEK_CUR);
53
54 if (cur >= 0)
55 {
56 start = cur + start;
57 whence = SEEK_SET;
58 }
59 }
60
61 switch (whence)
62 {
63 case SEEK_SET:
64 if (start == 0 && len == 0) /* Whole file request. */
65 break;
66 /* It seems to be common for applications to lock the first
67 byte of the file when they are really doing whole-file locking.
68 So, since it's so wrong already, might as well do that too. */
69 if (start == 0 && len == 1)
70 break;
71 /* FALLTHROUGH */
72 case SEEK_CUR:
73 case SEEK_END:
74 errno = ENOTSUP;
75 return -1;
76 default:
77 errno = EINVAL;
78 return -1;
79 }
80
81 return __flock (fd, cmd);
82 }
83