1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) Wipro Technologies Ltd, 2002. All Rights Reserved.
4 */
5
6 /*\
7 * [Description]
8 *
9 * This test case checks whether swapoff(2) system call returns
10 * 1. EINVAL when the path does not exist
11 * 2. ENOENT when the path exists but is invalid
12 * 3. EPERM when user is not a superuser
13 */
14
15 #include <errno.h>
16 #include <pwd.h>
17 #include "tst_test.h"
18 #include "lapi/syscalls.h"
19 #include "libswap.h"
20
21 #define MNTPOINT "mntpoint"
22 #define TEST_FILE MNTPOINT"/testswap"
23 #define SWAP_FILE MNTPOINT"/swapfile"
24
25 static int setup01(void);
26 static void cleanup01(void);
27
28 static uid_t nobody_uid;
29
30 static struct tcase {
31 char *err_desc;
32 int exp_errno;
33 char *exp_errval;
34 char *path;
35 int (*setup)(void);
36 void (*cleanup)(void);
37 } tcases[] = {
38 {"path does not exist", ENOENT, "ENOENT", "./doesnotexist", NULL, NULL},
39 {"Invalid file", EINVAL, "EINVAL", SWAP_FILE, NULL, NULL},
40 {"Permission denied", EPERM, "EPERM", SWAP_FILE, setup01, cleanup01}
41 };
42
verify_swapoff(unsigned int i)43 static void verify_swapoff(unsigned int i)
44 {
45 struct tcase *tc = tcases + i;
46 if (tc->setup)
47 tc->setup();
48
49 TEST(tst_syscall(__NR_swapoff, tc->path));
50
51 if (tc->cleanup)
52 tc->cleanup();
53
54 if (TST_RET == -1 && (TST_ERR == tc->exp_errno)) {
55 tst_res(TPASS, "swapoff(2) expected failure;"
56 " Got errno - %s : %s",
57 tc->exp_errval, tc->err_desc);
58 } else {
59 tst_res(TFAIL, "swapoff(2) failed to produce"
60 " expected error; %d, errno"
61 ": %s and got %d",
62 tc->exp_errno, tc->exp_errval, TST_ERR);
63
64 if ((TST_RET == 0) && (i == 2)) {
65 if (tst_syscall(__NR_swapon, "./swapfile01", 0) != 0)
66 tst_brk(TBROK | TERRNO, " Failed to turn on swap file");
67 }
68 }
69 }
70
setup01(void)71 static int setup01(void)
72 {
73 SAFE_SETEUID(nobody_uid);
74 return 0;
75 }
76
cleanup01(void)77 static void cleanup01(void)
78 {
79 SAFE_SETEUID(0);
80 }
81
setup(void)82 static void setup(void)
83 {
84 struct passwd *nobody;
85
86 nobody = SAFE_GETPWNAM("nobody");
87 nobody_uid = nobody->pw_uid;
88
89 is_swap_supported(TEST_FILE);
90 SAFE_MAKE_SMALL_SWAPFILE(SWAP_FILE);
91 }
92
93 static struct tst_test test = {
94 .mntpoint = MNTPOINT,
95 .mount_device = 1,
96 .all_filesystems = 1,
97 .needs_root = 1,
98 .test = verify_swapoff,
99 .tcnt = ARRAY_SIZE(tcases),
100 .setup = setup
101 };
102