1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2017 RedHat.  All Rights Reserved.
4  *
5  * Started by Xiong Zhou <xzhou@redhat.com>
6  *
7  * DESCRIPTION
8  *     Sanity check fanotify_init flag FAN_CLOEXEC by fcntl.
9  */
10 #define _GNU_SOURCE
11 #include "config.h"
12 
13 #include <stdio.h>
14 #include <sys/stat.h>
15 #include <sys/types.h>
16 #include <fcntl.h>
17 #include <errno.h>
18 #include <string.h>
19 #include <sys/syscall.h>
20 #include "tst_test.h"
21 #include "fanotify.h"
22 
23 #if defined(HAVE_SYS_FANOTIFY_H)
24 #include <sys/fanotify.h>
25 
26 static int fd_notify;
27 
test_init_bit(unsigned int fan_bit,unsigned int fd_bit,char * msg)28 static void test_init_bit(unsigned int fan_bit,
29 			unsigned int fd_bit, char *msg)
30 {
31 	int ret;
32 
33 	fd_notify = SAFE_FANOTIFY_INIT(FAN_CLASS_NOTIF|fan_bit, O_RDONLY);
34 
35 	ret = SAFE_FCNTL(fd_notify, F_GETFD);
36 
37 	if ((ret & FD_CLOEXEC) == fd_bit) {
38 		tst_res(TPASS, "%s", msg);
39 	} else {
40 		tst_res(TFAIL, "%s", msg);
41 	}
42 
43 	SAFE_CLOSE(fd_notify);
44 }
45 
run(unsigned int i)46 static void run(unsigned int i)
47 {
48 	switch (i) {
49 	case 0:
50 		test_init_bit(0, 0, "not set close_on_exec");
51 		break;
52 	case 1:
53 		test_init_bit(FAN_CLOEXEC, FD_CLOEXEC, "set close_on_exec");
54 		break;
55 	}
56 }
57 
cleanup(void)58 static void cleanup(void)
59 {
60 	if (fd_notify > 0)
61 		SAFE_CLOSE(fd_notify);
62 }
63 
64 static struct tst_test test = {
65 	.test = run,
66 	.tcnt = 2,
67 	.cleanup = cleanup,
68 	.needs_root = 1,
69 };
70 
71 #else
72 	TST_TEST_TCONF("system doesn't have required fanotify support");
73 #endif
74