1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) 2020 FUJITSU LIMITED. All rights reserved.
4 * Author: Yang Xu <xuyang2018.jy@cn.jujitsu.com>
5 *
6 * Test basic error handling for fcntl(2) using F_SETPIPE_SZ, F_GETPIPE_SZ
7 * argument.
8 * 1)fcntl fails with EINVAL when cmd is F_SETPIPE_SZ and the arg is
9 * beyond 1<<31.
10 * 2)fcntl fails with EBUSY when cmd is F_SETPIPE_SZ and the arg is smaller
11 * than the amount of the current used buffer space.
12 * 3)fcntl fails with EPERM when cmd is F_SETPIPE_SZ and the arg is over
13 * /proc/sys/fs/pipe-max-size limit under unprivileged users.
14 */
15
16 #include <unistd.h>
17 #include <fcntl.h>
18 #include <sys/types.h>
19 #include <limits.h>
20 #include <stdlib.h>
21 #include "tst_test.h"
22 #include "lapi/fcntl.h"
23 #include "lapi/capability.h"
24
25 static int fds[2];
26 static unsigned int invalid_value, half_value, sys_value;
27
28 static struct tcase {
29 unsigned int *setvalue;
30 int exp_err;
31 char *message;
32 } tcases[] = {
33 {&invalid_value, EINVAL, "F_SETPIPE_SZ and size is beyond 1<<31"},
34 {&half_value, EBUSY, "F_SETPIPE_SZ and size < data stored in pipe"},
35 {&sys_value, EPERM, "F_SETPIPE_SZ and size is over limit for unpriviledged user"},
36 };
37
verify_fcntl(unsigned int n)38 static void verify_fcntl(unsigned int n)
39 {
40 struct tcase *tc = &tcases[n];
41
42 tst_res(TINFO, "%s", tc->message);
43
44 TEST(fcntl(fds[1], F_SETPIPE_SZ, *(tc->setvalue)));
45 if (TST_RET != -1) {
46 tst_res(TFAIL, "F_SETPIPE_SZ succeed and return %ld", TST_RET);
47 return;
48 }
49 if (TST_ERR == tc->exp_err)
50 tst_res(TPASS | TTERRNO, "F_SETPIPE_SZ failed as expected");
51 else
52 tst_res(TFAIL | TTERRNO, "F_SETPIPE_SZ failed expected %s got",
53 tst_strerrno(tc->exp_err));
54 }
55
setup(void)56 static void setup(void)
57 {
58 char *wrbuf;
59 unsigned int orig_value;
60
61 SAFE_PIPE(fds);
62
63 TEST(fcntl(fds[1], F_GETPIPE_SZ));
64 if (TST_ERR == EINVAL)
65 tst_brk(TCONF, "kernel doesn't support F_GET/SETPIPE_SZ");
66
67 orig_value = TST_RET;
68
69 wrbuf = SAFE_MALLOC(orig_value);
70 memset(wrbuf, 'x', orig_value);
71 SAFE_WRITE(1, fds[1], wrbuf, orig_value);
72 free(wrbuf);
73
74 SAFE_FILE_SCANF("/proc/sys/fs/pipe-max-size", "%d", &sys_value);
75 sys_value++;
76
77 half_value = orig_value / 2;
78 invalid_value = (1U << 31) + 1;
79 }
80
cleanup(void)81 static void cleanup(void)
82 {
83 if (fds[0] > 0)
84 SAFE_CLOSE(fds[0]);
85 if (fds[1] > 0)
86 SAFE_CLOSE(fds[1]);
87 }
88
89 static struct tst_test test = {
90 .setup = setup,
91 .cleanup = cleanup,
92 .tcnt = ARRAY_SIZE(tcases),
93 .test = verify_fcntl,
94 .caps = (struct tst_cap []) {
95 TST_CAP(TST_CAP_DROP, CAP_SYS_RESOURCE),
96 {}
97 },
98 };
99