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 <errno.h>
15 #include <pthread.h>
16 #include <stdio.h>
17 #include <unistd.h>
18 #include <netinet/in.h>
19 #include <sys/socket.h>
20 #include <sys/syscall.h>
21 #include "lapi/fcntl.h"
22 #include "tst_test.h"
23
24 static int fds[2];
25
26 static struct tcase {
27 int type;
28 int flag;
29 int fl_flag;
30 char *des;
31 } tcases[] = {
32 {SOCK_STREAM, 0, F_GETFD, "no close-on-exec"},
33 {SOCK_STREAM | SOCK_CLOEXEC, FD_CLOEXEC, F_GETFD, "close-on-exec"},
34 {SOCK_STREAM, 0, F_GETFL, "no non-blocking"},
35 {SOCK_STREAM | SOCK_NONBLOCK, O_NONBLOCK, F_GETFL, "non-blocking"}
36 };
37
verify_socketpair(unsigned int n)38 static void verify_socketpair(unsigned int n)
39 {
40 int res, i;
41 struct tcase *tc = &tcases[n];
42
43 TEST(socketpair(PF_UNIX, tc->type, 0, fds));
44
45 if (TST_RET == -1)
46 tst_brk(TFAIL | TTERRNO, "socketpair() failed");
47
48 for (i = 0; i < 2; i++) {
49 res = SAFE_FCNTL(fds[i], tc->fl_flag);
50
51 if (tc->flag != 0 && (res & tc->flag) == 0) {
52 tst_res(TFAIL, "socketpair() failed to set %s flag for fds[%d]",
53 tc->des, i);
54 goto ret;
55 }
56
57 if (tc->flag == 0 && (res & tc->flag) != 0) {
58 tst_res(TFAIL, "socketpair() failed to set %s flag for fds[%d]",
59 tc->des, i);
60 goto ret;
61 }
62 }
63
64 tst_res(TPASS, "socketpair() passed to set %s flag", tc->des);
65
66 ret:
67 SAFE_CLOSE(fds[0]);
68 SAFE_CLOSE(fds[1]);
69 }
70
cleanup(void)71 static void cleanup(void)
72 {
73 if (fds[0] > 0)
74 SAFE_CLOSE(fds[0]);
75
76 if (fds[1] > 0)
77 SAFE_CLOSE(fds[1]);
78 }
79
80 static struct tst_test test = {
81 .tcnt = ARRAY_SIZE(tcases),
82 .test = verify_socketpair,
83 .cleanup = cleanup
84 };
85