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 static int setup01(void);
22 static void cleanup01(void);
23
24 static uid_t nobody_uid;
25
26 static struct tcase {
27 char *err_desc;
28 int exp_errno;
29 char *exp_errval;
30 char *path;
31 int (*setup)(void);
32 void (*cleanup)(void);
33 } tcases[] = {
34 {"path does not exist", ENOENT, "ENOENT", "./doesnotexist", NULL, NULL},
35 {"Invalid file", EINVAL, "EINVAL", "./swapfile01", NULL, NULL},
36 {"Permission denied", EPERM, "EPERM", "./swapfile01", setup01, cleanup01}
37 };
38
verify_swapoff(unsigned int i)39 static void verify_swapoff(unsigned int i)
40 {
41 struct tcase *tc = tcases + i;
42 if (tc->setup)
43 tc->setup();
44
45 TEST(tst_syscall(__NR_swapoff, tc->path));
46
47 if (tc->cleanup)
48 tc->cleanup();
49
50 if (TST_RET == -1 && (TST_ERR == tc->exp_errno)) {
51 tst_res(TPASS, "swapoff(2) expected failure;"
52 " Got errno - %s : %s",
53 tc->exp_errval, tc->err_desc);
54 } else {
55 tst_res(TFAIL, "swapoff(2) failed to produce"
56 " expected error; %d, errno"
57 ": %s and got %d",
58 tc->exp_errno, tc->exp_errval, TST_ERR);
59
60 if ((TST_RET == 0) && (i == 2)) {
61 if (tst_syscall(__NR_swapon, "./swapfile01", 0) != 0)
62 tst_brk(TBROK | TERRNO, " Failed to turn on swap file");
63 }
64 }
65 }
66
setup01(void)67 static int setup01(void)
68 {
69 SAFE_SETEUID(nobody_uid);
70 return 0;
71 }
72
cleanup01(void)73 static void cleanup01(void)
74 {
75 SAFE_SETEUID(0);
76 }
77
setup(void)78 static void setup(void)
79 {
80 struct passwd *nobody;
81
82 nobody = SAFE_GETPWNAM("nobody");
83 nobody_uid = nobody->pw_uid;
84
85 is_swap_supported("./tstswap");
86
87 if (!tst_fs_has_free(".", 1, TST_KB))
88 tst_brk(TBROK, "Insufficient disk space to create swap file");
89
90 if (tst_fill_file("./swapfile01", 0x00, 1024, 1))
91 tst_brk(TBROK, "Failed to create swapfile");
92 }
93
94 static struct tst_test test = {
95 .needs_root = 1,
96 .needs_tmpdir = 1,
97 .test = verify_swapoff,
98 .tcnt = ARRAY_SIZE(tcases),
99 .setup = setup
100 };
101