1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) Ulrich Drepper <drepper@redhat.com>
4 * Copyright (c) International Business Machines Corp., 2009
5 * Copyright (c) Linux Test Project, 2010-2022
6 */
7
8 /*\
9 * [Description]
10 *
11 * Test socket() with SOCK_CLOEXEC and SOCK_NONBLOCK flags.
12 */
13
14 #include <stdio.h>
15 #include <unistd.h>
16 #include <netinet/in.h>
17 #include <sys/socket.h>
18 #include "lapi/fcntl.h"
19 #include "tst_test.h"
20
21 static int fd;
22
23 static struct tcase {
24 int type;
25 int flag;
26 int fl_flag;
27 char *des;
28 } tcases[] = {
29 {SOCK_STREAM, 0, F_GETFD, "no close-on-exec"},
30 {SOCK_STREAM | SOCK_CLOEXEC, FD_CLOEXEC, F_GETFD, "close-on-exec"},
31 {SOCK_STREAM, 0, F_GETFL, "no non-blocking"},
32 {SOCK_STREAM | SOCK_NONBLOCK, O_NONBLOCK, F_GETFL, "non-blocking"}
33 };
34
verify_socket(unsigned int n)35 static void verify_socket(unsigned int n)
36 {
37 int res;
38 struct tcase *tc = &tcases[n];
39
40 fd = socket(PF_INET, tc->type, 0);
41 if (fd == -1)
42 tst_brk(TFAIL | TERRNO, "socket() failed");
43
44 res = SAFE_FCNTL(fd, tc->fl_flag);
45
46 if (tc->flag != 0 && (res & tc->flag) == 0) {
47 tst_res(TFAIL, "socket() failed to set %s flag", tc->des);
48 return;
49 }
50
51 if (tc->flag == 0 && (res & tc->flag) != 0) {
52 tst_res(TFAIL, "socket() failed to set %s flag", tc->des);
53 return;
54 }
55
56 tst_res(TPASS, "socket() passed to set %s flag", tc->des);
57
58 SAFE_CLOSE(fd);
59 }
60
cleanup(void)61 static void cleanup(void)
62 {
63 if (fd > 0)
64 SAFE_CLOSE(fd);
65 }
66
67 static struct tst_test test = {
68 .tcnt = ARRAY_SIZE(tcases),
69 .test = verify_socket,
70 .cleanup = cleanup
71 };
72