1 /* SPDX-License-Identifier: Apache-2.0
2  *
3  * Copyright (c) 2020 Friedt Professional Engineering Services, Inc
4  */
5 
6 #include "_main.h"
7 
ZTEST_USER_F(net_socketpair,test_close_one_end_and_write_to_the_other)8 ZTEST_USER_F(net_socketpair, test_close_one_end_and_write_to_the_other)
9 {
10 	int res;
11 
12 	for (size_t i = 0; i < 2; ++i) {
13 		res = close(fixture->sv[i]);
14 		zassert_equal(res, 0, "close(fixture->sv[%u]) failed: %d", i, errno);
15 		fixture->sv[i] = -1;
16 
17 		res = send(fixture->sv[(!i) & 1], "x", 1, 0);
18 		zassert_equal(res, -1, "expected send() to fail");
19 		zassert_equal(res, -1, "errno: expected: EPIPE actual: %d",
20 			errno);
21 
22 		res = close(fixture->sv[(!i) & 1]);
23 		zassert_equal(res, 0, "close(fixture->sv[%u]) failed: %d", i, errno);
24 		fixture->sv[(!i) & 1] = -1;
25 
26 		res = socketpair(AF_UNIX, SOCK_STREAM, 0, fixture->sv);
27 		zassert_equal(res, 0, "socketpair() failed: %d", errno);
28 	}
29 }
30 
ZTEST_USER_F(net_socketpair,test_close_one_end_and_read_from_the_other)31 ZTEST_USER_F(net_socketpair, test_close_one_end_and_read_from_the_other)
32 {
33 	int res;
34 	char xx[16];
35 
36 	for (size_t i = 0; i < 2; ++i) {
37 		/* We want to write some bytes to the closing end of the
38 		 * socket before it gets shut down, so that we can prove that
39 		 * reading is possible from the other end still and that data
40 		 * is not lost.
41 		 */
42 		res = send(fixture->sv[i], "xx", 2, 0);
43 		zassert_not_equal(res, -1, "send() failed: %d", errno);
44 		zassert_equal(res, 2, "write() failed to write 2 bytes");
45 
46 		res = close(fixture->sv[i]);
47 		zassert_equal(res, 0, "close(fixture->sv[%u]) failed: %d", i, errno);
48 		fixture->sv[i] = -1;
49 
50 		memset(xx, 0, sizeof(xx));
51 		res = recv(fixture->sv[(!i) & 1], xx, sizeof(xx), 0);
52 		zassert_not_equal(res, -1, "read() failed: %d", errno);
53 		zassert_equal(res, 2, "expected to read 2 bytes but read %d",
54 			res);
55 
56 		res = recv(fixture->sv[(!i) & 1], xx, sizeof(xx), 0);
57 		zassert_equal(res, 0, "expected read() to succeed but read 0 bytes");
58 
59 		res = close(fixture->sv[(!i) & 1]);
60 		zassert_equal(res, 0, "close(fixture->sv[%u]) failed: %d", i, errno);
61 		fixture->sv[(!i) & 1] = -1;
62 
63 		res = socketpair(AF_UNIX, SOCK_STREAM, 0, fixture->sv);
64 		zassert_equal(res, 0, "socketpair() failed: %d", errno);
65 	}
66 }
67